repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
gribozavr/swift
test/SourceKit/Indexing/index_operators.swift
1
516
// RUN: %sourcekitd-test -req=index %s -- -Xfrontend -serialize-diagnostics-path -Xfrontend %t.dia %s | %sed_clean > %t.response // RUN: diff --strip-trailing-cr -u %s.response %t.response class ClassA { init(){} } func +(lhs: ClassA, rhs: ClassA) -> ClassA { return lhs } struct StructB { func method() { let a = ClassA() let b = a + a let c = StructB() let d = c - c } public static func -(lhs: StructB, rhs: StructB) -> StructB { return lhs } }
apache-2.0
598cb8a77ff3b8b1c11970cd75d4b8ce
21.434783
128
0.563953
3.265823
false
false
false
false
youngsoft/TangramKit
TangramKit/TGRelativeLayout.swift
1
57486
// // TGRelativeLayout.swift // TangramKit // // Created by apple on 16/3/13. // Copyright © 2016年 youngsoft. All rights reserved. // import UIKit /** *相对布局是一种里面的子视图通过相互之间的约束和依赖来进行布局和定位的布局视图。 *相对布局里面的子视图的布局位置和添加的顺序无关,而是通过设置子视图的相对依赖关系来进行定位和布局的。 *相对布局提供和AutoLayout等价的功能。 */ open class TGRelativeLayout: TGBaseLayout,TGRelativeLayoutViewSizeClass { //MARK: override method override internal func tgCalcLayoutRect(_ size:CGSize, isEstimate:Bool, hasSubLayout:inout Bool!, sbs:[UIView]!, type :TGSizeClassType) -> CGSize { var selfSize = super.tgCalcLayoutRect(size, isEstimate:isEstimate, hasSubLayout:&hasSubLayout, sbs:sbs, type:type) let lsc = self.tgCurrentSizeClass as! TGRelativeLayoutViewSizeClassImpl for sbv: UIView in self.subviews { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if sbvsc.tg_useFrame { continue } if !isEstimate || (hasSubLayout != nil && hasSubLayout) { sbvtgFrame.reset() } if sbvsc.isHorzMarginHasValue { sbvsc.width.resetValue() } if sbvsc.isVertMarginHasValue { sbvsc.height.resetValue() } if let sbvl: TGBaseLayout = sbv as? TGBaseLayout { if hasSubLayout != nil && sbvsc.isSomeSizeWrap { hasSubLayout = true } if isEstimate && (sbvsc.isSomeSizeWrap) { var sz = sbvtgFrame.frame.size if sz.width == CGFloat.greatestFiniteMagnitude { sz.width = 0 } if sz.height == CGFloat.greatestFiniteMagnitude { sz.height = 0 } _ = sbvl.tg_sizeThatFits(sz, inSizeClass:type) sbvtgFrame.leading = CGFloat.greatestFiniteMagnitude sbvtgFrame.trailing = CGFloat.greatestFiniteMagnitude sbvtgFrame.top = CGFloat.greatestFiniteMagnitude sbvtgFrame.bottom = CGFloat.greatestFiniteMagnitude; if sbvtgFrame.multiple { sbvtgFrame.sizeClass = sbv.tgMatchBestSizeClass(type) //因为tg_sizeThatFits执行后会还原,所以这里要重新设置 } } } } let isWrap = lsc.isSomeSizeWrap let (maxSize,recalc) = tgCalcLayoutRectHelper(selfSize, lsc:lsc, isWrap: isWrap) if isWrap { if _tgCGFloatNotEqual(selfSize.height, maxSize.height) || _tgCGFloatNotEqual(selfSize.width, maxSize.width) { if lsc.width.isWrap { selfSize.width = maxSize.width } if lsc.height.isWrap { selfSize.height = maxSize.height } if recalc { for sbv: UIView in self.subviews { let sbvtgFrame = sbv.tgFrame if let _ = sbv as? TGBaseLayout , isEstimate { sbvtgFrame.leading = CGFloat.greatestFiniteMagnitude sbvtgFrame.trailing = CGFloat.greatestFiniteMagnitude sbvtgFrame.top = CGFloat.greatestFiniteMagnitude sbvtgFrame.bottom = CGFloat.greatestFiniteMagnitude } else { sbvtgFrame.reset() } } _ = tgCalcLayoutRectHelper(selfSize, lsc:lsc, isWrap: false) } } } let sbs2 = self.tgGetLayoutSubviews() tgAdjustLayoutSelfSize(selfSize: &selfSize, lsc: lsc) tgAdjustSubviewsLayoutTransform(sbs: sbs2, lsc: lsc, selfSize: selfSize) tgAdjustSubviewsRTLPos(sbs: sbs2, selfWidth: selfSize.width) return self.tgAdjustSizeWhenNoSubviews(size: selfSize, sbs: sbs2, lsc:lsc) } internal override func tgCreateInstance() -> AnyObject { return TGRelativeLayoutViewSizeClassImpl(view:self) } } extension TGRelativeLayout { fileprivate func tgCalcSubviewLeadingTrailing(_ sbv: UIView, sbvsc:TGViewSizeClassImpl, sbvtgFrame:TGFrame, lsc:TGRelativeLayoutViewSizeClassImpl, selfSize: CGSize) { if sbvtgFrame.leading != CGFloat.greatestFiniteMagnitude && sbvtgFrame.trailing != CGFloat.greatestFiniteMagnitude && sbvtgFrame.width != CGFloat.greatestFiniteMagnitude { return } if tgCalcSubviewWidth(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) { return } let sbvLeadingMargin = sbvsc.leading.absPos let sbvTrailingMargin = sbvsc.trailing.absPos let sbvCenterXMargin = sbvsc.centerX.absPos if sbvsc.centerX.hasValue { if sbvsc.width.isFill && !self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.width = sbvsc.width.measure(selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding) } } if let t = sbvsc.centerX.posVal { let relaView = t.view sbvtgFrame.leading = tgCalcRelationalSubview(relaView, lsc:lsc, gravity: t.type, selfSize: selfSize) - sbvtgFrame.width / 2 + sbvCenterXMargin if relaView != self && self.tgIsNoLayoutSubview(relaView) { sbvtgFrame.leading -= sbvCenterXMargin } if lsc.width.isWrap && sbvtgFrame.leading < 0 && relaView === self { sbvtgFrame.leading = 0 } sbvtgFrame.trailing = sbvtgFrame.leading + sbvtgFrame.width } else if sbvsc.centerX.numberVal != nil { sbvtgFrame.leading = (selfSize.width - lsc.tgTrailingPadding - lsc.tgLeadingPadding - sbvtgFrame.width) / 2 + lsc.tgLeadingPadding + sbvCenterXMargin if lsc.width.isWrap && sbvtgFrame.leading < 0 { sbvtgFrame.leading = 0 } sbvtgFrame.trailing = sbvtgFrame.leading + sbvtgFrame.width } else if sbvsc.centerX.weightVal != nil { sbvtgFrame.leading = (selfSize.width - lsc.tgTrailingPadding - lsc.tgLeadingPadding - sbvtgFrame.width) / 2 + lsc.tgLeadingPadding + sbvsc.centerX.weightPosIn(selfSize.width - lsc.tgTrailingPadding - lsc.tgLeadingPadding) if lsc.width.isWrap && sbvtgFrame.leading < 0 { sbvtgFrame.leading = 0 } sbvtgFrame.trailing = sbvtgFrame.leading + sbvtgFrame.width } else { if sbvsc.leading.hasValue { if let t = sbvsc.leading.posVal { let relaView = t.view sbvtgFrame.leading = tgCalcRelationalSubview(relaView, lsc:lsc, gravity:t.type, selfSize: selfSize) + sbvLeadingMargin if relaView != self && self.tgIsNoLayoutSubview(relaView) { sbvtgFrame.leading -= sbvLeadingMargin } } else if sbvsc.leading.numberVal != nil { sbvtgFrame.leading = sbvLeadingMargin + lsc.tgLeadingPadding } else if sbvsc.leading.weightVal != nil { sbvtgFrame.leading = sbvsc.leading.weightPosIn(selfSize.width - lsc.tgTrailingPadding - lsc.tgLeadingPadding) + lsc.tgLeadingPadding } if sbvsc.width.isFill && !self.tgIsNoLayoutSubview(sbv) { //lsc.tgLeadingPadding 这里因为sbvtgFrame.leading已经包含了leftPadding所以这里不需要再减 sbvtgFrame.width = sbvsc.width.measure(selfSize.width - lsc.tgTrailingPadding - sbvtgFrame.leading) } sbvtgFrame.trailing = sbvtgFrame.leading + sbvtgFrame.width } if sbvsc.trailing.hasValue { if let t = sbvsc.trailing.posVal { let relaView = t.view sbvtgFrame.trailing = tgCalcRelationalSubview(relaView, lsc:lsc, gravity: t.type, selfSize: selfSize) - sbvTrailingMargin + sbvLeadingMargin if relaView != self && self.tgIsNoLayoutSubview(relaView) { sbvtgFrame.trailing += sbvTrailingMargin } } else if sbvsc.trailing.numberVal != nil { sbvtgFrame.trailing = selfSize.width - lsc.tgTrailingPadding - sbvTrailingMargin + sbvLeadingMargin } else if sbvsc.trailing.weightVal != nil { sbvtgFrame.trailing = selfSize.width - lsc.tgTrailingPadding - sbvsc.trailing.weightPosIn(selfSize.width - lsc.tgTrailingPadding - lsc.tgLeadingPadding) + sbvLeadingMargin } if sbvsc.width.isFill && !self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.width = sbvsc.width.measure(sbvtgFrame.trailing - sbvLeadingMargin - lsc.tgLeadingPadding) } sbvtgFrame.leading = sbvtgFrame.trailing - sbvtgFrame.width } if !sbvsc.leading.hasValue && !sbvsc.trailing.hasValue { if sbvsc.width.isFill && !self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.width = sbvsc.width.measure(selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding) } sbvtgFrame.leading = sbvLeadingMargin + lsc.tgLeadingPadding sbvtgFrame.trailing = sbvtgFrame.leading + sbvtgFrame.width } } //这里要更新左边最小和右边最大约束的情况。 if case let(minrt?, maxrt?) = (sbvsc.leading.minVal?.posVal , sbvsc.trailing.maxVal?.posVal) { //让宽度缩小并在最小和最大的中间排列。 let minLeading = self.tgCalcRelationalSubview(minrt.view, lsc:lsc, gravity: minrt.type, selfSize: selfSize) + sbvsc.leading.minVal!.offset let maxTrailing = self.tgCalcRelationalSubview(maxrt.view, lsc:lsc, gravity: maxrt.type, selfSize: selfSize) - sbvsc.trailing.maxVal!.offset //用maxTrailing减去minLeading得到的宽度再减去视图的宽度,然后让其居中。。如果宽度超过则缩小视图的宽度。 if _tgCGFloatLess(maxTrailing - minLeading , sbvtgFrame.width) { sbvtgFrame.width = maxTrailing - minLeading sbvtgFrame.leading = minLeading } else { sbvtgFrame.leading = (maxTrailing - minLeading - sbvtgFrame.width) / 2 + minLeading } sbvtgFrame.trailing = sbvtgFrame.leading + sbvtgFrame.width } else if let t = sbvsc.leading.minVal?.posVal { //得到左边的最小位置。如果当前的左边距小于这个位置则缩小视图的宽度。 let minLeading = self.tgCalcRelationalSubview(t.view, lsc:lsc, gravity: t.type, selfSize: selfSize) + sbvsc.leading.minVal!.offset if _tgCGFloatLess(sbvtgFrame.leading , minLeading) { sbvtgFrame.leading = minLeading sbvtgFrame.width = sbvtgFrame.trailing - sbvtgFrame.leading } } else if let t = sbvsc.trailing.maxVal?.posVal { //得到右边的最大位置。如果当前的右边距大于了这个位置则缩小视图的宽度。 let maxTrailing = self.tgCalcRelationalSubview(t.view, lsc:lsc, gravity: t.type, selfSize: selfSize) - sbvsc.trailing.maxVal!.offset if _tgCGFloatGreat(sbvtgFrame.trailing , maxTrailing) { sbvtgFrame.trailing = maxTrailing; sbvtgFrame.width = sbvtgFrame.trailing - sbvtgFrame.leading } } } fileprivate func tgCalcSubviewTopBottom(_ sbv: UIView, sbvsc:TGViewSizeClassImpl, sbvtgFrame:TGFrame, lsc:TGRelativeLayoutViewSizeClassImpl,selfSize: CGSize) { if sbvtgFrame.top != CGFloat.greatestFiniteMagnitude && sbvtgFrame.bottom != CGFloat.greatestFiniteMagnitude && sbvtgFrame.height != CGFloat.greatestFiniteMagnitude { return } if tgCalcSubviewHeight(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) { return } let sbvTopMargin = sbvsc.top.absPos let sbvBottomMargin = sbvsc.bottom.absPos let sbvCenterYMargin = sbvsc.centerY.absPos if sbvsc.centerY.hasValue { if sbvsc.height.isFill && !self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.height = sbvsc.height.measure(selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) } } if let t = sbvsc.baseline.posVal { //得到基线的位置。基线的位置等于top + (子视图的高度 - 字体的高度) / 2 + 字体基线以上的高度。 let sbvFont:UIFont! = self.tgGetSubviewFont(sbv) if sbvFont != nil { //得到基线的位置。 let relaView = t.view sbvtgFrame.top = self.tgCalcRelationalSubview(relaView, lsc:lsc, gravity:t.type,selfSize:selfSize) - sbvFont.ascender - (sbvtgFrame.height - sbvFont.lineHeight) / 2.0 + sbvsc.baseline.absPos if relaView != self && self.tgIsNoLayoutSubview(relaView) { sbvtgFrame.top -= sbvsc.baseline.absPos } } else { sbvtgFrame.top = lsc.tgTopPadding + sbvsc.baseline.absPos } sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height } else if let t = sbvsc.baseline.numberVal { //得到基线的位置。基线的位置等于top + (子视图的高度 - 字体的高度) / 2 + 字体基线以上的高度。 let sbvFont:UIFont! = self.tgGetSubviewFont(sbv) if sbvFont != nil { //得到基线的位置。 sbvtgFrame.top = lsc.tgTopPadding - sbvFont.ascender - (sbvtgFrame.height - sbvFont.lineHeight) / 2.0 + t } else { sbvtgFrame.top = lsc.tgTopPadding + t } sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height } else if let t = sbvsc.centerY.posVal { let relaView = t.view sbvtgFrame.top = tgCalcRelationalSubview(relaView, lsc:lsc, gravity: t.type, selfSize: selfSize) - sbvtgFrame.height / 2 + sbvCenterYMargin if relaView != self && self.tgIsNoLayoutSubview(relaView) { sbvtgFrame.top -= sbvCenterYMargin } if lsc.height.isWrap && sbvtgFrame.top < 0 && relaView === self { sbvtgFrame.top = 0 } sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height } else if sbvsc.centerY.numberVal != nil { sbvtgFrame.top = (selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding - sbvtgFrame.height) / 2 + lsc.tgTopPadding + sbvCenterYMargin if lsc.height.isWrap && sbvtgFrame.top < 0 { sbvtgFrame.top = 0 } sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height } else if sbvsc.centerY.weightVal != nil { sbvtgFrame.top = (selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding - sbvtgFrame.height) / 2 + lsc.tgTopPadding + sbvsc.centerY.weightPosIn(selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) if lsc.height.isWrap && sbvtgFrame.top < 0 { sbvtgFrame.top = 0 } sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height } else { if sbvsc.top.hasValue { if let t = sbvsc.top.posVal { let relaView = t.view sbvtgFrame.top = tgCalcRelationalSubview(relaView, lsc:lsc, gravity: t.type, selfSize: selfSize) + sbvTopMargin if relaView != self && self.tgIsNoLayoutSubview(relaView) { sbvtgFrame.top -= sbvTopMargin } } else if sbvsc.top.numberVal != nil { sbvtgFrame.top = sbvTopMargin + lsc.tgTopPadding } else if sbvsc.top.weightVal != nil { sbvtgFrame.top = sbvsc.top.weightPosIn(selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) + lsc.tgTopPadding } if sbvsc.height.isFill && !self.tgIsNoLayoutSubview(sbv) { //lsc.tgTopPadding 这里因为sbvtgFrame.top已经包含了topPadding所以这里不需要再减 sbvtgFrame.height = sbvsc.height.measure(selfSize.height - lsc.tgTopPadding - sbvtgFrame.top) } sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height } if sbvsc.bottom.hasValue { if let t = sbvsc.bottom.posVal { let relaView = t.view sbvtgFrame.bottom = tgCalcRelationalSubview(relaView, lsc:lsc, gravity: t.type, selfSize: selfSize) - sbvBottomMargin + sbvTopMargin if relaView != self && self.tgIsNoLayoutSubview(relaView) { sbvtgFrame.bottom += sbvBottomMargin } } else if sbvsc.bottom.numberVal != nil { sbvtgFrame.bottom = selfSize.height - sbvBottomMargin - lsc.tgBottomPadding + sbvTopMargin } else if sbvsc.bottom.weightVal != nil { sbvtgFrame.bottom = selfSize.height - sbvsc.bottom.weightPosIn(selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) - lsc.tgBottomPadding + sbvTopMargin } if sbvsc.height.isFill && !self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.height = sbvsc.height.measure(sbvtgFrame.bottom - sbvTopMargin - lsc.tgTopPadding) } sbvtgFrame.top = sbvtgFrame.bottom - sbvtgFrame.height } if !sbvsc.top.hasValue && !sbvsc.bottom.hasValue { if sbvsc.height.isFill && !self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.height = sbvsc.height.measure(selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) } sbvtgFrame.top = sbvTopMargin + lsc.tgTopPadding sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height } } //这里要更新上边最小和下边最大约束的情况。 if case let(minrt?, maxrt?) = (sbvsc.top.minVal?.posVal , sbvsc.bottom.maxVal?.posVal) { //让高度缩小并在最小和最大的中间排列。 let minTop = self.tgCalcRelationalSubview(minrt.view,lsc:lsc, gravity: minrt.type, selfSize: selfSize) + sbvsc.top.minVal!.offset let maxBottom = self.tgCalcRelationalSubview(maxrt.view, lsc:lsc, gravity: maxrt.type, selfSize: selfSize) - sbvsc.bottom.maxVal!.offset //用maxBottom减去minTop得到的高度再减去视图的高度,然后让其居中。。如果高度超过则缩小视图的高度。 if _tgCGFloatLess(maxBottom - minTop , sbvtgFrame.height) { sbvtgFrame.height = maxBottom - minTop sbvtgFrame.top = minTop } else { sbvtgFrame.top = (maxBottom - minTop - sbvtgFrame.height) / 2 + minTop } sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height } else if let t = sbvsc.top.minVal?.posVal { //得到上边的最小位置。如果当前的上边距小于这个位置则缩小视图的高度。 let minTop = self.tgCalcRelationalSubview(t.view, lsc:lsc, gravity: t.type, selfSize: selfSize) + sbvsc.top.minVal!.offset if _tgCGFloatLess(sbvtgFrame.top , minTop) { sbvtgFrame.top = minTop sbvtgFrame.height = sbvtgFrame.bottom - sbvtgFrame.top } } else if let t = sbvsc.bottom.maxVal?.posVal { //得到下边的最大位置。如果当前的下边距大于了这个位置则缩小视图的高度。 let maxBottom = self.tgCalcRelationalSubview(t.view, lsc:lsc, gravity: t.type, selfSize: selfSize) - sbvsc.bottom.maxVal!.offset if _tgCGFloatGreat(sbvtgFrame.bottom, maxBottom) { sbvtgFrame.bottom = maxBottom; sbvtgFrame.height = sbvtgFrame.bottom - sbvtgFrame.top } } } fileprivate func tgCalcSubviewWidth(_ sbv: UIView, sbvsc:TGViewSizeClassImpl, sbvtgFrame:TGFrame, lsc:TGRelativeLayoutViewSizeClassImpl, selfSize: CGSize) -> Bool { if sbvtgFrame.width == CGFloat.greatestFiniteMagnitude { if let t = sbvsc.width.sizeVal { sbvtgFrame.width = sbvsc.width.measure(tgCalcRelationalSubview(t.view, lsc:lsc, gravity:t.type, selfSize: selfSize)) sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: sbvtgFrame.width, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } else if sbvsc.width.numberVal != nil { sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: sbvsc.width.measure, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } else if let t = sbvsc.width.weightVal { sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: sbvsc.width.measure((selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding) * t.rawValue/100), sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } if self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.width = 0 } if sbvsc.isHorzMarginHasValue { if let t = sbvsc.leading.posVal { sbvtgFrame.leading = tgCalcRelationalSubview(t.view, lsc:lsc, gravity:t.type, selfSize: selfSize) + sbvsc.leading.absPos } else { sbvtgFrame.leading = sbvsc.leading.weightPosIn(selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding) + lsc.tgLeadingPadding } if let t = sbvsc.trailing.posVal { sbvtgFrame.trailing = tgCalcRelationalSubview(t.view, lsc:lsc, gravity:t.type, selfSize: selfSize) - sbvsc.trailing.absPos } else { sbvtgFrame.trailing = selfSize.width - sbvsc.trailing.weightPosIn(selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding) - lsc.tgTrailingPadding } sbvtgFrame.width = sbvtgFrame.trailing - sbvtgFrame.leading sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: sbvtgFrame.width, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) if self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.width = 0 sbvtgFrame.trailing = sbvtgFrame.leading + sbvtgFrame.width } return true } if sbvtgFrame.width == CGFloat.greatestFiniteMagnitude { sbvtgFrame.width = sbv.bounds.size.width sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: sbvtgFrame.width, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } } if ( (sbvsc.width.minVal?.numberVal != nil && sbvsc.width.minVal!.numberVal != -CGFloat.greatestFiniteMagnitude) || (sbvsc.width.maxVal?.numberVal != nil && sbvsc.width.maxVal!.numberVal != CGFloat.greatestFiniteMagnitude)) { sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: sbvtgFrame.width, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } return false } fileprivate func tgCalcSubviewHeight(_ sbv: UIView, sbvsc:TGViewSizeClassImpl, sbvtgFrame:TGFrame, lsc:TGRelativeLayoutViewSizeClassImpl,selfSize: CGSize) -> Bool { if sbvtgFrame.height == CGFloat.greatestFiniteMagnitude { if let t = sbvsc.height.sizeVal { sbvtgFrame.height = sbvsc.height.measure(self.tgCalcRelationalSubview(t.view, lsc:lsc, gravity:t.type, selfSize: selfSize)) sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: sbvtgFrame.height, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } else if sbvsc.height.numberVal != nil { sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: sbvsc.height.measure, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } else if let t = sbvsc.height.weightVal { sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: sbvsc.height.measure((selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) * t.rawValue/100), sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } if self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.height = 0 } if sbvsc.isVertMarginHasValue { if let t = sbvsc.top.posVal { sbvtgFrame.top = self.tgCalcRelationalSubview(t.view,lsc:lsc, gravity:t.type, selfSize: selfSize) + sbvsc.top.absPos } else { sbvtgFrame.top = sbvsc.top.weightPosIn(selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) + lsc.tgTopPadding } if let t = sbvsc.bottom.posVal { sbvtgFrame.bottom = self.tgCalcRelationalSubview(t.view,lsc:lsc, gravity:t.type, selfSize: selfSize) - sbvsc.bottom.absPos } else { sbvtgFrame.bottom = selfSize.height - sbvsc.bottom.weightPosIn(selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) - lsc.tgBottomPadding } sbvtgFrame.height = sbvtgFrame.bottom - sbvtgFrame.top sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: sbvtgFrame.height, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) if self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.height = 0 sbvtgFrame.bottom = sbvtgFrame.top + sbvtgFrame.height } return true } if sbvtgFrame.height == CGFloat.greatestFiniteMagnitude { sbvtgFrame.height = sbv.bounds.size.height if sbvsc.height.isFlexHeight && !self.tgIsNoLayoutSubview(sbv) { if sbvtgFrame.width == CGFloat.greatestFiniteMagnitude { _ = self.tgCalcSubviewWidth(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) } sbvtgFrame.height = self.tgCalcHeightFromHeightWrapView(sbv,sbvsc:sbvsc, width: sbvtgFrame.width) } sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: sbvtgFrame.height, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } } if ( (sbvsc.height.minVal?.numberVal != nil && sbvsc.height.minVal!.numberVal != -CGFloat.greatestFiniteMagnitude) || (sbvsc.height.maxVal?.numberVal != nil && sbvsc.height.maxVal!.numberVal != CGFloat.greatestFiniteMagnitude)) { sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: sbvtgFrame.height, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } return false } fileprivate func tgCalcLayoutRectHelper(_ selfSize: CGSize, lsc:TGRelativeLayoutViewSizeClassImpl, isWrap:Bool) -> (selfSize: CGSize, reCalc: Bool) { var recalc = false for sbv:UIView in self.subviews { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) self.tgCalcSizeFromSizeWrapSubview(sbv, sbvsc:sbvsc, sbvtgFrame: sbvtgFrame); if (sbvtgFrame.width != CGFloat.greatestFiniteMagnitude) { if let maxRela = sbvsc.width.maxVal?.sizeVal, maxRela.view !== self { _ = self.tgCalcSubviewWidth(maxRela.view,sbvsc:maxRela.view.tgCurrentSizeClass as! TGViewSizeClassImpl,sbvtgFrame:maxRela.view.tgFrame, lsc:lsc, selfSize:selfSize) } if let minRela = sbvsc.width.minVal?.sizeVal, minRela.view != self { _ = self.tgCalcSubviewWidth(minRela.view, sbvsc:minRela.view.tgCurrentSizeClass as! TGViewSizeClassImpl,sbvtgFrame:minRela.view.tgFrame, lsc:lsc, selfSize:selfSize) } sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv:sbv, calcSize:sbvtgFrame.width, sbvSize:sbvtgFrame.frame.size,selfLayoutSize:selfSize) } if (sbvtgFrame.height != CGFloat.greatestFiniteMagnitude) { if let maxRela = sbvsc.height.maxVal?.sizeVal, maxRela.view !== self { _ = self.tgCalcSubviewHeight(maxRela.view,sbvsc:maxRela.view.tgCurrentSizeClass as! TGViewSizeClassImpl,sbvtgFrame:maxRela.view.tgFrame, lsc:lsc, selfSize:selfSize) } if let minRela = sbvsc.height.minVal?.sizeVal, minRela.view != self { _ = self.tgCalcSubviewHeight(minRela.view, sbvsc:minRela.view.tgCurrentSizeClass as! TGViewSizeClassImpl,sbvtgFrame:minRela.view.tgFrame, lsc:lsc, selfSize:selfSize) } sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: sbvtgFrame.height, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } } for sbv: UIView in self.subviews { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) if let dimeArray: [TGLayoutSize] = sbvsc.width.arrayVal { recalc = true var isViewHidden = self.tgIsNoLayoutSubview(sbv) var totalMulti: CGFloat = isViewHidden ? 0 : sbvsc.width.multiple var totalAdd: CGFloat = isViewHidden ? 0 : sbvsc.width.increment for dime:TGLayoutSize in dimeArray { if dime.isActive { isViewHidden = self.tgIsNoLayoutSubview(dime.view) if !isViewHidden { if dime.hasValue { _ = self.tgCalcSubviewWidth(dime.view, sbvsc:dime.view.tgCurrentSizeClass as! TGViewSizeClassImpl, sbvtgFrame:dime.view.tgFrame, lsc:lsc, selfSize:selfSize) totalAdd += -1.0 * dime.view.tgFrame.width } else { totalMulti += dime.multiple } totalAdd += dime.increment } } } var floatingWidth: CGFloat = selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding + totalAdd if _tgCGFloatLessOrEqual(floatingWidth, 0) { floatingWidth = 0 } if totalMulti != 0 { var tempWidth = _tgRoundNumber(floatingWidth * (sbvsc.width.multiple / totalMulti)) sbvtgFrame.width = self.tgValidMeasure(sbvsc.width, sbv: sbv, calcSize: tempWidth, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) if self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.width = 0 } else { floatingWidth -= tempWidth totalMulti -= sbvsc.width.multiple } for dime:TGLayoutSize in dimeArray { if dime.isActive && !self.tgIsNoLayoutSubview(dime.view) { let (dimetgFrame, dimesbvsc) = self.tgGetSubviewFrameAndSizeClass(dime.view) if !dime.hasValue { tempWidth = _tgRoundNumber(floatingWidth * (dime.multiple / totalMulti)) floatingWidth -= tempWidth totalMulti -= dime.multiple dimetgFrame.width = tempWidth } dimetgFrame.width = self.tgValidMeasure(dimesbvsc.width, sbv: dime.view, calcSize: dimetgFrame.width, sbvSize: dimetgFrame.frame.size, selfLayoutSize: selfSize) } else { dime.view.tgFrame.width = 0 } } } } if let dimeArray: [TGLayoutSize] = sbvsc.height.arrayVal { recalc = true var isViewHidden: Bool = self.tgIsNoLayoutSubview(sbv) var totalMulti = isViewHidden ? 0 : sbvsc.height.multiple var totalAdd = isViewHidden ? 0 : sbvsc.height.increment for dime:TGLayoutSize in dimeArray { if dime.isActive { isViewHidden = self.tgIsNoLayoutSubview(dime.view) if !isViewHidden { if dime.hasValue { _ = self.tgCalcSubviewHeight(dime.view, sbvsc:dime.view.tgCurrentSizeClass as! TGViewSizeClassImpl, sbvtgFrame:dime.view.tgFrame, lsc:lsc, selfSize:selfSize) totalAdd += -1.0 * dime.view.tgFrame.height } else { totalMulti += dime.multiple } totalAdd += dime.increment } } } var floatingHeight = selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding + totalAdd if _tgCGFloatLessOrEqual(floatingHeight, 0) { floatingHeight = 0 } if totalMulti != 0 { var tempHeight = _tgRoundNumber(floatingHeight * (sbvsc.height.multiple / totalMulti)) sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: floatingHeight * (sbvsc.height.multiple / totalMulti), sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) if self.tgIsNoLayoutSubview(sbv) { sbvtgFrame.height = 0 } else { floatingHeight -= tempHeight totalMulti -= sbvsc.height.multiple } for dime: TGLayoutSize in dimeArray { if dime.isActive && !self.tgIsNoLayoutSubview(dime.view) { let (dimetgFrame, dimesbvsc) = self.tgGetSubviewFrameAndSizeClass(dime.view) if !dime.hasValue { tempHeight = _tgRoundNumber(floatingHeight * (dime.multiple / totalMulti)) floatingHeight -= tempHeight totalMulti -= dime.multiple dimetgFrame.height = tempHeight } dimetgFrame.height = self.tgValidMeasure(dimesbvsc.height, sbv: dime.view, calcSize: dimetgFrame.height, sbvSize: dimetgFrame.frame.size, selfLayoutSize: selfSize) } else { dime.view.tgFrame.height = 0 } } } } if let centerArray: [TGLayoutPos] = sbvsc.centerX.arrayVal { var totalWidth: CGFloat = 0.0 var totalOffset:CGFloat = 0.0 var nextPos:TGLayoutPos! = nil var i = centerArray.count - 1 while (i >= 0) { let pos = centerArray[i] if !self.tgIsNoLayoutSubview(pos.view) { if totalWidth != 0 { if nextPos != nil { totalOffset += nextPos.view.tg_centerX.absPos } } _ = self.tgCalcSubviewWidth(pos.view, sbvsc:pos.view.tgCurrentSizeClass as! TGViewSizeClassImpl, sbvtgFrame: pos.view.tgFrame, lsc:lsc, selfSize: selfSize) totalWidth += pos.view.tgFrame.width } nextPos = pos i -= 1 } if !self.tgIsNoLayoutSubview(sbv) { if totalWidth != 0 { if nextPos != nil { totalOffset += nextPos.view.tg_centerX.absPos } } _ = self.tgCalcSubviewWidth(sbv,sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) totalWidth += sbvtgFrame.width totalOffset += sbvsc.centerX.absPos } var leadingOffset: CGFloat = (selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding - totalWidth - totalOffset) / 2.0 leadingOffset += lsc.tgLeadingPadding var prev:AnyObject! = nil sbv.tg_leading.equal(leadingOffset) prev = sbv.tg_trailing for pos: TGLayoutPos in centerArray { let (_, possbvsc) = self.tgGetSubviewFrameAndSizeClass(pos.view) if let prevf = prev as? CGFloat { pos.view.tg_leading.equal(prevf,offset:possbvsc.centerX.absPos) } else { pos.view.tg_leading.equal(prev as? TGLayoutPos, offset:possbvsc.centerX.absPos) } prev = pos.view.tg_trailing } } if let centerArray: [TGLayoutPos] = sbvsc.centerY.arrayVal { var totalHeight: CGFloat = 0.0 var totalOffset:CGFloat = 0.0 var nextPos:TGLayoutPos! = nil var i = centerArray.count - 1 while (i >= 0) { let pos = centerArray[i] if !self.tgIsNoLayoutSubview(pos.view) { if totalHeight != 0 { if nextPos != nil { totalOffset += nextPos.view.tg_centerY.absPos } } _ = self.tgCalcSubviewHeight(pos.view,sbvsc:pos.view.tgCurrentSizeClass as! TGViewSizeClassImpl, sbvtgFrame: pos.view.tgFrame, lsc:lsc, selfSize: selfSize) totalHeight += pos.view.tgFrame.height } nextPos = pos i -= 1 } if !self.tgIsNoLayoutSubview(sbv) { if totalHeight != 0 { if nextPos != nil { totalOffset += nextPos.view.tg_centerY.absPos } } _ = self.tgCalcSubviewHeight(sbv,sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) totalHeight += sbvtgFrame.height totalOffset += sbvsc.centerY.absPos } var topOffset: CGFloat = (selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding - totalHeight - totalOffset) / 2.0 topOffset += lsc.tgTopPadding var prev:AnyObject! = nil sbv.tg_top.equal(topOffset) prev = sbv.tg_bottom for pos: TGLayoutPos in centerArray { let (_, possbvsc) = self.tgGetSubviewFrameAndSizeClass(pos.view) if let prevf = prev as? CGFloat { pos.view.tg_top.equal(prevf,offset:possbvsc.centerY.absPos) } else { pos.view.tg_top.equal(prev as? TGLayoutPos, offset:possbvsc.centerY.absPos) } prev = pos.view.tg_bottom } } } var maxWidth = lsc.tgLeadingPadding + lsc.tgTrailingPadding var maxHeight = lsc.tgTopPadding + lsc.tgBottomPadding for sbv: UIView in self.subviews { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) tgCalcSubviewLeadingTrailing(sbv, sbvsc:sbvsc, sbvtgFrame: sbvtgFrame, lsc:lsc, selfSize: selfSize) if sbvsc.height.isFlexHeight { sbvtgFrame.height = self.tgCalcHeightFromHeightWrapView(sbv, sbvsc:sbvsc, width: sbvtgFrame.width) sbvtgFrame.height = self.tgValidMeasure(sbvsc.height, sbv: sbv, calcSize: sbvtgFrame.height, sbvSize: sbvtgFrame.frame.size, selfLayoutSize: selfSize) } tgCalcSubviewTopBottom(sbv, sbvsc:sbvsc, sbvtgFrame: sbvtgFrame, lsc:lsc,selfSize: selfSize) if self.tgIsNoLayoutSubview(sbv) { continue } if isWrap { maxWidth = self.tgCalcMaxWrapSize(sbvHead: sbvsc.leading, sbvCenter: sbvsc.centerX, sbvTail: sbvsc.trailing, sbvSize: sbvsc.width, sbvMeasure: sbvtgFrame.width, sbvMinPos: sbvtgFrame.leading, sbvMaxPos: sbvtgFrame.trailing, headPadding: lsc.tgLeadingPadding, tailPadding: lsc.tgTrailingPadding, lscSize: lsc.width, maxSize: maxWidth, recalc: &recalc) maxHeight = self.tgCalcMaxWrapSize(sbvHead: sbvsc.top, sbvCenter: sbvsc.centerY, sbvTail: sbvsc.bottom, sbvSize: sbvsc.height, sbvMeasure: sbvtgFrame.height, sbvMinPos: sbvtgFrame.top, sbvMaxPos: sbvtgFrame.bottom, headPadding: lsc.tgTopPadding, tailPadding: lsc.tgBottomPadding, lscSize: lsc.height, maxSize: maxHeight, recalc: &recalc) } } return (CGSize(width: maxWidth, height: maxHeight),recalc) } fileprivate func tgCalcMaxWrapSize(sbvHead:TGLayoutPosValue2, sbvCenter:TGLayoutPosValue2, sbvTail:TGLayoutPosValue2, sbvSize:TGLayoutSizeValue2, sbvMeasure:CGFloat, sbvMinPos:CGFloat, sbvMaxPos:CGFloat, headPadding:CGFloat, tailPadding:CGFloat, lscSize:TGLayoutSizeValue2, maxSize:CGFloat, recalc:inout Bool) -> CGFloat { var maxSize = maxSize if lscSize.isWrap { let headMargin = sbvHead.absPos let tailMargin = sbvTail.absPos if (sbvTail.numberVal != nil || sbvTail.posVal?.view === self || sbvTail.weightVal != nil || sbvCenter.numberVal != nil || sbvCenter.posVal?.view === self || sbvCenter.weightVal != nil || sbvSize.sizeVal === self || sbvSize.weightVal != nil || sbvSize.isFill ) { recalc = true } if _tgCGFloatLess(maxSize , headMargin + tailMargin + headPadding + tailPadding) { maxSize = headMargin + tailMargin + headPadding + tailPadding } //宽度没有相对约束或者宽度不依赖父视图并且没有指定比重并且不是填充时才计算最大宽度。 if (sbvSize.sizeVal == nil || sbvSize.sizeVal !== lscSize.realSize) && sbvSize.weightVal == nil && !sbvSize.isFill { if sbvCenter.hasValue { if _tgCGFloatLess(maxSize , sbvMeasure + headMargin + tailMargin + headPadding + tailPadding) { maxSize = sbvMeasure + headMargin + tailMargin + headPadding + tailPadding } } else if sbvHead.hasValue && sbvTail.hasValue { if _tgCGFloatLess(maxSize , abs(sbvMaxPos) + headMargin + headPadding) { maxSize = abs(sbvMaxPos) + headMargin + headPadding } } else if sbvTail.hasValue { if _tgCGFloatLess(maxSize , abs(sbvMinPos) + headPadding) { maxSize = abs(sbvMinPos) + headPadding } } else { if _tgCGFloatLess(maxSize , abs(sbvMaxPos) + tailPadding) { maxSize = abs(sbvMaxPos) + tailPadding } } if _tgCGFloatLess(maxSize , sbvMaxPos + tailMargin + tailPadding) { maxSize = sbvMaxPos + tailMargin + tailPadding } } } return maxSize } fileprivate func tgCalcRelationalSubview(_ sbv: UIView!, lsc:TGRelativeLayoutViewSizeClassImpl, gravity:TGGravity, selfSize: CGSize) -> CGFloat { let (sbvtgFrame, sbvsc) = self.tgGetSubviewFrameAndSizeClass(sbv) switch gravity { case TGGravity.horz.leading: if sbv == self || sbv == nil { return lsc.tgLeadingPadding } if sbvtgFrame.leading != CGFloat.greatestFiniteMagnitude { return sbvtgFrame.leading } tgCalcSubviewLeadingTrailing(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) return sbvtgFrame.leading case TGGravity.horz.trailing: if sbv == self || sbv == nil { return selfSize.width - lsc.tgTrailingPadding } if sbvtgFrame.trailing != CGFloat.greatestFiniteMagnitude { return sbvtgFrame.trailing } tgCalcSubviewLeadingTrailing(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) return sbvtgFrame.trailing case TGGravity.vert.top: if sbv == self || sbv == nil { return lsc.tgTopPadding } if sbvtgFrame.top != CGFloat.greatestFiniteMagnitude { return sbvtgFrame.top } tgCalcSubviewTopBottom(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) return sbvtgFrame.top case TGGravity.vert.bottom: if sbv == self || sbv == nil { return selfSize.height - lsc.tgBottomPadding } if sbvtgFrame.bottom != CGFloat.greatestFiniteMagnitude { return sbvtgFrame.bottom } tgCalcSubviewTopBottom(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) return sbvtgFrame.bottom case TGGravity.vert.baseline: if sbv == self || sbv == nil { return lsc.tgTopPadding } let sbvFont:UIFont! = self.tgGetSubviewFont(sbv) if sbvFont != nil { if sbvtgFrame.top == CGFloat.greatestFiniteMagnitude || sbvtgFrame.height == CGFloat.greatestFiniteMagnitude { self.tgCalcSubviewTopBottom(sbv,sbvsc:sbvsc,sbvtgFrame:sbvtgFrame,lsc:lsc,selfSize:selfSize) } //得到基线的位置。 return sbvtgFrame.top + (sbvtgFrame.height - sbvFont.lineHeight)/2.0 + sbvFont.ascender } else { if sbvtgFrame.top != CGFloat.greatestFiniteMagnitude { return sbvtgFrame.top } self.tgCalcSubviewTopBottom(sbv,sbvsc:sbvsc,sbvtgFrame:sbvtgFrame,lsc:lsc,selfSize:selfSize) return sbvtgFrame.top } case TGGravity.horz.fill: if sbv == self || sbv == nil { return selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding } if sbvtgFrame.width != CGFloat.greatestFiniteMagnitude { return sbvtgFrame.width } tgCalcSubviewLeadingTrailing(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) return sbvtgFrame.width case TGGravity.vert.fill: if sbv == self || sbv == nil { return selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding } if sbvtgFrame.height != CGFloat.greatestFiniteMagnitude { return sbvtgFrame.height } tgCalcSubviewTopBottom(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) return sbvtgFrame.height case TGGravity.horz.center: if sbv == self || sbv == nil { return (selfSize.width - lsc.tgLeadingPadding - lsc.tgTrailingPadding) / 2 + lsc.tgLeadingPadding } if sbvtgFrame.leading != CGFloat.greatestFiniteMagnitude && sbvtgFrame.trailing != CGFloat.greatestFiniteMagnitude && sbvtgFrame.width != CGFloat.greatestFiniteMagnitude { return sbvtgFrame.leading + sbvtgFrame.width / 2 } tgCalcSubviewLeadingTrailing(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) return sbvtgFrame.leading + sbvtgFrame.width / 2.0 case TGGravity.vert.center: if sbv == self || sbv == nil { return (selfSize.height - lsc.tgTopPadding - lsc.tgBottomPadding) / 2 + lsc.tgTopPadding } if sbvtgFrame.top != CGFloat.greatestFiniteMagnitude && sbvtgFrame.bottom != CGFloat.greatestFiniteMagnitude && sbvtgFrame.height != CGFloat.greatestFiniteMagnitude { return sbvtgFrame.top + sbvtgFrame.height / 2.0 } tgCalcSubviewTopBottom(sbv, sbvsc:sbvsc, sbvtgFrame:sbvtgFrame, lsc:lsc, selfSize: selfSize) return sbvtgFrame.top + sbvtgFrame.height / 2 default: print("do nothing") } return 0 } }
mit
64fcd07f9580b12f708dc23c0016752d
40.593058
366
0.499263
5.292951
false
false
false
false
EngrAhsanAli/AAPopUp
AAPopUp/Classes/AAPopUp.swift
1
6427
// // AAPopUp.swift // AAPopUp // // Created by Engr. Ahsan Ali on 12/29/2016. // Copyright (c) 2016 AA-Creations. All rights reserved. // import UIKit @objcMembers open class AAPopUp: UIViewController { /// Global options public static var options = AAPopUpOptions() /// Popup View controller open var viewController: UIViewController! /// Absolute Height open var absoluteHeight: CGFloat? { didSet { guard let height = absoluteHeight else { return } viewController.view.bounds.size.height = height } } /// Keyboard visibility flag var keyboardIsVisible = false /// Init with UIViewController of AAPopUp with options /// /// - Parameters: /// - popup: UIViewController of popup /// - options: AAPopUpOptions (optional) public convenience init(_ popup: UIViewController, withOptions options: AAPopUpOptions? = nil) { self.init() self.viewController = popup initPopUp() } deinit { NotificationCenter.default.removeObserver(self) } /// Popup did load override open func viewDidLoad() { super.viewDidLoad() registerKeyboardNotifications() } /// Popup did appear /// /// - Parameter animated: flag override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) presentPopUpView() dismissWithTag(AAPopUp.options.dismissTag) } /// layout subviews override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.viewController.view.center = self.view.center self.viewController.view!.layoutIfNeeded() self.view!.setNeedsLayout() } /// Create Popupup view func initPopUp() { guard setContentBounds() else { return } if #available(iOS 9.0, *) { self.loadViewIfNeeded() } let scrollView = UIScrollView(frame: self.view.bounds) scrollView.contentSize = view.bounds.size scrollView.alwaysBounceHorizontal = false scrollView.showsVerticalScrollIndicator = false scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) scrollView.bindWithBounds() let scrollContentView = UIView(frame: scrollView.bounds) scrollView.addSubview(scrollContentView) self.addChild(viewController) scrollContentView.addSubview(viewController.view!) viewController.didMove(toParent: self) modalPresentationStyle = .overFullScreen viewController.view.layer.cornerRadius = AAPopUp.options.cornerRadius viewController.view.layer.masksToBounds = true viewController.view.backgroundColor = .clear togglePopup() // First Invisible Animaiton } /// Set ContentView Bounds /// /// - Parameter: bounds func setContentBounds(_ bounds: CGRect? = nil) -> Bool { if let customBounds = bounds { viewController.view.bounds = customBounds } else { guard let contentView = viewController.view.subviews.first?.bounds else { print("AAPopUp - All child views must be encapsulate in a single UIView instace. Aborting ...") return false } viewController.view.bounds = contentView } return true } /// toggle the popup /// /// - Parameter show: flag for show func togglePopup(_ show: Bool = false) { var alpha: CGFloat = 1.0 var backgroundColor: UIColor = AAPopUp.options.backgroundColor var transform: CGAffineTransform = .identity if !show { alpha = 0.0 backgroundColor = backgroundColor.withAlphaComponent(0.0) transform = transform.scaledBy(x: 0.6, y: 0.6) } self.viewController.view.alpha = alpha self.view.backgroundColor = backgroundColor self.viewController.view.transform = transform } } //MARK:- public functions extension AAPopUp { /// get view with tag in popup /// /// - Parameter tag: tag for a view /// - Returns: UIView object open func viewWithTag(_ tag: Int) -> UIView? { return view.viewWithTag(tag) } /// dismiss popup with tag /// /// - Parameter tag: tag open func dismissWithTag(_ tag: Int?) { if let dismissTag = tag { if let button = view.viewWithTag(dismissTag) as? UIButton { button.addTarget(self, action:#selector(AAPopUp.dismissPopup), for: .touchUpInside) } } } /// dismiss popup selector @objc func dismissPopup() { dismissPopUpView() } /// present popup with completion /// /// - Parameter completion: view did load closure open func present(_ bounds: CGRect? = nil, completion: ((_ popup: AAPopUp) -> ())? = nil) { guard let root = UIApplication.shared.keyWindow?.rootViewController else { fatalError("AAPopUp - Application key window not found. Please check UIWindow in AppDelegate.") } _ = setContentBounds(bounds) root.present(self, animated: false, completion: { completion?(self) }) } /// present popup view with animation func presentPopUpView() { UIView.animate(withDuration: AAPopUp.options.animationDuration, delay: 0, animations: {() -> Void in self.togglePopup(true) }, completion: nil) } /// Dismiss popup with animation /// /// - Parameter completion: completion closure open func dismissPopUpView(_ completion: (() -> ())? = nil) { UIView.animate(withDuration: AAPopUp.options.animationDuration, animations: {() -> Void in self.togglePopup() }, completion: {(finished: Bool) -> Void in self.presentingViewController!.dismiss(animated: false, completion: completion) }) } }
mit
c8803aaeeff50245cc5cae5aa5299539
27.438053
111
0.592189
5.259411
false
false
false
false
macemmi/HBCI4Swift
HBCI4Swift/HBCI4Swift/Source/Message/HBCIResultMessage.swift
1
23400
// // HBCIResultMessage.swift // HBCI4Swift // // Created by Frank Emminghaus on 05.01.15. // Copyright (c) 2015 Frank Emminghaus. All rights reserved. // import Foundation // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } func isEscaped(_ pointer:UnsafePointer<CChar>) ->Bool { var count = 0; var p = UnsafeMutablePointer<CChar>(mutating: pointer); p = p.advanced(by: -1); while p.pointee == HBCIChar.qmark.rawValue { p = p.advanced(by: -1); count += 1; } return count%2 == 1; } func isDelimiter(_ pointer:UnsafePointer<CChar>) ->Bool { if pointer.pointee == HBCIChar.plus.rawValue || pointer.pointee == HBCIChar.dpoint.rawValue || pointer.pointee == HBCIChar.quote.rawValue { if !isEscaped(pointer) { return true; } } return false; } func checkForDataTag(_ pointer:UnsafePointer<CChar>) ->(dataLength:Int, tagLength:Int) { // first check if we are at the beginning of a syntax element let prev = pointer.advanced(by: -1); if !isDelimiter(prev) { return (0,0); } // now search for ending @ var p = pointer.advanced(by: 1); var i = 0; while p.pointee != HBCIChar.amper.rawValue { if p.pointee < 0x30 || p.pointee > 0x39 { // no number return (0,0); } i += 1; p = p.advanced(by: 1); if i > 9 { // safety exit condition return (0,0); } } if i == 0 { return (0,0); } var endp:UnsafeMutablePointer<Int8>? = UnsafeMutablePointer<Int8>(mutating: pointer.advanced(by: 1)); let dataLength = strtol(endp, &endp, 10); return (dataLength, i+2); } open class HBCIResultMessage { open var hbciParameterUpdated = false; let syntax:HBCISyntax; var binaries = Array<Data>(); var segmentData = Array<Data>(); var segmentStrings = Array<NSString>(); var segments = Array<HBCISegment>(); var messageResponses = Array<HBCIMessageResponse>(); var segmentResponses = Array<HBCIOrderResponse>(); init(syntax:HBCISyntax) { self.syntax = syntax; } func addBinary(_ binary:Data) ->Int { let idx = binaries.count; binaries.append(binary); return idx; } var description: String { var result = ""; for segment in segments { result += segment.description; result += "\n"; } return result; } class func debugDataDescription(start: UnsafePointer<CChar>, length: Int) -> String? { var i=0; // check if we have non-printable characters while i<length { let c = UInt8(bitPattern: start[i]); if c < 32 && c != 10 && c != 13 { break; } if c > 127 { if c != 0xC4 && //Ä c != 0xD6 && //Ö c != 0xDC && //Ü c != 0xDF && //ß c != 0xE4 && //ä c != 0xF6 && //ö c != 0xFC { //ü break; } } i += 1; } let data = Data(bytes: start, count: length); if i==length { return String(data: data, encoding: String.Encoding.isoLatin1); } else { return data.debugDescription; } } class func debugDescription(_ msgData:Data) ->String { var result = ""; let source = UnsafeMutableBufferPointer<CChar>.allocate(capacity: msgData.count); let target = UnsafeMutableBufferPointer<CChar>.allocate(capacity: msgData.count); defer { source.deallocate(); target.deallocate() } target.initialize(repeating: 0); _ = msgData.copyBytes(to: source); var i=0; while i<msgData.count { if i>0 && source[i] == HBCIChar.amper.rawValue && source[i-1] != HBCIChar.qmark.rawValue { let p = source.baseAddress!.advanced(by: i); let (bin_size, tag_size) = checkForDataTag(p); if bin_size > 0 { let bin_start = p.advanced(by: tag_size); let data = Data(bytes: bin_start, count: bin_size); if data.hasNonPrintableChars() { result += data.debugDescription; } else { result += String(data: data, encoding: String.Encoding.isoLatin1) ?? "<unknown>"; } if let descr = self.debugDataDescription(start: bin_start, length: bin_size) { result += descr; } else { result += "<unknown>"; } i += tag_size+bin_size; continue; } } let c = UInt8(bitPattern: source[i]); result.append(Character(Unicode.Scalar(c))); i+=1; } return result; } func extractSegmentData(_ msgData:Data) ->[Data]? { var segmentData = [Data](); var i=0, j=0; let source = UnsafeMutableBufferPointer<CChar>.allocate(capacity: msgData.count); let target = UnsafeMutableBufferPointer<CChar>.allocate(capacity: msgData.count); defer { source.deallocate(); target.deallocate(); } _ = msgData.copyBytes(to: source); while i < msgData.count { if i>0 && source[i] == HBCIChar.amper.rawValue && source[i-1] != HBCIChar.qmark.rawValue { // first check if we have binary data let p = source.baseAddress!.advanced(by: i); let (bin_size, tag_size) = checkForDataTag(p); if bin_size > 0 { // now we have binary data let bin_start = p.advanced(by: tag_size); let data = Data(bytes: bin_start, count: bin_size); // add data to repository let bin_idx = addBinary(data); let tag = "@\(bin_idx)@"; if let cstr = tag.cString(using: String.Encoding.isoLatin1) { // copy tag to buffer for c in cstr { if c != 0 { target[j] = c; j += 1; } } i += tag_size+bin_size; } else { // issue during conversion logInfo("tag \(tag) cannot be converted to Latin1"); return nil; } continue; } } target[j] = source[i]; j += 1; i += 1; } // now we have data that does not contain binary data any longer // next step: split into sequence of segments let messageSize = j; var segContent = [CChar](repeating: 0, count: messageSize); i = 0; var segSize = 0; while i < messageSize { segContent[segSize] = target[i]; segSize += 1; let p = UnsafeMutablePointer<CChar>(target.baseAddress)!.advanced(by: i); if target[i] == HBCIChar.quote.rawValue && !isEscaped(p) { // now we have a segment in segContent let data = Data(bytes: segContent, count: segSize); segmentData.append(data); // we convert to String as well for debugging if let s = NSString(data: data, encoding: String.Encoding.isoLatin1.rawValue) { self.segmentStrings.append(s); } segSize = 0; } i += 1; } return segmentData; } func parse(_ msgData:Data) ->Bool { if let segmentData = extractSegmentData(msgData) { self.segmentData = segmentData; } // now we have all segment strings and we can start to parse each segment for segData in self.segmentData { // we convert to String as well for debugging if let s = NSString(data: segData, encoding: String.Encoding.isoLatin1.rawValue) { self.segmentStrings.append(s); } do { if let segment = try self.syntax.parseSegment(segData, binaries: self.binaries) { self.segments.append(segment); } } catch { if let segmentString = NSString(data: segData, encoding: String.Encoding.isoLatin1.rawValue) { logInfo("Parse error: segment \(segmentString) could not be parsed"); } else { logInfo("Parse error: segment (no conversion possible) could not be parsed"); } return false; } } return true; } func valueForPath(_ path:String) ->Any? { var name:String? var newPath:String? if let range = path.range(of: ".", options: NSString.CompareOptions(), range: nil, locale: nil) { //name = path.substring(to: range.lowerBound); name = String(path[..<range.lowerBound]); newPath = String(path.suffix(from: path.index(after: range.lowerBound))); } else { name = path; } for seg in self.segments { if seg.name == name { if newPath == nil { return nil; } else { return seg.elementValueForPath(newPath!); } } } logInfo("Segment with name \(name ?? "<nil>") not found"); return nil; } func valuesForPath(_ path:String) ->Array<Any> { var result = Array<Any>(); var name:String? var newPath:String? if let range = path.range(of: ".", options: NSString.CompareOptions(), range: nil, locale: nil) { name = String(path[..<range.lowerBound]); newPath = String(path.suffix(from: path.index(after: range.lowerBound))); } else { name = path; } for seg in self.segments { if seg.name == name { if newPath == nil { result.append(seg); } else { result += seg.elementValuesForPath(newPath!); } } } return result; } func extractBPData() ->Data? { let bpData = NSMutableData(); for data in segmentData { //print(NSString(data: data, encoding: NSISOLatin1StringEncoding)); if let code = NSString(bytes: (data as NSData).bytes, length: 5, encoding: String.Encoding.isoLatin1.rawValue) { if code == "HIUPA" || code == "HIUPD" || code == "HIBPA" || (code.hasPrefix("HI") && code.hasSuffix("S")) { bpData.append(data); continue; } } if let code = NSString(bytes: (data as NSData).bytes, length: 6, encoding: String.Encoding.isoLatin1.rawValue) { if code == "DIPINS" || (code.hasPrefix("HI") && code.hasSuffix("S")) { bpData.append(data); } } } if bpData.length > 0 { return bpData as Data; } else { return nil; } } func hasParameterSegments() ->Bool { for seg in segments { if seg.name == "BPA" || seg.name == "UPA" { return true; } } return false; } func updateParameterForUser(_ user:HBCIUser) { // find BPD version var updateBankParameters = false; var updateUserParameters = false; for seg in segments { if seg.name == "BPA" { if let version = valueForPath("BPA.version") as? Int { if version > user.parameters.bpdVersion { user.parameters.bpdVersion = version; user.bankName = seg.elementValueForPath("kiname") as? String; updateBankParameters = true; } } } if seg.name == "UPA" { if let version = valueForPath("UPA.version") as? Int { if version > user.parameters.updVersion { user.parameters.updVersion = version; updateUserParameters = true; } } } } if user.parameters.bpdVersion == 0 { updateBankParameters = true; } if user.parameters.updVersion == 0 { updateUserParameters = true; } if updateBankParameters == false && updateUserParameters == false { return; } var oldSegments = [Data](); if let bpData = user.parameters.bpData { if let oldSegs = extractSegmentData(bpData) { oldSegments = oldSegs; } } var addedSegments = [Data](); for data in self.segmentData { if let code = NSString(bytes: (data as NSData).bytes, length: 5, encoding: String.Encoding.isoLatin1.rawValue) { let bankSegment = code == "HIUPA" || code == "HIBPA" || (code.hasPrefix("HI") && code.hasSuffix("S")); let userSegment = code == "HIUPD"; // special case for HIRMS - supported TAN methods are stored in parameter 3920 if code == "HIRMS" { guard let s = NSString(data: data, encoding: String.Encoding.isoLatin1.rawValue) else { continue; } if s.range(of: "3920").location == NSNotFound { continue; } } if (bankSegment && updateBankParameters) || (userSegment && updateUserParameters) { // code is a valid segment code - remove it from the list of old segments var idx = 0; for oldData in oldSegments { if let _code = NSString(bytes: (oldData as NSData).bytes, length: 5, encoding: String.Encoding.isoLatin1.rawValue) { if code == _code { oldSegments.remove(at: idx); continue; } } idx += 1; } addedSegments.append(data); } } if let code = NSString(bytes: (data as NSData).bytes, length: 6, encoding: String.Encoding.isoLatin1.rawValue) { let bankSegment = code == "DIPINS" || (code.hasPrefix("HI") && code.hasSuffix("S")); if (bankSegment && updateBankParameters) { // code is a valid segment code - remove it from the list of old segments var idx = 0; for oldData in oldSegments { if let _code = NSString(bytes: (oldData as NSData).bytes, length: 6, encoding: String.Encoding.isoLatin1.rawValue) { if code == _code { oldSegments.remove(at: idx); continue; } } idx += 1; } addedSegments.append(data); } } } var newData = Data(); for data in oldSegments { newData.append(data); } for data in addedSegments { newData.append(data); } // now we update user and bank parameters do { user.parameters = try HBCIParameters(data: newData, syntax: syntax); self.hbciParameterUpdated = true; } catch { logInfo("Could not process HBCI parameters"); } } func segmentWithReference(_ number:Int, orderName:String) ->HBCISegment? { for segment in self.segments { if segment.name == orderName + "Res" { if let _ = segment.elementValueForPath("SegHead.ref") as? Int { return segment; } } } return nil; } func segmentsWithReference(_ number:Int, orderName:String) ->Array<HBCISegment> { var segs = Array<HBCISegment>(); for segment in self.segments { if segment.name == orderName + "Res" { if let _ = segment.elementValueForPath("SegHead.ref") as? Int { segs.append(segment); } } } return segs; } func segmentsWithName(_ name:String) ->Array<HBCISegment> { var segs = Array<HBCISegment>(); for segment in self.segments { if segment.name == name + "Res" { segs.append(segment); } } return segs; } func hasSegmentWithVersion(_ code:String, version: Int?) -> Bool { for segment in self.segments { if segment.code == code { if let version = version { if version == segment.version { return true; } } else { return true; } } } return false; } func isBankInPSD2Migration() ->Bool { // if the bank sends HKTAN#6 and an oder version we assume it is in migration phase // we currently set this always to true if a HKTAN#6 is found as the HIPINS segment in a personal dialog is not always reliable var hasVersion6 = false; var hasOldVersion = false; for segment in self.segments { if segment.code == "HITANS" { if segment.version >= 6 { hasVersion6 = true; } if segment.version < 6 { hasOldVersion = true; } } } return hasVersion6; } func hasResponseWithCode(_ code:String) -> Bool { for response in responsesForMessage() { if response.code == code { return true; } } return false; } open func bankMessages() ->Array<HBCIBankMessage> { var messages = Array<HBCIBankMessage>(); for segment in self.segments { if segment.name == "KIMsg" { if let msg = HBCIBankMessage(element: segment) { messages.append(msg); } } } return messages; } func responsesForSegmentWithNumber(_ number:Int) ->Array<HBCIOrderResponse> { var responses = Array<HBCIOrderResponse>(); for response in responsesForSegments() { if response.reference == number { responses.append(response); } } return responses; } func responsesForSegments() ->Array<HBCIOrderResponse> { if self.segmentResponses.count == 0 { for segment in self.segments { if segment.name == "RetSeg" { // only segments with references if let reference = segment.elementValueForPath("SegHead.ref") as? Int { let values = segment.elementsForPath("RetVal"); for retVal in values { if let response = HBCIOrderResponse(element: retVal, reference: reference) { self.segmentResponses.append(response); } } } } } } return self.segmentResponses; } func checkResponses() throws ->Bool { var success = true; for response in responsesForMessage() { if Int(response.code) >= 9000 { logError("Banknachricht: "+response.description); success = false; if response.description.contains("PIN") { throw HBCIError.PINError; } } } for response in responsesForSegments() { if Int(response.code) >= 9000 || (!success && Int(response.code) >= 3000) { logError("Banknachricht: "+response.description); success = false; if response.description.contains("PIN") { throw HBCIError.PINError; } } } return success; } func responsesForMessage() ->Array<HBCIMessageResponse> { if self.messageResponses.count == 0 { for segment in self.segments { if segment.name == "RetGlob" { let values = segment.elementsForPath("RetVal"); for retVal in values { if let response = HBCIMessageResponse(element: retVal) { self.messageResponses.append(response); } } } } } return self.messageResponses; } open func isOk() ->Bool { let responses = responsesForMessage(); for response in responses { if let code = Int(response.code) { if code >= 9000 { return false; } } else { return false; } } return true; } open func hbciParameters() -> HBCIParameters { return HBCIParameters(segments: self.segments, syntax: self.syntax); } func segmentsForOrder(_ orderName:String) ->Array<HBCISegment> { var result = Array<HBCISegment>(); for segment in self.segments { if segment.name == orderName + "Res" { result.append(segment); } } return result; } }
gpl-2.0
19aff4fe3f04ea674b4d0260c0c42c82
34.071964
143
0.482751
4.804477
false
false
false
false
ben-ng/swift
test/Sema/accessibility_private.swift
1
12502
// RUN: %target-typecheck-verify-swift class Container { private func foo() {} // expected-note * {{declared here}} private var bar = 0 // expected-note * {{declared here}} private struct PrivateInner {} // expected-note * {{declared here}} func localTest() { foo() self.foo() _ = bar bar = 5 _ = self.bar self.bar = 5 privateExtensionMethod() // expected-error {{'privateExtensionMethod' is inaccessible due to 'private' protection level}} self.privateExtensionMethod() // expected-error {{'privateExtensionMethod' is inaccessible due to 'private' protection level}} _ = PrivateInner() _ = Container.PrivateInner() } struct Inner { func test(obj: Container) { obj.foo() _ = obj.bar obj.bar = 5 obj.privateExtensionMethod() // expected-error {{'privateExtensionMethod' is inaccessible due to 'private' protection level}} _ = PrivateInner() _ = Container.PrivateInner() } var inner: PrivateInner? // expected-error {{property must be declared private because its type uses a private type}} var innerQualified: Container.PrivateInner? // expected-error {{property must be declared private because its type uses a private type}} } var inner: PrivateInner? // expected-error {{property must be declared private because its type uses a private type}} var innerQualified: Container.PrivateInner? // expected-error {{property must be declared private because its type uses a private type}} } func test(obj: Container) { obj.foo() // expected-error {{'foo' is inaccessible due to 'private' protection level}} _ = obj.bar // expected-error {{'bar' is inaccessible due to 'private' protection level}} obj.bar = 5 // expected-error {{'bar' is inaccessible due to 'private' protection level}} obj.privateExtensionMethod() // expected-error {{'privateExtensionMethod' is inaccessible due to 'private' protection level}} _ = Container.PrivateInner() // expected-error {{'PrivateInner' is inaccessible due to 'private' protection level}} } extension Container { private func privateExtensionMethod() {} // expected-note * {{declared here}} func extensionTest() { foo() // expected-error {{'foo' is inaccessible due to 'private' protection level}} self.foo() // expected-error {{'foo' is inaccessible due to 'private' protection level}} _ = bar // expected-error {{'bar' is inaccessible due to 'private' protection level}} bar = 5 // expected-error {{'bar' is inaccessible due to 'private' protection level}} _ = self.bar // expected-error {{'bar' is inaccessible due to 'private' protection level}} self.bar = 5 // expected-error {{'bar' is inaccessible due to 'private' protection level}} privateExtensionMethod() self.privateExtensionMethod() _ = PrivateInner() // expected-error {{'PrivateInner' is inaccessible due to 'private' protection level}} _ = Container.PrivateInner() // expected-error {{'PrivateInner' is inaccessible due to 'private' protection level}} } // FIXME: Why do these errors happen twice? var extensionInner: PrivateInner? { return nil } // expected-error 2 {{'PrivateInner' is inaccessible due to 'private' protection level}} var extensionInnerQualified: Container.PrivateInner? { return nil } // expected-error 2 {{'PrivateInner' is inaccessible due to 'private' protection level}} } extension Container.Inner { func extensionTest(obj: Container) { obj.foo() // expected-error {{'foo' is inaccessible due to 'private' protection level}} _ = obj.bar // expected-error {{'bar' is inaccessible due to 'private' protection level}} obj.bar = 5 // expected-error {{'bar' is inaccessible due to 'private' protection level}} obj.privateExtensionMethod() // expected-error {{'privateExtensionMethod' is inaccessible due to 'private' protection level}} // FIXME: Unqualified lookup won't look into Container from here. _ = PrivateInner() // expected-error {{use of unresolved identifier 'PrivateInner'}} _ = Container.PrivateInner() // expected-error {{'PrivateInner' is inaccessible due to 'private' protection level}} } // FIXME: Why do these errors happen twice? // FIXME: Unqualified lookup won't look into Container from here. var inner: PrivateInner? { return nil } // expected-error 2 {{use of undeclared type 'PrivateInner'}} var innerQualified: Container.PrivateInner? { return nil } // expected-error 2 {{'PrivateInner' is inaccessible due to 'private' protection level}} } class Sub : Container { func subTest() { foo() // expected-error {{'foo' is inaccessible due to 'private' protection level}} self.foo() // expected-error {{'foo' is inaccessible due to 'private' protection level}} _ = bar // expected-error {{'bar' is inaccessible due to 'private' protection level}} bar = 5 // expected-error {{'bar' is inaccessible due to 'private' protection level}} _ = self.bar // expected-error {{'bar' is inaccessible due to 'private' protection level}} self.bar = 5 // expected-error {{'bar' is inaccessible due to 'private' protection level}} privateExtensionMethod() // expected-error {{'privateExtensionMethod' is inaccessible due to 'private' protection level}} self.privateExtensionMethod() // expected-error {{'privateExtensionMethod' is inaccessible due to 'private' protection level}} _ = PrivateInner() // expected-error {{'PrivateInner' is inaccessible due to 'private' protection level}} _ = Container.PrivateInner() // expected-error {{'PrivateInner' is inaccessible due to 'private' protection level}} } var subInner: PrivateInner? // expected-error {{'PrivateInner' is inaccessible due to 'private' protection level}} var subInnerQualified: Container.PrivateInner? // expected-error {{'PrivateInner' is inaccessible due to 'private' protection level}} } protocol VeryImportantProto { associatedtype Assoc var value: Int { get set } // expected-note {{protocol requires property 'value' with type 'Int'; do you want to add a stub?}} } private struct VIPPrivateType : VeryImportantProto { private typealias Assoc = Int // expected-error {{type alias 'Assoc' must be as accessible as its enclosing type because it matches a requirement in protocol 'VeryImportantProto'}} var value: Int } private struct VIPPrivateProp : VeryImportantProto { typealias Assoc = Int private var value: Int // expected-error {{property 'value' must be as accessible as its enclosing type because it matches a requirement in protocol 'VeryImportantProto'}} {{3-10=fileprivate}} } private struct VIPPrivateSetProp : VeryImportantProto { typealias Assoc = Int private(set) var value: Int // expected-error {{setter for property 'value' must be as accessible as its enclosing type because it matches a requirement in protocol 'VeryImportantProto'}} {{3-10=fileprivate}} } private class VIPPrivateSetBase { private var value: Int = 0 } private class VIPPrivateSetSub : VIPPrivateSetBase, VeryImportantProto { // expected-error {{type 'VIPPrivateSetSub' does not conform to protocol 'VeryImportantProto'}} typealias Assoc = Int } private class VIPPrivateSetPropBase { private(set) var value: Int = 0 // expected-error {{setter for property 'value' must be as accessible as its enclosing type because it matches a requirement in protocol 'VeryImportantProto'}} {{3-10=fileprivate}} } private class VIPPrivateSetPropSub : VIPPrivateSetPropBase, VeryImportantProto { typealias Assoc = Int } extension Container { private typealias ExtensionConflictingType = Int // expected-note * {{declared here}} } extension Container { private typealias ExtensionConflictingType = Double // expected-note * {{declared here}} } extension Container { func test() { let a: ExtensionConflictingType? = nil // expected-error {{'ExtensionConflictingType' is inaccessible due to 'private' protection level}} let b: Container.ExtensionConflictingType? = nil // expected-error {{'ExtensionConflictingType' is inaccessible due to 'private' protection level}} _ = ExtensionConflictingType() // expected-error {{'ExtensionConflictingType' is inaccessible due to 'private' protection level}} _ = Container.ExtensionConflictingType() // expected-error {{'ExtensionConflictingType' is inaccessible due to 'private' protection level}} } } // All of these should be errors, but didn't have the correct behavior in Swift // 3.0GM. extension Container { private struct VeryPrivateStruct { // expected-note * {{type declared here}} private typealias VeryPrivateType = Int // expected-note * {{type declared here}} var privateVar: VeryPrivateType { fatalError() } // expected-warning {{property should be declared private because its type uses a private type}} var privateVar2 = VeryPrivateType() // expected-warning {{property should be declared private because its type 'Container.VeryPrivateStruct.VeryPrivateType' (aka 'Int') uses a private type}} typealias PrivateAlias = VeryPrivateType // expected-warning {{type alias should be declared private because its underlying type uses a private type}} subscript(_: VeryPrivateType) -> Void { return () } // expected-warning {{subscript should be declared private because its index uses a private type}} func privateMethod(_: VeryPrivateType) -> Void {} // expected-warning {{method should be declared private because its parameter uses a private type}} {{none}} enum PrivateRawValue: VeryPrivateType { // expected-warning {{enum should be declared private because its raw type uses a private type}} {{none}} case A } enum PrivatePayload { case A(VeryPrivateType) // expected-warning {{enum case in an internal enum uses a private type}} {{none}} } private class PrivateInnerClass {} // expected-note * {{declared here}} class PrivateSuper: PrivateInnerClass {} // expected-warning {{class should be declared private because its superclass is private}} {{none}} } fileprivate var privateVar: VeryPrivateStruct { fatalError() } // expected-warning {{property should not be declared fileprivate because its type uses a private type}} {{none}} fileprivate typealias PrivateAlias = VeryPrivateStruct // expected-warning {{type alias should not be declared fileprivate because its underlying type uses a private type}} {{none}} fileprivate subscript(_: VeryPrivateStruct) -> Void { return () } // expected-warning {{subscript should not be declared fileprivate because its index uses a private type}} {{none}} fileprivate func privateMethod(_: VeryPrivateStruct) -> Void {} // expected-warning {{method should not be declared fileprivate because its parameter uses a private type}} {{none}} fileprivate enum PrivateRawValue: VeryPrivateStruct {} // expected-warning {{enum should not be declared fileprivate because its raw type uses a private type}} {{none}} // expected-error@-1 {{raw type 'Container.VeryPrivateStruct' is not expressible by any literal}} // expected-error@-2 {{'Container.PrivateRawValue' declares raw type 'Container.VeryPrivateStruct', but does not conform to RawRepresentable and conformance could not be synthesized}} fileprivate enum PrivatePayload { case A(VeryPrivateStruct) // expected-warning {{enum case in an internal enum uses a private type}} {{none}} } private class PrivateInnerClass {} // expected-note * {{declared here}} fileprivate class PrivateSuperClass: PrivateInnerClass {} // expected-warning {{class should not be declared fileprivate because its superclass is private}} {{none}} fileprivate class PrivateGenericUser<T> where T: PrivateInnerClass {} // expected-warning {{generic class should not be declared fileprivate because its generic requirement uses a private type}} {{none}} } fileprivate struct SR2579 { private struct Inner { private struct InnerPrivateType {} var innerProperty = InnerPrivateType() // expected-warning {{property should be declared private because its type 'SR2579.Inner.InnerPrivateType' uses a private type}} } // FIXME: We need better errors when one access violation results in more // downstream. private var outerProperty = Inner().innerProperty // expected-warning {{property should not be declared in this context because its type 'SR2579.Inner.InnerPrivateType' uses a private type}} var outerProperty2 = Inner().innerProperty // expected-warning {{property should be declared private because its type 'SR2579.Inner.InnerPrivateType' uses a private type}} }
apache-2.0
38b5b24b591e9c3fe362d65a8c3d9f64
57.971698
214
0.734762
4.838235
false
true
false
false
TheDarkCode/Example-Swift-Apps
Playgrounds/EnumExtensions.playground/Contents.swift
1
2686
// //: Enum Extensions Playground // // Created by Mark Hamilton on 4/9/16. // Copyright © 2016 dryverless. All rights reserved. // import UIKit // Optimized public func iterateOver<T: Hashable>(_: T.Type) -> AnyGenerator<T> { var x = 0 return AnyGenerator { let y = withUnsafePointer(&x) { UnsafePointer<T>($0).memory } if y.hashValue == x { x += 1 return y } else { return nil } } } // Original func iterateEnum<T: Hashable>(_: T.Type) -> AnyGenerator<T> { var i = 0 return AnyGenerator { let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory } let currentI = i i = i + 1 return next.hashValue == currentI ? next : nil } } // Int Extended func iterateOverEnum<T: Hashable>(_: T.Type) -> AnyGenerator<T> { var i = 0 return AnyGenerator { let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory } return next.hashValue == i.postIncrement() ? next : nil } } public extension Int { mutating func postIncrement() -> Int { defer { self += 1 } return self } mutating func postfix(increment: Int) -> Int { defer { self += increment } return self } mutating func postfixIncrement() -> Int { defer { self += 1 } return self } } // Defer inside AnyGenerator func iterateEnums<T: Hashable>(_: T.Type) -> AnyGenerator<T> { var i = 0 return AnyGenerator { let next = withUnsafePointer(&i) { UnsafePointer<T>($0).memory } defer { i += 1 } return next.hashValue == i ? next : nil } } // Color Samples public enum ColorType: String { case Emerland case Pomegranate case WetAsphalt case Turquoise case Concrete case Orange case Asbestos case PeterRiver case Silver } // Optimized for color in iterateOver(ColorType) { print(color.rawValue) } // Original for color in iterateEnum(ColorType) { print(color.rawValue) } // Int Extended for color in iterateOverEnum(ColorType) { print(color.rawValue) } // Defer inside AnyGenerator for color in iterateEnums(ColorType) { print(color.rawValue) }
mit
07a8a1bac4ae5eb928a332ee5784bd82
16.664474
72
0.498696
4.645329
false
false
false
false
yoshiki/LINEBotAPI
Sources/ImagemapMessageBuilder.swift
1
3666
import JSON public typealias ImagemapBuilder = () -> Imagemap // Base Size 1040, 700, 460, 300, 240 public enum ImagemapBaseSize: Int { case length1040 = 1040 case length700 = 700 case length460 = 460 case length300 = 300 case lenght240 = 240 public var asJSON: JSON { return JSON.infer(rawValue) } } public enum ImagemapActionType: String{ case uri = "uri" case message = "message" public var asJSON: JSON { return JSON.infer(rawValue) } } public struct Bounds { let x: Int let y: Int let width: Int let height: Int public init(x: Int = 0, y: Int = 0, width: Int = 1040, height: Int = 1040) { self.x = x self.y = y self.width = width self.height = height } private var array: [Int] { return [x, y, width, height] } public var asJSON: JSON { return JSON.infer([ "x": x.asJSON, "y": y.asJSON, "width": width.asJSON, "height": height.asJSON ]) } } public protocol ImagemapActionMutable { var actions: [ImagemapAction] { get } func addAction(action: ImagemapAction) } public protocol ImagemapAction { var type: ImagemapActionType { get } var area: Bounds { get } var asJSON: JSON { get } } public struct MessageImagemapAction: ImagemapAction { public let type: ImagemapActionType = .message public let area: Bounds private let text: String public init(text: String, area: Bounds) { self.text = text self.area = area } public var asJSON: JSON { return JSON.infer([ "type": type.asJSON, "text": text.asJSON, "area": area.asJSON ]) } } public struct UriImagemapAction: ImagemapAction { public let type: ImagemapActionType = .uri public let area: Bounds private let linkUri: String public init(linkUri: String, area: Bounds) { self.linkUri = linkUri self.area = area } public var asJSON: JSON { return JSON.infer([ "type": type.asJSON, "linkUri": linkUri.asJSON, "area": area.asJSON ]) } } public class Imagemap: ImagemapActionMutable { private struct BaseSize { let width: ImagemapBaseSize let height: ImagemapBaseSize var asJSON: JSON { return JSON.infer([ "width": width.asJSON, "height": height.asJSON ]) } } private let baseUrl: String private let altText: String private let baseSize: BaseSize public var actions = [ImagemapAction]() public init(baseUrl: String, altText: String, width: ImagemapBaseSize = .length1040, height: ImagemapBaseSize = .length1040) { self.baseUrl = baseUrl self.altText = altText self.baseSize = BaseSize(width: width, height: height) } public func addAction(action: ImagemapAction) { actions.append(action) } public var asJSON: JSON { return JSON.infer([ "type": MessageType.imagemap.asJSON, "baseUrl": baseUrl.asJSON, "altText": altText.asJSON, "baseSize": baseSize.asJSON, "actions": JSON.infer(actions.flatMap { $0.asJSON }) ]) } } public struct ImagemapMessageBuilder: Builder { private let imagemap: Imagemap public init(imagemap: Imagemap) { self.imagemap = imagemap } public func build() -> JSON? { return imagemap.asJSON } }
mit
68d99421f3cfe2d8fcc7544c071fd5b8
22.651613
80
0.577196
4.100671
false
false
false
false
parkera/swift-corelibs-foundation
Foundation/Calendar.swift
1
66199
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import CoreFoundation internal func __NSCalendarIsAutoupdating(_ calendar: NSCalendar) -> Bool { return false } internal func __NSCalendarCurrent() -> NSCalendar { return _NSCopyOnWriteCalendar(backingCalendar: CFCalendarCopyCurrent()._nsObject) } internal func __NSCalendarInit(_ identifier: String) -> NSCalendar? { return NSCalendar(identifier: NSCalendar.Identifier(rawValue: identifier)) } /** `Calendar` encapsulates information about systems of reckoning time in which the beginning, length, and divisions of a year are defined. It provides information about the calendar and support for calendrical computations such as determining the range of a given calendrical unit and adding units to a given absolute time. */ public struct Calendar : Hashable, Equatable, ReferenceConvertible, _MutableBoxing { public typealias ReferenceType = NSCalendar private var _autoupdating: Bool internal var _handle: _MutableHandle<NSCalendar> /// Calendar supports many different kinds of calendars. Each is identified by an identifier here. public enum Identifier { /// The common calendar in Europe, the Western Hemisphere, and elsewhere. case gregorian case buddhist case chinese case coptic case ethiopicAmeteMihret case ethiopicAmeteAlem case hebrew case iso8601 case indian case islamic case islamicCivil case japanese case persian case republicOfChina /// A simple tabular Islamic calendar using the astronomical/Thursday epoch of CE 622 July 15 case islamicTabular /// The Islamic Umm al-Qura calendar used in Saudi Arabia. This is based on astronomical calculation, instead of tabular behavior. case islamicUmmAlQura } /// An enumeration for the various components of a calendar date. /// /// Several `Calendar` APIs use either a single unit or a set of units as input to a search algorithm. /// /// - seealso: `DateComponents` public enum Component { case era case year case month case day case hour case minute case second case weekday case weekdayOrdinal case quarter case weekOfMonth case weekOfYear case yearForWeekOfYear case nanosecond case calendar case timeZone } /// Returns the user's current calendar. /// /// This calendar does not track changes that the user makes to their preferences. public static var current: Calendar { return Calendar(adoptingReference: __NSCalendarCurrent(), autoupdating: false) } /// A Calendar that tracks changes to user's preferred calendar. /// /// If mutated, this calendar will no longer track the user's preferred calendar. /// /// - note: The autoupdating Calendar will only compare equal to another autoupdating Calendar. public static var autoupdatingCurrent: Calendar { // swift-corelibs-foundation does not yet support autoupdating, but we can return the current calendar (which will not change). return Calendar(adoptingReference: __NSCalendarCurrent(), autoupdating: true) } // MARK: - // MARK: init /// Returns a new Calendar. /// /// - parameter identifier: The kind of calendar to use. public init(identifier: Identifier) { let result = __NSCalendarInit(Calendar._toNSCalendarIdentifier(identifier).rawValue)! _handle = _MutableHandle(adoptingReference: result) _autoupdating = false } // MARK: - // MARK: Bridging internal init(reference: NSCalendar) { _handle = _MutableHandle(reference: reference) if __NSCalendarIsAutoupdating(reference) { _autoupdating = true } else { _autoupdating = false } } private init(adoptingReference reference: NSCalendar, autoupdating: Bool) { _handle = _MutableHandle(adoptingReference: reference) _autoupdating = autoupdating } // MARK: - // /// The identifier of the calendar. public var identifier: Identifier { return Calendar._fromNSCalendarIdentifier(_handle.map({ $0.calendarIdentifier })) } /// The locale of the calendar. public var locale: Locale? { get { return _handle.map { $0.locale } } set { _applyMutation { $0.locale = newValue } } } /// The time zone of the calendar. public var timeZone: TimeZone { get { return _handle.map { $0.timeZone } } set { _applyMutation { $0.timeZone = newValue } } } /// The first weekday of the calendar. public var firstWeekday: Int { get { return _handle.map { $0.firstWeekday } } set { _applyMutation { $0.firstWeekday = newValue } } } /// The number of minimum days in the first week. public var minimumDaysInFirstWeek: Int { get { return _handle.map { $0.minimumDaysInFirstWeek } } set { _applyMutation { $0.minimumDaysInFirstWeek = newValue } } } /// A list of eras in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["BC", "AD"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var eraSymbols: [String] { return _handle.map { $0.eraSymbols } } /// A list of longer-named eras in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Before Christ", "Anno Domini"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var longEraSymbols: [String] { return _handle.map { $0.longEraSymbols } } /// A list of months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var monthSymbols: [String] { return _handle.map { $0.monthSymbols } } /// A list of shorter-named months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortMonthSymbols: [String] { return _handle.map { $0.shortMonthSymbols } } /// A list of very-shortly-named months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var veryShortMonthSymbols: [String] { return _handle.map { $0.veryShortMonthSymbols } } /// A list of standalone months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var standaloneMonthSymbols: [String] { return _handle.map { $0.standaloneMonthSymbols } } /// A list of shorter-named standalone months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortStandaloneMonthSymbols: [String] { return _handle.map { $0.shortStandaloneMonthSymbols } } /// A list of very-shortly-named standalone months in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var veryShortStandaloneMonthSymbols: [String] { return _handle.map { $0.veryShortStandaloneMonthSymbols } } /// A list of weekdays in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var weekdaySymbols: [String] { return _handle.map { $0.weekdaySymbols } } /// A list of shorter-named weekdays in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortWeekdaySymbols: [String] { return _handle.map { $0.shortWeekdaySymbols } } /// A list of very-shortly-named weekdays in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["S", "M", "T", "W", "T", "F", "S"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var veryShortWeekdaySymbols: [String] { return _handle.map { $0.veryShortWeekdaySymbols } } /// A list of standalone weekday names in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var standaloneWeekdaySymbols: [String] { return _handle.map { $0.standaloneWeekdaySymbols } } /// A list of shorter-named standalone weekdays in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortStandaloneWeekdaySymbols: [String] { return _handle.map { $0.shortStandaloneWeekdaySymbols } } /// A list of very-shortly-named weekdays in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["S", "M", "T", "W", "T", "F", "S"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var veryShortStandaloneWeekdaySymbols: [String] { return _handle.map { $0.veryShortStandaloneWeekdaySymbols } } /// A list of quarter names in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var quarterSymbols: [String] { return _handle.map { $0.quarterSymbols } } /// A list of shorter-named quarters in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Q1", "Q2", "Q3", "Q4"]`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortQuarterSymbols: [String] { return _handle.map { $0.shortQuarterSymbols } } /// A list of standalone quarter names in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var standaloneQuarterSymbols: [String] { return _handle.map { $0.standaloneQuarterSymbols } } /// A list of shorter-named standalone quarters in this calendar, localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `["Q1", "Q2", "Q3", "Q4"]`. /// - note: Stand-alone properties are for use in places like calendar headers. Non-stand-alone properties are for use in context (for example, "Saturday, November 12th"). /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var shortStandaloneQuarterSymbols: [String] { return _handle.map { $0.shortStandaloneQuarterSymbols } } /// The symbol used to represent "AM", localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `"AM"`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var amSymbol: String { return _handle.map { $0.amSymbol } } /// The symbol used to represent "PM", localized to the Calendar's `locale`. /// /// For example, for English in the Gregorian calendar, returns `"PM"`. /// /// - note: By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the `locale` property first - most likely to `Locale.autoupdatingCurrent`. public var pmSymbol: String { return _handle.map { $0.pmSymbol } } // MARK: - // /// Returns the minimum range limits of the values that a given component can take on in the receiver. /// /// As an example, in the Gregorian calendar the minimum range of values for the Day component is 1-28. /// - parameter component: A component to calculate a range for. /// - returns: The range, or nil if it could not be calculated. public func minimumRange(of component: Component) -> Range<Int>? { return _handle.map { Range($0.minimumRange(of: Calendar._toCalendarUnit([component]))) } } /// The maximum range limits of the values that a given component can take on in the receive /// /// As an example, in the Gregorian calendar the maximum range of values for the Day component is 1-31. /// - parameter component: A component to calculate a range for. /// - returns: The range, or nil if it could not be calculated. public func maximumRange(of component: Component) -> Range<Int>? { return _handle.map { Range($0.maximumRange(of: Calendar._toCalendarUnit([component]))) } } @available(*, unavailable, message: "use range(of:in:for:) instead") public func range(of smaller: NSCalendar.Unit, in larger: NSCalendar.Unit, for date: Date) -> NSRange { fatalError() } /// Returns the range of absolute time values that a smaller calendar component (such as a day) can take on in a larger calendar component (such as a month) that includes a specified absolute time. /// /// You can use this method to calculate, for example, the range the `day` component can take on in the `month` in which `date` lies. /// - parameter smaller: The smaller calendar component. /// - parameter larger: The larger calendar component. /// - parameter date: The absolute time for which the calculation is performed. /// - returns: The range of absolute time values smaller can take on in larger at the time specified by date. Returns `nil` if larger is not logically bigger than smaller in the calendar, or the given combination of components does not make sense (or is a computation which is undefined). public func range(of smaller: Component, in larger: Component, for date: Date) -> Range<Int>? { return _handle.map { Range($0.range(of: Calendar._toCalendarUnit([smaller]), in: Calendar._toCalendarUnit([larger]), for: date)) } } /// Returns, via two inout parameters, the starting time and duration of a given calendar component that contains a given date. /// /// - seealso: `range(of:for:)` /// - seealso: `dateInterval(of:for:)` /// - parameter component: A calendar component. /// - parameter start: Upon return, the starting time of the calendar component that contains the date. /// - parameter interval: Upon return, the duration of the calendar component that contains the date. /// - parameter date: The specified date. /// - returns: `true` if the starting time and duration of a component could be calculated, otherwise `false`. public func dateInterval(of component: Component, start: inout Date, interval: inout TimeInterval, for date: Date) -> Bool { if let result = _handle.map({ $0.range(of: Calendar._toCalendarUnit([component]), for: date)}) { start = result.start interval = result.duration return true } else { return false } } /// Returns the starting time and duration of a given calendar component that contains a given date. /// /// - parameter component: A calendar component. /// - parameter date: The specified date. /// - returns: A new `DateInterval` if the starting time and duration of a component could be calculated, otherwise `nil`. public func dateInterval(of component: Component, for date: Date) -> DateInterval? { var start: Date = Date(timeIntervalSinceReferenceDate: 0) var interval: TimeInterval = 0 if self.dateInterval(of: component, start: &start, interval: &interval, for: date) { return DateInterval(start: start, duration: interval) } else { return nil } } /// Returns, for a given absolute time, the ordinal number of a smaller calendar component (such as a day) within a specified larger calendar component (such as a week). /// /// The ordinality is in most cases not the same as the decomposed value of the component. Typically return values are 1 and greater. For example, the time 00:45 is in the first hour of the day, and for components `hour` and `day` respectively, the result would be 1. An exception is the week-in-month calculation, which returns 0 for days before the first week in the month containing the date. /// /// - note: Some computations can take a relatively long time. /// - parameter smaller: The smaller calendar component. /// - parameter larger: The larger calendar component. /// - parameter date: The absolute time for which the calculation is performed. /// - returns: The ordinal number of smaller within larger at the time specified by date. Returns `nil` if larger is not logically bigger than smaller in the calendar, or the given combination of components does not make sense (or is a computation which is undefined). public func ordinality(of smaller: Component, in larger: Component, for date: Date) -> Int? { let result = _handle.map { $0.ordinality(of: Calendar._toCalendarUnit([smaller]), in: Calendar._toCalendarUnit([larger]), for: date) } if result == NSNotFound { return nil } return result } // MARK: - // @available(*, unavailable, message: "use dateComponents(_:from:) instead") public func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, year yearValuePointer: UnsafeMutablePointer<Int>?, month monthValuePointer: UnsafeMutablePointer<Int>?, day dayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { fatalError() } @available(*, unavailable, message: "use dateComponents(_:from:) instead") public func getEra(_ eraValuePointer: UnsafeMutablePointer<Int>?, yearForWeekOfYear yearValuePointer: UnsafeMutablePointer<Int>?, weekOfYear weekValuePointer: UnsafeMutablePointer<Int>?, weekday weekdayValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { fatalError() } @available(*, unavailable, message: "use dateComponents(_:from:) instead") public func getHour(_ hourValuePointer: UnsafeMutablePointer<Int>?, minute minuteValuePointer: UnsafeMutablePointer<Int>?, second secondValuePointer: UnsafeMutablePointer<Int>?, nanosecond nanosecondValuePointer: UnsafeMutablePointer<Int>?, from date: Date) { fatalError() } // MARK: - // @available(*, unavailable, message: "use date(byAdding:to:wrappingComponents:) instead") public func date(byAdding unit: NSCalendar.Unit, value: Int, to date: Date, options: NSCalendar.Options = []) -> Date? { fatalError() } /// Returns a new `Date` representing the date calculated by adding components to a given date. /// /// - parameter components: A set of values to add to the date. /// - parameter date: The starting date. /// - parameter wrappingComponents: If `true`, the component should be incremented and wrap around to zero/one on overflow, and should not cause higher components to be incremented. The default value is `false`. /// - returns: A new date, or nil if a date could not be calculated with the given input. public func date(byAdding components: DateComponents, to date: Date, wrappingComponents: Bool = false) -> Date? { return _handle.map { $0.date(byAdding: components, to: date, options: wrappingComponents ? [.wrapComponents] : []) } } @available(*, unavailable, message: "use date(byAdding:to:wrappingComponents:) instead") public func date(byAdding comps: DateComponents, to date: Date, options opts: NSCalendar.Options = []) -> Date? { fatalError() } /// Returns a new `Date` representing the date calculated by adding an amount of a specific component to a given date. /// /// - parameter component: A single component to add. /// - parameter value: The value of the specified component to add. /// - parameter date: The starting date. /// - parameter wrappingComponents: If `true`, the component should be incremented and wrap around to zero/one on overflow, and should not cause higher components to be incremented. The default value is `false`. /// - returns: A new date, or nil if a date could not be calculated with the given input. public func date(byAdding component: Component, value: Int, to date: Date, wrappingComponents: Bool = false) -> Date? { return _handle.map { $0.date(byAdding: Calendar._toCalendarUnit([component]), value: value, to: date, options: wrappingComponents ? [.wrapComponents] : []) } } /// Returns a date created from the specified components. /// /// - parameter components: Used as input to the search algorithm for finding a corresponding date. /// - returns: A new `Date`, or nil if a date could not be found which matches the components. public func date(from components: DateComponents) -> Date? { return _handle.map { $0.date(from: components) } } @available(*, unavailable, renamed: "dateComponents(_:from:)") public func components(_ unitFlags: NSCalendar.Unit, from date: Date) -> DateComponents { fatalError() } /// Returns all the date components of a date, using the calendar time zone. /// /// - note: If you want "date information in a given time zone" in order to display it, you should use `DateFormatter` to format the date. /// - parameter date: The `Date` to use. /// - returns: The date components of the specified date. public func dateComponents(_ components: Set<Component>, from date: Date) -> DateComponents { return _handle.map { $0.components(Calendar._toCalendarUnit(components), from: date) } } @available(*, unavailable, renamed: "dateComponents(in:from:)") public func components(in timezone: TimeZone, from date: Date) -> DateComponents { fatalError() } /// Returns all the date components of a date, as if in a given time zone (instead of the `Calendar` time zone). /// /// The time zone overrides the time zone of the `Calendar` for the purposes of this calculation. /// - note: If you want "date information in a given time zone" in order to display it, you should use `DateFormatter` to format the date. /// - parameter timeZone: The `TimeZone` to use. /// - parameter date: The `Date` to use. /// - returns: All components, calculated using the `Calendar` and `TimeZone`. public func dateComponents(in timeZone: TimeZone, from date: Date) -> DateComponents { return _handle.map { $0.components(in: timeZone, from: date) } } @available(*, unavailable, renamed: "dateComponents(_:from:to:)") public func components(_ unitFlags: NSCalendar.Unit, from startingDate: Date, to resultDate: Date, options opts: NSCalendar.Options = []) -> DateComponents { fatalError() } /// Returns the difference between two dates. /// /// - parameter components: Which components to compare. /// - parameter start: The starting date. /// - parameter end: The ending date. /// - returns: The result of calculating the difference from start to end. public func dateComponents(_ components: Set<Component>, from start: Date, to end: Date) -> DateComponents { return _handle.map { $0.components(Calendar._toCalendarUnit(components), from: start, to: end, options: []) } } @available(*, unavailable, renamed: "dateComponents(_:from:to:)") public func components(_ unitFlags: NSCalendar.Unit, from startingDateComp: DateComponents, to resultDateComp: DateComponents, options: NSCalendar.Options = []) -> DateComponents { fatalError() } /// Returns the difference between two dates specified as `DateComponents`. /// /// For components which are not specified in each `DateComponents`, but required to specify an absolute date, the base value of the component is assumed. For example, for an `DateComponents` with just a `year` and a `month` specified, a `day` of 1, and an `hour`, `minute`, `second`, and `nanosecond` of 0 are assumed. /// Calendrical calculations with unspecified `year` or `year` value prior to the start of a calendar are not advised. /// For each `DateComponents`, if its `timeZone` property is set, that time zone is used for it. If the `calendar` property is set, that is used rather than the receiving calendar, and if both the `calendar` and `timeZone` are set, the `timeZone` property value overrides the time zone of the `calendar` property. /// /// - parameter components: Which components to compare. /// - parameter start: The starting date components. /// - parameter end: The ending date components. /// - returns: The result of calculating the difference from start to end. public func dateComponents(_ components: Set<Component>, from start: DateComponents, to end: DateComponents) -> DateComponents { return _handle.map { $0.components(Calendar._toCalendarUnit(components), from: start, to: end, options: []) } } /// Returns the value for one component of a date. /// /// - parameter component: The component to calculate. /// - parameter date: The date to use. /// - returns: The value for the component. public func component(_ component: Component, from date: Date) -> Int { return _handle.map { $0.component(Calendar._toCalendarUnit([component]), from: date) } } @available(*, unavailable, message: "Use date(from:) instead") public func date(era: Int, year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, nanosecond: Int) -> Date? { fatalError() } @available(*, unavailable, message: "Use date(from:) instead") public func date(era: Int, yearForWeekOfYear: Int, weekOfYear: Int, weekday: Int, hour: Int, minute: Int, second: Int, nanosecond: Int) -> Date? { fatalError() } /// Returns the first moment of a given Date, as a Date. /// /// For example, pass in `Date()`, if you want the start of today. /// If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist. /// - parameter date: The date to search. /// - returns: The first moment of the given date. public func startOfDay(for date: Date) -> Date { return _handle.map { $0.startOfDay(for: date) } } @available(*, unavailable, renamed: "compare(_:to:toGranularity:)") public func compare(_ date1: Date, to date2: Date, toUnitGranularity unit: NSCalendar.Unit) -> ComparisonResult { fatalError() } /// Compares the given dates down to the given component, reporting them `orderedSame` if they are the same in the given component and all larger components, otherwise either `orderedAscending` or `orderedDescending`. /// /// - parameter date1: A date to compare. /// - parameter date2: A date to compare. /// - parameter component: A granularity to compare. For example, pass `.hour` to check if two dates are in the same hour. public func compare(_ date1: Date, to date2: Date, toGranularity component: Component) -> ComparisonResult { return _handle.map { $0.compare(date1, to: date2, toUnitGranularity: Calendar._toCalendarUnit([component])) } } @available(*, unavailable, renamed: "isDate(_:equalTo:toGranularity:)") public func isDate(_ date1: Date, equalTo date2: Date, toUnitGranularity unit: NSCalendar.Unit) -> Bool { fatalError() } /// Compares the given dates down to the given component, reporting them equal if they are the same in the given component and all larger components. /// /// - parameter date1: A date to compare. /// - parameter date2: A date to compare. /// - parameter component: A granularity to compare. For example, pass `.hour` to check if two dates are in the same hour. /// - returns: `true` if the given date is within tomorrow. public func isDate(_ date1: Date, equalTo date2: Date, toGranularity component: Component) -> Bool { return _handle.map { $0.isDate(date1, equalTo: date2, toUnitGranularity: Calendar._toCalendarUnit([component])) } } /// Returns `true` if the given date is within the same day as another date, as defined by the calendar and calendar's locale. /// /// - parameter date1: A date to check for containment. /// - parameter date2: A date to check for containment. /// - returns: `true` if `date1` and `date2` are in the same day. public func isDate(_ date1: Date, inSameDayAs date2: Date) -> Bool { return _handle.map { $0.isDate(date1, inSameDayAs: date2) } } /// Returns `true` if the given date is within today, as defined by the calendar and calendar's locale. /// /// - parameter date: The specified date. /// - returns: `true` if the given date is within today. public func isDateInToday(_ date: Date) -> Bool { return _handle.map { $0.isDateInToday(date) } } /// Returns `true` if the given date is within yesterday, as defined by the calendar and calendar's locale. /// /// - parameter date: The specified date. /// - returns: `true` if the given date is within yesterday. public func isDateInYesterday(_ date: Date) -> Bool { return _handle.map { $0.isDateInYesterday(date) } } /// Returns `true` if the given date is within tomorrow, as defined by the calendar and calendar's locale. /// /// - parameter date: The specified date. /// - returns: `true` if the given date is within tomorrow. public func isDateInTomorrow(_ date: Date) -> Bool { return _handle.map { $0.isDateInTomorrow(date) } } /// Returns `true` if the given date is within a weekend period, as defined by the calendar and calendar's locale. /// /// - parameter date: The specified date. /// - returns: `true` if the given date is within a weekend. public func isDateInWeekend(_ date: Date) -> Bool { return _handle.map { $0.isDateInWeekend(date) } } /// Find the range of the weekend around the given date, returned via two by-reference parameters. /// /// Note that a given entire day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a day in some calendars and locales. /// - seealso: `dateIntervalOfWeekend(containing:)` /// - parameter date: The date at which to start the search. /// - parameter start: When the result is `true`, set /// - returns: `true` if a date range could be found, and `false` if the date is not in a weekend. public func dateIntervalOfWeekend(containing date: Date, start: inout Date, interval: inout TimeInterval) -> Bool { if let result = _handle.map({ $0.range(ofWeekendContaining: date) }) { start = result.start interval = result.duration return true } else { return false } } /// Returns a `DateInterval` of the weekend contained by the given date, or nil if the date is not in a weekend. /// /// - parameter date: The date contained in the weekend. /// - returns: A `DateInterval`, or nil if the date is not in a weekend. public func dateIntervalOfWeekend(containing date: Date) -> DateInterval? { return _handle.map({ $0.range(ofWeekendContaining: date) }) } /// Returns the range of the next weekend via two inout parameters. The weekend starts strictly after the given date. /// /// If `direction` is `.backward`, then finds the previous weekend range strictly before the given date. /// /// Note that a given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a day in some calendars and locales. /// - parameter date: The date at which to begin the search. /// - parameter direction: Which direction in time to search. The default value is `.forward`. /// - returns: A `DateInterval`, or nil if the weekend could not be found. public func nextWeekend(startingAfter date: Date, start: inout Date, interval: inout TimeInterval, direction: SearchDirection = .forward) -> Bool { // The implementation actually overrides previousKeepSmaller and nextKeepSmaller with matchNext, always - but strict still trumps all. if let result = _handle.map({ $0.nextWeekendAfter(date, options: direction == .backward ? [.searchBackwards] : []) }) { start = result.start interval = result.duration return true } else { return false } } /// Returns a `DateInterval` of the next weekend, which starts strictly after the given date. /// /// If `direction` is `.backward`, then finds the previous weekend range strictly before the given date. /// /// Note that a given entire Day within a calendar is not necessarily all in a weekend or not; weekends can start in the middle of a day in some calendars and locales. /// - parameter date: The date at which to begin the search. /// - parameter direction: Which direction in time to search. The default value is `.forward`. /// - returns: A `DateInterval`, or nil if weekends do not exist in the specific calendar or locale. public func nextWeekend(startingAfter date: Date, direction: SearchDirection = .forward) -> DateInterval? { // The implementation actually overrides previousKeepSmaller and nextKeepSmaller with matchNext, always - but strict still trumps all. return _handle.map({ $0.nextWeekendAfter(date, options: direction == .backward ? [.searchBackwards] : []) }) } // MARK: - // MARK: Searching /// The direction in time to search. public enum SearchDirection { /// Search for a date later in time than the start date. case forward /// Search for a date earlier in time than the start date. case backward } /// Determines which result to use when a time is repeated on a day in a calendar (for example, during a daylight saving transition when the times between 2:00am and 3:00am may happen twice). public enum RepeatedTimePolicy { /// If there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher component to the highest specified component, then the algorithm will return the first occurrence. case first /// If there are two or more matching times (all the components are the same, including isLeapMonth) before the end of the next instance of the next higher component to the highest specified component, then the algorithm will return the last occurrence. case last } /// A hint to the search algorithm to control the method used for searching for dates. public enum MatchingPolicy { /// If there is no matching time before the end of the next instance of the next higher component to the highest specified component in the `DateComponents` argument, the algorithm will return the next existing time which exists. /// /// For example, during a daylight saving transition there may be no 2:37am. The result would then be 3:00am, if that does exist. case nextTime /// If specified, and there is no matching time before the end of the next instance of the next higher component to the highest specified component in the `DateComponents` argument, the method will return the next existing value of the missing component and preserves the lower components' values (e.g., no 2:37am results in 3:37am, if that exists). case nextTimePreservingSmallerComponents /// If there is no matching time before the end of the next instance of the next higher component to the highest specified component in the `DateComponents` argument, the algorithm will return the previous existing value of the missing component and preserves the lower components' values. /// /// For example, during a daylight saving transition there may be no 2:37am. The result would then be 1:37am, if that does exist. case previousTimePreservingSmallerComponents /// If specified, the algorithm travels as far forward or backward as necessary looking for a match. /// /// For example, if searching for Feb 29 in the Gregorian calendar, the algorithm may choose March 1 instead (for example, if the year is not a leap year). If you wish to find the next Feb 29 without the algorithm adjusting the next higher component in the specified `DateComponents`, then use the `strict` option. /// - note: There are ultimately implementation-defined limits in how far distant the search will go. case strict } @available(*, unavailable, message: "use nextWeekend(startingAfter:matching:matchingPolicy:repeatedTimePolicy:direction:using:) instead") public func enumerateDates(startingAfter start: Date, matching comps: DateComponents, options opts: NSCalendar.Options = [], using block: (Date?, Bool, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { fatalError() } /// Computes the dates which match (or most closely match) a given set of components, and calls the closure once for each of them, until the enumeration is stopped. /// /// There will be at least one intervening date which does not match all the components (or the given date itself must not match) between the given date and any result. /// /// If `direction` is set to `.backward`, this method finds the previous match before the given date. The intent is that the same matches as for a `.forward` search will be found (that is, if you are enumerating forwards or backwards for each hour with minute "27", the seconds in the date you will get in forwards search would obviously be 00, and the same will be true in a backwards search in order to implement this rule. Similarly for DST backwards jumps which repeats times, you'll get the first match by default, where "first" is defined from the point of view of searching forwards. So, when searching backwards looking for a particular hour, with no minute and second specified, you don't get a minute and second of 59:59 for the matching hour (which would be the nominal first match within a given hour, given the other rules here, when searching backwards). /// /// If an exact match is not possible, and requested with the `strict` option, nil is passed to the closure and the enumeration ends. (Logically, since an exact match searches indefinitely into the future, if no match is found there's no point in continuing the enumeration.) /// /// Result dates have an integer number of seconds (as if 0 was specified for the nanoseconds property of the `DateComponents` matching parameter), unless a value was set in the nanoseconds property, in which case the result date will have that number of nanoseconds (or as close as possible with floating point numbers). /// /// The enumeration is stopped by setting `stop` to `true` in the closure and returning. It is not necessary to set `stop` to `false` to keep the enumeration going. /// - parameter start: The `Date` at which to start the search. /// - parameter components: The `DateComponents` to use as input to the search algorithm. /// - parameter matchingPolicy: Determines the behavior of the search algorithm when the input produces an ambiguous result. /// - parameter repeatedTimePolicy: Determines the behavior of the search algorithm when the input produces a time that occurs twice on a particular day. /// - parameter direction: Which direction in time to search. The default value is `.forward`, which means later in time. /// - parameter block: A closure that is called with search results. public func enumerateDates(startingAfter start: Date, matching components: DateComponents, matchingPolicy: MatchingPolicy, repeatedTimePolicy: RepeatedTimePolicy = .first, direction: SearchDirection = .forward, using block: (_ result: Date?, _ exactMatch: Bool, _ stop: inout Bool) -> Void) { _handle.map { $0.enumerateDates(startingAfter: start, matching: components, options: Calendar._toCalendarOptions(matchingPolicy: matchingPolicy, repeatedTimePolicy: repeatedTimePolicy, direction: direction)) { (result, exactMatch, stop) in var stopv = false block(result, exactMatch, &stopv) if stopv { stop.pointee = true } } } } @available(*, unavailable, message: "use nextDate(after:matching:matchingPolicy:repeatedTimePolicy:direction:) instead") public func nextDate(after date: Date, matching comps: DateComponents, options: NSCalendar.Options = []) -> Date? { fatalError() } /// Computes the next date which matches (or most closely matches) a given set of components. /// /// The general semantics follow those of the `enumerateDates` function. /// To compute a sequence of results, use the `enumerateDates` function, rather than looping and calling this method with the previous loop iteration's result. /// - parameter date: The starting date. /// - parameter components: The components to search for. /// - parameter matchingPolicy: Specifies the technique the search algorithm uses to find results. Default value is `.nextTime`. /// - parameter repeatedTimePolicy: Specifies the behavior when multiple matches are found. Default value is `.first`. /// - parameter direction: Specifies the direction in time to search. Default is `.forward`. /// - returns: A `Date` representing the result of the search, or `nil` if a result could not be found. public func nextDate(after date: Date, matching components: DateComponents, matchingPolicy: MatchingPolicy, repeatedTimePolicy: RepeatedTimePolicy = .first, direction: SearchDirection = .forward) -> Date? { return _handle.map { $0.nextDate(after: date, matching: components, options: Calendar._toCalendarOptions(matchingPolicy: matchingPolicy, repeatedTimePolicy: repeatedTimePolicy, direction: direction)) } } @available(*, unavailable, message: "use nextDate(after:matching:matchingPolicy:repeatedTimePolicy:direction:) instead") public func nextDate(after date: Date, matchingHour hourValue: Int, minute minuteValue: Int, second secondValue: Int, options: NSCalendar.Options = []) -> Date? { fatalError() } // MARK: - // @available(*, unavailable, renamed: "date(bySetting:value:of:)") public func date(bySettingUnit unit: NSCalendar.Unit, value v: Int, of date: Date, options opts: NSCalendar.Options = []) -> Date? { fatalError() } /// Returns a new `Date` representing the date calculated by setting a specific component to a given time, and trying to keep lower components the same. If the component already has that value, this may result in a date which is the same as the given date. /// /// Changing a component's value often will require higher or coupled components to change as well. For example, setting the Weekday to Thursday usually will require the Day component to change its value, and possibly the Month and Year as well. /// If no such time exists, the next available time is returned (which could, for example, be in a different day, week, month, ... than the nominal target date). Setting a component to something which would be inconsistent forces other components to change; for example, setting the Weekday to Thursday probably shifts the Day and possibly Month and Year. /// The exact behavior of this method is implementation-defined. For example, if changing the weekday to Thursday, does that move forward to the next, backward to the previous, or to the nearest Thursday? The algorithm will try to produce a result which is in the next-larger component to the one given (there's a table of this mapping at the top of this document). So for the "set to Thursday" example, find the Thursday in the Week in which the given date resides (which could be a forwards or backwards move, and not necessarily the nearest Thursday). For more control over the exact behavior, use `nextDate(after:matching:matchingPolicy:behavior:direction:)`. public func date(bySetting component: Component, value: Int, of date: Date) -> Date? { return _handle.map { $0.date(bySettingUnit: Calendar._toCalendarUnit([component]), value: value, of: date, options: []) } } @available(*, unavailable, message: "use date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:) instead") public func date(bySettingHour h: Int, minute m: Int, second s: Int, of date: Date, options opts: NSCalendar.Options = []) -> Date? { fatalError() } /// Returns a new `Date` representing the date calculated by setting hour, minute, and second to a given time on a specified `Date`. /// /// If no such time exists, the next available time is returned (which could, for example, be in a different day than the nominal target date). /// The intent is to return a date on the same day as the original date argument. This may result in a date which is backward than the given date, of course. /// - parameter hour: A specified hour. /// - parameter minute: A specified minute. /// - parameter second: A specified second. /// - parameter date: The date to start calculation with. /// - parameter matchingPolicy: Specifies the technique the search algorithm uses to find results. Default value is `.nextTime`. /// - parameter repeatedTimePolicy: Specifies the behavior when multiple matches are found. Default value is `.first`. /// - parameter direction: Specifies the direction in time to search. Default is `.forward`. /// - returns: A `Date` representing the result of the search, or `nil` if a result could not be found. public func date(bySettingHour hour: Int, minute: Int, second: Int, of date: Date, matchingPolicy: MatchingPolicy = .nextTime, repeatedTimePolicy: RepeatedTimePolicy = .first, direction: SearchDirection = .forward) -> Date? { return _handle.map { $0.date(bySettingHour: hour, minute: minute, second: second, of: date, options: Calendar._toCalendarOptions(matchingPolicy: matchingPolicy, repeatedTimePolicy: repeatedTimePolicy, direction: direction)) } } /// Determine if the `Date` has all of the specified `DateComponents`. /// /// It may be useful to test the return value of `nextDate(after:matching:matchingPolicy:behavior:direction:)` to find out if the components were obeyed or if the method had to fudge the result value due to missing time (for example, a daylight saving time transition). /// /// - returns: `true` if the date matches all of the components, otherwise `false`. public func date(_ date: Date, matchesComponents components: DateComponents) -> Bool { return _handle.map { $0.date(date, matchesComponents: components) } } // MARK: - public func hash(into hasher: inout Hasher) { // We implement hash ourselves, because we need to make sure autoupdating calendars have the same hash if _autoupdating { hasher.combine(1 as Int8) } else { hasher.combine(_handle.map { $0 }) } } public static func ==(lhs: Calendar, rhs: Calendar) -> Bool { if lhs._autoupdating || rhs._autoupdating { return lhs._autoupdating == rhs._autoupdating } else { // NSCalendar's isEqual is broken (27019864) so we must implement this ourselves return lhs.identifier == rhs.identifier && lhs.locale == rhs.locale && lhs.timeZone == rhs.timeZone && lhs.firstWeekday == rhs.firstWeekday && lhs.minimumDaysInFirstWeek == rhs.minimumDaysInFirstWeek } } // MARK: - // MARK: Conversion Functions /// Turn our more-specific options into the big bucket option set of NSCalendar internal static func _toCalendarOptions(matchingPolicy: MatchingPolicy, repeatedTimePolicy: RepeatedTimePolicy, direction: SearchDirection) -> NSCalendar.Options { var result: NSCalendar.Options = [] switch matchingPolicy { case .nextTime: result.insert(.matchNextTime) case .nextTimePreservingSmallerComponents: result.insert(.matchNextTimePreservingSmallerUnits) case .previousTimePreservingSmallerComponents: result.insert(.matchPreviousTimePreservingSmallerUnits) case .strict: result.insert(.matchStrictly) } switch repeatedTimePolicy { case .first: result.insert(.matchFirst) case .last: result.insert(.matchLast) } switch direction { case .backward: result.insert(.searchBackwards) case .forward: break } return result } internal static func _toCalendarUnit(_ units: Set<Component>) -> NSCalendar.Unit { let unitMap: [Component : NSCalendar.Unit] = [.era: .era, .year: .year, .month: .month, .day: .day, .hour: .hour, .minute: .minute, .second: .second, .weekday: .weekday, .weekdayOrdinal: .weekdayOrdinal, .quarter: .quarter, .weekOfMonth: .weekOfMonth, .weekOfYear: .weekOfYear, .yearForWeekOfYear: .yearForWeekOfYear, .nanosecond: .nanosecond, .calendar: .calendar, .timeZone: .timeZone] var result = NSCalendar.Unit() for u in units { result.insert(unitMap[u]!) } return result } internal static func _fromCalendarUnit(_ unit: NSCalendar.Unit) -> Component { switch unit { case .era: return .era case .year: return .year case .month: return .month case .day: return .day case .hour: return .hour case .minute: return .minute case .second: return .second case .weekday: return .weekday case .weekdayOrdinal: return .weekdayOrdinal case .quarter: return .quarter case .weekOfMonth: return .weekOfMonth case .weekOfYear: return .weekOfYear case .yearForWeekOfYear: return .yearForWeekOfYear case .nanosecond: return .nanosecond case .calendar: return .calendar case .timeZone: return .timeZone default: fatalError() } } internal static func _fromCalendarUnits(_ units: NSCalendar.Unit) -> Set<Component> { var result = Set<Component>() if units.contains(.era) { result.insert(.era) } if units.contains(.year) { result.insert(.year) } if units.contains(.month) { result.insert(.month) } if units.contains(.day) { result.insert(.day) } if units.contains(.hour) { result.insert(.hour) } if units.contains(.minute) { result.insert(.minute) } if units.contains(.second) { result.insert(.second) } if units.contains(.weekday) { result.insert(.weekday) } if units.contains(.weekdayOrdinal) { result.insert(.weekdayOrdinal) } if units.contains(.quarter) { result.insert(.quarter) } if units.contains(.weekOfMonth) { result.insert(.weekOfMonth) } if units.contains(.weekOfYear) { result.insert(.weekOfYear) } if units.contains(.yearForWeekOfYear) { result.insert(.yearForWeekOfYear) } if units.contains(.nanosecond) { result.insert(.nanosecond) } if units.contains(.calendar) { result.insert(.calendar) } if units.contains(.timeZone) { result.insert(.timeZone) } return result } internal static func _toNSCalendarIdentifier(_ identifier: Identifier) -> NSCalendar.Identifier { if #available(macOS 10.10, iOS 8.0, *) { let identifierMap: [Identifier : NSCalendar.Identifier] = [.gregorian: .gregorian, .buddhist: .buddhist, .chinese: .chinese, .coptic: .coptic, .ethiopicAmeteMihret: .ethiopicAmeteMihret, .ethiopicAmeteAlem: .ethiopicAmeteAlem, .hebrew: .hebrew, .iso8601: .ISO8601, .indian: .indian, .islamic: .islamic, .islamicCivil: .islamicCivil, .japanese: .japanese, .persian: .persian, .republicOfChina: .republicOfChina, .islamicTabular: .islamicTabular, .islamicUmmAlQura: .islamicUmmAlQura] return identifierMap[identifier]! } else { let identifierMap: [Identifier : NSCalendar.Identifier] = [.gregorian: .gregorian, .buddhist: .buddhist, .chinese: .chinese, .coptic: .coptic, .ethiopicAmeteMihret: .ethiopicAmeteMihret, .ethiopicAmeteAlem: .ethiopicAmeteAlem, .hebrew: .hebrew, .iso8601: .ISO8601, .indian: .indian, .islamic: .islamic, .islamicCivil: .islamicCivil, .japanese: .japanese, .persian: .persian, .republicOfChina: .republicOfChina] return identifierMap[identifier]! } } internal static func _fromNSCalendarIdentifier(_ identifier: NSCalendar.Identifier) -> Identifier { if #available(macOS 10.10, iOS 8.0, *) { let identifierMap: [NSCalendar.Identifier : Identifier] = [.gregorian: .gregorian, .buddhist: .buddhist, .chinese: .chinese, .coptic: .coptic, .ethiopicAmeteMihret: .ethiopicAmeteMihret, .ethiopicAmeteAlem: .ethiopicAmeteAlem, .hebrew: .hebrew, .ISO8601: .iso8601, .indian: .indian, .islamic: .islamic, .islamicCivil: .islamicCivil, .japanese: .japanese, .persian: .persian, .republicOfChina: .republicOfChina, .islamicTabular: .islamicTabular, .islamicUmmAlQura: .islamicUmmAlQura] return identifierMap[identifier]! } else { let identifierMap: [NSCalendar.Identifier : Identifier] = [.gregorian: .gregorian, .buddhist: .buddhist, .chinese: .chinese, .coptic: .coptic, .ethiopicAmeteMihret: .ethiopicAmeteMihret, .ethiopicAmeteAlem: .ethiopicAmeteAlem, .hebrew: .hebrew, .ISO8601: .iso8601, .indian: .indian, .islamic: .islamic, .islamicCivil: .islamicCivil, .japanese: .japanese, .persian: .persian, .republicOfChina: .republicOfChina] return identifierMap[identifier]! } } } extension Calendar : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable { private var _kindDescription : String { if self == .autoupdatingCurrent { return "autoupdatingCurrent" } else if self == .current { return "current" } else { return "fixed" } } public var description: String { return "\(identifier) (\(_kindDescription))" } public var debugDescription: String { return "\(identifier) (\(_kindDescription))" } public var customMirror: Mirror { let children: [(label: String?, value: Any)] = [ (label: "identifier", value: identifier), (label: "kind", value: _kindDescription), (label: "locale", value: locale as Any), (label: "timeZone", value: timeZone), (label: "firstWeekday", value: firstWeekday), (label: "minimumDaysInFirstWeek", value: minimumDaysInFirstWeek) ] return Mirror(self, children: children, displayStyle: .struct) } } extension Calendar: _ObjectiveCBridgeable { public typealias _ObjectType = NSCalendar @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSCalendar { return _handle._copiedReference() } public static func _forceBridgeFromObjectiveC(_ input: NSCalendar, result: inout Calendar?) { if !_conditionallyBridgeFromObjectiveC(input, result: &result) { fatalError("Unable to bridge \(NSCalendar.self) to \(self)") } } @discardableResult public static func _conditionallyBridgeFromObjectiveC(_ input: NSCalendar, result: inout Calendar?) -> Bool { result = Calendar(reference: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSCalendar?) -> Calendar { var result: Calendar? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension Calendar : Codable { private enum CodingKeys : Int, CodingKey { case identifier case locale case timeZone case firstWeekday case minimumDaysInFirstWeek } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let identifierString = try container.decode(String.self, forKey: .identifier) let identifier = Calendar._fromNSCalendarIdentifier(NSCalendar.Identifier(rawValue: identifierString)) self.init(identifier: identifier) self.locale = try container.decodeIfPresent(Locale.self, forKey: .locale) self.timeZone = try container.decode(TimeZone.self, forKey: .timeZone) self.firstWeekday = try container.decode(Int.self, forKey: .firstWeekday) self.minimumDaysInFirstWeek = try container.decode(Int.self, forKey: .minimumDaysInFirstWeek) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) let identifier = Calendar._toNSCalendarIdentifier(self.identifier).rawValue try container.encode(identifier, forKey: .identifier) try container.encode(self.locale, forKey: .locale) try container.encode(self.timeZone, forKey: .timeZone) try container.encode(self.firstWeekday, forKey: .firstWeekday) try container.encode(self.minimumDaysInFirstWeek, forKey: .minimumDaysInFirstWeek) } }
apache-2.0
21a13fe69166b97fd1d082214283dff3
53.08415
874
0.658107
4.748512
false
false
false
false
tensorflow/swift-models
Models/ImageClassification/WideResNet.swift
1
6177
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import TensorFlow // Original Paper: // "Wide Residual Networks" // Sergey Zagoruyko, Nikos Komodakis // https://arxiv.org/abs/1605.07146 // https://github.com/szagoruyko/wide-residual-networks public struct BatchNormConv2DBlock: Layer { public var norm1: BatchNorm<Float> public var conv1: Conv2D<Float> public var norm2: BatchNorm<Float> public var conv2: Conv2D<Float> public var shortcut: Conv2D<Float> @noDerivative let isExpansion: Bool @noDerivative let dropout: Dropout<Float> = Dropout(probability: 0.3) public init( featureCounts: (Int, Int), kernelSize: Int = 3, strides: (Int, Int) = (1, 1), padding: Padding = .same ) { self.norm1 = BatchNorm(featureCount: featureCounts.0) self.conv1 = Conv2D( filterShape: (kernelSize, kernelSize, featureCounts.0, featureCounts.1), strides: strides, padding: padding) self.norm2 = BatchNorm(featureCount: featureCounts.1) self.conv2 = Conv2D(filterShape: (kernelSize, kernelSize, featureCounts.1, featureCounts.1), strides: (1, 1), padding: padding) self.shortcut = Conv2D(filterShape: (1, 1, featureCounts.0, featureCounts.1), strides: strides, padding: padding) self.isExpansion = featureCounts.1 != featureCounts.0 || strides != (1, 1) } @differentiable public func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> { let preact1 = relu(norm1(input)) var residual = conv1(preact1) let preact2: Tensor<Float> let shortcutResult: Tensor<Float> if isExpansion { shortcutResult = shortcut(preact1) preact2 = relu(norm2(residual)) } else { shortcutResult = input preact2 = dropout(relu(norm2(residual))) } residual = conv2(preact2) return residual + shortcutResult } } public struct WideResNetBasicBlock: Layer { public var blocks: [BatchNormConv2DBlock] public init( featureCounts: (Int, Int), kernelSize: Int = 3, depthFactor: Int = 2, initialStride: (Int, Int) = (2, 2) ) { self.blocks = [BatchNormConv2DBlock(featureCounts: featureCounts, strides: initialStride)] for _ in 1..<depthFactor { self.blocks += [BatchNormConv2DBlock(featureCounts: (featureCounts.1, featureCounts.1))] } } @differentiable public func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> { return blocks.differentiableReduce(input) { $1($0) } } } public struct WideResNet: Layer { public var l1: Conv2D<Float> public var l2: WideResNetBasicBlock public var l3: WideResNetBasicBlock public var l4: WideResNetBasicBlock public var norm: BatchNorm<Float> public var avgPool: AvgPool2D<Float> public var flatten = Flatten<Float>() public var classifier: Dense<Float> public init(depthFactor: Int = 2, widenFactor: Int = 8) { self.l1 = Conv2D(filterShape: (3, 3, 3, 16), strides: (1, 1), padding: .same) self.l2 = WideResNetBasicBlock( featureCounts: (16, 16 * widenFactor), depthFactor: depthFactor, initialStride: (1, 1)) self.l3 = WideResNetBasicBlock(featureCounts: (16 * widenFactor, 32 * widenFactor), depthFactor: depthFactor) self.l4 = WideResNetBasicBlock(featureCounts: (32 * widenFactor, 64 * widenFactor), depthFactor: depthFactor) self.norm = BatchNorm(featureCount: 64 * widenFactor) self.avgPool = AvgPool2D(poolSize: (8, 8), strides: (8, 8)) self.classifier = Dense(inputSize: 64 * widenFactor, outputSize: 10) } @differentiable public func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> { let inputLayer = input.sequenced(through: l1, l2, l3, l4) let finalNorm = relu(norm(inputLayer)) return finalNorm.sequenced(through: avgPool, flatten, classifier) } } extension WideResNet { public enum Kind { case wideResNet16 case wideResNet16k8 case wideResNet16k10 case wideResNet22 case wideResNet22k8 case wideResNet22k10 case wideResNet28 case wideResNet28k10 case wideResNet28k12 case wideResNet40k1 case wideResNet40k2 case wideResNet40k4 case wideResNet40k8 } public init(kind: Kind) { switch kind { case .wideResNet16, .wideResNet16k8: self.init(depthFactor: 2, widenFactor: 8) case .wideResNet16k10: self.init(depthFactor: 2, widenFactor: 10) case .wideResNet22, .wideResNet22k8: self.init(depthFactor: 3, widenFactor: 8) case .wideResNet22k10: self.init(depthFactor: 3, widenFactor: 10) case .wideResNet28, .wideResNet28k10: self.init(depthFactor: 4, widenFactor: 10) case .wideResNet28k12: self.init(depthFactor: 4, widenFactor: 12) case .wideResNet40k1: self.init(depthFactor: 6, widenFactor: 1) case .wideResNet40k2: self.init(depthFactor: 6, widenFactor: 2) case .wideResNet40k4: self.init(depthFactor: 6, widenFactor: 4) case .wideResNet40k8: self.init(depthFactor: 6, widenFactor: 8) } } }
apache-2.0
c28ce88763e3d6f3003f369000091cad
35.767857
102
0.629756
3.761876
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 2/4-4-Presentation/PresentingDemo5/PresentingDemo/ModalViewController1.swift
1
3934
// // ModalViewController1.swift // PresentingDemo // // Created by Nicholas Outram on 14/01/2016. // Copyright © 2016 Plymouth University. All rights reserved. // import UIKit protocol ModalViewController1Protocol : class { func dismissWithStringData(str : String) } class ModalViewController1: UIViewController { @IBOutlet weak var titleLabel: UILabel! var titleText : String = "Default Title" weak var delegate : ModalViewController1Protocol? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. titleLabel.text = titleText } //***************************** //Create a view programatically //***************************** override func loadView() { // super.loadView() would load from a Nib // As we have overridden this, then the nib loading mechanism is disabled. //Has a nib been provided? if let _ = self.nibName { super.loadView() return } //Instantiate a view self.view = UIView(frame: UIScreen.mainScreen().bounds) self.view.backgroundColor = UIColor.lightGrayColor() //Instantiate the label (no position specified) let label = UILabel() //Instantiate the button let button = UIButton(type: UIButtonType.RoundedRect) //Set the properties of the label label.text = "Demo 5" //Set property label.textAlignment = NSTextAlignment.Center self.titleLabel = label //Setup outlet //Set the properties of the button button.setTitle("Dismiss", forState: UIControlState.Normal) button.userInteractionEnabled = true button.addTarget(self, action: #selector(ModalViewController1.doDismiss(_:)), forControlEvents: UIControlEvents.TouchUpInside) button.showsTouchWhenHighlighted = true //Add label to the view heirarchy self.view.addSubview(label) self.view.addSubview(button) //Add constraints (center of the view) let c1 = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0) let c2 = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0) let c3 = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: label, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 60.0) let c4 = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: label, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0) label.translatesAutoresizingMaskIntoConstraints = false button.translatesAutoresizingMaskIntoConstraints = false self.view.addConstraint(c1) self.view.addConstraint(c2) self.view.addConstraint(c3) self.view.addConstraint(c4) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ @IBAction func doDismiss(sender: AnyObject) { delegate?.dismissWithStringData("Message from DEMO 1") } }
mit
28ea60265a2d59cfc2b7be341922f37a
36.457143
207
0.664124
5.154653
false
false
false
false
mirego/PinLayout
Tests/iOS/ReadableLayoutMarginsSpec.swift
1
3865
// Copyright (c) 2017 Luc Dion // 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 Quick import Nimble import PinLayout class ReadableLayoutMargins: QuickSpec { override func spec() { var viewController: PViewController! var window: UIWindow! var rootView: BasicView! var aView: BasicView! var bView: BasicView! var bViewChild: BasicView! /* root | |- aView | | | - aViewChild | - bView | - bViewChild */ beforeEach { viewController = PViewController() viewController.view = BasicView() rootView = BasicView() viewController.view.addSubview(rootView) aView = BasicView() rootView.addSubview(aView) bView = BasicView() rootView.addSubview(bView) bViewChild = BasicView() bView.addSubview(bViewChild) rootView.frame = CGRect(x: 0, y: 0, width: 400, height: 400) aView.frame = CGRect(x: 140, y: 100, width: 200, height: 120) bView.frame = CGRect(x: 0, y: 0, width: 100, height: 50) bViewChild.frame = CGRect(x: 40, y: 10, width: 60, height: 20) } func setupWindow(with viewController: UIViewController) { window = UIWindow() window.rootViewController = viewController window.addSubview(viewController.view) window.makeKeyAndVisible(); // Testing UIViewController's layout methods is kind of bad // but needed in our case so we need to wait some time RunLoop.current.run(until: Date().addingTimeInterval(0.2)) } describe("Using pin.readableMargins") { it("test") { setupWindow(with: viewController) aView.pin.all(rootView.pin.readableMargins) #if os(iOS) expect(aView.frame).to(equal(CGRect(x: 8, y: 8, width: 384.0, height: 384.0))) #else expect(aView.frame).to(equal(CGRect(x: 98, y: 68, width: 294.0, height: 324.0))) #endif } } describe("Using pin.layoutMargins") { it("test") { setupWindow(with: viewController) aView.pin.all(rootView.pin.layoutMargins) #if os(iOS) expect(aView.frame).to(equal(CGRect(x: 8, y: 8, width: 384.0, height: 384.0))) #else expect(aView.frame).to(equal(CGRect(x: 98, y: 68, width: 294.0, height: 324.0))) #endif } } } }
mit
cb121f984737e7845effad246d9f31db
34.787037
96
0.576714
4.639856
false
false
false
false
wuyezhiguhun/DDSwift
DDSwift/内涵段子/Main/DDNeiHanTabBarController.swift
1
2679
// // DDNeiHanTabBarController.swift // DDSwift // // Created by 王允顶 on 17/7/1. // Copyright © 2017年 王允顶. All rights reserved. // import UIKit class DDNeiHanTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.setNavigation() self.getChildVc(viewController: DDNeiHanHomeViewController(), title: "首页", image: "home", selectedImage: "home_press") self.getChildVc(viewController: DDNeiHanBaseViewController(), title: "发现", image: "Found", selectedImage: "Found_press") self.getChildVc(viewController: DDNeiHanCheckViewController(), title: "审核", image: "audit", selectedImage: "audit_press") self.getChildVc(viewController: DDNeiHanMessageViewController(), title: "消息", image: "newstab", selectedImage: "newstab_press") // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setNavigation() -> Void { let leftImage = UIImage(named: "back_neihan")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: leftImage, style: UIBarButtonItemStyle.done, target: self, action:#selector(backTouch)) } func backTouch() -> Void { dismiss(animated: true, completion: nil) } override open class func initialize() ->Void { UITabBar.appearance().isTranslucent = false //RGBA(r: 0.97, g: 0.97, b: 0.97) UITabBar.appearance().tintColor = UIColor(red: 0.42, green: 0.33, blue: 0.27, alpha: 1.0) } func getChildVc(viewController: UIViewController,title: String,image: String,selectedImage: String) -> Void { let nav = UINavigationController(rootViewController: viewController) self.addChildViewController(nav) viewController.title = title viewController.tabBarItem.image = UIImage(named: image)?.withRenderingMode(UIImageRenderingMode.alwaysOriginal) viewController.tabBarItem.selectedImage = UIImage(named: selectedImage)?.withRenderingMode(UIImageRenderingMode.alwaysOriginal) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
aa847256a93c06e11208e23bc576a72f
36.295775
158
0.699773
4.629371
false
false
false
false
vkedwardli/SignalR-Swift
SignalR-Swift/Client/HeartbeatMonitor.swift
1
1819
// // HeartbeatMonitor.swift // SignalR-Swift // // // Copyright © 2017 Jordan Camara. All rights reserved. // import Foundation public final class HeartbeatMonitor { private(set) var hasBeenWarned = false private(set) var didTimeOut = false private var timer: WeakRefTimer? private unowned let connection: ConnectionProtocol init(withConnection connection: ConnectionProtocol) { self.connection = connection } func start() { self.connection.updateLastKeepAlive() self.hasBeenWarned = false self.didTimeOut = false if let interval = self.connection.keepAliveData?.checkInterval { timer = WeakRefTimer(withInterval: interval, repeats: true) { [weak self] in self?.heartBeat() } } } @objc func heartBeat() { guard let lastKeepAlive = connection.keepAliveData?.lastKeepAlive else { return } let timeElapsed = Date().timeIntervalSince(lastKeepAlive) self.beat(timeElapsed: timeElapsed) } func beat(timeElapsed: Double) { guard self.connection.state == .connected, let keepAlive = self.connection.keepAliveData else { return } if timeElapsed >= keepAlive.timeout { if !self.didTimeOut { self.didTimeOut = true self.connection.transport?.lostConnection(connection: self.connection) } } else if timeElapsed >= keepAlive.timeoutWarning { if !self.hasBeenWarned { self.hasBeenWarned = true self.connection.connectionDidSlow() } } else { self.hasBeenWarned = false self.didTimeOut = false } } func stop() { self.timer?.invalidate() self.timer = nil } }
mit
9e6bfd5a0d5d235880eaa7f6cb9e9943
27.857143
112
0.615512
4.746736
false
false
false
false
DaRkD0G/EasyHelper
EasyHelper/NSLayoutConstraintsExtensions.swift
1
2434
// // NSLayoutConstraints.swift // EasyHelper // // Created by DaRk-_-D0G on 09/10/2015. // Copyright © 2015 DaRk-_-D0G. All rights reserved. // import Foundation public extension NSLayoutConstraint { /** Apply Honrizontal constraint on View Contener with array of View - parameter viewContener: UIView - parameter views: [UIView] */ class func applyHorizontalConstraint(viewContener:UIView,views:[UIView]) { viewContener.translatesAutoresizingMaskIntoConstraints = false for (index, button) in views.enumerate() { let topConstraint = NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0) let bottomConstraint = NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0) let rightConstraint : NSLayoutConstraint! if index == 2 { rightConstraint = NSLayoutConstraint(item: button, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .Right, multiplier: 1.0, constant: 0) viewContener.addConstraint(rightConstraint) } let leftConstraint : NSLayoutConstraint! if index == 0 { leftConstraint = NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 0) } else { let prevtButton = views[index-1] leftConstraint = NSLayoutConstraint(item: button, attribute: .Left, relatedBy: .Equal, toItem: prevtButton, attribute: .Right, multiplier: 1.0, constant: 1) let firstButton = views[0] let widthConstraint = NSLayoutConstraint(item: firstButton, attribute: .Width, relatedBy: .Equal, toItem: button, attribute: .Width, multiplier: 1.0, constant: 1) widthConstraint.priority = 800 viewContener.addConstraint(widthConstraint) } viewContener.removeConstraints([topConstraint, bottomConstraint, leftConstraint]) viewContener.addConstraints([topConstraint, bottomConstraint, leftConstraint]) } } }
mit
7904de59f183892ea63d4af06dca41d2
43.254545
178
0.613646
5.079332
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/SellingPlanFixedPriceAdjustment.swift
1
3335
// // SellingPlanFixedPriceAdjustment.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// A fixed price adjustment for a variant that's purchased with a selling /// plan. open class SellingPlanFixedPriceAdjustmentQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = SellingPlanFixedPriceAdjustment /// A new price of the variant when it's purchased with the selling plan. @discardableResult open func price(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> SellingPlanFixedPriceAdjustmentQuery { let subquery = MoneyV2Query() subfields(subquery) addField(field: "price", aliasSuffix: alias, subfields: subquery) return self } } /// A fixed price adjustment for a variant that's purchased with a selling /// plan. open class SellingPlanFixedPriceAdjustment: GraphQL.AbstractResponse, GraphQLObject, SellingPlanPriceAdjustmentValue { public typealias Query = SellingPlanFixedPriceAdjustmentQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "price": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: SellingPlanFixedPriceAdjustment.self, field: fieldName, value: fieldValue) } return try MoneyV2(fields: value) default: throw SchemaViolationError(type: SellingPlanFixedPriceAdjustment.self, field: fieldName, value: fieldValue) } } /// A new price of the variant when it's purchased with the selling plan. open var price: Storefront.MoneyV2 { return internalGetPrice() } func internalGetPrice(alias: String? = nil) -> Storefront.MoneyV2 { return field(field: "price", aliasSuffix: alias) as! Storefront.MoneyV2 } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "price": response.append(internalGetPrice()) response.append(contentsOf: internalGetPrice().childResponseObjectMap()) default: break } } return response } } }
mit
81feab08f2790475e4ce2a76be87a390
36.47191
119
0.73913
4.107143
false
false
false
false
King-Wizard/GTNotification
GTNotification/GTNotificationManager.swift
1
25826
// // GTNotificationManager.swift // An in app notification banner for Swift. // // Release 1.4.3 // Solid red background + Exclamation mark symbol's image left aligned + Title left aligned + Message left aligned. // // Created by Mathieu White on 2015-06-20. // Modified by King-Wizard // Copyright (c) 2015 Mathieu White. All rights reserved. // import UIKit /// Identifies the position of the GTNotificationView when presented on the window public enum GTNotificationPosition: UInt { case Top case Bottom } /// Identifies the animation of the GTNotificationView when presenting public enum GTNotificationAnimation: UInt { case Fade case Slide } /** The GTNotificationViewDelegate protocol defines an optional method to receive user touches on objects. */ @objc public protocol GTNotificationViewDelegate: NSObjectProtocol { /** Tells the delegate the notification view was tapped. - parameter notificationView: the GTNotificationView object being tapped */ optional func notificationViewTapped(notificationView: GTNotificationView) } /** A GTNotificationView object specifies a GTNotification that can be displayed in the app on the key window. */ public class GTNotificationView: UIView { // MARK: - Constants /// The vertical padding of the GTNotificationView let verticalPadding: CGFloat = 20.0 /// The horizontal padding of the GTNotificationView let horizontalPadding: CGFloat = 20.0 /// The vertical spacing between the title and message labels let labelSpacing: CGFloat = 16.0 // MARK: - Variables /// Identifies if the GTNotificationView is visible or not var isVisible: Bool = false /// The title label of the GTNotificationView weak var titleLabel: UILabel? /// The message label of the GTNotificationView weak var messageLabel: UILabel? /// The image view of the GTNotificationView weak var imageView: UIImageView? override public var tintColor: UIColor? { didSet { self.titleLabel?.textColor = tintColor self.messageLabel?.textColor = tintColor self.imageView?.tintColor = tintColor } } /// The position of the GTNotificationView var position: GTNotificationPosition = GTNotificationPosition.Top /// The animation of the GTNotificationView public var animation: GTNotificationAnimation = GTNotificationAnimation.Fade /// The height of the GTNotificationView var notificationViewHeight: CGFloat? /// The visual blur effect for the notification view var blurView: UIVisualEffectView? /// The top layout constraint of the GTNotificationView var topConstraint: NSLayoutConstraint? /// The bottom layout constraint of the GTNotificationView var bottomConstraint: NSLayoutConstraint? /// The tap gesture that fires the action of the notification var tapGesture: UITapGestureRecognizer? /// The delegate of the GTNotificationView public weak var delegate: GTNotificationViewDelegate? // MARK: - Initialization required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.initNotificationView() } convenience init() { self.init(frame: CGRectZero) } func initNotificationView() { // Set the default properties of the GTNotificationView self.backgroundColor = UIColor.clearColor() self.alpha = 1.0 self.translatesAutoresizingMaskIntoConstraints = false // Initialize the title label for the notification view // let titleLabel: UILabel = UILabel() // titleLabel.font = UIFont.systemFontOfSize(16.0) // titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false) // Initialize the message label for the notification view let messageLabel: UILabel = UILabel() messageLabel.font = UIFont.systemFontOfSize(13.0) messageLabel.numberOfLines = 0 messageLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping messageLabel.translatesAutoresizingMaskIntoConstraints = false // Initialize the image view for the notification view let imageView: UIImageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false // Initialize the tap gesture // let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("notificationTapped")) // self.addGestureRecognizer(tapGesture) // Add the labels to the notification view // self.addSubview(titleLabel) self.addSubview(messageLabel) self.addSubview(imageView) // Set each label to their variable // self.titleLabel = titleLabel // titleLabel.textAlignment = NSTextAlignment.Center self.messageLabel = messageLabel self.messageLabel!.textAlignment = NSTextAlignment.Center self.imageView = imageView // self.tapGesture = tapGesture } // MARK: - Auto Layout /** This method will setup the constraints for the notification view. */ func setupConstraints() { if (self.blurView != nil) { // Layout the blur view vertically self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[_blur]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["_blur" : self.blurView!])) // Layout the blur view horizontally self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[_blur]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["_blur" : self.blurView!])) } if (self.imageView?.image != nil) { // Image Center Y self.addConstraint(NSLayoutConstraint(item: self.imageView!, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0)) // Image Left self.addConstraint(NSLayoutConstraint(item: self.imageView!, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: self.horizontalPadding)) // Image Width self.addConstraint(NSLayoutConstraint(item: self.imageView!, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 36.0)) // Image Height self.addConstraint(NSLayoutConstraint(item: self.imageView!, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 36.0)) } // // Title Label Top // self.addConstraint(NSLayoutConstraint(item: self.titleLabel!, // attribute: NSLayoutAttribute.Top, // relatedBy: NSLayoutRelation.Equal, // toItem: self, // attribute: NSLayoutAttribute.Top, // multiplier: 1.0, // constant: self.verticalPadding)) // // // Title Label Left // self.addConstraint(NSLayoutConstraint(item: self.titleLabel!, // attribute: NSLayoutAttribute.Left, // relatedBy: NSLayoutRelation.Equal, // toItem: (self.imageView?.image == nil) ? self : self.imageView!, // attribute: (self.imageView?.image == nil) ? NSLayoutAttribute.Left : NSLayoutAttribute.Right, // multiplier: 1.0, // constant: self.horizontalPadding)) // // // Title Label Right // self.addConstraint(NSLayoutConstraint(item: self.titleLabel!, // attribute: NSLayoutAttribute.Right, // relatedBy: NSLayoutRelation.Equal, // toItem: self, // attribute: NSLayoutAttribute.Right, // multiplier: 1.0, // constant: -self.horizontalPadding)) // Message Label Top self.addConstraint(NSLayoutConstraint(item: self.messageLabel!, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, // toItem: self.titleLabel!, toItem: self, // attribute: NSLayoutAttribute.Baseline, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0 )) // Message Label Left self.addConstraint(NSLayoutConstraint(item: self.messageLabel!, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, // toItem: self.titleLabel!, // attribute: NSLayoutAttribute.Left, toItem: self.imageView!, attribute: NSLayoutAttribute.Right, multiplier: 1.0, // constant: 0.0 constant: 10.0 )) // Message Label Right self.addConstraint(NSLayoutConstraint(item: self.messageLabel!, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, // toItem: self.titleLabel!, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1.0, // constant: 0.0 constant: -self.verticalPadding - 10 )) // Message Label Bottom self.addConstraint(NSLayoutConstraint(item: self.messageLabel!, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, // constant: -self.verticalPadding constant: 0.0 )) } /** This method will layout the notification view and add it to the key window of the application. */ func layoutNotificationViewInWindow() { // Get a reference of the application window let window: UIWindow? = UIApplication.sharedApplication().keyWindow // The application has a key window if let window = window { // Add the notification view to the window window.addSubview(self) // Calculate the height of the notification view self.notificationViewHeight = self.heightForNoticationView() // Views Dictionary var viewsDict = [String : AnyObject]() viewsDict["_view"] = self // Metrics Dictionary var metricsDict = [String : AnyObject]() metricsDict["_h"] = self.notificationViewHeight // Notification View Width let notificationHorizontalConstraints: [NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("H:|[_view]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: metricsDict, views: viewsDict) // Notification View Height let notificationVerticalConstraints: [NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("V:[_view(_h)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: metricsDict, views: viewsDict) // Notification View Top if (self.position == GTNotificationPosition.Top) { var topConstant: CGFloat = 0.0 if (self.animation == GTNotificationAnimation.Slide) { topConstant = -self.notificationViewHeight! } let topConstraint: NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: window, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: topConstant) window.addConstraint(topConstraint) self.topConstraint = topConstraint } // Notification View Bottom if (self.position == GTNotificationPosition.Bottom) { var bottomConstant: CGFloat = 0.0 if (self.animation == GTNotificationAnimation.Slide) { bottomConstant = self.notificationViewHeight! } let bottomConstraint: NSLayoutConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: window, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: bottomConstant) window.addConstraint(bottomConstraint) self.bottomConstraint = bottomConstraint } // Add the constraints to the window window.addConstraints(notificationVerticalConstraints) window.addConstraints(notificationHorizontalConstraints) // Layout the notification view self.layoutIfNeeded() self.titleLabel?.layoutIfNeeded() self.messageLabel?.layoutIfNeeded() } else { // No key window found assertionFailure("Warning: make sure to call makeKeyAndVisible on the application's window.") } } // MARK: - Instance Methods /** This method calculates and returns the height for the notification view. - returns: the height of the notification view */ func heightForNoticationView() -> CGFloat { // Determine the maximum with of our labels let maximumLabelWidth: CGFloat = CGRectGetWidth(UIScreen.mainScreen().bounds) - (self.horizontalPadding * 2.0) // Initialize our maximum label size let maximumLabelSize: CGSize = CGSizeMake(maximumLabelWidth, CGFloat.max) // Get the height of the title label // let titleLabelHeight: CGFloat = (self.titleLabel!.text! as NSString).boundingRectWithSize(maximumLabelSize, // options: NSStringDrawingOptions.UsesLineFragmentOrigin, // attributes: [NSFontAttributeName : self.titleLabel!.font], // context: nil).height // Get the height of the message label let messageLabelHeight: CGFloat = (self.messageLabel!.text! as NSString).boundingRectWithSize(maximumLabelSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName : self.messageLabel!.font], context: nil).height // Return the total height, (vertical top and bottom padding + label heights + label spacing) // return self.verticalPadding * 2.0 + titleLabelHeight + messageLabelHeight + self.labelSpacing return self.verticalPadding * 2.0 + messageLabelHeight + self.labelSpacing } /** This method applies the notification view's visual attributes. - parameter notification: the notification that will be displayed */ func prepareForNotification(notification: GTNotification) { self.tintColor = notification.tintColor // self.titleLabel?.text = notification.title self.messageLabel?.text = notification.message self.imageView?.image = notification.image self.position = notification.position self.animation = notification.animation // Get the font for the title label if (notification.delegate?.respondsToSelector(Selector("notificationFontForTitleLabel:")) == true) { self.titleLabel?.font = notification.delegate!.notificationFontForTitleLabel!(notification) } // Get the font for the message label if (notification.delegate?.respondsToSelector(Selector("notificationFontForMessageLabel:")) == true) { self.messageLabel?.font = notification.delegate!.notificationFontForMessageLabel!(notification) } if (notification.blurEnabled == true) { self.backgroundColor = UIColor.clearColor() // Add the blur effect to the notification view let blurEffect: UIBlurEffect = UIBlurEffect(style: notification.blurEffectStyle!) let blurView: UIVisualEffectView = UIVisualEffectView(effect: blurEffect) blurView.translatesAutoresizingMaskIntoConstraints = false self.insertSubview(blurView, atIndex: 0) self.blurView = blurView } else { self.backgroundColor = notification.backgroundColor } // Set the initial alpha to 0.0 for the fade animation if (self.animation == GTNotificationAnimation.Fade) { self.alpha = 0.0 } else { // self.alpha = 1.0 self.alpha = 0.95 } // Layout the view's subviews self.setupConstraints() // Layout the view in the window self.layoutNotificationViewInWindow() } /** This method animates the notification view on the application's window - parameter show: true if the notification view will dismiss, false otherwise - parameter completion: the completion closure to execute after the animation */ func animateNotification(willShow show: Bool, completion: (finished: Bool) -> Void) { // Set the animation view's visibility self.isVisible = show // The notification view should animate with a fade if (self.animation == GTNotificationAnimation.Fade) { UIView.animateWithDuration(0.4, animations: { self.alpha = (show == true) ? 1.0 : 0.0 }, completion: { (finished) -> Void in completion(finished: finished) }) } // The notification view should animate with a slide if (self.animation == GTNotificationAnimation.Slide) { if (self.position == GTNotificationPosition.Top) { self.topConstraint?.constant = (show == true) ? 0.0 : -self.notificationViewHeight! } else { self.bottomConstraint?.constant = (show == true) ? 0.0 : self.notificationViewHeight! } UIView.animateWithDuration(0.4, animations: { self.layoutIfNeeded() }, completion: {(finished) -> Void in completion(finished: finished) }) } } // MARK: - Gesture Recognizer Methods /** This method fires when the notification view is tapped. NOTE: Tapping the notification view will dismiss it immediately. */ @objc private func notificationTapped() { // Notify the delegate that the notification view was tapped if (self.delegate?.respondsToSelector(Selector("notificationViewTapped:")) == true) { self.delegate!.notificationViewTapped!(self) } } } public class GTNotificationManager: NSObject, GTNotificationViewDelegate { // MARK: - Variables /// The singleton instance of the GTNotificationManager public static var sharedInstance: GTNotificationManager = GTNotificationManager() /// The private array of notifications queued for display private var mutableNotifications: [GTNotification] = [] /// The current notification view being displayed private var currentNotificationView: GTNotificationView? /// The timer that fires the scheduled dismissal of the notification private var dismissalTimer: NSTimer? // MARK: - Read Only /// The array of notifications queued for display internal var notifications: [GTNotification] { get { let immutableNotifications = self.mutableNotifications return immutableNotifications } } // MARK: - Initializers override init() { super.init() } // MARK: - Instance Methods /** This method shows the notification on the application's window. - parameter notification: the notification to display */ public func showNotification(notification: GTNotification) { // Only show one notification at a time if (self.currentNotificationView == nil) { // Queue the notification for display self.mutableNotifications.append(notification) // Initialize a GTNotificationView let notificationView: GTNotificationView = GTNotificationView() notificationView.delegate = self // Prepare the view for the notification to display notificationView.prepareForNotification(notification) // Animate the notification notificationView.animateNotification(willShow: true, completion: {(finished: Bool) -> Void in if !notification.isDurationUnlimited { // Schedule the notification view's dismissal self.dismissalTimer = NSTimer.scheduledTimerWithTimeInterval(notification.duration, target: self, selector: Selector("dismissCurrentNotification:"), userInfo: notification, repeats: false) } }) // Set the current notification self.currentNotificationView = notificationView } } /** This method dismissed the current notification on the application's window. */ @objc private func dismissCurrentNotification(timer: NSTimer?) { let notification: GTNotification? = timer?.userInfo as? GTNotification self.dismissalTimer?.invalidate() self.dismissalTimer = nil if let notificationView = self.currentNotificationView { // Animate the notification notificationView.animateNotification(willShow: false, completion: {(finished: Bool) -> Void in // Notify the delegate of the notification's dismissal if let notification = notification { if (notification.delegate?.respondsToSelector(Selector("notificationDidDismiss:")) == true) { notification.delegate!.notificationDidDismiss!(notification) } } notificationView.removeFromSuperview() self.currentNotificationView = nil }) } } /** This method dismissed the current notification on the application's window. Custom method added by King Wizard. */ public func dismissCurrentNotification() { if let notificationView = self.currentNotificationView { self.dismissalTimer?.invalidate() self.dismissalTimer = nil // Animate the notification notificationView.animateNotification(willShow: false, completion: { (finished: Bool) -> Void in notificationView.removeFromSuperview() self.currentNotificationView = nil }) } } // MARK: - GTNotificationViewDelegate Methods @objc public func notificationViewTapped(notificationView: GTNotificationView) { let notification = self.mutableNotifications.removeAtIndex(0) self.dismissCurrentNotification(nil) if let target: AnyObject = notification.target, let action = notification.action { if (target.respondsToSelector(action) == true) { dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), { NSThread.detachNewThreadSelector(action, toTarget: target, withObject: nil) }) } } } }
mit
a1826b238ea1b45bd35bf1b9964ceaf6
35.738265
135
0.589483
5.978241
false
false
false
false
Mobelux/MONK
MONK/Internal/Classes/MutableDownloadTask.swift
1
4372
// // MutableDownloadTask.swift // MONK // // MIT License // // Copyright (c) 2017 Mobelux // // 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 /// A `DownloadTask` that allows it's `result` and `downloadProgress` to be mutated, so that we can update a task as it recieves the file final class MutableDownloadTask: DownloadTask, CompletableTask { let downloadRequest: DownloadRequestType let downloadTask: URLSessionDownloadTask var result: DownloadTaskResult? var cache: Cache var downloadProgress: BytesProgress? var progressHandlers: [BytesProgressHandler] = [] var completionHandlers: [DownloadCompletionHandler] = [] init(request: DownloadRequestType, task: URLSessionDownloadTask, cache: Cache) { downloadRequest = request downloadTask = task self.cache = cache } func addProgress(handler: @escaping BytesProgressHandler) { progressHandlers.append(handler) } func addCompletion(handler: @escaping DownloadCompletionHandler) { completionHandlers.append(handler) } /** Finalize moving the just downloaded file from the session's temporary location, to the `downloadRequest.localURL` This should be called from `urlSession(_, downloadTask:, didFinishDownloadingTo location)` - parameter url: The temporary `URL` that the session downloaded the file to */ func didFinishDownloading(to url: URL) { do { // incoming URL is a temporary location decided by URLSession. We have to move it to our final destination before the end of `urlSession(_, downloadTask:, didFinishDownloadingTo location)` or else the system will delete it out from under us if FileManager.default.fileExists(atPath: downloadRequest.localURL.path) { let _ = try? FileManager.default.removeItem(at: downloadRequest.localURL) } try FileManager.default.moveItem(at: url, to: downloadRequest.localURL) } catch let error as NSError { self.result = .failure(error: error) } } func didComplete(statusCode: Int?, error: Error?, cachedResponse: Bool) { // Download tasks aren't cached guard !cachedResponse else { return } let taskResult: DownloadTaskResult = { if let existingResult = self.result { // We could already have a failure result from trying to move the file from the temp URL to the localURL. If we do, preserve that result/error. return existingResult } else if let statusCode = statusCode { return .success(statusCode: statusCode, localURL: downloadRequest.localURL) } else { return .failure(error: error) } }() result = taskResult completionHandlers.forEach { $0(taskResult) } removeHandlers() } func cancel() { downloadTask.cancel() completionHandlers.forEach { $0(.failure(error: nil)) } removeHandlers() let _ = try? FileManager.default.removeItem(at: downloadRequest.localURL) } private func removeHandlers() { progressHandlers.removeAll() completionHandlers.removeAll() } }
mit
0d1f182f467db075ed038bc3894c7cc0
39.859813
252
0.678408
5.008018
false
false
false
false
TonnyTao/HowSwift
how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Sample.swift
8
4564
// // Sample.swift // RxSwift // // Created by Krunoslav Zaher on 5/1/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Samples the source observable sequence using a sampler observable sequence producing sampling ticks. Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. **In case there were no new elements between sampler ticks, you may provide a default value to be emitted, instead to the resulting sequence otherwise no element is sent.** - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) - parameter sampler: Sampling tick sequence. - parameter defaultValue: a value to return if there are no new elements between sampler ticks - returns: Sampled observable sequence. */ public func sample<Source: ObservableType>(_ sampler: Source, defaultValue: Element? = nil) -> Observable<Element> { return Sample(source: self.asObservable(), sampler: sampler.asObservable(), defaultValue: defaultValue) } } final private class SamplerSink<Observer: ObserverType, SampleType> : ObserverType , LockOwnerType , SynchronizedOnType { typealias Element = SampleType typealias Parent = SampleSequenceSink<Observer, SampleType> private let parent: Parent var lock: RecursiveLock { self.parent.lock } init(parent: Parent) { self.parent = parent } func on(_ event: Event<Element>) { self.synchronizedOn(event) } func synchronized_on(_ event: Event<Element>) { switch event { case .next, .completed: if let element = parent.element ?? self.parent.defaultValue { self.parent.element = nil self.parent.forwardOn(.next(element)) } if self.parent.atEnd { self.parent.forwardOn(.completed) self.parent.dispose() } case .error(let e): self.parent.forwardOn(.error(e)) self.parent.dispose() } } } final private class SampleSequenceSink<Observer: ObserverType, SampleType> : Sink<Observer> , ObserverType , LockOwnerType , SynchronizedOnType { typealias Element = Observer.Element typealias Parent = Sample<Element, SampleType> fileprivate let parent: Parent fileprivate let defaultValue: Element? let lock = RecursiveLock() // state fileprivate var element = nil as Element? fileprivate var atEnd = false private let sourceSubscription = SingleAssignmentDisposable() init(parent: Parent, observer: Observer, cancel: Cancelable, defaultValue: Element? = nil) { self.parent = parent self.defaultValue = defaultValue super.init(observer: observer, cancel: cancel) } func run() -> Disposable { self.sourceSubscription.setDisposable(self.parent.source.subscribe(self)) let samplerSubscription = self.parent.sampler.subscribe(SamplerSink(parent: self)) return Disposables.create(sourceSubscription, samplerSubscription) } func on(_ event: Event<Element>) { self.synchronizedOn(event) } func synchronized_on(_ event: Event<Element>) { switch event { case .next(let element): self.element = element case .error: self.forwardOn(event) self.dispose() case .completed: self.atEnd = true self.sourceSubscription.dispose() } } } final private class Sample<Element, SampleType>: Producer<Element> { fileprivate let source: Observable<Element> fileprivate let sampler: Observable<SampleType> fileprivate let defaultValue: Element? init(source: Observable<Element>, sampler: Observable<SampleType>, defaultValue: Element? = nil) { self.source = source self.sampler = sampler self.defaultValue = defaultValue } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel, defaultValue: self.defaultValue) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
4c0ae41b424985e8063720643d0dfb30
31.827338
171
0.655928
4.981441
false
false
false
false
gerlandiolucena/iosvisits
iOSVisits/iOSVisits/Controller/PlaceListViewController.swift
1
1913
// // PlaceListViewController.swift // iOSVisits // // Created by Gerlandio da Silva Lucena on 6/3/16. // Copyright © 2016 ZAP Imóveis. All rights reserved. // import Foundation import UIKit import RealmSwift class PlaceListViewController: UITableViewController { var places: Results<MyPlaces>? var arrayList = [MyPlaces]() override func viewDidLoad() { let realm = try! Realm() places = realm.objects(MyPlaces.self) arrayList = [MyPlaces]() if let places = places { for place in places { arrayList.append(place) } } } override func viewDidAppear(_ animated: Bool) { tableView.contentInset = UIEdgeInsetsMake(40.0, 0.0, 0.0, 0.0) tableView.reloadData() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "default", for: indexPath) if let defaultCell = cell as? Default { let formatter = DateFormatter() formatter.dateFormat = "dd/MM/YYYY" let formatterTime = DateFormatter() formatterTime.dateFormat = "hh:mm:ss" defaultCell.title.text = formatter.string(from: arrayList[indexPath.row].chegada as Date) defaultCell.arrived.text = "Chegada ás \(formatterTime.string(from: arrayList[indexPath.row].chegada as Date))" defaultCell.departure.text = "Saída ás \(formatterTime.string(from: arrayList[indexPath.row].saida as Date))" return defaultCell } return cell } }
gpl-3.0
16e0379f01230471b555a623c0fdc280
31.896552
123
0.635744
4.457944
false
false
false
false
jackchmbrln/FormKit
FormKit/FKFormView.swift
1
8080
// // FKView.swift // FormKit // // Created by Jack Chamberlain on 01/07/2016. // Copyright © 2016 Off Piste. All rights reserved. // import UIKit public class FKFormView: UIView { // TODO: Specify return button // TODO: Figure out and write way of allowing users to add custom cells with custom actions // MARK: Definitions // Form sections public var sections: Array<FKFormSection>? // MARK: Modifiers // A list of variables that can be set to alter the behaviour of the form public var autoReturn = true // MARK: Value variable // Get only property that returns an array of all of the currently set field values // Returns an array of only the stored values // Can be nil // Loops through the form sections and form fields to retrieve all of the non nil values // TODO: Fix auto correct bug with values public var values: [String?]? { get { var array = [String?]() guard let sections = self.sections else { return nil } for section in sections { guard let fields = section.fields else { return nil } for field in fields { if let value = field.value { array.append(value) } } } return array } } // MARK: Form view style // Defines any custom styling for the font if it is set by the user // Otherwise it will just revert to default values // Refresh the table view when a new style is set public var style = FKFormFieldStyle() { didSet { self.reloadForm() } } // MARK: Private variables // Table view private var tableView: UITableView! // Disabled cells // Maintains an array of all cells that are disabled private var disabledCells: [NSIndexPath]? // MARK: Optional init // Initialise a new FKFormView and return it public class func newForm() -> FKFormView { return FKFormView() } // Initialise a form with section and return it // If the fields and sections for the form have already been defined then they can be added // at the time of initialisation public class func newForm(withSections sections: Array<FKFormSection>) -> FKFormView { let form = FKFormView() form.sections = sections return form } // MARK: Awake from nib override public func awakeFromNib() { super.awakeFromNib() self.buildTableView() } // MARK: Draw rect override public func drawRect(rect: CGRect) { super.drawRect(rect) self.buildTableView() } // MARK: Create table view // Initialise the table view and add it to the view private func buildTableView() -> Void { self.tableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Grouped) self.tableView.register(FKFormTableViewCell) self.tableView.register(FKNamedHeaderTableViewCell) self.tableView.dataSource = self self.tableView.delegate = self // Add the table view with constraints let views = ["table": self.tableView] self.tableView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(self.tableView) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[table]|", options: [], metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[table]|", options: [], metrics: nil, views: views)) } // MARK: Append section to form // Adding a new section to the form will cause the form to reload public func addSection(section: FKFormSection) { self.sections?.append(section) } // MARK: Add row to section } // MARK: UITableViewDataSource extension FKFormView: UITableViewDataSource { // MARK: Number of sections in table view public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.sections?.count ?? 1 } // MARK: Number of rows in section public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.sections?[section].fields?.count ?? 1 } // MARK: Cell for row at index path public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = FKFormTableViewCell() guard let fkField = self.sections?[indexPath.section].fields?[indexPath.row] else { return cell } cell.setCell(withField: fkField) cell.indexPath = indexPath cell.delegate = self cell.applyStyle(self.style) if let disabled = self.disabledCells { if disabled.contains(indexPath) { cell.disabled = true } else { cell.disabled = false } } return cell } // MARK: Table view headers // MARK: View for header in section public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let sectionName = self.sections?[section].sectionName else { return nil } if sectionName == "" { return nil } let namedHeader = FKNamedHeaderTableViewCell() namedHeader.setTitle(sectionName) return namedHeader } // MARK: Height for header public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let sectionName = self.sections?[section].sectionName else { return 20.0 } if sectionName == "" { return 20.0 } return 35.0 } // MARK: Change text for cell // Supply the index path of the cell that needs to be altered public func changeValue(forIndexPath indexPath: NSIndexPath, newValue: String) { self.sections?[indexPath.section].fields?[indexPath.row].value = newValue guard let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? FKFormTableViewCell else { return } cell.textField.text = newValue } // MARK: Enable cell public func enableField(forIndexPath indexPath: NSIndexPath) { guard let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? FKFormTableViewCell else { return } cell.disabled = false if self.disabledCells != nil { self.disabledCells!.removeObject(indexPath) } return } // MARK: Disable cell public func disableField(forIndexPath indexPath: NSIndexPath) { guard let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? FKFormTableViewCell else { return } cell.disabled = true if self.disabledCells != nil { self.disabledCells!.append(indexPath) } else { self.disabledCells = [indexPath] } } // MARK: Reload form // Reload the entire form public func reloadForm() { self.tableView.reloadData() } } // MARK: FKFormFieldTableViewCellDelegate extension FKFormView: FKFormTableViewCellDelegate { func fk_textFieldDidChange(withIndexPath indexPath: NSIndexPath, text: String) { self.sections?[indexPath.section].fields?[indexPath.row].value = text } } extension FKFormView: UITableViewDelegate {} // MARK: Remove object from array extension RangeReplaceableCollectionType where Generator.Element : Equatable { // Remove first collection element that is equal to the given `object`: mutating func removeObject(object : Generator.Element) { if let index = self.indexOf(object) { self.removeAtIndex(index) } } }
mit
9c1bda1de5a3c2cd3251333723756b36
28.922222
131
0.621116
5.123018
false
false
false
false
JakubTudruj/SweetCherry
SweetCherryExample/SweetCherryExample/Logger.swift
1
1797
// // Log.swift // SweetCherryExample // // Created by Jakub Tudruj on 19/02/2017. // Copyright © 2017 Jakub Tudruj. All rights reserved. // import UIKit import CocoaLumberjack import Alamofire import SweetCherry //TODO: add headers logs class Log: SweetCherryLoggable { static let shared = Log() private init() {} func apiRequest(_ message: Any, requestType: HTTPMethod, action: String) { Log.shared.api(message, requestType: requestType, action: action, prefix: "🔵") } func apiSuccess(_ message: Any, requestType: HTTPMethod, action: String) { Log.shared.api(message, requestType: requestType, action: action, prefix: "✅") } func apiFailure(_ message: Any, error: Error, requestType: HTTPMethod, action: String) { Log.shared.api("\(error)\n======\n\(message)", requestType: requestType, action: action, prefix: "🔴") } func api(_ message: Any, requestType: HTTPMethod? = nil, action: String? = nil, prefix: String = "🔵") { var m = "\n\(message)" if let a = action { m = "\(a)\(m)" } if let r = requestType { m = "\("\(r)".uppercased()) \(m)" } Log.shared.info(m, prefix: prefix, level: .debug) } func error(_ message: String) { Log.shared.info(message, prefix: "💔", level: .warning) } func info(_ message: String, prefix: String = "💛", level: DDLogLevel = .verbose) { let m = "\(prefix) \(message)" switch level { case .error: DDLogError(m) case .warning: DDLogWarn(m) case .info: DDLogInfo(m) case .debug: DDLogDebug(m) default: DDLogVerbose(m) } } }
mit
a4c7b78eafc09245aa4559a9bdb5d024
27.238095
109
0.5638
4.061644
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/FoundationDateComponentsTests.swift
1
37363
import XCTest import GRDB class FoundationDateComponentsTests : GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createDates") { db in try db.execute(sql: """ CREATE TABLE dates ( ID INTEGER PRIMARY KEY, creationDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP) """) } try migrator.migrate(dbWriter) } func testDatabaseDateComponentsFormatHM() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var dateComponents = DateComponents() dateComponents.year = 1973 dateComponents.month = 9 dateComponents.day = 18 dateComponents.hour = 10 dateComponents.minute = 11 dateComponents.second = 12 dateComponents.nanosecond = 123_456_789 try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: [DatabaseDateComponents(dateComponents, format: .HM)]) let string = try String.fetchOne(db, sql: "SELECT creationDate from dates")! XCTAssertEqual(string, "10:11") let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.HM) XCTAssertTrue(databaseDateComponents.dateComponents.year == nil) XCTAssertTrue(databaseDateComponents.dateComponents.month == nil) XCTAssertTrue(databaseDateComponents.dateComponents.day == nil) XCTAssertEqual(databaseDateComponents.dateComponents.hour, dateComponents.hour) XCTAssertEqual(databaseDateComponents.dateComponents.minute, dateComponents.minute) XCTAssertTrue(databaseDateComponents.dateComponents.second == nil) XCTAssertTrue(databaseDateComponents.dateComponents.nanosecond == nil) } } func testDatabaseDateComponentsFormatHMS() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var dateComponents = DateComponents() dateComponents.year = 1973 dateComponents.month = 9 dateComponents.day = 18 dateComponents.hour = 10 dateComponents.minute = 11 dateComponents.second = 12 dateComponents.nanosecond = 123_456_789 try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: [DatabaseDateComponents(dateComponents, format: .HMS)]) let string = try String.fetchOne(db, sql: "SELECT creationDate from dates")! XCTAssertEqual(string, "10:11:12") let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.HMS) XCTAssertTrue(databaseDateComponents.dateComponents.year == nil) XCTAssertTrue(databaseDateComponents.dateComponents.month == nil) XCTAssertTrue(databaseDateComponents.dateComponents.day == nil) XCTAssertEqual(databaseDateComponents.dateComponents.hour, dateComponents.hour) XCTAssertEqual(databaseDateComponents.dateComponents.minute, dateComponents.minute) XCTAssertEqual(databaseDateComponents.dateComponents.second, dateComponents.second) XCTAssertTrue(databaseDateComponents.dateComponents.nanosecond == nil) } } func testDatabaseDateComponentsFormatHMSS() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var dateComponents = DateComponents() dateComponents.year = 1973 dateComponents.month = 9 dateComponents.day = 18 dateComponents.hour = 10 dateComponents.minute = 11 dateComponents.second = 12 dateComponents.nanosecond = 123_456_789 try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: [DatabaseDateComponents(dateComponents, format: .HMSS)]) let string = try String.fetchOne(db, sql: "SELECT creationDate from dates")! XCTAssertEqual(string, "10:11:12.123") let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.HMSS) XCTAssertTrue(databaseDateComponents.dateComponents.year == nil) XCTAssertTrue(databaseDateComponents.dateComponents.month == nil) XCTAssertTrue(databaseDateComponents.dateComponents.day == nil) XCTAssertEqual(databaseDateComponents.dateComponents.hour, dateComponents.hour) XCTAssertEqual(databaseDateComponents.dateComponents.minute, dateComponents.minute) XCTAssertEqual(databaseDateComponents.dateComponents.second, dateComponents.second) XCTAssertEqual(round(Double(databaseDateComponents.dateComponents.nanosecond!) / 1.0e6), round(Double(dateComponents.nanosecond!) / 1.0e6)) } } func testDatabaseDateComponentsFormatYMD() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var dateComponents = DateComponents() dateComponents.year = 1973 dateComponents.month = 9 dateComponents.day = 18 dateComponents.hour = 10 dateComponents.minute = 11 dateComponents.second = 12 dateComponents.nanosecond = 123_456_789 try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: [DatabaseDateComponents(dateComponents, format: .YMD)]) let string = try String.fetchOne(db, sql: "SELECT creationDate from dates")! XCTAssertEqual(string, "1973-09-18") let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.YMD) XCTAssertEqual(databaseDateComponents.dateComponents.year, dateComponents.year) XCTAssertEqual(databaseDateComponents.dateComponents.month, dateComponents.month) XCTAssertEqual(databaseDateComponents.dateComponents.day, dateComponents.day) XCTAssertTrue(databaseDateComponents.dateComponents.hour == nil) XCTAssertTrue(databaseDateComponents.dateComponents.minute == nil) XCTAssertTrue(databaseDateComponents.dateComponents.second == nil) XCTAssertTrue(databaseDateComponents.dateComponents.nanosecond == nil) } } func testDatabaseDateComponentsFormatYMD_HM() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var dateComponents = DateComponents() dateComponents.year = 1973 dateComponents.month = 9 dateComponents.day = 18 dateComponents.hour = 10 dateComponents.minute = 11 dateComponents.second = 12 dateComponents.nanosecond = 123_456_789 try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: [DatabaseDateComponents(dateComponents, format: .YMD_HM)]) let string = try String.fetchOne(db, sql: "SELECT creationDate from dates")! XCTAssertEqual(string, "1973-09-18 10:11") let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.YMD_HM) XCTAssertEqual(databaseDateComponents.dateComponents.year, dateComponents.year) XCTAssertEqual(databaseDateComponents.dateComponents.month, dateComponents.month) XCTAssertEqual(databaseDateComponents.dateComponents.day, dateComponents.day) XCTAssertEqual(databaseDateComponents.dateComponents.hour, dateComponents.hour) XCTAssertEqual(databaseDateComponents.dateComponents.minute, dateComponents.minute) XCTAssertTrue(databaseDateComponents.dateComponents.second == nil) XCTAssertTrue(databaseDateComponents.dateComponents.nanosecond == nil) } } func testDatabaseDateComponentsFormatYMD_HMS() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var dateComponents = DateComponents() dateComponents.year = 1973 dateComponents.month = 9 dateComponents.day = 18 dateComponents.hour = 10 dateComponents.minute = 11 dateComponents.second = 12 dateComponents.nanosecond = 123_456_789 try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: [DatabaseDateComponents(dateComponents, format: .YMD_HMS)]) let string = try String.fetchOne(db, sql: "SELECT creationDate from dates")! XCTAssertEqual(string, "1973-09-18 10:11:12") let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.YMD_HMS) XCTAssertEqual(databaseDateComponents.dateComponents.year, dateComponents.year) XCTAssertEqual(databaseDateComponents.dateComponents.month, dateComponents.month) XCTAssertEqual(databaseDateComponents.dateComponents.day, dateComponents.day) XCTAssertEqual(databaseDateComponents.dateComponents.hour, dateComponents.hour) XCTAssertEqual(databaseDateComponents.dateComponents.minute, dateComponents.minute) XCTAssertEqual(databaseDateComponents.dateComponents.second, dateComponents.second) XCTAssertTrue(databaseDateComponents.dateComponents.nanosecond == nil) } } func testDatabaseDateComponentsFormatYMD_HMSS() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var dateComponents = DateComponents() dateComponents.year = 1973 dateComponents.month = 9 dateComponents.day = 18 dateComponents.hour = 10 dateComponents.minute = 11 dateComponents.second = 12 dateComponents.nanosecond = 123_456_789 try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: [DatabaseDateComponents(dateComponents, format: .YMD_HMSS)]) let string = try String.fetchOne(db, sql: "SELECT creationDate from dates")! XCTAssertEqual(string, "1973-09-18 10:11:12.123") let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.YMD_HMSS) XCTAssertEqual(databaseDateComponents.dateComponents.year, dateComponents.year) XCTAssertEqual(databaseDateComponents.dateComponents.month, dateComponents.month) XCTAssertEqual(databaseDateComponents.dateComponents.day, dateComponents.day) XCTAssertEqual(databaseDateComponents.dateComponents.hour, dateComponents.hour) XCTAssertEqual(databaseDateComponents.dateComponents.minute, dateComponents.minute) XCTAssertEqual(databaseDateComponents.dateComponents.second, dateComponents.second) XCTAssertEqual(round(Double(databaseDateComponents.dateComponents.nanosecond!) / 1.0e6), round(Double(dateComponents.nanosecond!) / 1.0e6)) } } func testUndefinedDatabaseDateComponentsFormatYMD_HMSS() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let dateComponents = DateComponents() try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: [DatabaseDateComponents(dateComponents, format: .YMD_HMSS)]) let string = try String.fetchOne(db, sql: "SELECT creationDate from dates")! XCTAssertEqual(string, "0000-01-01 00:00:00.000") let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.YMD_HMSS) XCTAssertEqual(databaseDateComponents.dateComponents.year, 0) XCTAssertEqual(databaseDateComponents.dateComponents.month, 1) XCTAssertEqual(databaseDateComponents.dateComponents.day, 1) XCTAssertEqual(databaseDateComponents.dateComponents.hour, 0) XCTAssertEqual(databaseDateComponents.dateComponents.minute, 0) XCTAssertEqual(databaseDateComponents.dateComponents.second, 0) XCTAssertEqual(databaseDateComponents.dateComponents.nanosecond, 0) } } func testDatabaseDateComponentsFormatIso8601YMD_HM() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var dateComponents = DateComponents() dateComponents.year = 1973 dateComponents.month = 9 dateComponents.day = 18 dateComponents.hour = 10 dateComponents.minute = 11 dateComponents.second = 12 dateComponents.nanosecond = 123_456_789 try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: ["1973-09-18T10:11"]) let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.YMD_HM) XCTAssertEqual(databaseDateComponents.dateComponents.year, dateComponents.year) XCTAssertEqual(databaseDateComponents.dateComponents.month, dateComponents.month) XCTAssertEqual(databaseDateComponents.dateComponents.day, dateComponents.day) XCTAssertEqual(databaseDateComponents.dateComponents.hour, dateComponents.hour) XCTAssertEqual(databaseDateComponents.dateComponents.minute, dateComponents.minute) XCTAssertTrue(databaseDateComponents.dateComponents.second == nil) XCTAssertTrue(databaseDateComponents.dateComponents.nanosecond == nil) } } func testDatabaseDateComponentsFormatIso8601YMD_HMS() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var dateComponents = DateComponents() dateComponents.year = 1973 dateComponents.month = 9 dateComponents.day = 18 dateComponents.hour = 10 dateComponents.minute = 11 dateComponents.second = 12 dateComponents.nanosecond = 123_456_789 try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: ["1973-09-18T10:11:12"]) let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.YMD_HMS) XCTAssertEqual(databaseDateComponents.dateComponents.year, dateComponents.year) XCTAssertEqual(databaseDateComponents.dateComponents.month, dateComponents.month) XCTAssertEqual(databaseDateComponents.dateComponents.day, dateComponents.day) XCTAssertEqual(databaseDateComponents.dateComponents.hour, dateComponents.hour) XCTAssertEqual(databaseDateComponents.dateComponents.minute, dateComponents.minute) XCTAssertEqual(databaseDateComponents.dateComponents.second, dateComponents.second) XCTAssertTrue(databaseDateComponents.dateComponents.nanosecond == nil) } } func testDatabaseDateComponentsFormatIso8601YMD_HMSS() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var dateComponents = DateComponents() dateComponents.year = 1973 dateComponents.month = 9 dateComponents.day = 18 dateComponents.hour = 10 dateComponents.minute = 11 dateComponents.second = 12 dateComponents.nanosecond = 123_456_789 try db.execute(sql: "INSERT INTO dates (creationDate) VALUES (?)", arguments: ["1973-09-18T10:11:12.123"]) let databaseDateComponents = try DatabaseDateComponents.fetchOne(db, sql: "SELECT creationDate FROM dates")! XCTAssertEqual(databaseDateComponents.format, DatabaseDateComponents.Format.YMD_HMSS) XCTAssertEqual(databaseDateComponents.dateComponents.year, dateComponents.year) XCTAssertEqual(databaseDateComponents.dateComponents.month, dateComponents.month) XCTAssertEqual(databaseDateComponents.dateComponents.day, dateComponents.day) XCTAssertEqual(databaseDateComponents.dateComponents.hour, dateComponents.hour) XCTAssertEqual(databaseDateComponents.dateComponents.minute, dateComponents.minute) XCTAssertEqual(databaseDateComponents.dateComponents.second, dateComponents.second) XCTAssertEqual(round(Double(databaseDateComponents.dateComponents.nanosecond!) / 1.0e6), round(Double(dateComponents.nanosecond!) / 1.0e6)) } } func testFormatYMD_HMSIsLexicallyComparableToCURRENT_TIMESTAMP() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var calendar = Calendar(identifier: .gregorian) calendar.timeZone = TimeZone(secondsFromGMT: 0)! do { let date = Date().addingTimeInterval(-1) let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) try db.execute( sql: "INSERT INTO dates (id, creationDate) VALUES (?,?)", arguments: [1, DatabaseDateComponents(dateComponents, format: .YMD_HMS)]) } do { try db.execute( sql: "INSERT INTO dates (id) VALUES (?)", arguments: [2]) } do { let date = Date().addingTimeInterval(1) let dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) try db.execute( sql: "INSERT INTO dates (id, creationDate) VALUES (?,?)", arguments: [3, DatabaseDateComponents(dateComponents, format: .YMD_HMS)]) } let ids = try Int.fetchAll(db, sql: "SELECT id FROM dates ORDER BY creationDate") XCTAssertEqual(ids, [1,2,3]) } } func testDatabaseDateComponentsParsing() { func assertParse(_ string: String, _ dateComponent: DatabaseDateComponents, file: StaticString = #file, line: UInt = #line) { do { // Test DatabaseValueConvertible adoption guard let parsed = DatabaseDateComponents.fromDatabaseValue(string.databaseValue) else { XCTFail("Could not parse \(String(reflecting: string))", file: file, line: line) return } XCTAssertEqual(parsed.format, dateComponent.format, file: file, line: line) XCTAssertEqual(parsed.dateComponents, dateComponent.dateComponents, file: file, line: line) } do { // Test StatementColumnConvertible adoption guard let parsed = try? DatabaseQueue().inDatabase({ try DatabaseDateComponents.fetchOne($0, sql: "SELECT ?", arguments: [string]) }) else { XCTFail("Could not parse \(String(reflecting: string))", file: file, line: line) return } XCTAssertEqual(parsed.format, dateComponent.format, file: file, line: line) XCTAssertEqual(parsed.dateComponents, dateComponent.dateComponents, file: file, line: line) } } assertParse( "0000-01-01", DatabaseDateComponents( DateComponents(year: 0, month: 1, day: 1, hour: nil, minute: nil, second: nil, nanosecond: nil), format: .YMD)) assertParse( "2018-12-31", DatabaseDateComponents( DateComponents(year: 2018, month: 12, day: 31, hour: nil, minute: nil, second: nil, nanosecond: nil), format: .YMD)) assertParse( "2018-04-21 00:00", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: nil, nanosecond: nil), format: .YMD_HM)) assertParse( "2018-04-21 00:00Z", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: nil, nanosecond: nil), format: .YMD_HM)) assertParse( "2018-04-21 00:00+00:00", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: nil, nanosecond: nil), format: .YMD_HM)) assertParse( "2018-04-21 00:00-00:00", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: nil, nanosecond: nil), format: .YMD_HM)) assertParse( "2018-04-21 00:00+01:15", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 4500), year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: nil, nanosecond: nil), format: .YMD_HM)) assertParse( "2018-04-21 00:00-01:15", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: -4500), year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: nil, nanosecond: nil), format: .YMD_HM)) assertParse( "2018-04-21T23:59", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: nil, nanosecond: nil), format: .YMD_HM)) assertParse( "2018-04-21 00:00:00", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: nil), format: .YMD_HMS)) assertParse( "2018-04-21T23:59:59", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: nil), format: .YMD_HMS)) assertParse( "2018-04-21 00:00:00.0", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.9", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.9Z", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.00", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.01", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 10_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.99", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.99Z", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.000", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.001", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 1_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.999", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.999Z", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.999+00:00", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.999-00:00", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.999+01:15", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 4500), year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.999-01:15", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: -4500), year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.999123", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.999123Z", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .YMD_HMSS)) assertParse( "00:00", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: nil, nanosecond: nil), format: .HM)) assertParse( "23:59", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: nil, nanosecond: nil), format: .HM)) assertParse( "23:59Z", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: nil, nanosecond: nil), format: .HM)) assertParse( "23:59+00:00", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: nil, nanosecond: nil), format: .HM)) assertParse( "23:59-00:00", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: nil, nanosecond: nil), format: .HM)) assertParse( "23:59+01:15", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 4500), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: nil, nanosecond: nil), format: .HM)) assertParse( "23:59-01:15", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: -4500), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: nil, nanosecond: nil), format: .HM)) assertParse( "00:00:00", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: nil), format: .HMS)) assertParse( "23:59:59", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: nil), format: .HMS)) assertParse( "00:00:00.0", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), format: .HMSS)) assertParse( "23:59:59.9", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), format: .HMSS)) assertParse( "23:59:59.9Z", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), format: .HMSS)) assertParse( "00:00:00.00", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), format: .HMSS)) assertParse( "00:00:00.01", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 10_000_000), format: .HMSS)) assertParse( "23:59:59.99", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), format: .HMSS)) assertParse( "23:59:59.99Z", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), format: .HMSS)) assertParse( "00:00:00.000", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), format: .HMSS)) assertParse( "00:00:00.001", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 1_000_000), format: .HMSS)) assertParse( "23:59:59.999", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .HMSS)) assertParse( "23:59:59.999Z", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .HMSS)) assertParse( "23:59:59.999+00:00", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .HMSS)) assertParse( "23:59:59.999-00:00", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .HMSS)) assertParse( "23:59:59.999+01:15", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 4500), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .HMSS)) assertParse( "23:59:59.999-01:15", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: -4500), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .HMSS)) assertParse( "23:59:59.999123", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .HMSS)) assertParse( "23:59:59.999123Z", DatabaseDateComponents( DateComponents( timeZone: TimeZone(secondsFromGMT: 0), year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), format: .HMSS)) } func testDatabaseDateComponentsFromUnparsableString() { let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue("foo".databaseValue) XCTAssertTrue(databaseDateComponents == nil) } func testJSONEncodingOfDatabaseDateComponents() throws { // Encoding root string is not supported by all system version: use an object struct Record: Encodable { var date: DatabaseDateComponents } let record = Record(date: DatabaseDateComponents(DateComponents(year: 2018, month: 12, day: 31), format: .YMD)) let jsonData = try JSONEncoder().encode(record) let json = String(data: jsonData, encoding: .utf8)! XCTAssertEqual(json, """ {"date":"2018-12-31"} """) } func testJSONDecodingOfDatabaseDateComponents() throws { // Decoding root string is not supported by all system version: use an object struct Record: Decodable { var date: DatabaseDateComponents } let json = """ {"date":"2018-12-31"} """ let record = try JSONDecoder().decode(Record.self, from: json.data(using: .utf8)!) XCTAssertEqual(record.date.format, .YMD) XCTAssertEqual(record.date.dateComponents, DateComponents(year: 2018, month: 12, day: 31)) } }
mit
c3f5acf8dae9c6c7bedaa803e3097f62
50.252401
151
0.600273
5.080636
false
false
false
false
vbudhram/firefox-ios
Shared/SystemUtils.swift
2
2499
/* 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 /** * System helper methods written in Swift. */ public struct SystemUtils { /** Returns an accurate version of the system uptime even while the device is asleep. http://stackoverflow.com/questions/12488481/getting-ios-system-uptime-that-doesnt-pause-when-asleep - returns: Time interval since last reboot. */ public static func systemUptime() -> TimeInterval { var boottime = timeval() var mib = [CTL_KERN, KERN_BOOTTIME] var size = MemoryLayout<timeval>.stride var now = time_t() time(&now) sysctl(&mib, u_int(mib.count), &boottime, &size, nil, 0) let tv_sec: time_t = withUnsafePointer(to: &boottime.tv_sec) { $0.pointee } return TimeInterval(now - tv_sec) } } extension SystemUtils { // This should be run on first run of the application. // It shouldn't be run from an extension. // Its function is to write a lock file that is only accessible from the application, // and not accessible from extension when the device is locked. Thus, we can tell if an extension is being run // when the device is locked. public static func onFirstRun() { guard let lockFileURL = lockedDeviceURL else { return } let lockFile = lockFileURL.path let fm = FileManager.default if fm.fileExists(atPath: lockFile) { return } let contents = "Device is unlocked".data(using: .utf8) fm.createFile(atPath: lockFile, contents: contents, attributes: [FileAttributeKey.protectionKey.rawValue: FileProtectionType.complete]) } private static var lockedDeviceURL: URL? { let directoryURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: AppInfo.sharedContainerIdentifier) return directoryURL?.appendingPathComponent("security.dummy") } public static func isDeviceLocked() -> Bool { guard let lockFileURL = lockedDeviceURL else { return true } do { _ = try Data(contentsOf: lockFileURL, options: .mappedIfSafe) return false } catch let err as NSError { return err.code == 257 } catch _ { return true } } }
mpl-2.0
b6284e6928452a9656b76a3da619eadd
35.217391
143
0.647459
4.376532
false
false
false
false
devlucky/Kakapo
Examples/NewsFeed/Pods/Fakery/Source/Generators/Number.swift
1
881
import Foundation import CoreGraphics open class Number { fileprivate var lastUsedId: Int64 = 0 open func randomBool() -> Bool { return randomInt() % 2 == 0 } open func randomInt(min: Int = 0, max: Int = 1000) -> Int { return min + Int(arc4random_uniform(UInt32(max - min + 1))) } open func randomFloat(min: Float = 0, max: Float = 1000) -> Float { return (Float(arc4random()) / Float(UInt32.max)) * (max - min) + min } open func randomCGFloat(min: CGFloat = 0, max: CGFloat = 1000) -> CGFloat { return CGFloat(Float(arc4random()) / Float(UInt32.max)) * (max - min) + min } open func randomDouble(min: Double = 0, max: Double = 1000) -> Double { return (Double(arc4random()) / Double(UInt32.max)) * (max - min) + min } open func increasingUniqueId() -> Int { OSAtomicIncrement64(&lastUsedId) return Int(lastUsedId) } }
mit
138e1a724d4e0555259c946fe1921063
26.53125
79
0.637911
3.468504
false
false
false
false
jfosterdavis/Charles
Charles/CoreDataNSObject.swift
1
4351
// // CoreDataNSObject.swift // Charles // // Created by Jacob Foster Davis on 5/22/17. // Copyright © 2017 Zero Mu, LLC. All rights reserved. // import Foundation import CoreData import UIKit class CoreDataNSObject: NSObject { /******************************************************/ /******************* Properties **************/ /******************************************************/ //MARK: - Properties var frcDict : [String:NSFetchedResultsController<NSFetchRequestResult>] = [:] var stack: CoreDataStack! /******************************************************/ /******************* Life Cycle **************/ /******************************************************/ //MARK: - Life Cycle override init() { super.init() // Get the stack let delegate = UIApplication.shared.delegate as! AppDelegate stack = delegate.stack } func executeSearch(frcKey: String) { if let fc = frcDict[frcKey] { do { try fc.performFetch() } catch let e as NSError { print("Error while trying to perform a search: \n\(e)\n\(String(describing: frcDict[frcKey]))") } } } func setupFetchedResultsController(frcKey: String, entityName: String, sortDescriptors: [NSSortDescriptor]? = nil, predicate: NSPredicate? = nil) -> NSFetchedResultsController<NSFetchRequestResult> { //set up stack and fetchrequest // Get the stack let delegate = UIApplication.shared.delegate as! AppDelegate let stack = delegate.stack // Create Fetch Request let fr = NSFetchRequest<NSFetchRequestResult>(entityName: entityName) if let sortDescriptors = sortDescriptors { fr.sortDescriptors = sortDescriptors } if let predicate = predicate { fr.predicate = predicate } // Create FetchedResultsController let fc = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: stack.context, sectionNameKeyPath: nil, cacheName: nil) fc.delegate = self frcDict[frcKey] = fc executeSearch(frcKey: frcKey) return fc } } // MARK: - CoreDataCollectionViewController: NSFetchedResultsControllerDelegate extension CoreDataNSObject: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { //about to make updates. wrapping actions with updates will allow for animation and auto reloading //self.tableView.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { //if anObject is AnyObject { switch(type) { case .insert: //from apple documentation //self.tableView.insertRows(at: [newIndexPath!], with: UITableViewRowAnimation.automatic) //TODO: initiate download of terms? //print("case insert") break case .delete: //from apple documentation //self.tableView.deleteRows(at: [indexPath!], with: UITableViewRowAnimation.automatic) //print("case delete") break case .update: //from apple documentation //nothing is needed here because when data is updated the tableView displays datas current state //print("case update") break case .move: //TODO: move a cell... this may not be needed //print("case move") break } //save stack.save() } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { //finished with updates, allow table view to animate and reload //self.tableView.endUpdates() } }
apache-2.0
0a183ba4afcaa712b81a604948cc44c6
32.461538
204
0.544368
6.214286
false
false
false
false
apple/swift-driver
Sources/SwiftDriver/IncrementalCompilation/ModuleDependencyGraphParts/Tracer.swift
1
4503
//===----------------------------- Tracer.swift ---------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 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 class TSCBasic.DiagnosticsEngine extension ModuleDependencyGraph { /// Trace dependencies through the graph struct Tracer { typealias Graph = ModuleDependencyGraph let startingPoints: DirectlyInvalidatedNodeSet let graph: ModuleDependencyGraph private(set) var tracedUses = TransitivelyInvalidatedNodeArray() /// Record the paths taking so that -driver-show-incremental can explain why things are recompiled /// If tracing dependencies, holds a vector used to hold the current path /// def - use/def - use/def - ... private var currentPathIfTracing: [Node]? private let diagnosticEngine: DiagnosticsEngine } } // MARK:- Tracing extension ModuleDependencyGraph.Tracer { /// Find all uses of `defs` that have not already been traced. /// /// - Parameters: /// - defNodes: Nodes for changed declarations /// - graph: The graph hosting the nodes /// - diagnosticEngine: The complaint department /// - Returns: all uses of the changed nodes that have not already been traced. These represent /// heretofore-unschedule compilations that are now required. static func collectPreviouslyUntracedNodesUsing( defNodes: DirectlyInvalidatedNodeSet, in graph: ModuleDependencyGraph, diagnosticEngine: DiagnosticsEngine ) -> Self { var tracer = Self(collectingUsesOf: defNodes, in: graph, diagnosticEngine: diagnosticEngine) tracer.collectPreviouslyUntracedDependents() return tracer } private init(collectingUsesOf defs: DirectlyInvalidatedNodeSet, in graph: ModuleDependencyGraph, diagnosticEngine: DiagnosticsEngine) { self.graph = graph self.startingPoints = defs self.currentPathIfTracing = graph.info.reporter != nil ? [] : nil self.diagnosticEngine = diagnosticEngine } private mutating func collectPreviouslyUntracedDependents() { for n in startingPoints { collectNextPreviouslyUntracedDependent(of: n) } } private mutating func collectNextPreviouslyUntracedDependent( of definition: ModuleDependencyGraph.Node ) { guard definition.isUntraced else { return } definition.setTraced() tracedUses.append(definition) // If this node is merely used, but not defined anywhere, nothing else // can possibly depend upon it if case .unknown = definition.definitionLocation { return } let pathLengthAfterArrival = traceArrival(at: definition); // If this use also provides something, follow it for use in graph.nodeFinder.uses(of: definition) { collectNextPreviouslyUntracedDependent(of: use) } traceDeparture(pathLengthAfterArrival); } private mutating func traceArrival(at visitedNode: ModuleDependencyGraph.Node ) -> Int { guard var currentPath = currentPathIfTracing else { return 0 } currentPath.append(visitedNode) currentPathIfTracing = currentPath printPath(currentPath) return currentPath.count } private mutating func traceDeparture(_ pathLengthAfterArrival: Int) { guard var currentPath = currentPathIfTracing else { return } assert(pathLengthAfterArrival == currentPath.count, "Path must be maintained throughout recursive visits.") currentPath.removeLast() currentPathIfTracing = currentPath } private func printPath(_ path: [Graph.Node]) { guard path.first?.definitionLocation != path.last?.definitionLocation else { return } graph.info.reporter?.report( [ "Traced:", path.compactMap { node in guard case let .known(source) = node.definitionLocation else { return nil } return source.typedFile.type == .swift ? "\(node.key.description(in: graph)) in \(source.file.basename)" : "\(node.key.description(in: graph))" } .joined(separator: " -> ") ].joined(separator: " ") ) } }
apache-2.0
c3207f653fd768f052a5b38c0f76cfbd
31.630435
103
0.674217
4.795527
false
false
false
false
muenzpraeger/salesforce-einstein-vision-swift
SalesforceEinsteinVision/Classes/http/parts/MultiPartTraining.swift
1
2729
// // MultiPartTraining.swift // Pods // // Created by René Winkelmeyer on 02/28/2017. // // import Alamofire import Foundation public struct MultiPartTraining : MultiPart { private let DEFAULT_LEARNING_RATE = 0.0001 private let MIN_LEARNING_RATE = 0.0001 private let MAX_LEARNING_RATE = 0.01 private let MAX_NAME = 180 private var _datasetId:Int? private var _name:String? private var _epochs:Int? private var _learningRateChecked:Double? private var _trainParams:String? public init() {} public mutating func build(datasetId: Int, name: String, epochs: Int, learningRate: Double, trainParams: String) throws { if (datasetId==0) { throw ModelError.noFieldValue(field: "datasetId") } if name.isEmpty { throw ModelError.noFieldValue(field: "name") } if (name.characters.count>MAX_NAME) { throw ModelError.stringTooLong(field: "name", maxValue: MAX_NAME, currentValue: name.characters.count) } if (epochs>100) { throw ModelError.intTooBig(field: "epochs", maxValue: 100, currentValue: epochs) } var learningRateChecked = learningRate if (learningRateChecked==0) { learningRateChecked = DEFAULT_LEARNING_RATE } else if (learningRateChecked<MIN_LEARNING_RATE) { throw ModelError.doubleTooSmall(field: "learningRate", minValue: MIN_LEARNING_RATE, currentValue: learningRateChecked) } else if (learningRateChecked>MAX_LEARNING_RATE) { throw ModelError.doubleTooBig(field: "learningRate", maxValue: MAX_LEARNING_RATE, currentValue: learningRateChecked) } _datasetId = datasetId _name = name _epochs = epochs _learningRateChecked = learningRateChecked _trainParams = trainParams } public func form(multipart: MultipartFormData) { let nameData = _name?.data(using: String.Encoding.utf8) multipart.append(nameData!, withName: "name") if (_epochs!>0) { let epochsData = (String(describing: _epochs)).data(using: String.Encoding.utf8) multipart.append(epochsData!, withName: "epochs") } let learningRateData = (String(describing: _learningRateChecked)).data(using: String.Encoding.utf8) multipart.append(learningRateData!, withName: "learningRate") if (!_trainParams!.isEmpty) { let trainParamsData = _trainParams?.data(using: String.Encoding.utf8) multipart.append(trainParamsData!, withName: "trainParamsData") } } }
apache-2.0
c8d0634aa6994eaae9f1aa619adc1021
33.1
130
0.628666
4.2625
false
false
false
false
steven7/ParkingApp
rethink-swift-master/Sources/Rethink/ReArguments.swift
1
12265
import Foundation public enum ReTableReadMode: String { case single = "single" case majority = "majority" case outdated = "outdated" } public enum ReTableIdentifierFormat: String { case name = "name" case uuid = "uuid" } /** Optional arguments are instances of ReArg. */ public protocol ReArg { var serialization: (String, Any) { get } } /** Optional arguments for the R.table command. */ public enum ReTableArg: ReArg { case readMode(ReTableReadMode) case identifierFormat(ReTableIdentifierFormat) public var serialization: (String, Any) { switch self { case .readMode(let rm): return ("read_mode", rm.rawValue) case .identifierFormat(let i): return ("identifier_format", i.rawValue) } } } public enum ReFilterArg: ReArg { case `default`(AnyObject) public var serialization: (String, Any) { switch self { case .default(let a): return ("default", a) } } } public enum ReTableDurability: String { case soft = "soft" case hard = "hard" } public enum ReTableCreateArg: ReArg { case primaryKey(String) case durability(ReTableDurability) case shards(Int) case replicas(Int) public var serialization: (String, Any) { switch self { case .primaryKey(let p): return ("primary_key", p) case .durability(let d): return ("durability", d.rawValue) case .shards(let s): return ("shards", s) case .replicas(let r): return ("replicas", r) } } } public enum ReIndexCreateArg: ReArg { case multi(Bool) case geo(Bool) public var serialization: (String, Any) { switch self { case .multi(let m): return ("multi", m) case .geo(let g): return ("geo", g) } } } public enum ReIndexRenameArg: ReArg { /** If the optional argument overwrite is specified as true, a previously existing index with the new name will be deleted and the index will be renamed. If overwrite is false (the default) an error will be raised if the new index name already exists. */ case overwrite(Bool) public var serialization: (String, Any) { switch self { case .overwrite(let o): return ("overwrite", o) } } } public enum RePermission: ReArg { case read(Bool) case write(Bool) case connect(Bool) case config(Bool) public var serialization: (String, Any) { switch self { case .read(let b): return ("read", b) case .write(let b): return ("write", b) case .connect(let b): return ("connect", b) case .config(let b): return ("config", b) } } } public enum ReChangesArg: ReArg { /** squash: Controls how change notifications are batched. Acceptable values are true, false and a numeric value: - true: When multiple changes to the same document occur before a batch of notifications is sent, the changes are "squashed" into one change. The client receives a notification that will bring it fully up to date with the server. - false: All changes will be sent to the client verbatim. This is the default. - n: A numeric value (floating point). Similar to true, but the server will wait n seconds to respond in order to squash as many changes together as possible, reducing network traffic. The first batch will always be returned immediately. */ case squash(Bool, n: Double?) /** changefeedQueueSize: the number of changes the server will buffer between client reads before it starts dropping changes and generates an error (default: 100,000). */ case changeFeedQueueSize(Int) /** includeInitial: if true, the changefeed stream will begin with the current contents of the table or selection being monitored. These initial results will have new_val fields, but no old_val fields. The initial results may be intermixed with actual changes, as long as an initial result for the changed document has already been given. If an initial result for a document has been sent and a change is made to that document that would move it to the unsent part of the result set (e.g., a changefeed monitors the top 100 posters, the first 50 have been sent, and poster 48 has become poster 52), an “uninitial” notification will be sent, with an old_val field but no new_val field.*/ case includeInitial(Bool) /** includeStates: if true, the changefeed stream will include special status documents consisting of the field state and a string indicating a change in the feed’s state. These documents can occur at any point in the feed between the notification documents described below. If includeStates is false (the default), the status documents will not be sent.*/ case includeStates(Bool) /** includeOffsets: if true, a changefeed stream on an orderBy.limit changefeed will include old_offset and new_offset fields in status documents that include old_val and new_val. This allows applications to maintain ordered lists of the stream’s result set. If old_offset is set and not null, the element at old_offset is being deleted; if new_offset is set and not null, then new_val is being inserted at new_offset. Setting includeOffsets to true on a changefeed that does not support it will raise an error.*/ case includeOffsets(Bool) /** includeTypes: if true, every result on a changefeed will include a type field with a string that indicates the kind of change the result represents: add, remove, change, initial, uninitial, state. Defaults to false.*/ case includeTypes(Bool) public var serialization: (String, Any) { switch self { case .squash(let b, let i): assert(!(i != nil && !b), "Do not specify a time interval when squashing is to be disabled") if let interval = i, b { return ("squash", interval) } else { return ("squash", b) } case .changeFeedQueueSize(let i): return ("changefeed_queue_size", i) case .includeInitial(let b): return ("include_initial", b) case .includeStates(let b): return ("include_states", b) case .includeOffsets(let b): return ("include_offsets", b) case .includeTypes(let b): return ("include_types", b) } } } public enum ReFoldArg: ReArg { /** When an emit function is provided, fold will: - proceed through the sequence in order and take an initial base value, as above. - for each element in the sequence, call both the combining function and a separate emitting function with the current element and previous reduction result. - optionally pass the result of the combining function to the emitting function. If provided, the emitting function must return a list. */ case emit(ReQueryLambda) case finalEmit(ReQueryLambda) public var serialization: (String, Any) { switch self { case .emit(let r): return ("emit", r) case .finalEmit(let r): return ("final_emit", r) } } } public enum ReEqJoinArg: ReArg { /** The results from eqJoin are, by default, not ordered. The optional ordered: true parameter will cause eqJoin to order the output based on the left side input stream. (If there are multiple matches on the right side for a document on the left side, their order is not guaranteed even if ordered is true.) Requiring ordered results can significantly slow down eqJoin, and in many circumstances this ordering will not be required. (See the first example, in which ordered results are obtained by using orderBy after eqJoin.) */ case ordered(Bool) case index(String) public var serialization: (String, Any) { switch self { case .ordered(let o): return ("ordered", o) case .index(let i): return ("index", i) } } } public enum ReDurability: String { case hard = "hard" case soft = "soft" } public enum ReConflictResolution: String { /** Do not insert the new document and record the conflict as an error. This is the default. */ case error = "error" /** Replace the old document in its entirety with the new one. */ case replace = "replace" /** Update fields of the old document with fields from the new one. */ case update = "update" } public enum ReInsertArg: ReArg { /** This option will override the table or query’s durability setting (set in run). In soft durability mode RethinkDB will acknowledge the write immediately after receiving and caching it, but before the write has been committed to disk. */ case durability(ReDurability) /** true: return a changes array consisting of old_val/new_val objects describing the changes made, only including the documents actually updated. false: do not return a changes array (the default). */ case returnChanges(Bool) /** Determine handling of inserting documents with the same primary key as existing entries. */ case conflict(ReConflictResolution) public var serialization: (String, Any) { switch self { case .durability(let d): return ("durability", d.rawValue) case .returnChanges(let r): return ("return_changes", r) case .conflict(let r): return ("conflict", r.rawValue) } } } public enum ReUpdateArg: ReArg { /** This option will override the table or query’s durability setting (set in run). In soft durability mode RethinkDB will acknowledge the write immediately after receiving and caching it, but before the write has been committed to disk. */ case durability(ReDurability) /** true: return a changes array consisting of old_val/new_val objects describing the changes made, only including the documents actually updated. false: do not return a changes array (the default). */ case returnChanges(Bool) /** If set to true, executes the update and distributes the result to replicas in a non-atomic fashion. This flag is required to perform non-deterministic updates, such as those that require reading data from another table. */ case nonAtomic(Bool) public var serialization: (String, Any) { switch self { case .durability(let d): return ("durability", d.rawValue) case .returnChanges(let r): return ("return_changes", r) case .nonAtomic(let b): return ("non_atomic", b) } } } public enum ReDeleteArg: ReArg { /** This option will override the table or query’s durability setting (set in run). In soft durability mode RethinkDB will acknowledge the write immediately after receiving and caching it, but before the write has been committed to disk. */ case durability(ReDurability) /** true: return a changes array consisting of old_val/new_val objects describing the changes made, only including the documents actually updated. false: do not return a changes array (the default). */ case returnChanges(Bool) public var serialization: (String, Any) { switch self { case .durability(let d): return ("durability", d.rawValue) case .returnChanges(let r): return ("return_changes", r) } } } public enum ReUnit: String { case meter = "m" case kilometer = "km" case internationalMile = "mi" case nauticalMile = "nm" case internationalFoot = "ft" } public enum ReGeoSystem: String { case wgs84 = "WGS84" case unitSphere = "unit_sphere" } public enum ReCircleArg: ReArg { /** The number of vertices in the polygon or line. Defaults to 32. */ case numVertices(Int) /** The reference ellipsoid to use for geographic coordinates. Possible values are WGS84 (the default), a common standard for Earth’s geometry, or unit_sphere, a perfect sphere of 1 meter radius. */ case geoSystem(ReGeoSystem) /** Unit for the radius distance. */ case unit(ReUnit) /** If true (the default) the circle is filled, creating a polygon; if false the circle is unfilled (creating a line). */ case fill(Bool) public var serialization: (String, Any) { switch self { case .numVertices(let n): return ("num_vertices", n) case .geoSystem(let s): return ("geo_system", s.rawValue) case .unit(let u): return ("unit", u.rawValue) case .fill(let b): return ("fill", b) } } } public enum ReDistanceArg: ReArg { case geoSystem(ReGeoSystem) case unit(ReUnit) public var serialization: (String, Any) { switch self { case .geoSystem(let s): return ("geo_system", s.rawValue) case .unit(let u): return ("unit", u.rawValue) } } } public enum ReIntersectingArg: ReArg { /** The index argument is mandatory. This command returns the same results as table.filter(r.row('index').intersects(geometry)). The total number of results is limited to the array size limit which defaults to 100,000, but can be changed with the arrayLimit option to run. */ case index(String) public var serialization: (String, Any) { switch self { case .index(let s): return ("index", s) } } }
isc
a85a2421d890d2a717f27740e6e6b5c0
35.783784
123
0.730019
3.65751
false
false
false
false
mrlegowatch/RolePlayingCore
RolePlayingCore/RolePlayingCore/Configuration/Configuration.swift
1
3173
// // Configuration.swift // RolePlayingCore // // Created by Brian Arnold on 3/4/17. // Copyright © 2017 Brian Arnold. All rights reserved. // import Foundation // TODO: this needs work. Nominally it's purpose is to help integrate related classes, // but because we don't have much in terms of requirements, it's not doing much besides // wiring up races and classes to players. public struct ConfigurationFiles: Decodable { let currencies: [String] let races: [String] let classes: [String] let players: [String]? let racialNames: String? private enum CodingKeys: String, CodingKey { case currencies case races case classes case players case racialNames = "racial names" } } /// This is designed to configure a client from a framework or application bundle. public struct Configuration { let bundle: Bundle public var configurationFiles: ConfigurationFiles public var races = Races() public var classes = Classes() public var players = Players() public init(_ configurationFile: String, from bundle: Bundle = .main) throws { self.bundle = bundle let data = try bundle.loadJSON(configurationFile) let decoder = JSONDecoder() self.configurationFiles = try decoder.decode(ConfigurationFiles.self, from: data) try self.load(configurationFiles) } public mutating func load(_ configurationFiles: ConfigurationFiles) throws { let jsonDecoder = JSONDecoder() for currenciesFile in configurationFiles.currencies { let jsonData = try bundle.loadJSON(currenciesFile) _ = try jsonDecoder.decode(Currencies.self, from: jsonData) } for raceFile in configurationFiles.races { let jsonData = try bundle.loadJSON(raceFile) let races = try jsonDecoder.decode(Races.self, from: jsonData) self.races.races += races.races } for classFile in configurationFiles.classes { let jsonData = try bundle.loadJSON(classFile) let classes = try jsonDecoder.decode(Classes.self, from: jsonData) self.classes.classes += classes.classes // Update the shared classes experience points table, then // update all of the classes to point to it. TODO: improve this. if let experiencePoints = classes.experiencePoints { self.classes.experiencePoints = experiencePoints for (index, _) in self.classes.classes.enumerated() { self.classes.classes[index].experiencePoints = experiencePoints } } } if let playersFiles = configurationFiles.players { for playersFile in playersFiles { let jsonData = try bundle.loadJSON(playersFile) let players = try jsonDecoder.decode(Players.self, from: jsonData) try players.resolve(classes: self.classes, races: self.races) self.players.players += players.players } } } }
mit
4f081da3e51568f97ed271dadfe03961
34.640449
89
0.633354
4.88
false
true
false
false
alaphao/gitstatus
GitStatus/GitStatus/GitNavigationController.swift
1
1686
// // GitNavigationController.swift // GitStatus // // Created by Aleph Retamal on 4/30/15. // Copyright (c) 2015 Guilherme Ferreira de Souza. All rights reserved. // import UIKit class GitNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() // var navigationBarAppearance = UINavigationBar.appearance() // navigationBarAppearance.tintColor = UIColor(hex: "ffffff") // navigationBarAppearance.barTintColor = UIColor(hex: "333333") // self.navigationBar.backgroundColor = UIColor(hex: "f5f5f5") self.navigationBar.frame = CGRect(x: 0, y: 0, width: self.navigationBar.bounds.width, height: self.navigationBar.bounds.height + 1) let borderBottom = CALayer() borderBottom.backgroundColor = UIColor(hex: "e5e5e5").CGColor borderBottom.bounds = CGRect(x: 0, y: 0, width: self.navigationBar.bounds.width, height: 1) borderBottom.position = CGPoint(x: self.navigationBar.center.x, y: self.navigationBar.bounds.height - 1) self.navigationBar.layer.addSublayer(borderBottom) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
a7591a83497652fdd11e4243df7bdd2b
34.125
139
0.682681
4.532258
false
false
false
false
ncalexan/firefox-ios
Client/Frontend/AuthenticationManager/AuthenticationSettingsViewController.swift
1
13863
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import SwiftKeychainWrapper import LocalAuthentication private let logger = Logger.browserLogger private func presentNavAsFormSheet(_ presented: UINavigationController, presenter: UINavigationController?, settings: AuthenticationSettingsViewController?) { presented.modalPresentationStyle = .formSheet presenter?.present(presented, animated: true, completion: { if let selectedRow = settings?.tableView.indexPathForSelectedRow { settings?.tableView.deselectRow(at: selectedRow, animated: false) } }) } class TurnPasscodeOnSetting: Setting { weak var settings: AuthenticationSettingsViewController? init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.settings = settings as? AuthenticationSettingsViewController super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOnPasscode, enabled: true), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: SetupPasscodeViewController()), presenter: navigationController, settings: settings) } } class TurnPasscodeOffSetting: Setting { weak var settings: AuthenticationSettingsViewController? init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.settings = settings as? AuthenticationSettingsViewController super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOffPasscode, enabled: true), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: RemovePasscodeViewController()), presenter: navigationController, settings: settings) } } class ChangePasscodeSetting: Setting { weak var settings: AuthenticationSettingsViewController? init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool) { self.settings = settings as? AuthenticationSettingsViewController let attributedTitle: NSAttributedString = NSAttributedString.tableRowTitle(AuthenticationStrings.changePasscode, enabled: enabled) super.init(title: attributedTitle, delegate: delegate, enabled: enabled) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: ChangePasscodeViewController()), presenter: navigationController, settings: settings) } } class RequirePasscodeSetting: Setting { weak var settings: AuthenticationSettingsViewController? fileprivate weak var navigationController: UINavigationController? override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { // Only show the interval if we are enabled and have an interval set. let authenticationInterval = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() if let interval = authenticationInterval?.requiredPasscodeInterval, enabled { return NSAttributedString.tableRowTitle(interval.settingTitle, enabled: false) } return NSAttributedString(string: "") } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) { self.navigationController = settings.navigationController self.settings = settings as? AuthenticationSettingsViewController let title = AuthenticationStrings.requirePasscode let attributedTitle = NSAttributedString.tableRowTitle(title, enabled: enabled ?? true) super.init(title: attributedTitle, delegate: delegate, enabled: enabled) } func deselectRow () { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRow(at: selectedRow, animated: true) } } override func onClick(_: UINavigationController?) { guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() else { navigateToRequireInterval() return } if authInfo.requiresValidation() { AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: AuthenticationStrings.requirePasscodeTouchReason, success: { self.navigateToRequireInterval() }, cancel: nil, fallback: { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self) self.deselectRow() }) } else { self.navigateToRequireInterval() } } fileprivate func navigateToRequireInterval() { navigationController?.pushViewController(RequirePasscodeIntervalViewController(), animated: true) } } extension RequirePasscodeSetting: PasscodeEntryDelegate { @objc func passcodeValidationDidSucceed() { navigationController?.dismiss(animated: true) { self.navigateToRequireInterval() } } } class TouchIDSetting: Setting { fileprivate let authInfo: AuthenticationKeychainInfo? fileprivate weak var navigationController: UINavigationController? fileprivate weak var switchControl: UISwitch? fileprivate var touchIDSuccess: (() -> Void)? fileprivate var touchIDFallback: (() -> Void)? init( title: NSAttributedString?, navigationController: UINavigationController? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil, touchIDSuccess: (() -> Void)? = nil, touchIDFallback: (() -> Void)? = nil) { self.touchIDSuccess = touchIDSuccess self.touchIDFallback = touchIDFallback self.navigationController = navigationController self.authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() super.init(title: title, delegate: delegate, enabled: enabled) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .none // In order for us to recognize a tap gesture without toggling the switch, // the switch is wrapped in a UIView which has a tap gesture recognizer. This way // we can disable interaction of the switch and still handle tap events. let control = UISwitch() control.onTintColor = UIConstants.ControlTintColor control.isOn = authInfo?.useTouchID ?? false control.isUserInteractionEnabled = false switchControl = control let accessoryContainer = UIView(frame: control.frame) accessoryContainer.addSubview(control) let gesture = UITapGestureRecognizer(target: self, action: #selector(TouchIDSetting.switchTapped)) accessoryContainer.addGestureRecognizer(gesture) cell.accessoryView = accessoryContainer } @objc fileprivate func switchTapped() { guard let authInfo = authInfo else { logger.error("Authentication info should always be present when modifying Touch ID preference.") return } if authInfo.useTouchID { AppAuthenticator.presentAuthenticationUsingInfo( authInfo, touchIDReason: AuthenticationStrings.disableTouchReason, success: self.touchIDSuccess, cancel: nil, fallback: self.touchIDFallback ) } else { toggleTouchID(true) } } func toggleTouchID(_ enabled: Bool) { authInfo?.useTouchID = enabled KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authInfo) switchControl?.setOn(enabled, animated: true) } } class AuthenticationSettingsViewController: SettingsTableViewController { override func viewDidLoad() { super.viewDidLoad() updateTitleForTouchIDState() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: NSNotification.Name(rawValue: NotificationPasscodeDidRemove), object: nil) notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: NSNotification.Name(rawValue: NotificationPasscodeDidCreate), object: nil) notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) tableView.accessibilityIdentifier = "AuthenticationManager.settingsTableView" } deinit { let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self, name: NSNotification.Name(rawValue: NotificationPasscodeDidRemove), object: nil) notificationCenter.removeObserver(self, name: NSNotification.Name(rawValue: NotificationPasscodeDidCreate), object: nil) notificationCenter.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } override func generateSettings() -> [SettingSection] { if let _ = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() { return passcodeEnabledSettings() } else { return passcodeDisabledSettings() } } fileprivate func updateTitleForTouchIDState() { if LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { navigationItem.title = AuthenticationStrings.touchIDPasscodeSetting } else { navigationItem.title = AuthenticationStrings.passcode } } fileprivate func passcodeEnabledSettings() -> [SettingSection] { var settings = [SettingSection]() let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode) let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [ TurnPasscodeOffSetting(settings: self), ChangePasscodeSetting(settings: self, delegate: nil, enabled: true) ]) var requirePasscodeSectionChildren: [Setting] = [RequirePasscodeSetting(settings: self)] let localAuthContext = LAContext() if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { requirePasscodeSectionChildren.append( TouchIDSetting( title: NSAttributedString.tableRowTitle( NSLocalizedString("Use Touch ID", tableName: "AuthenticationManager", comment: "List section title for when to use Touch ID"), enabled: true ), navigationController: self.navigationController, delegate: nil, enabled: true, touchIDSuccess: { [unowned self] in self.touchIDAuthenticationSucceeded() }, touchIDFallback: { [unowned self] in self.fallbackOnTouchIDFailure() } ) ) } let requirePasscodeSection = SettingSection(title: nil, children: requirePasscodeSectionChildren) settings += [ passcodeSection, requirePasscodeSection, ] return settings } fileprivate func passcodeDisabledSettings() -> [SettingSection] { var settings = [SettingSection]() let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode) let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [ TurnPasscodeOnSetting(settings: self), ChangePasscodeSetting(settings: self, delegate: nil, enabled: false) ]) let requirePasscodeSection = SettingSection(title: nil, children: [ RequirePasscodeSetting(settings: self, delegate: nil, enabled: false), ]) settings += [ passcodeSection, requirePasscodeSection, ] return settings } } extension AuthenticationSettingsViewController { func refreshSettings(_ notification: Notification) { updateTitleForTouchIDState() settings = generateSettings() tableView.reloadData() } } extension AuthenticationSettingsViewController: PasscodeEntryDelegate { fileprivate func getTouchIDSetting() -> TouchIDSetting? { guard settings.count >= 2 && settings[1].count >= 2 else { return nil } return settings[1][1] as? TouchIDSetting } func touchIDAuthenticationSucceeded() { getTouchIDSetting()?.toggleTouchID(false) } func fallbackOnTouchIDFailure() { AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self) } @objc func passcodeValidationDidSucceed() { getTouchIDSetting()?.toggleTouchID(false) navigationController?.dismiss(animated: true, completion: nil) } }
mpl-2.0
88197e9e7a94c0a894b07225ee189d9f
39.773529
204
0.686576
6.197139
false
false
false
false
oisdk/ContiguousDeque
ContiguousDequeTests/ContiguousListIndexTests.swift
1
819
import XCTest import Foundation @testable import ContiguousDeque class ContiguousListIndexTests: XCTestCase { func testIndex() { let x = ContiguousListIndex(Int(arc4random_uniform(10000))) XCTAssert(x.distanceTo(x.successor()) == 1) XCTAssert(x.distanceTo(x.predecessor()) == -1) let y = ContiguousListIndex(Int(arc4random_uniform(10000))) XCTAssert(x.advancedBy(x.distanceTo(y)) == y) XCTAssert(x == x) XCTAssert(x.successor() > x) XCTAssert(x.predecessor() < x) XCTAssert(x.advancedBy(0) == x) XCTAssert(x.advancedBy(1) == x.successor()) XCTAssert(x.advancedBy(-1) == x.predecessor()) let m = Int(arc4random_uniform(10000)) - 5000 XCTAssert(x.distanceTo(x.advancedBy(m)) == m) } }
mit
231842dd35cf21324000405557efefb2
21.162162
63
0.619048
3.881517
false
true
false
false
SoySauceLab/CollectionKit
Sources/Extensions/Util.swift
1
3926
import UIKit extension Array { func get(_ index: Int) -> Element? { if (0..<count).contains(index) { return self[index] } return nil } } extension Collection { /// Finds such index N that predicate is true for all elements up to /// but not including the index N, and is false for all elements /// starting with index N. /// Behavior is undefined if there is no such N. func binarySearch(predicate: (Iterator.Element) -> Bool) -> Index { var low = startIndex var high = endIndex while low != high { let mid = index(low, offsetBy: distance(from: low, to: high)/2) if predicate(self[mid]) { low = index(after: mid) } else { high = mid } } return low } } extension CGFloat { func clamp(_ minValue: CGFloat, _ maxValue: CGFloat) -> CGFloat { return self < minValue ? minValue : (self > maxValue ? maxValue : self) } } extension CGPoint { func translate(_ dx: CGFloat, dy: CGFloat) -> CGPoint { return CGPoint(x: self.x+dx, y: self.y+dy) } func transform(_ trans: CGAffineTransform) -> CGPoint { return self.applying(trans) } func distance(_ point: CGPoint) -> CGFloat { return sqrt(pow(self.x - point.x, 2)+pow(self.y - point.y, 2)) } var transposed: CGPoint { return CGPoint(x: y, y: x) } } extension CGSize { func insets(by insets: UIEdgeInsets) -> CGSize { return CGSize(width: width - insets.left - insets.right, height: height - insets.top - insets.bottom) } var transposed: CGSize { return CGSize(width: height, height: width) } } func abs(_ left: CGPoint) -> CGPoint { return CGPoint(x: abs(left.x), y: abs(left.y)) } func min(_ left: CGPoint, _ right: CGPoint) -> CGPoint { return CGPoint(x: min(left.x, right.x), y: min(left.y, right.y)) } func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } func += (left: inout CGPoint, right: CGPoint) { left.x += right.x left.y += right.y } func + (left: CGRect, right: CGPoint) -> CGRect { return CGRect(origin: left.origin + right, size: left.size) } func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } func - (left: CGRect, right: CGPoint) -> CGRect { return CGRect(origin: left.origin - right, size: left.size) } func / (left: CGPoint, right: CGFloat) -> CGPoint { return CGPoint(x: left.x/right, y: left.y/right) } func * (left: CGPoint, right: CGFloat) -> CGPoint { return CGPoint(x: left.x*right, y: left.y*right) } func * (left: CGFloat, right: CGPoint) -> CGPoint { return right * left } func * (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x*right.x, y: left.y*right.y) } prefix func - (point: CGPoint) -> CGPoint { return CGPoint.zero - point } func / (left: CGSize, right: CGFloat) -> CGSize { return CGSize(width: left.width/right, height: left.height/right) } func - (left: CGPoint, right: CGSize) -> CGPoint { return CGPoint(x: left.x - right.width, y: left.y - right.height) } prefix func - (inset: UIEdgeInsets) -> UIEdgeInsets { return UIEdgeInsets(top: -inset.top, left: -inset.left, bottom: -inset.bottom, right: -inset.right) } extension CGRect { var center: CGPoint { return CGPoint(x: midX, y: midY) } var bounds: CGRect { return CGRect(origin: .zero, size: size) } init(center: CGPoint, size: CGSize) { self.init(origin: center - size / 2, size: size) } var transposed: CGRect { return CGRect(origin: origin.transposed, size: size.transposed) } #if swift(>=4.2) #else func inset(by insets: UIEdgeInsets) -> CGRect { return UIEdgeInsetsInsetRect(self, insets) } #endif } func delay(_ delay: Double, closure:@escaping () -> Void) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) }
mit
93ed8ee6ccce5fa6d3ce58272287e78d
27.656934
120
0.647988
3.329941
false
false
false
false
ykws/yomblr
yomblr/TumblrAPI/Responses/PhotoPost.swift
1
4220
// // PhotoPost.swift // yomblr // // Created by Yoshiyuki Kawashima on 2017/06/24. // Copyright © 2017 ykws. All rights reserved. // /** Post's information **only Photo Posts** Including in Tumblr API /user/dashboard - Retrieve a User's Dashboard Responses returned in Tumblr API /posts - Retrieve Published Posts Responses. https://www.tumblr.com/docs/en/api/v2#m-posts-responses exclude. reason: for quotes, reblogs, etc. - `source_url` - `source_title` reason: missing field. - `total_posts` - `width` - `height` */ struct PhotoPost : JSONDecodable { // MARK: - All Post Types let blogName: String let id: Int let postUrl: String let type: String let timestamp: Int let date: String let format: String let reblogKey: String let tags: [String] let bookmarklet: Bool let mobile: Bool let sourceUrl: String? let sourceTitle: String? let liked: Bool let state: String // MARK: - Photo Posts let photos : [Photo] let caption: String // MARK: - Initializer init(json: Any) throws { guard let dictionary = json as? [String : Any] else { throw JSONDecodeError.invalidFormat(json: json) } guard let blogName = dictionary["blog_name"] as? String else { throw JSONDecodeError.missingValue(key: "blog_name", actualValue: dictionary["blog_name"]) } guard let id = dictionary["id"] as? Int else { throw JSONDecodeError.missingValue(key: "id", actualValue: dictionary["id"]) } guard let postUrl = dictionary["post_url"] as? String else { throw JSONDecodeError.missingValue(key: "post_url", actualValue: dictionary["post_url"]) } guard let type = dictionary["type"] as? String else { throw JSONDecodeError.missingValue(key: "type", actualValue: dictionary["type"]) } guard type == "photo" else { throw JSONDecodeError.unsupportedType(type) } guard let timestamp = dictionary["timestamp"] as? Int else { throw JSONDecodeError.missingValue(key: "timestamp", actualValue: dictionary["timestamp"]) } guard let date = dictionary["date"] as? String else { throw JSONDecodeError.missingValue(key: "date", actualValue: dictionary["date"]) } guard let format = dictionary["format"] as? String else { throw JSONDecodeError.missingValue(key: "format", actualValue: dictionary["format"]) } guard let reblogKey = dictionary["reblog_key"] as? String else { throw JSONDecodeError.missingValue(key: "reblog_key", actualValue: dictionary["reblog_key"]) } guard let tags = dictionary["tags"] as? [String] else { throw JSONDecodeError.missingValue(key: "tags", actualValue: dictionary["tags"]) } let bookmarklet = dictionary["bookmarklet"] as? Bool ?? false let mobile = dictionary["mobile"] as? Bool ?? false let sourceUrl = dictionary["source_url"] as? String ?? nil let sourceTitle = dictionary["source_title"] as? String ?? nil guard let liked = dictionary["liked"] as? Bool else { throw JSONDecodeError.missingValue(key: "liked", actualValue: dictionary["liked"]) } guard let state = dictionary["state"] as? String else { throw JSONDecodeError.missingValue(key: "state", actualValue: dictionary["state"]) } guard let photoObjects = dictionary["photos"] as? [Any] else { throw JSONDecodeError.missingValue(key: "photos", actualValue: dictionary["photos"]) } let photos = try photoObjects.map { return try Photo(json: $0) } guard let caption = dictionary["caption"] as? String else { throw JSONDecodeError.missingValue(key: "caption", actualValue: dictionary["caption"]) } self.blogName = blogName self.id = id self.postUrl = postUrl self.type = type self.timestamp = timestamp self.date = date self.format = format self.reblogKey = reblogKey self.tags = tags self.bookmarklet = bookmarklet self.mobile = mobile self.sourceUrl = sourceUrl self.sourceTitle = sourceTitle self.liked = liked self.state = state self.photos = photos self.caption = caption } }
mit
2de50a9518f79740e5527022d7a9cfcd
27.89726
98
0.658924
4.223223
false
false
false
false
toicodedoec/ios-tour-flicks
Flicks/InfiniteScrollActivityView.swift
1
1226
// // InfiniteScrollActivityView.swift // Flicks // // Created by john on 2/19/17. // Copyright © 2017 doannx. All rights reserved. // import Foundation import UIKit class InfiniteScrollActivityView: UIView { var activityIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView() static let defaultHeight:CGFloat = 60.0 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupActivityIndicator() } override init(frame aRect: CGRect) { super.init(frame: aRect) setupActivityIndicator() } override func layoutSubviews() { super.layoutSubviews() activityIndicatorView.center = CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2) } func setupActivityIndicator() { activityIndicatorView.activityIndicatorViewStyle = .gray activityIndicatorView.hidesWhenStopped = true self.addSubview(activityIndicatorView) } func stopAnimating() { self.activityIndicatorView.stopAnimating() self.isHidden = true } func startAnimating() { self.isHidden = false self.activityIndicatorView.startAnimating() } }
apache-2.0
720ba37b72effc1ac3f82b343d379268
25.630435
105
0.672653
5.125523
false
false
false
false
spacedrabbit/CatAerisWeatherDemo
CatAerisWeatherDemo/WeatherCodeParser.swift
1
3588
// // WeatherCodeParser.swift // CatAerisWeatherDemo // // Created by Louis Tur on 8/31/16. // Copyright © 2016 catthoughts. All rights reserved. // import Foundation import UIKit // [coverage]:[intensity]:[weather] internal struct WeatherCode: CodeParser { internal static let Hail: String = "A" internal static let BlowingDust: String = "BD" internal static let BlowingSand: String = "BN" internal static let Mist: String = "BR" internal static let BlowingSnow: String = "BS" internal static let BlowingSpray: String = "BY" internal static let Fog: String = "F" internal static let Frost: String = "FR" internal static let Haze: String = "H" internal static let IceCrystals: String = "IC" internal static let IceFog: String = "IF" internal static let IcePelletsOrSleet: String = "IP" internal static let Smoke: String = "K" internal static let Drizzle: String = "L" internal static let Rain: String = "R" internal static let RainShowers: String = "RW" internal static let RainSnowMix: String = "RS" // Rain/snow mix internal static let SnowSleetMix: String = "SI" // Snow/sleet mix internal static let WintryMix: String = "WM" // Wintry mix (snow, sleet, rain) internal static let Snow: String = "S" internal static let SnowShowers: String = "SW" internal static let Thunderstorms: String = "T" internal static let UnknownPrecipitation: String = "UP" // Unknown precipitation internal static let VolcanicAsh: String = "VA" internal static let Waterspouts: String = "WP" internal static let FreezingFog: String = "ZF" internal static let FreezingDrizzle: String = "ZL" internal static let FreezingRain: String = "ZR" internal static let FreezingSpray: String = "ZY" internal static func valueForCode(_ code: String) -> String? { switch code { case WeatherCode.Hail: return "Hail" case WeatherCode.BlowingDust: return "Blowing Dust" case WeatherCode.BlowingSand: return "Blowing Sand" case WeatherCode.Mist: return "Mist" case WeatherCode.BlowingSnow: return "Blowing Snow" case WeatherCode.BlowingSpray: return "Blowing Spray" case WeatherCode.Fog: return "Fog" case WeatherCode.Frost: return "Frost" case WeatherCode.Haze: return "Haze" case WeatherCode.IceCrystals: return "Ice crystals" case WeatherCode.IceFog: return "Ice fog" case WeatherCode.IcePelletsOrSleet: return "Ice pellets/Sleet" case WeatherCode.Smoke: return "Smoke" case WeatherCode.Drizzle: return "Drizzle" case WeatherCode.Rain: return "Rain" case WeatherCode.RainShowers: return "Rain showers" case WeatherCode.RainSnowMix: return "Rain/snow mix" case WeatherCode.SnowSleetMix: return "Snow/sleet mix" case WeatherCode.WintryMix: return "Wintry mix (snow, sleet, rain)" case WeatherCode.Snow: return "Snow" case WeatherCode.SnowShowers: return "Snow showers" case WeatherCode.Thunderstorms: return "Thunderstorms" case WeatherCode.UnknownPrecipitation: return "Unknown Precipitation" case WeatherCode.VolcanicAsh: return "Volcanic ash" case WeatherCode.Waterspouts: return "Water spouts" case WeatherCode.FreezingFog: return "Freezing fog" case WeatherCode.FreezingDrizzle: return "Freezing drizzle" case WeatherCode.FreezingRain: return "Freezing rain" case WeatherCode.FreezingSpray: return "Freezing spray" default: return nil } } }
mit
11524a10535985c9cf7ae0cf31f1892a
32.523364
82
0.697798
3.645325
false
false
false
false
FlaneurApp/FlaneurOpen
Sources/Classes/Search View Controller/FlaneurSearchViewController.swift
1
5620
// // FlaneurSearchViewController.swift // FlaneurOpen_Example // // Created by Mickaël Floc'hlay on 07/02/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit /// This class is a convenience wrapper around `UISearchController` that view controllers /// can subclass to inherit some behaviors. /// /// ## Why this class? /// /// If you don't use a `UITableView` or `UINavigationItem`'s `searchController` introduced in iOS 11.0, /// or any other immediate location for a `UISearchController`'s `searchBar`, and you want to use /// AutoLayout, things can get weird/hacky/difficult. /// /// This class fixes all positioning problems found in an app using a navigation controller hierarchy /// with hidden navigation bars, and using iOS 9.0. /// /// It will display the search bar right under your view controller's top layout guide. /// /// ## Subclassing /// /// To subclass this class, provide your own implementations of `instanciateSearchResultsController` /// and `searchControllerWillBecomeActive`, and call `startSearchAction` when relevant. open class FlaneurSearchViewController: UIViewController { private let searchBarContainer: UIView = UIView() private var searchBarContainerHeightConstraint: NSLayoutConstraint? = nil private var searchController: UISearchController? // MARK: - Customizing behavior /// This property provides the intended search results controller of `UISearchController`. /// Please refer to `UISearchController` documentation for details. /// /// The resulting `UIViewController` will typically implement `UISearchResultsUpdating` and /// will act as the `UISearchController`'s `searchResultsUpdater`. public var instanciateSearchResultsController: () -> (UIViewController?) = { return nil } /// This property can be used as a hook for the subclass to implement some /// custom behavior using the search controller, like styling the search bar, get /// information about its height, etc. public var searchControllerWillBecomeActive: (UISearchController) -> () = { _ in () } private var transient = false // - MARK: Lifecycle /// Calling this method adds the search bar container within the view and sets up constraints /// to reveal the search bar when relevant. override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // View hierarchy view.addSubview(searchBarContainer) // Constraints searchBarContainer.translatesAutoresizingMaskIntoConstraints = false searchBarContainerHeightConstraint = searchBarContainer.heightAnchor.constraint(equalToConstant: 0.0) NSLayoutConstraint.activate([ searchBarContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor), searchBarContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor), searchBarContainer.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor), searchBarContainerHeightConstraint! ]) } /// Deactivates the search controller before calling `super`. override open func viewWillDisappear(_ animated: Bool) { // Dismiss the search before leaving the screen - Cf. #297 dismissSearchBar() super.viewWillDisappear(animated) } // - MARK: Searching /// Calls this method when the subclass is ready to show the search bar **transiently** (ie after a user action). /// /// - Parameter sender: the sender of the action @IBAction public func startSearchAction(_ sender: Any? = nil) { transient = true presentSearchBar() searchController?.searchBar.becomeFirstResponder() } /// Calls this method when the subclass is ready to show the search bar **permanently**. public func presentSearchBar() { let searchController = UISearchController(searchResultsController: instanciateSearchResultsController()) self.searchController = searchController if let searchResultsUpdater = searchController.searchResultsController as? UISearchResultsUpdating { searchController.searchResultsUpdater = searchResultsUpdater } searchController.delegate = self searchController.searchBar.delegate = self searchControllerWillBecomeActive(searchController) // Add the search bar to the view... searchBarContainer.addSubview(searchController.searchBar) searchBarContainerHeightConstraint?.constant = searchController.searchBar.frame.height searchController.hidesNavigationBarDuringPresentation = false self.definesPresentationContext = true } public func dismissSearchBar() { searchController?.isActive = false } } extension FlaneurSearchViewController: UISearchControllerDelegate { // - MARK: UISearchControllerDelegate public func willDismissSearchController(_ searchController: UISearchController) { view.backgroundColor = .white view.alpha = 1.0 if transient { searchBarContainer.removeAllSubviews() searchBarContainerHeightConstraint?.constant = 0 self.searchController = nil } } public func willPresentSearchController(_ searchController: UISearchController) { view.backgroundColor = .black view.alpha = 0.3 } } extension FlaneurSearchViewController: UISearchBarDelegate { // - MARK: UISearchBarDelegate public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } }
mit
62940dfb3e527cc8accea2c08803faa2
38.286713
117
0.718405
5.646231
false
false
false
false
EstefaniaGilVaquero/ciceIOS
AppCoreData_GDP/AppCoreData_GDP/AppDelegate.swift
1
6916
// // AppDelegate.swift // AppCoreData_GDP // // Created by User on 15/2/16. // Copyright © 2016 iCologic. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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. self.saveContext() } //MARK: - RECUPERCION DE DATOS func getAllDataContratos() -> NSArray{ //1. Solicitud de recuperadion de Datos let fetchRequest = NSFetchRequest() //2. Establecemos la entrada general a la BBDD let entity : NSEntityDescription = NSEntityDescription.entityForName("Contratos", inManagedObjectContext: managedObjectContext)! //3. Definimos de que entidad debe obtener los datos solicitados fetchRequest.entity = entity let fetchContratos : NSArray? do{ fetchContratos = try! managedObjectContext.executeFetchRequest(fetchRequest) }catch{ print(error) } return fetchContratos! } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "es.cice.App_TestCoreData" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("AppCoreData_GDP", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
79039679d3a6fccc50f8f5c4ee8623c5
47.697183
291
0.701663
5.781773
false
false
false
false
apple/swift
test/Profiler/coverage_closures.swift
2
3213
// RUN: %target-swift-frontend -emit-sil -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -module-name coverage_closures %s | %FileCheck %s // RUN: %target-swift-frontend -profile-generate -profile-coverage-mapping -emit-ir %s func bar(arr: [(Int32) -> Int32]) { // CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 (Swift.Int32) -> Swift.Int32 in coverage_closures.bar // CHECK-NEXT: [[@LINE+1]]:13 -> [[@LINE+1]]:42 : 0 for a in [{ (b : Int32) -> Int32 in b }] { a(0) } } func foo() { // CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo() // CHECK-NEXT: [[@LINE+1]]:12 -> [[@LINE+1]]:59 : 0 let c1 = { (i1 : Int32, i2 : Int32) -> Bool in i1 < i2 } // CHECK-LABEL: sil_coverage_map {{.*}}// f1 #1 ((Swift.Int32, Swift.Int32) -> Swift.Bool) -> Swift.Bool in coverage_closures.foo() // CHECK-NEXT: [[@LINE+1]]:55 -> {{.*}}:4 : 0 func f1(_ closure : (Int32, Int32) -> Bool) -> Bool { // CHECK-LABEL: sil_coverage_map {{.*}}// implicit closure #1 () throws -> Swift.Bool in f1 // CHECK-NEXT: [[@LINE+1]]:29 -> [[@LINE+1]]:42 : 0 return closure(0, 1) && closure(1, 0) } f1(c1) // CHECK-LABEL: sil_coverage_map {{.*}}// closure #2 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo() // CHECK-NEXT: [[@LINE+1]]:6 -> [[@LINE+1]]:27 : 0 f1 { i1, i2 in i1 > i2 } // CHECK-LABEL: sil_coverage_map {{.*}}// closure #3 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo() // CHECK-NEXT: [[@LINE+3]]:6 -> [[@LINE+3]]:48 : 0 // CHECK-LABEL: sil_coverage_map {{.*}}// implicit closure #1 () throws -> {{.*}} in coverage_closures.foo // CHECK-NEXT: [[@LINE+1]]:36 -> [[@LINE+1]]:46 : 0 f1 { left, right in left == 0 || right == 1 } } // https://github.com/apple/swift/issues/45220 // Display coverage for implicit member initializers without crashing. struct C1 { // CHECK-LABEL: sil_coverage_map{{.*}}// variable initialization expression of coverage_closures.C1 // CHECK-NEXT: [[@LINE+1]]:24 -> [[@LINE+1]]:34 : 0 private var errors = [String]() } // rdar://39200851: Closure in init method covered twice class C2 { init() { // CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 () -> () in coverage_closures.C2.init() // CHECK-NEXT: [[@LINE+2]]:13 -> [[@LINE+4]]:6 : 0 // CHECK-NEXT: } let _ = { () in print("hello") } } } // https://github.com/apple/swift/issues/61129 – Make sure we don't emit // duplicate coverage for closure expressions as property initializers. struct S { // CHECK-LABEL: sil_coverage_map {{.*}} "$s17coverage_closures1SV1xSiycvpfi" {{.*}} // variable initialization expression of coverage_closures.S.x : () -> Swift.Int // CHECK-NEXT: [[@LINE+8]]:11 -> [[@LINE+8]]:30 : 0 // CHECK-NEXT: } // CHECK-LABEL: sil_coverage_map {{.*}} "$s17coverage_closures1SV1xSiycvpfiSiycfU_" {{.*}} // closure #1 () -> Swift.Int in variable initialization expression of coverage_closures.S.x : () -> Swift.Int // CHECK-NEXT: [[@LINE+4]]:24 -> [[@LINE+4]]:25 : 1 // CHECK-NEXT: [[@LINE+3]]:28 -> [[@LINE+3]]:29 : (0 - 1) // CHECK-NEXT: [[@LINE+2]]:11 -> [[@LINE+2]]:30 : 0 // CHECK-NEXT: } var x = {.random() ? 1 : 2} }
apache-2.0
4392ebfcabe784712688a10b717a8181
43.597222
203
0.603239
3.04649
false
false
false
false
Senspark/ee-x
src/ios/ee/core/Logger.swift
1
1174
// // Logger.swift // Pods // // Created by eps on 6/25/20. // import Foundation internal class Logger: ILogger { private let _tag: String private var _logLevel: LogLevel init(_ tag: String, _ logLevel: LogLevel = LogLevel.Debug) { _tag = tag _logLevel = logLevel } var logLevel: LogLevel { get { _logLevel } set(value) { _logLevel = value } } func error(_ message: String) { if _logLevel.rawValue <= LogLevel.Error.rawValue { print("\(_tag): \(message)") } } func warn(_ message: String) { if _logLevel.rawValue <= LogLevel.Warn.rawValue { print("\(_tag): \(message)") } } func info(_ message: String) { if _logLevel.rawValue <= LogLevel.Info.rawValue { print("\(_tag): \(message)") } } func debug(_ message: String) { if _logLevel.rawValue <= LogLevel.Debug.rawValue { print("\(_tag): \(message)") } } func verbose(_ message: String) { if _logLevel.rawValue <= LogLevel.Verbose.rawValue { print("\(_tag): \(message)") } } }
mit
ad910e269582f4c116b8967963416bcc
21.150943
64
0.524702
4.104895
false
false
false
false
fguchelaar/AdventOfCode2016
AdventOfCode2016/aoc-day5/main.swift
1
1597
// // main.swift // AdventOfCode2016 // // Created by Frank Guchelaar on 05/12/2016. // Copyright © 2016 Awesomation. All rights reserved. // import Foundation let input = "abbhdwsy" //let range = 7777889...Int.max let range = [1739529, 1910966, 1997199, 2854555, 2963716, 3237361, 4063427, 7777889, 8460345, 9417946, 12389322, 12434824, 12850790, 12942170, 12991290, 13256331, 14024976, 15299586, 17786793, 17931630, 19357601, 19359925, 19808330, 20214395, 22339420, 23135423, 24055333, 24538150, 25056365, 25651067, 25858460, 25943617] for salt in range { if let hash = input.appending("\(salt)").md5() { let hex = hash.hexString() if hex.hasPrefix("00000") { let key = hex.characters[hex.index(hex.startIndex, offsetBy: 5)] print ("PART ONE >> [\(salt)] - \(hex) \(key)") if let keyAsInt = Int("\(key)") { if keyAsInt < 8 { let key2 = hex.characters[hex.index(hex.startIndex, offsetBy: 6)] print ("PART TWO >> [\(salt)] - \(hex) \(key) \(key2)") } } } } }
mit
8f6597ef750e9e053093668ec614ff70
22.820896
85
0.416667
4.102828
false
false
false
false
cloudinary/cloudinary_ios
Cloudinary/Classes/Core/Features/UploadWidget/CropView/CLDCropScrollViewController.swift
1
2885
// // CLDCropViewScrollViewDelegate.swift // // Copyright (c) 2020 Cloudinary (http://cloudinary.com) // // 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 CLDCropScrollViewController: NSObject, UIScrollViewDelegate { weak var cropView: CLDCropView! init(cropView: CLDCropView) { self.cropView = cropView super.init() } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return cropView.backgroundContainerView } func scrollViewDidScroll(_ scrollView: UIScrollView) { cropView.matchForegroundToBackground() } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { cropView.startEditing() cropView.isResettable = true } func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { cropView.startEditing() cropView.isResettable = true } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { cropView.startResetTimer() cropView.checkForCanReset() } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { cropView.startResetTimer() cropView.checkForCanReset() } func scrollViewDidZoom(_ scrollView: UIScrollView) { if scrollView.isTracking { cropView.cropBoxLastEditedZoomScale = scrollView.zoomScale cropView.cropBoxLastEditedMinZoomScale = scrollView.minimumZoomScale } cropView.matchForegroundToBackground() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { cropView.startResetTimer() } } }
mit
9e1c68b26a53171bcb254f4c2d50059a
32.941176
106
0.686655
5.188849
false
false
false
false
tlax/looper
looper/Model/Camera/Filter/Item/MCameraFilterItemBlend.swift
1
2201
import UIKit class MCameraFilterItemBlend:MCameraFilterItem { init() { let title:String = NSLocalizedString("MCameraFilterItemBlend_title", comment:"") let viewTitle:String = NSLocalizedString("MCameraFilterItemBlend_viewTitle", comment:"") let image:UIImage = #imageLiteral(resourceName: "assetFilterBlender") super.init(title:title, viewTitle:viewTitle, image:image) } override func selectorModel() -> MCameraFilterSelector { let records:[MCameraFilterSelectorItem] = recordItems() var items:[MCameraFilterSelectorItem] = [] let itemBlack:MCameraFilterSelectorItemColor = MCameraFilterSelectorItemColor( color:UIColor.black) let itemWhite:MCameraFilterSelectorItemColor = MCameraFilterSelectorItemColor( color:UIColor.white) items.append(itemBlack) items.append(itemWhite) items.append(contentsOf:records) let model:MCameraFilterSelector = MCameraFilterSelector(items:items) return model } override func selected( filterSelectedItem:MCameraFilterSelectorItem, controller:CCameraFilterSelector) { let controllerOverlay:CCameraFilterBlenderOverlay = CCameraFilterBlenderOverlay( model:self, filterSelectedItem:filterSelectedItem) controller.parentController.push( controller:controllerOverlay, horizontal:CParent.TransitionHorizontal.fromRight) } //MARK: public func filter( filterSelectedItem:MCameraFilterSelectorItem, overlays:[MCameraFilterItemBlendOverlay]) -> MCameraRecord { let filteredRecord:MCameraRecord guard let blender:MCameraFilterProcessorBlender = MCameraFilterProcessorBlender() else { filteredRecord = MCameraRecord() return filteredRecord } filteredRecord = blender.blend( filterSelectedItem:filterSelectedItem, overlays:overlays) return filteredRecord } }
mit
dea8b4896ff5ea3c0d011635a74a2246
30.442857
96
0.646979
5.731771
false
false
false
false
tardieu/swift
benchmark/utils/DriverUtils.swift
5
10766
//===--- DriverUtils.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 // //===----------------------------------------------------------------------===// import Darwin struct BenchResults { var delim: String = "," var sampleCount: UInt64 = 0 var min: UInt64 = 0 var max: UInt64 = 0 var mean: UInt64 = 0 var sd: UInt64 = 0 var median: UInt64 = 0 init() {} init(delim: String, sampleCount: UInt64, min: UInt64, max: UInt64, mean: UInt64, sd: UInt64, median: UInt64) { self.delim = delim self.sampleCount = sampleCount self.min = min self.max = max self.mean = mean self.sd = sd self.median = median // Sanity the bounds of our results precondition(self.min <= self.max, "min should always be <= max") precondition(self.min <= self.mean, "min should always be <= mean") precondition(self.min <= self.median, "min should always be <= median") precondition(self.max >= self.mean, "max should always be >= mean") precondition(self.max >= self.median, "max should always be >= median") } } extension BenchResults : CustomStringConvertible { var description: String { return "\(sampleCount)\(delim)\(min)\(delim)\(max)\(delim)\(mean)\(delim)\(sd)\(delim)\(median)" } } struct Test { let name: String let index: Int let f: (Int) -> () var run: Bool init(name: String, n: Int, f: @escaping (Int) -> ()) { self.name = name self.index = n self.f = f run = true } } public var precommitTests: [String : (Int) -> ()] = [:] public var otherTests: [String : (Int) -> ()] = [:] enum TestAction { case Run case ListTests case Fail(String) } struct TestConfig { /// The delimiter to use when printing output. var delim: String = "," /// The filters applied to our test names. var filters = [String]() /// The scalar multiple of the amount of times a test should be run. This /// enables one to cause tests to run for N iterations longer than they /// normally would. This is useful when one wishes for a test to run for a /// longer amount of time to perform performance analysis on the test in /// instruments. var iterationScale: Int = 1 /// If we are asked to have a fixed number of iterations, the number of fixed /// iterations. var fixedNumIters: UInt = 0 /// The number of samples we should take of each test. var numSamples: Int = 1 /// Is verbose output enabled? var verbose: Bool = false /// Should we only run the "pre-commit" tests? var onlyPrecommit: Bool = true /// After we run the tests, should the harness sleep to allow for utilities /// like leaks that require a PID to run on the test harness. var afterRunSleep: Int? /// The list of tests to run. var tests = [Test]() mutating func processArguments() -> TestAction { let validOptions = [ "--iter-scale", "--num-samples", "--num-iters", "--verbose", "--delim", "--run-all", "--list", "--sleep" ] let maybeBenchArgs: Arguments? = parseArgs(validOptions) if maybeBenchArgs == nil { return .Fail("Failed to parse arguments") } let benchArgs = maybeBenchArgs! if let _ = benchArgs.optionalArgsMap["--list"] { return .ListTests } if let x = benchArgs.optionalArgsMap["--iter-scale"] { if x.isEmpty { return .Fail("--iter-scale requires a value") } iterationScale = Int(x)! } if let x = benchArgs.optionalArgsMap["--num-iters"] { if x.isEmpty { return .Fail("--num-iters requires a value") } fixedNumIters = numericCast(Int(x)!) } if let x = benchArgs.optionalArgsMap["--num-samples"] { if x.isEmpty { return .Fail("--num-samples requires a value") } numSamples = Int(x)! } if let _ = benchArgs.optionalArgsMap["--verbose"] { verbose = true print("Verbose") } if let x = benchArgs.optionalArgsMap["--delim"] { if x.isEmpty { return .Fail("--delim requires a value") } delim = x } if let _ = benchArgs.optionalArgsMap["--run-all"] { onlyPrecommit = false } if let x = benchArgs.optionalArgsMap["--sleep"] { if x.isEmpty { return .Fail("--sleep requires a non-empty integer value") } let v: Int? = Int(x) if v == nil { return .Fail("--sleep requires a non-empty integer value") } afterRunSleep = v! } filters = benchArgs.positionalArgs return .Run } mutating func findTestsToRun() { var i = 1 for benchName in precommitTests.keys.sorted() { tests.append(Test(name: benchName, n: i, f: precommitTests[benchName]!)) i += 1 } for benchName in otherTests.keys.sorted() { tests.append(Test(name: benchName, n: i, f: otherTests[benchName]!)) i += 1 } for i in 0..<tests.count { if onlyPrecommit && precommitTests[tests[i].name] == nil { tests[i].run = false } if !filters.isEmpty && !filters.contains(String(tests[i].index)) && !filters.contains(tests[i].name) { tests[i].run = false } } } } func internalMeanSD(_ inputs: [UInt64]) -> (UInt64, UInt64) { // If we are empty, return 0, 0. if inputs.isEmpty { return (0, 0) } // If we have one element, return elt, 0. if inputs.count == 1 { return (inputs[0], 0) } // Ok, we have 2 elements. var sum1: UInt64 = 0 var sum2: UInt64 = 0 for i in inputs { sum1 += i } let mean: UInt64 = sum1 / UInt64(inputs.count) for i in inputs { sum2 = sum2 &+ UInt64((Int64(i) &- Int64(mean))&*(Int64(i) &- Int64(mean))) } return (mean, UInt64(sqrt(Double(sum2)/(Double(inputs.count) - 1)))) } func internalMedian(_ inputs: [UInt64]) -> UInt64 { return inputs.sorted()[inputs.count / 2] } #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER @_silgen_name("swift_leaks_startTrackingObjects") func startTrackingObjects(_: UnsafeMutableRawPointer) -> () @_silgen_name("swift_leaks_stopTrackingObjects") func stopTrackingObjects(_: UnsafeMutableRawPointer) -> Int #endif class SampleRunner { var info = mach_timebase_info_data_t(numer: 0, denom: 0) init() { mach_timebase_info(&info) } func run(_ name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 { // Start the timer. #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER var str = name startTrackingObjects(UnsafeMutableRawPointer(str._core.startASCII)) #endif let start_ticks = mach_absolute_time() fn(Int(num_iters)) // Stop the timer. let end_ticks = mach_absolute_time() #if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER stopTrackingObjects(UnsafeMutableRawPointer(str._core.startASCII)) #endif // Compute the spent time and the scaling factor. let elapsed_ticks = end_ticks - start_ticks return elapsed_ticks * UInt64(info.numer) / UInt64(info.denom) } } /// Invoke the benchmark entry point and return the run time in milliseconds. func runBench(_ name: String, _ fn: (Int) -> Void, _ c: TestConfig) -> BenchResults { var samples = [UInt64](repeating: 0, count: c.numSamples) if c.verbose { print("Running \(name) for \(c.numSamples) samples.") } let sampler = SampleRunner() for s in 0..<c.numSamples { let time_per_sample: UInt64 = 1_000_000_000 * UInt64(c.iterationScale) var scale : UInt var elapsed_time : UInt64 = 0 if c.fixedNumIters == 0 { elapsed_time = sampler.run(name, fn: fn, num_iters: 1) scale = UInt(time_per_sample / elapsed_time) } else { // Compute the scaling factor if a fixed c.fixedNumIters is not specified. scale = c.fixedNumIters } // Rerun the test with the computed scale factor. if scale > 1 { if c.verbose { print(" Measuring with scale \(scale).") } elapsed_time = sampler.run(name, fn: fn, num_iters: scale) } else { scale = 1 } // save result in microseconds or k-ticks samples[s] = elapsed_time / UInt64(scale) / 1000 if c.verbose { print(" Sample \(s),\(samples[s])") } } let (mean, sd) = internalMeanSD(samples) // Return our benchmark results. return BenchResults(delim: c.delim, sampleCount: UInt64(samples.count), min: samples.min()!, max: samples.max()!, mean: mean, sd: sd, median: internalMedian(samples)) } func printRunInfo(_ c: TestConfig) { if c.verbose { print("--- CONFIG ---") print("NumSamples: \(c.numSamples)") print("Verbose: \(c.verbose)") print("IterScale: \(c.iterationScale)") if c.fixedNumIters != 0 { print("FixedIters: \(c.fixedNumIters)") } print("Tests Filter: \(c.filters)") print("Tests to run: ", terminator: "") for t in c.tests { if t.run { print("\(t.name), ", terminator: "") } } print("") print("") print("--- DATA ---") } } func runBenchmarks(_ c: TestConfig) { let units = "us" print("#\(c.delim)TEST\(c.delim)SAMPLES\(c.delim)MIN(\(units))\(c.delim)MAX(\(units))\(c.delim)MEAN(\(units))\(c.delim)SD(\(units))\(c.delim)MEDIAN(\(units))") var SumBenchResults = BenchResults() SumBenchResults.sampleCount = 0 for t in c.tests { if !t.run { continue } let BenchIndex = t.index let BenchName = t.name let BenchFunc = t.f let results = runBench(BenchName, BenchFunc, c) print("\(BenchIndex)\(c.delim)\(BenchName)\(c.delim)\(results.description)") fflush(stdout) SumBenchResults.min += results.min SumBenchResults.max += results.max SumBenchResults.mean += results.mean SumBenchResults.sampleCount += 1 // Don't accumulate SD and Median, as simple sum isn't valid for them. // TODO: Compute SD and Median for total results as well. // SumBenchResults.sd += results.sd // SumBenchResults.median += results.median } print("") print("Totals\(c.delim)\(SumBenchResults.description)") } public func main() { var config = TestConfig() switch (config.processArguments()) { case let .Fail(msg): // We do this since we need an autoclosure... fatalError("\(msg)") case .ListTests: config.findTestsToRun() print("Enabled Tests:") for t in config.tests { print(" \(t.name)") } case .Run: config.findTestsToRun() printRunInfo(config) runBenchmarks(config) if let x = config.afterRunSleep { sleep(UInt32(x)) } } }
apache-2.0
08b990768aed6f0515e4173cec4122dd
27.709333
161
0.618614
3.785513
false
true
false
false
TheBrewery/Hikes
WorldHeritage/Views/TBAnimatingSearchBar.swift
1
8307
import UIKit enum TBAnimatingSearchBarState { case Expanded case Collapsed case Floating } private let placeholderOffsetX: CGFloat = 4.0 private let viewHeight: CGFloat = 50.0 class TBAnimatingSearchBar: UIView, UITextFieldDelegate { class TBTextField: UITextField { override func placeholderRectForBounds(bounds: CGRect) -> CGRect { return CGRectInset(bounds, placeholderOffsetX, 0) } } class TBControl: UIControl { // private let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) // // private func commonInit() { // backgroundView.frame = frame // addSubview(backgroundView) // } // // override init(frame: CGRect) { // super.init(frame: frame) // commonInit() // } // // required init?(coder aDecoder: NSCoder) { // super.init(coder: aDecoder) // commonInit() // } override var highlighted: Bool { didSet { UIView.animateWithDuration(0.25) { self.backgroundColor = UIColor(white: self.highlighted ? 0.9 : 1.0, alpha: 1.0) } } } } var statusBarView: UIView! var iconLabel: UILabel! var backgroundView: TBControl! var textField: TBTextField! private var previousBarState: TBAnimatingSearchBarState = .Floating var barState: TBAnimatingSearchBarState = .Floating { willSet { previousBarState = barState } didSet { guard previousBarState != barState else { return } respondsToContentOffset = barState != .Expanded animateSizeForState(barState) } } var stateChangeDidComplete: ((TBAnimatingSearchBarState) -> ())? var textDidChange: ((String) -> ())? private var respondsToContentOffset = true var cancelButton = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 44)) var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .White) override init(frame: CGRect) { super.init(frame: frame) backgroundView = TBControl(frame: CGRect(x: 20, y: 40, width: frame.width - 40, height: viewHeight) ) backgroundView.layer.cornerRadius = 3 backgroundView.backgroundColor = UIColor.whiteColor() backgroundView.addTarget(self, action: #selector(TBAnimatingSearchBar.didTap), forControlEvents: .TouchUpInside) backgroundView.layer.shadowColor = UIColor.blackColor().CGColor backgroundView.layer.shadowRadius = 2.0 backgroundView.layer.shadowOffset = CGSize(width: 0, height: 1) backgroundView.layer.shadowOpacity = 0.16 cancelButton.setTitle("Cancel", forState: .Normal) cancelButton.setTitleColor(UIColor.darkTextColor(), forState: .Normal) cancelButton.titleLabel?.font = UIFont(name: "AvenirNext-Medium", size: 16)! cancelButton.addTarget(self, action: #selector(TBAnimatingSearchBar.didTapCancelButton), forControlEvents: .TouchUpInside) cancelButton.center = CGPoint(x: frame.width - cancelButton.frame.width/2.0, y: backgroundView.frame.height/2.0) cancelButton.alpha = 0 iconLabel = UILabel(frame: CGRect(x: 0, y: 0, width: backgroundView.frame.height, height: backgroundView.frame.height)) iconLabel.textColor = UIColor.whDarkBlueColor() iconLabel.attributedText = Ionic.IosSearch.attributedStringWithFontSize(20) iconLabel.textAlignment = NSTextAlignment.Center textField = TBTextField(frame: CGRect(x: iconLabel.frame.width - placeholderOffsetX, y: 0, width: backgroundView.frame.width - iconLabel.frame.height, height: backgroundView.frame.height)) textField.font = UIFont(name: "AvenirNext-Medium", size: 16)! textField.attributedPlaceholder = NSAttributedString(string: "Find Your Adventure", attributes: [NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont(name: "Avenir Next", size: 16)!]) textField.tintColor = UIColor.whDarkBlueColor() textField.textColor = UIColor.whDarkBlueColor() textField.returnKeyType = .Search textField.userInteractionEnabled = false textField.delegate = self backgroundView.addSubview(iconLabel) backgroundView.addSubview(textField) backgroundView.addSubview(cancelButton) addSubview(backgroundView) addSubview(activityIndicator) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(TBAnimatingSearchBar.textFieldTextDidChange(_:)), name: UITextFieldTextDidChangeNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func textFieldTextDidChange(notification: NSNotification) { if let textField = notification.object as? UITextField where textField == self.textField { self.textDidChange?(textField.text!) } } func didTap() { barState = .Expanded } func didTapCancelButton() { self.textField.userInteractionEnabled = false self.textField.text = nil executeOn(.Main, afterDelay: 0.5) {[weak self] Void in guard let _self = self else { return } _self.textDidChange?("") } barState = previousBarState } // MARK: - Public func contentOffsetDidChange(contentOffset: CGPoint) { guard respondsToContentOffset else { return } barState = contentOffset.y > 30 ? .Collapsed : .Floating } func animateSizeForState(barState: TBAnimatingSearchBarState) { self.stateChangeDidComplete?(barState) guard barState != .Expanded else { UIView.animateKeyframesWithDuration(0.35, delay: 0, options: UIViewKeyframeAnimationOptions.CalculationModeCubic, animations: { UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.75) { self.backgroundView.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: viewHeight + 20) self.backgroundView.layer.cornerRadius = 0 self.iconLabel.frame.origin.y = 20 self.iconLabel.transform = CGAffineTransformMakeScale(0.5, 0.5) self.iconLabel.alpha = 0 self.textField.frame.origin = CGPoint(x: 10, y: 20) self.textField.alpha = 1.0 self.cancelButton.frame.origin.y = 20 } UIView.addKeyframeWithRelativeStartTime(0.75, relativeDuration: 0.25) { self.cancelButton.alpha = 1 } }) { (finished) -> Void in self.textField.userInteractionEnabled = true self.textField.becomeFirstResponder() } return } let expand = barState == .Floating let animation = CABasicAnimation(keyPath: "cornerRadius") animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.fromValue = backgroundView.layer.cornerRadius animation.toValue = expand ? 3.0 : viewHeight/2.0 animation.duration = 0.15 backgroundView.layer.addAnimation(animation, forKey: "cornerRadius") backgroundView.layer.cornerRadius = animation.toValue as! CGFloat self.cancelButton.alpha = 0 UIView.animateWithDuration(0.15, animations: { () -> Void in self.iconLabel.transform = CGAffineTransformMakeScale(1.0, 1.0) self.iconLabel.alpha = 1.0 self.iconLabel.frame.origin.y = 0 let width = expand ? self.frame.width - 40 : viewHeight self.backgroundView.frame = CGRect(x: 20, y: 40, width: width, height: viewHeight) self.textField.frame.origin = CGPoint(x: self.iconLabel.frame.maxX - placeholderOffsetX, y: 0) self.textField.alpha = CGFloat(expand) self.cancelButton.frame.origin.y = 0 }, completion: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
6c08dc1dcc82b7e1ef2b7ce942461959
38.183962
224
0.647165
4.986194
false
false
false
false
ibari/StationToStation
StationToStation/StationCell.swift
1
886
// // StationCell.swift // StationToStation // // Created by Ian on 6/8/15. // Copyright (c) 2015 Ian Bari. All rights reserved. // import UIKit class StationCell: UICollectionViewCell { @IBOutlet weak var banerImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var trackCountLabel: UILabel! var station: Station! { didSet { banerImageView.setImageWithURL(NSURL(string: station.imageUrl)) nameLabel.text = station!.name let tracks = station.playlist!.tracks.count trackCountLabel.text = (tracks == 1) ? "\(station.playlist!.tracks.count) Track" : "\(station.playlist!.tracks.count) Tracks" } } override func awakeFromNib() { super.awakeFromNib() } override func layoutSubviews() { super.layoutSubviews() } }
gpl-2.0
e0e279ff657a33c8fd8484c045aea7a8
25.058824
137
0.626411
4.43
false
false
false
false
sandeep-chhabra/SDSegmentController
SDSegmentController/Classes/SDSegmentControl.swift
1
22963
// // SDSegmentControl.swift // SDSegmentController // // Created by Sandeep Chhabra on 29/05/17. // Copyright © 2017 Sandeep Chhabra. All rights reserved. // //TODO : ERROR HANDLING FOR WRONG OR NOT INPUT //TODO: HANDLING FOR IMAGE SIZE BIGGER THAN OWN SIZE import UIKit public enum SDSegmentWidth { case dynamic case fixed } public enum SDSegmentControlType{ case text case image case imageText } public enum SDMoveDirection{ case forward case backward } fileprivate extension UIButton { func centerVeticallyWith(padding:CGFloat){ guard let imageSize = self.imageView?.image?.size, let text = self.titleLabel?.text, let font = self.titleLabel?.font else { return } self.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: -(imageSize.height + padding), right: 0.0) let labelString = NSString(string: text) let titleSize = labelString.size(attributes: [NSFontAttributeName: font]) self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + padding), left: 0.0, bottom: 0.0, right: -titleSize.width) let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0; self.contentEdgeInsets = UIEdgeInsets(top: edgeOffset, left: 0.0, bottom: edgeOffset, right: 0.0) } func centerVertically() { centerVeticallyWith(padding:5) } } public class SDButton:UIButton{ override public var isSelected: Bool{ set (val){ super.isSelected = val centerVertically() } get{ return super.isSelected } } } fileprivate extension UIImage{ func resizeImage( newHeight: CGFloat) -> UIImage { let scale = newHeight / self.size.height let newWidth = self.size.width * scale UIGraphicsBeginImageContext(CGSize.init(width: newWidth, height: newHeight)) self.draw(in: CGRect.init(x: 0, y: 0, width: newWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage { let scale = newWidth / image.size.width let newHeight = image.size.height * scale UIGraphicsBeginImageContext(CGSize.init(width: newWidth, height: newHeight)) image.draw(in: CGRect.init(x: 0, y: 0, width: newWidth, height: newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } } public protocol SDSegmentControlDelegate { //delegate method called aways even when user selects segment func segmentControl(segmentControl:SDSegmentControl, willSelectSegmentAt index:Int) func segmentControl(segmentControl:SDSegmentControl, didSelectSegmentAt index:Int) } open class SDSegmentControl: UIControl { override open func awakeFromNib() { // NSLog("awwake from nib") } public var delegate: SDSegmentControlDelegate? //set these values accordingly if using default init or to change segments at runtime public var _sectionTitles:[String]? public var _sectionImages:[UIImage]? public var _selectedSectionImages:[UIImage]? public var _controlType:SDSegmentControlType = .text private var _scrollView:UIScrollView! private var _selectionIndicator : UIView //movement to next segment private var _currentProgress : CGFloat = 0 private var _currentDirection : SDMoveDirection = .forward public var selectionIndicatorHeight :CGFloat = 4 public var segmentWidthStyle : SDSegmentWidth = .fixed public var selectionIndicatorColor:UIColor = UIColor.init(red: 84/255, green: 182/255, blue: 74/255, alpha: 1) public var sectionColor:UIColor = UIColor.white public var titleTextAttributes : [String: AnyObject] public var selectedTitleTextAttributes : [String: AnyObject] public var selectedSectionIndex : Int = 0 public var lastSelectedSectionIndex :Int = 0 // inset applied to left and right of section each public var sectionInset:CGFloat = 0 public var numberOfSegments : Int { get{ var count = 0 switch _controlType { case .image: count = (_sectionImages?.count)! break case .imageText: count = (_sectionTitles?.count)! break case .text: count = (_sectionTitles?.count)! break } return count } } public var moveDirection : SDMoveDirection { get{ return lastSelectedSectionIndex > selectedSectionIndex ? .backward : .forward } } //MARK: - Initialization public init(){ sectionInset = 10 _scrollView = UIScrollView() _selectionIndicator = UIView() _sectionTitles = ["this","is","test","for","segments"] titleTextAttributes = [NSForegroundColorAttributeName : UIColor.init(red: 67/255, green: 67/255, blue: 67/255, alpha: 1), NSFontAttributeName : UIFont.systemFont(ofSize: 18)] selectedTitleTextAttributes = [NSForegroundColorAttributeName : UIColor.init(red: 84/255, green: 182/255, blue: 74/255, alpha: 1), NSFontAttributeName : UIFont.systemFont(ofSize: 18)] super.init(frame: CGRect()) } convenience public init(sectionTitles:[String]){ self.init() _sectionTitles = sectionTitles _controlType = .text } convenience public init(sectionImages:[UIImage],selectedSectionImages:[UIImage]) { self.init() _sectionImages = sectionImages _selectedSectionImages = selectedSectionImages _controlType = .image } convenience public init(sectionImages:[UIImage],selectedSectionImages:[UIImage],sectionTitles:[String]) { self.init() _sectionImages = sectionImages _selectedSectionImages = selectedSectionImages _sectionTitles = sectionTitles _controlType = .imageText } required public init?(coder aDecoder: NSCoder) { sectionInset = 10 _scrollView = UIScrollView() _selectionIndicator = UIView() _sectionTitles = ["this","is","test","for","segments"] titleTextAttributes = [NSForegroundColorAttributeName : UIColor.init(red: 67/255, green: 67/255, blue: 67/255, alpha: 1), NSFontAttributeName : UIFont.systemFont(ofSize: 18)] selectedTitleTextAttributes = [NSForegroundColorAttributeName : UIColor.init(red: 84/255, green: 182/255, blue: 74/255, alpha: 1), NSFontAttributeName : UIFont.systemFont(ofSize: 18)] super.init(coder : aDecoder) } // MARK: - Draw segments open func drawSegments(){ NSLog("draw segments") _scrollView.removeFromSuperview() _scrollView = UIScrollView() //Add scroll view _scrollView.isDirectionalLockEnabled = true _scrollView.showsVerticalScrollIndicator = false _scrollView.showsHorizontalScrollIndicator = false _scrollView.frame = self.bounds self.addSubview(_scrollView) //temp _scrollView.backgroundColor = sectionColor self.backgroundColor = UIColor.gray rescaleImagesIfNeeded() //Add sections let maxWidth = self.maxWidth() var x:CGFloat = 0 //sectionMargin let count = numberOfSegments for index in 0...count-1 { let btnWidth = ( segmentWidthStyle == .fixed ? maxWidth : widthAt(index: index)) + (sectionInset * 2) let rect = CGRect(x: x, y: CGFloat(0), width: btnWidth ,height: self.frame.size.height - selectionIndicatorHeight ) let button = SDButton(frame:rect ) button.addTarget(self, action: #selector(sectionSlected(button:)), for: UIControlEvents.touchUpInside) button.tag = index + 999 //temp button.backgroundColor = sectionColor // switch _controlType { case .image: if var image = _sectionImages?[index] { let height = image.size.height if height > self.frame.size.height{ image = image.resizeImage( newHeight: self.frame.size.height) } button.setImage(image, for: .normal) } if var selectedImage = _selectedSectionImages?[index] { let height = selectedImage.size.height if height > self.frame.size.height{ selectedImage = selectedImage.resizeImage( newHeight: self.frame.size.height) } button.setImage(selectedImage, for: .selected) } break case .imageText: let attrTitle = NSAttributedString(string: (_sectionTitles?[index])!, attributes: titleTextAttributes) let attrTitleSelected = NSAttributedString(string: (_sectionTitles?[index])!, attributes: selectedTitleTextAttributes) button.setAttributedTitle(attrTitle, for: .normal) button.setAttributedTitle(attrTitleSelected, for: .selected) button.setImage(_sectionImages?[index], for: .normal) button.setImage(_selectedSectionImages?[index], for: .selected) //call after setting image and text button.centerVertically() break case .text: let attrTitle = NSAttributedString(string: (_sectionTitles?[index])!, attributes: titleTextAttributes) let attrTitleSelected = NSAttributedString(string: (_sectionTitles?[index])!, attributes: selectedTitleTextAttributes) button.setAttributedTitle(attrTitle, for: .normal) button.setAttributedTitle(attrTitleSelected, for: .selected) break } _scrollView.addSubview(button) x = x+btnWidth //+ sectionMargin } _scrollView.contentSize = CGSize(width: x, height: self.frame.size.height) //check selected section less than total section selectedSectionIndex = selectedSectionIndex < numberOfSegments ? selectedSectionIndex : 0 //Add Selection indicator let selectedView = (_scrollView.viewWithTag(selectedSectionIndex + 999)) as! UIButton var frame = selectedView.frame frame.origin.y += (frame.size.height) frame.size.height = selectionIndicatorHeight _selectionIndicator.frame = frame _scrollView.addSubview(_selectionIndicator) _selectionIndicator.backgroundColor = selectionIndicatorColor // //change state of selected section selectedView.isSelected = true _scrollView.scrollRectToVisible(selectedView.frame, animated: true) } func rescaleImagesIfNeeded(){ if _controlType != .imageText && _controlType != .image { return } let padding : CGFloat = 5 let topInset : CGFloat = 7 let bottomInset : CGFloat = 7 for index in 0..<numberOfSegments{ var titleHeight : CGFloat = 0 var selectedTitleHeight : CGFloat = 0 if _controlType == .imageText { let attrTitle = NSAttributedString(string: (_sectionTitles?[index])!, attributes: titleTextAttributes) let attrTitleSelected = NSAttributedString(string: (_sectionTitles?[index])!, attributes: selectedTitleTextAttributes) titleHeight = attrTitle.size().height + padding selectedTitleHeight = attrTitleSelected.size().height + padding } if let image = _sectionImages?[index] , let selectedImage = _selectedSectionImages?[index] { //Match heights of images and selected images by taking min so that chances of rescaling are reduced in next step let minHeight = min(image.size.height, selectedImage.size.height) if image.size.height != selectedImage.size.height { if image.size.height > selectedImage.size.height{ _sectionImages?[index] = image.resizeImage( newHeight: minHeight) } else{ _selectedSectionImages?[index] = selectedImage.resizeImage( newHeight: minHeight) } } //rescale section images if they do not fit in button let totalHeight = minHeight + titleHeight + topInset + bottomInset let totalSelectedHeight = minHeight + selectedTitleHeight + topInset + bottomInset if totalHeight > self.frame.size.height{ _sectionImages?[index] = image.resizeImage( newHeight: self.frame.size.height - titleHeight - topInset - bottomInset) } if totalSelectedHeight > self.frame.size.height{ _selectedSectionImages?[index] = selectedImage.resizeImage( newHeight: self.frame.size.height - selectedTitleHeight - topInset - bottomInset) } } } } //MARK: Drawing helpers func attributedTitleAt(index:Int) -> NSAttributedString { let title = _sectionTitles?[index] let textAtt = selectedSectionIndex == index ? selectedTitleTextAttributes : titleTextAttributes return NSAttributedString.init(string: title!, attributes: textAtt) } func maxWidth() -> CGFloat { var maxWidth:CGFloat = 0 let count = numberOfSegments for i in 0...count-1{ let currentWidth = widthAt(index: i) maxWidth = currentWidth > maxWidth ? currentWidth : maxWidth } //IF the max width can be increased to fill screen // let calcMaxScrWidth = (self.frame.size.width - (CGFloat(numberOfSegments+1) * sectionMargin))/CGFloat( numberOfSegments) let calcMaxScrWidth = (self.frame.size.width - (CGFloat(numberOfSegments) * (sectionInset*2)))/CGFloat( numberOfSegments) maxWidth = calcMaxScrWidth > maxWidth ? calcMaxScrWidth : maxWidth return maxWidth } func widthAt(index:Int) -> CGFloat { switch _controlType { case .image: let image = _sectionImages?[index] return image!.size.width case .imageText: let attrStr = self.attributedTitleAt(index: index) let image = _sectionImages![index] let selectedImage = _selectedSectionImages![index] return max(attrStr.size().width,image.size.width, selectedImage.size.width) case .text: let attrStr = self.attributedTitleAt(index: index) return attrStr.size().width } } public func viewAt(segmentIndex:Int) -> UIView? { return self.viewWithTag(segmentIndex+999) } //MARK: - Action for sections tap func sectionSlected(button:UIButton) { selectSegment(segmentbButton: button,index: nil, shouldSendAction: true) } open func selectSegment(segmentbButton:UIButton?,index:Int?) { selectSegment(segmentbButton: segmentbButton, index: index, shouldSendAction: false) } private func selectSegment(segmentbButton:UIButton?,index:Int? , shouldSendAction:Bool) { selectSegment(segmentbButton: segmentbButton, index: index, shouldSendAction: shouldSendAction, isReselect: false) } private func selectSegment(segmentbButton:UIButton?,index:Int? , shouldSendAction:Bool, isReselect:Bool){ switch (index , segmentbButton) { case let (x,y) where x == nil && y == nil: return case ( let x , _) where x != nil : if x! > numberOfSegments - 1 || x! < 0 { return } default: break } let currentSelectionView = segmentbButton != nil ? segmentbButton : (_scrollView.viewWithTag(index! + 999) as! UIButton) let currentSectionIndex = (currentSelectionView?.tag)! - 999 if currentSectionIndex == self.selectedSectionIndex && isReselect == false { return } if isReselect == false { lastSelectedSectionIndex = self.selectedSectionIndex self.selectedSectionIndex = currentSectionIndex } //delegate method called always even when user selects segment self.delegate?.segmentControl(segmentControl: self, willSelectSegmentAt: currentSectionIndex) if shouldSendAction { self.sendActions(for: .valueChanged) } _selectionIndicator.layer.removeAllAnimations() _scrollView.scrollRectToVisible((currentSelectionView?.frame)!, animated: true) UIView.animate(withDuration: 0.2, animations: { let newPosition = CGRect(x: (currentSelectionView?.frame.origin.x)!, y: self._selectionIndicator.frame.origin.y, width: (currentSelectionView?.frame.size.width)!, height: self.selectionIndicatorHeight) self._selectionIndicator.frame = newPosition }) { (completed) in if isReselect == false{ currentSelectionView?.isSelected = true let lastSelectedView = self._scrollView.viewWithTag(self.lastSelectedSectionIndex+999) as! UIButton lastSelectedView.isSelected = false } //delegate method called always even when user selects segment self.delegate?.segmentControl(segmentControl: self, didSelectSegmentAt: currentSectionIndex) } } //MARK: - Refresh open func refreshSegemts() { // self.setNeedsDisplay() self.drawSegments() } //MARK: - Drag to next open func beginMoveToNextSegment(){ //disable touch } open func endMoveToNextSegment(){ switch (selectedSectionIndex,_currentDirection) { case (0, .backward): return case (numberOfSegments - 1,.forward): return default: // print("Default case endMoveToNextSegment \(selectedSectionIndex), \(_currentDirection), \(_currentProgress)") break } if _currentProgress > 0.5 { //move to next section selectSegment(segmentbButton: nil, index: selectedSectionIndex + (_currentDirection == .forward ? 1 : -1) , shouldSendAction: false) } else{ //move back to deafult pos selectSegment(segmentbButton: nil, index: selectedSectionIndex , shouldSendAction: false, isReselect: true) } //enable touch } open func setProgressToNextSegment(progress:CGFloat , direction : SDMoveDirection){ _currentDirection = direction switch (selectedSectionIndex,direction) { case (0,.backward): return case (numberOfSegments - 1,.forward): return default: break } switch progress { case let p where p <= 0: _currentProgress = 0 return case let p where p >= 1: _currentProgress = 1 // case let p where p > 0.5: // //TODO:select segment and deselect previous // break // case let p where p <= 0.5: // //TODO:deselect segment and select previous // break default: _currentProgress = progress break } let viewTag = selectedSectionIndex + (direction == .forward ? 1 : -1) + 999 let nxtSegmentView = _scrollView.viewWithTag(viewTag) as! UIButton let nxtFrame = nxtSegmentView.frame let currentView = _scrollView.viewWithTag(selectedSectionIndex + 999) as! UIButton let currentFrame = currentView.frame var x : CGFloat = 0 var width : CGFloat = 0 let y = _selectionIndicator.frame.origin.y switch (direction , segmentWidthStyle) { case (.forward , .fixed): x = currentFrame.origin.x + ((currentFrame.size.width ) * _currentProgress) width = nxtFrame.size.width break case (.forward , .dynamic): x = currentFrame.origin.x + ((currentFrame.size.width ) * _currentProgress) width = currentFrame.size.width + (nxtFrame.size.width - currentFrame.size.width) * _currentProgress break case (.backward , .fixed): x = currentFrame.origin.x - ((currentFrame.size.width ) * _currentProgress) width = nxtFrame.size.width break case (.backward , .dynamic): x = currentFrame.origin.x - ((nxtFrame.size.width ) * _currentProgress) width = currentFrame.size.width + (nxtFrame.size.width - currentFrame.size.width) * _currentProgress break } _selectionIndicator.frame = CGRect(x:x , y: y, width:width, height:selectionIndicatorHeight) // switch direction { // case .forward: // let x = currentFrame.origin.x + (nxtFrame.size.width * _currentProgress) // _selectionIndicator.frame = CGRect(x:x , y: _selectionIndicator.frame.origin.y, width:nxtFrame.size.width * (segmentWidthStyle == .fixed ? 1 : _currentProgress), height:selectionIndicatorHeight) // break // default: // let x = currentFrame.origin.x - (nxtFrame.size.width * _currentProgress) // NSLog("backx = \(x)") // _selectionIndicator.frame = CGRect(x:x , y: _selectionIndicator.frame.origin.y, width:nxtFrame.size.width * (segmentWidthStyle == .fixed ? 1 : _currentProgress), height:selectionIndicatorHeight) // // break // } } }
mit
97e383a20519e57d47b79b999d52e75f
35.274882
213
0.597596
5.207984
false
false
false
false
subdigital/ios-extensions-demo
Catify-starting/CatifyExtension/Functions.swift
1
1365
class Box<T> { var unbox: T init(_ value: T) { unbox = value } } enum Result<T> { case Success(Box<T>) case Error(String) func map<U>(transform: T -> U) -> Result<U> { switch self { case .Success(let value): return .Success(Box(transform(value.unbox))) case .Error(let error): return .Error(error) } } } func flatten<T>(array: [[T]]) -> [T] { return array.reduce([]) { $0 + $1 } } extension Array { func flatMap<U>(transform: T -> [U]) -> [U] { return flatten(self.map(transform)) } } func flatten<T>(result: Result<Result<T>>) -> Result<T> { switch result { case .Success(let box): switch box.unbox { case .Success(let value): return .Success(value) case .Error(let error): return .Error(error) } case .Error(let error): return .Error(error) } } extension Result { func flatMap<U>(transform: T -> Result<U>) -> Result<U> { return flatten(self.map(transform)) } } func compact<T>(items: [T?]) -> [T] { return items.reduce([]) { if let item = $1 { return $0 + [item] } return $0 } } infix operator >>== { associativity left } func >>==<T, U>(lhs: Result<T>, rhs: (T -> Result<U>)) -> Result<U> { return lhs.flatMap(rhs) }
mit
a272fe8d8ea9aea25f9f5b33260726c6
20
69
0.526007
3.337408
false
false
false
false
davidahouse/chute
chute/ChuteDetail/ChuteTestAttachment.swift
1
2128
// // ChuteTestAttachment.swift // chute // // Created by David House on 10/14/17. // Copyright © 2017 David House. All rights reserved. // import Foundation struct ChuteTestAttachment: Encodable { let testIdentifier: String let attachmentName: String let attachmentFileName: String init?(testIdentifier: String, attachment: ActivityAttachment) { guard let name = attachment.name, let filename = attachment.filename else { return nil } if attachment.uti == "chute.styleSheet" { return nil } self.testIdentifier = testIdentifier attachmentName = name attachmentFileName = filename } } extension ChuteTestAttachment { static func findAttachments(testSummary: TestSummary) -> [ChuteTestAttachment] { var results = [ChuteTestAttachment]() for summary in testSummary.testableSummaries { for test in summary.tests { results += findAttachments(testDetails: test) } } return results } private static func findAttachments(testDetails: TestDetails) -> [ChuteTestAttachment] { var results = [ChuteTestAttachment]() if let activities = testDetails.activitySummaries { for activity in activities { if let attachments = activity.attachments { for attachment in attachments { if let chuteAttachment = ChuteTestAttachment(testIdentifier: testDetails.testIdentifier ?? "", attachment: attachment) { results.append(chuteAttachment) } } } } } if let subtests = testDetails.subtests { for subtest in subtests { results += findAttachments(testDetails: subtest) } } return results } } extension Array where Element == ChuteTestAttachment { func sortedByName() -> [ChuteTestAttachment] { return self.sorted(by: { $0.attachmentName < $1.attachmentName }) } }
mit
557055bbbc6cb310bc9c3634cc5725ed
25.5875
144
0.599906
4.935035
false
true
false
false
wireapp/wire-ios-data-model
Source/Notifications/ObjectObserverTokens/ConversationListChangeInfo.swift
1
5048
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireSystem private var zmLog = ZMSLog(tag: "ConversationListObserverCenter") extension ZMConversationList { func toOrderedSetState() -> OrderedSetState<ZMConversation> { return OrderedSetState(array: self.map {$0 as! ZMConversation}) } } @objcMembers public final class ConversationListChangeInfo: NSObject, SetChangeInfoOwner { public typealias ChangeInfoContent = ZMConversation public var setChangeInfo: SetChangeInfo<ZMConversation> public var conversationList: ZMConversationList { return setChangeInfo.observedObject as! ZMConversationList } init(setChangeInfo: SetChangeInfo<ZMConversation>) { self.setChangeInfo = setChangeInfo } public var orderedSetState: OrderedSetState<ChangeInfoContent> { return setChangeInfo.orderedSetState } public var insertedIndexes: IndexSet { return setChangeInfo.insertedIndexes } public var deletedIndexes: IndexSet { return setChangeInfo.deletedIndexes } public var deletedObjects: Set<AnyHashable> { return setChangeInfo.deletedObjects } public var updatedIndexes: IndexSet { return setChangeInfo.updatedIndexes } public var movedIndexPairs: [MovedIndex] { return setChangeInfo.movedIndexPairs } public var zm_movedIndexPairs: [ZMMovedIndex] { return setChangeInfo.zm_movedIndexPairs} public func enumerateMovedIndexes(_ block:@escaping (_ from: Int, _ to: Int) -> Void) { setChangeInfo.enumerateMovedIndexes(block) } } @objc public protocol ZMConversationListObserver: NSObjectProtocol { func conversationListDidChange(_ changeInfo: ConversationListChangeInfo) @objc optional func conversationInsideList(_ list: ZMConversationList, didChange changeInfo: ConversationChangeInfo) } @objc public protocol ZMConversationListReloadObserver: NSObjectProtocol { func conversationListsDidReload() } @objc public protocol ZMConversationListFolderObserver: NSObjectProtocol { func conversationListsDidChangeFolders() } extension ConversationListChangeInfo { /// Adds a ZMConversationListObserver to the specified list /// You must hold on to the token and use it to unregister @objc(addObserver:forList:managedObjectContext:) public static func addListObserver(_ observer: ZMConversationListObserver, for list: ZMConversationList?, managedObjectContext: NSManagedObjectContext) -> NSObjectProtocol { if let list = list { zmLog.debug("Registering observer \(observer) for list \(list.identifier)") } else { zmLog.debug("Registering observer \(observer) for all lists") } return ManagedObjectObserverToken(name: .conversationListDidChange, managedObjectContext: managedObjectContext, object: list) { [weak observer] (note) in guard let `observer` = observer, let aList = note.object as? ZMConversationList else { return } zmLog.debug("Notifying registered observer \(observer) about changes in list: \(aList.identifier)") if let changeInfo = note.userInfo["conversationListChangeInfo"] as? ConversationListChangeInfo { observer.conversationListDidChange(changeInfo) } if let changeInfos = note.userInfo["conversationChangeInfos"] as? [ConversationChangeInfo] { changeInfos.forEach { observer.conversationInsideList?(aList, didChange: $0) } } } } @objc(addConversationListReloadObserver:managedObjectcontext:) public static func addReloadObserver(_ observer: ZMConversationListReloadObserver, managedObjectContext: NSManagedObjectContext) -> NSObjectProtocol { return ManagedObjectObserverToken(name: .conversationListsDidReload, managedObjectContext: managedObjectContext, block: { [weak observer] _ in observer?.conversationListsDidReload() }) } @objc(addConversationListFolderObserver:managedObjectcontext:) public static func addFolderObserver(_ observer: ZMConversationListFolderObserver, managedObjectContext: NSManagedObjectContext) -> NSObjectProtocol { return ManagedObjectObserverToken(name: .conversationListDidChangeFolders, managedObjectContext: managedObjectContext, block: { [weak observer] _ in observer?.conversationListsDidChangeFolders() }) } }
gpl-3.0
bbcdadb483bdb8b4e1938dd0ca7e07ca
45.311927
177
0.747623
5.172131
false
false
false
false
RickPasveer/RPSwiftExtension
Sources/Extensions/Classes/NestedArray.swift
1
2559
// // NestedArray.swift // bouw7-universal // // Created by Rick Pasveer on 25-05-16. // Copyright © 2016 Rick Pasveer. All rights reserved. // import Foundation public protocol SectionIdentifier { var sectionKeyPath: String { get } var sortProperty: String { get } } public struct SectionList<T> { fileprivate var array = Array<T>() fileprivate var title = "" public var count: Int { return array.count } public subscript(row: Int) -> T { get { return array[row] } set { array[row] = newValue } } } public struct NestedArray<T: SectionIdentifier> { fileprivate var array = Array<SectionList<T>>() public var sectionTitles = Array<String>() fileprivate var hasSubHeader = false public var sections: Int { return array.count } public var isEmpty: Bool { return array.isEmpty } public subscript(index: IndexPath) -> T { get { if hasSubHeader { return array[index.section][index.row - 1] } else { return array[index.section][index.row] } } set { } } public subscript(sectionTitle: Int) -> String { get { return array[sectionTitle].title } set { } } public subscript(section: Int) -> Int { get { if hasSubHeader { return array[section].count + 1 } else { return array[section].count } } set { } } public init() { } public init(empty: T) { } public init(empty: Array<T>) { } public init(list: Array<T>, withSubHeader: Bool, sortOrderAscending: Bool) { self.hasSubHeader = withSubHeader let sectionSet = Set(list.map { $0.sectionKeyPath }) let sectionList = sortOrderAscending ? Array(sectionSet).sorted(by: <) : Array(sectionSet).sorted(by: >) for sectionTitle in sectionList { let childList = list.filter({ $0.sectionKeyPath == sectionTitle }) var parent = SectionList<T>() parent.array = childList.sorted(by: {$0.sortProperty < $1.sortProperty}) parent.title = sectionTitle self.sectionTitles.append(sectionTitle) self.array.append(parent) } } }
mit
e41ba69f7362e7167ebb217f859ffd5e
21.839286
112
0.523065
4.584229
false
false
false
false
DaVinAhn/EPubParser
EPubParserTests/EPubParserTests.swift
1
3225
// // EPubParserTests.swift // EPubParserTests // // Created by DaVin Ahn on 2017. 1. 8.. // Copyright © 2017년 Davin Ahn. All rights reserved. // import XCTest @testable import EPubParser class EPubParserTests: 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 documentPath() -> String { return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] } func testUnzip() { let path1 = "Sample.epub" do { _ = try EPubHelper.entriesOfZipAt(path1, password: nil) } catch UnzipError.fileNotFound(let path) { XCTAssertTrue(path1 == path) } catch { XCTFail() } let path2 = Bundle(for: self.classForCoder).path(forResource: "Sample", ofType: "epub")! do { let results = [ "mimetype", "META-INF/container.xml", "OEBPS/content.opf", "OEBPS/Text/Section0001.xhtml", "OEBPS/toc.ncx" ] let entries = try EPubHelper.entriesOfZipAt(path2, password: nil) XCTAssertTrue(!entries.isEmpty && entries.count == results.count) for i in 0..<results.count { XCTAssertTrue(entries[i] == results[i]) } let data = try EPubHelper.dataOf("mimetype", atZipPath: path2, password: nil) XCTAssertTrue(String(data: data, encoding: String.Encoding.ascii)! == "application/epub+zip") _ = try EPubHelper.dataOf("OEBPS", atZipPath: path2, password: nil) } catch UnzipError.fileNotFound(let path) { XCTAssertTrue("OEBPS" == path) } catch { XCTFail() } do { try EPubHelper.validateZipAt(path2) } catch { XCTFail() } let url1 = Bundle(for: self.classForCoder).url(forResource: "Sample", withExtension: "cbz")! do { _ = try EPubHelper.entriesOfZipAt(url1, password: nil) } catch UnzipError.fileNotSupport(let path) { XCTAssertTrue(url1.path == path) } catch { XCTFail() } let url2 = URL(string: "https://github.com/DaVinAhn/EPubParser")! do { _ = try EPubHelper.entriesOfZipAt(url2, password: nil) } catch UnzipError.notFile(let url) { XCTAssertTrue(url2 == url) } catch { XCTFail() } let toPath = documentPath().appendingPathComponent("sample") do { let entries = try EPubHelper.unzipAt(path2, toPath: toPath, password: nil) for entry in entries { XCTAssertTrue(FileManager.default.fileExists(atPath: toPath.appendingPathComponent(entry))) } } catch { XCTFail() } } }
apache-2.0
4753edf5595bdb478a2c6e1b71fa4e15
32.216495
111
0.553693
4.377717
false
true
false
false
caicai0/ios_demo
Broadcast/BroadcastService/Upload/SampleHandler.swift
1
1272
// // SampleHandler.swift // Upload // // Created by 李玉峰 on 2018/4/25. // Copyright © 2018年 cai. All rights reserved. // import ReplayKit class SampleHandler: RPBroadcastSampleHandler { var encodePush :EncodeAndPush? = nil override func broadcastStarted(withSetupInfo setupInfo: [String : NSObject]?) { let videoConfiguration : LFLiveVideoConfiguration = LFLiveVideoConfiguration() let audioConfiguration : LFLiveAudioConfiguration = LFLiveAudioConfiguration() encodePush = EncodeAndPush(audioConfiguration: audioConfiguration, videoConfiguration: videoConfiguration) encodePush?.running = true } override func broadcastPaused() { } override func broadcastResumed() { } override func broadcastFinished() { } override func processSampleBuffer(_ sampleBuffer: CMSampleBuffer, with sampleBufferType: RPSampleBufferType) { switch sampleBufferType { case RPSampleBufferType.video: break case RPSampleBufferType.audioApp: break case RPSampleBufferType.audioMic: break } } }
mit
473e4c9b4fb620d80d40bafce58f47ab
25.3125
114
0.622328
5.397436
false
true
false
false
gustavoavena/MOPT
MOPT/TableViewHelper.swift
1
2914
// // TableViewHelper.swift // MOPT // // Created by Gustavo Avena on 114//17. // Copyright © 2017 Gustavo Avena. All rights reserved. // import UIKit import CloudKit import Dispatch // Definitely a faulty implementation, due to the use of semaphores. But it does what we need it to do for now... class TableViewHelper: NSObject { static let userServices = UserServices() static func assignImageByClass(cell: UITableViewCell, imageFile: UIImage) { // if cell is MeetingTableViewCell { // (cell as! MeetingTableViewCell).moderatorPicture.image = imageFile // } // else if cell is TopicsTableViewCell { // (cell as! TopicsTableViewCell).topicCreatorPicture.image = imageFile // } else if cell is SubtopicsTableViewCell { // (cell as! SubtopicsTableViewCell).subtopicCreatorPicture.image = imageFile // } else if cell is CommentsTableViewCell { // (cell as! CommentsTableViewCell).commentCreatorPicture.image = imageFile // } else if cell is PreviousMeetingsTableViewCell { // (cell as! PreviousMeetingsTableViewCell).moderatorPicture.image = imageFile // } } public static func loadCellProfilePicture(fromUser userID: ObjectID, cell: UITableViewCell) -> UITableViewCell { let semaphore = DispatchSemaphore(value: 0) let documentsDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let fileName = documentsDirectory.appendingPathComponent(String(format: "%@ProfilePicture.jpg", userID)) if let imageFile = UIImage(contentsOfFile: fileName.path) { self.assignImageByClass(cell: cell, imageFile: imageFile) semaphore.signal() // print("Loaded profile picture from file.") } else { let user = Cache.get(objectType: .user, objectWithID: userID) as! User self.userServices.downloadImage(imageURL: user.profilePictureURL, userID: userID) if let imageFile = UIImage(contentsOfFile: fileName.path) { self.assignImageByClass(cell: cell, imageFile: imageFile) } else { print("Error loading picture after downlaoding it.") } semaphore.signal() } semaphore.wait() return cell } public static func getImageFromDirectory(userRecordName: String?) -> UIImage? { guard userRecordName != nil else { return nil } let documentsDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let fileName = documentsDirectory.appendingPathComponent(String(format: "%@ProfilePicture.jpg", userRecordName!)) // Force unwrap because you can't get here without being logged in. if let imageFile = UIImage(contentsOfFile: fileName.path){ return imageFile } else { print("Couldn't load user picture to display by the comment textbox.") return nil } } }
mit
62e90410429f1ded46a636cd5c69bbea
33.270588
189
0.710951
4.246356
false
false
false
false
iOkay/MiaoWuWu
Pods/Material/Sources/iOS/Material+CALayer.swift
1
9941
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * 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 internal class MaterialLayer { /// A reference to the CALayer. internal weak var layer: CALayer? /// A property that sets the height of the layer's frame. internal var heightPreset = HeightPreset.default { didSet { layer?.height = CGFloat(heightPreset.rawValue) } } /// A property that sets the cornerRadius of the backing layer. internal var cornerRadiusPreset = CornerRadiusPreset.none { didSet { layer?.cornerRadius = CornerRadiusPresetToValue(preset: cornerRadiusPreset) } } /// A preset property to set the borderWidth. internal var borderWidthPreset = BorderWidthPreset.none { didSet { layer?.borderWidth = BorderWidthPresetToValue(preset: borderWidthPreset) } } /// A preset property to set the shape. internal var shapePreset = ShapePreset.none /// A preset value for Depth. internal var depthPreset: DepthPreset { get { return depth.preset } set(value) { depth.preset = value } } /// Grid reference. internal var depth = Depth.zero { didSet { guard let v = layer else { return } v.shadowOffset = depth.offset.asSize v.shadowOpacity = depth.opacity v.shadowRadius = depth.radius v.layoutShadowPath() } } /// Enables automatic shadowPath sizing. internal var isShadowPathAutoSizing = false /** Initializer that takes in a CALayer. - Parameter view: A CALayer reference. */ internal init(layer: CALayer?) { self.layer = layer } } /// A memory reference to the MaterialLayer instance for CALayer extensions. private var MaterialLayerKey: UInt8 = 0 /// Grid extension for UIView. extension CALayer { /// MaterialLayer Reference. internal var materialLayer: MaterialLayer { get { return AssociatedObject(base: self, key: &MaterialLayerKey) { return MaterialLayer(layer: self) } } set(value) { AssociateObject(base: self, key: &MaterialLayerKey, value: value) } } /// A property that accesses the frame.origin.x property. @IBInspectable open var x: CGFloat { get { return frame.origin.x } set(value) { frame.origin.x = value layoutShadowPath() } } /// A property that accesses the frame.origin.y property. @IBInspectable open var y: CGFloat { get { return frame.origin.y } set(value) { frame.origin.y = value layoutShadowPath() } } /// A property that accesses the frame.size.width property. @IBInspectable open var width: CGFloat { get { return frame.size.width } set(value) { frame.size.width = value if .none != shapePreset { frame.size.height = value layoutShape() } layoutShadowPath() } } /// A property that accesses the frame.size.height property. @IBInspectable open var height: CGFloat { get { return frame.size.height } set(value) { frame.size.height = value if .none != shapePreset { frame.size.width = value layoutShape() } layoutShadowPath() } } /// HeightPreset value. open var heightPreset: HeightPreset { get { return materialLayer.heightPreset } set(value) { materialLayer.heightPreset = value } } /** A property that manages the overall shape for the object. If either the width or height property is set, the other will be automatically adjusted to maintain the shape of the object. */ open var shapePreset: ShapePreset { get { return materialLayer.shapePreset } set(value) { materialLayer.shapePreset = value } } /// A preset value for Depth. open var depthPreset: DepthPreset { get { return depth.preset } set(value) { depth.preset = value } } /// Grid reference. open var depth: Depth { get { return materialLayer.depth } set(value) { materialLayer.depth = value } } /// Enables automatic shadowPath sizing. @IBInspectable open var isShadowPathAutoSizing: Bool { get { return materialLayer.isShadowPathAutoSizing } set(value) { materialLayer.isShadowPathAutoSizing = value } } /// A property that sets the cornerRadius of the backing layer. open var cornerRadiusPreset: CornerRadiusPreset { get { return materialLayer.cornerRadiusPreset } set(value) { materialLayer.cornerRadiusPreset = value } } /// A preset property to set the borderWidth. open var borderWidthPreset: BorderWidthPreset { get { return materialLayer.borderWidthPreset } set(value) { materialLayer.borderWidthPreset = value } } /** A method that accepts CAAnimation objects and executes them on the view's backing layer. - Parameter animation: A CAAnimation instance. */ open func animate(animation: CAAnimation) { if let a = animation as? CABasicAnimation { a.fromValue = (nil == presentation() ? self : presentation()!).value(forKeyPath: a.keyPath!) } if let a = animation as? CAPropertyAnimation { add(a, forKey: a.keyPath!) } else if let a = animation as? CAAnimationGroup { add(a, forKey: nil) } else if let a = animation as? CATransition { add(a, forKey: kCATransition) } } /** A delegation method that is executed when the backing layer stops running an animation. - Parameter animation: The CAAnimation instance that stopped running. - Parameter flag: A boolean that indicates if the animation stopped because it was completed or interrupted. True if completed, false if interrupted. */ open func animationDidStop(_ animation: CAAnimation, finished flag: Bool) { if let a = animation as? CAPropertyAnimation { if let b = a as? CABasicAnimation { if let v = b.toValue { if let k = b.keyPath { setValue(v, forKeyPath: k) removeAnimation(forKey: k) } } } } else if let a = animation as? CAAnimationGroup { for x in a.animations! { animationDidStop(x, finished: true) } } } /// Manages the layout for the shape of the view instance. open func layoutShape() { guard 0 < width, 0 < height else { return } if .none != shapePreset { if width < height { frame.size.width = height } else if width > height { frame.size.height = width } } if .circle == shapePreset { cornerRadius = width / 2 } } /// Sets the shadow path. open func layoutShadowPath() { guard isShadowPathAutoSizing else { return } if .none == depthPreset { shadowPath = nil } else if nil == shadowPath { shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath } else { let a = Animation.shadowPath(path: UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath) a.fromValue = shadowPath animate(animation: a) } } }
gpl-3.0
4f4abfc50bec66960fcdeb2b6c833b65
29.215805
116
0.580927
5.074528
false
false
false
false
kstaring/swift
test/IRGen/associated_type_witness.swift
4
11892
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir > %t.ll // RUN: %FileCheck %s -check-prefix=GLOBAL < %t.ll // RUN: %FileCheck %s < %t.ll // REQUIRES: CPU=x86_64 protocol P {} protocol Q {} protocol Assocked { associatedtype Assoc : P, Q } struct Universal : P, Q {} // Witness table access functions for Universal : P and Universal : Q. // CHECK-LABEL: define hidden i8** @_TWaV23associated_type_witness9UniversalS_1PS_() // CHECK: ret i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_TWPV23associated_type_witness9UniversalS_1PS_, i32 0, i32 0) // CHECK-LABEL: define hidden i8** @_TWaV23associated_type_witness9UniversalS_1QS_() // CHECK: ret i8** getelementptr inbounds ([0 x i8*], [0 x i8*]* @_TWPV23associated_type_witness9UniversalS_1QS_, i32 0, i32 0) // Witness table for WithUniversal : Assocked. // GLOBAL-LABEL: @_TWPV23associated_type_witness13WithUniversalS_8AssockedS_ = hidden constant [3 x i8*] [ // GLOBAL-SAME: i8* bitcast (%swift.type* ()* @_TMaV23associated_type_witness9Universal to i8*) // GLOBAL-SAME: i8* bitcast (i8** ()* @_TWaV23associated_type_witness9UniversalS_1PS_ to i8*) // GLOBAL-SAME: i8* bitcast (i8** ()* @_TWaV23associated_type_witness9UniversalS_1QS_ to i8*) // GLOBAL-SAME: ] struct WithUniversal : Assocked { typealias Assoc = Universal } // Witness table for GenericWithUniversal : Assocked. // GLOBAL-LABEL: @_TWPurGV23associated_type_witness20GenericWithUniversalx_S_8AssockedS_ = hidden constant [3 x i8*] [ // GLOBAL-SAME: i8* bitcast (%swift.type* ()* @_TMaV23associated_type_witness9Universal to i8*) // GLOBAL-SAME: i8* bitcast (i8** ()* @_TWaV23associated_type_witness9UniversalS_1PS_ to i8*) // GLOBAL-SAME: i8* bitcast (i8** ()* @_TWaV23associated_type_witness9UniversalS_1QS_ to i8*) // GLOBAL-SAME: ] struct GenericWithUniversal<T> : Assocked { typealias Assoc = Universal } // Witness table for Fulfilled : Assocked. // GLOBAL-LABEL: @_TWPuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_ = hidden constant [3 x i8*] [ // GLOBAL-SAME: i8* bitcast (%swift.type* (%swift.type*, i8**)* @_TWtuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5Assoc to i8*) // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_TWTuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5AssocPS_1P_ to i8*) // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_TWTuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5AssocPS_1Q_ to i8*) // GLOBAL-SAME: ] struct Fulfilled<T : P & Q> : Assocked { typealias Assoc = T } // Associated type metadata access function for Fulfilled.Assoc. // CHECK-LABEL: define internal %swift.type* @_TWtuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5Assoc(%swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked") // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to %swift.type** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i64 3 // CHECK-NEXT: [[T2:%.*]] = load %swift.type*, %swift.type** [[T1]], align 8, !invariant.load // CHECK-NEXT: ret %swift.type* [[T2]] // Associated type witness table access function for Fulfilled.Assoc : P. // CHECK-LABEL: define internal i8** @_TWTuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5AssocPS_1P_(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked") // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8*** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 4 // CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load // CHECK-NEXT: ret i8** [[T2]] // Associated type witness table access function for Fulfilled.Assoc : Q. // CHECK-LABEL: define internal i8** @_TWTuRx23associated_type_witness1PxS_1QrGVS_9Fulfilledx_S_8AssockedS_5AssocPS_1Q_(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked") // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8*** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 5 // CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load // CHECK-NEXT: ret i8** [[T2]] struct Pair<T, U> : P, Q {} // Generic witness table pattern for Computed : Assocked. // GLOBAL-LABEL: @_TWPu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_ = hidden constant [3 x i8*] [ // GLOBAL-SAME: i8* bitcast (%swift.type* (%swift.type*, i8**)* @_TWtu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_5Assoc to i8*) // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_TWTu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_5AssocPS_1P_ to i8*) // GLOBAL-SAME: i8* bitcast (i8** (%swift.type*, %swift.type*, i8**)* @_TWTu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_5AssocPS_1Q_ to i8*) // GLOBAL-SAME: ] // Generic witness table cache for Computed : Assocked. // GLOBAL-LABEL: @_TWGu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_ = internal global %swift.generic_witness_table_cache { // GLOBAL-SAME: i16 3, // GLOBAL-SAME: i16 1, // Relative reference to protocol // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (%swift.protocol* @_TMp23associated_type_witness8Assocked to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_TWGu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_, i32 0, i32 2) to i64)) to i32) // Relative reference to witness table template // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([3 x i8*]* @_TWPu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_ to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_TWGu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_, i32 0, i32 3) to i64)) to i32), // No instantiator function // GLOBAL-SAME: i32 0, // GLOBAL-SAME: [16 x i8*] zeroinitializer // GLOBAL-SAME: } struct Computed<T, U> : Assocked { typealias Assoc = Pair<T, U> } // Associated type metadata access function for Computed.Assoc. // CHECK-LABEL: define internal %swift.type* @_TWtu0_rGV23associated_type_witness8Computedxq__S_8AssockedS_5Assoc(%swift.type* %"Computed<T, U>", i8** %"Computed<T, U>.Assocked") // CHECK: entry: // CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** %"Computed<T, U>.Assocked", i32 -1 // CHECK-NEXT: [[CACHE:%.*]] = bitcast i8** [[T0]] to %swift.type** // CHECK-NEXT: [[CACHE_RESULT:%.*]] = load %swift.type*, %swift.type** [[CACHE]], align 8 // CHECK-NEXT: [[T1:%.*]] = icmp eq %swift.type* [[CACHE_RESULT]], null // CHECK-NEXT: br i1 [[T1]], label %fetch, label %cont // CHECK: cont: // CHECK-NEXT: [[T0:%.*]] = phi %swift.type* [ [[CACHE_RESULT]], %entry ], [ [[FETCH_RESULT:%.*]], %fetch ] // CHECK-NEXT: ret %swift.type* [[T0]] // CHECK: fetch: // CHECK-NEXT: [[T0:%.*]] = bitcast %swift.type* %"Computed<T, U>" to %swift.type** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i64 3 // CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T1]], align 8, !invariant.load // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Computed<T, U>" to %swift.type** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i64 4 // CHECK-NEXT: [[U:%.*]] = load %swift.type*, %swift.type** [[T1]], align 8, !invariant.load // CHECK-NEXT: [[FETCH_RESULT]] = call %swift.type* @_TMaV23associated_type_witness4Pair(%swift.type* [[T]], %swift.type* [[U]]) // CHECK-NEXT: store atomic %swift.type* [[FETCH_RESULT]], %swift.type** [[CACHE]] release, align 8 // CHECK-NEXT: br label %cont // Witness table instantiation function for Computed : Assocked. // CHECK-LABEL: define hidden i8** @_TWauRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_(%swift.type*) // CHECK: entry: // CHECK-NEXT: [[WTABLE:%.*]] = call i8** @swift_rt_swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_, %swift.type* %0, i8** null) // CHECK-NEXT: ret i8** [[WTABLE]] struct PBox<T: P> {} protocol HasSimpleAssoc { associatedtype Assoc } protocol DerivedFromSimpleAssoc : HasSimpleAssoc {} // Generic witness table pattern for GenericComputed : DerivedFromSimpleAssoc. // GLOBAL-LABEL: @_TWPuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_ = hidden constant [1 x i8*] zeroinitializer // Generic witness table cache for GenericComputed : DerivedFromSimpleAssoc. // GLOBAL-LABEL: @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_ = internal global %swift.generic_witness_table_cache { // GLOBAL-SAME: i16 1, // GLOBAL-SAME: i16 0, // Relative reference to protocol // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (%swift.protocol* @_TMp23associated_type_witness22DerivedFromSimpleAssoc to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_, i32 0, i32 2) to i64)) to i32) // Relative reference to witness table template // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([1 x i8*]* @_TWPuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_ to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_, i32 0, i32 3) to i64)) to i32), // Relative reference to instantiator function // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (void (i8**, %swift.type*, i8**)* @_TWIuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_ to i64), i64 ptrtoint (i32* getelementptr inbounds (%swift.generic_witness_table_cache, %swift.generic_witness_table_cache* @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_, i32 0, i32 4) to i64)) to i32), // GLOBAL-SAME: [16 x i8*] zeroinitializer // GLOBAL-SAME: } struct GenericComputed<T: P> : DerivedFromSimpleAssoc { typealias Assoc = PBox<T> } // Instantiation function for GenericComputed : DerivedFromSimpleAssoc. // CHECK-LABEL: define internal void @_TWIuRx23associated_type_witness1PrGVS_15GenericComputedx_S_22DerivedFromSimpleAssocS_(i8**, %swift.type*, i8**) // CHECK: [[T0:%.*]] = call i8** @_TWauRx23associated_type_witness1PrGVS_15GenericComputedx_S_14HasSimpleAssocS_(%swift.type* %1) // CHECK-NEXT: [[T1:%.*]] = bitcast i8** [[T0]] to i8* // CHECK-NEXT: [[T2:%.*]] = getelementptr inbounds i8*, i8** %0, i32 0 // CHECK-NEXT: store i8* [[T1]], i8** [[T2]], align 8 // CHECK-NEXT: ret void // Witness table instantiation function for GenericComputed : HasSimpleAssoc.. // CHECK-LABEL: define hidden i8** @_TWauRx23associated_type_witness1PrGVS_15GenericComputedx_S_14HasSimpleAssocS_(%swift.type*) // CHECK-NEXT: entry: // CHECK-NEXT: [[WTABLE:%.*]] = call i8** @swift_rt_swift_getGenericWitnessTable(%swift.generic_witness_table_cache* @_TWGuRx23associated_type_witness1PrGVS_15GenericComputedx_S_14HasSimpleAssocS_, %swift.type* %0, i8** null) // CHECK-NEXT: ret i8** %1 protocol HasAssocked { associatedtype Contents : Assocked } struct FulfilledFromAssociatedType<T : HasAssocked> : HasSimpleAssoc { typealias Assoc = PBox<T.Contents.Assoc> } struct UsesVoid : HasSimpleAssoc { typealias Assoc = () }
apache-2.0
c12b9af3c899ecd1e00967d0321a72c1
67.344828
418
0.693491
3.276936
false
false
false
false
brentsimmons/Evergreen
Account/Sources/Account/Feedly/OAuthAcessTokenRefreshing.swift
1
2293
// // OAuthAcessTokenRefreshing.swift // Account // // Created by Kiel Gillard on 4/11/19. // Copyright © 2019 Ranchero Software, LLC. All rights reserved. // import Foundation import RSWeb /// Models section 6 of the OAuth 2.0 Authorization Framework /// https://tools.ietf.org/html/rfc6749#section-6 public struct OAuthRefreshAccessTokenRequest: Encodable { public let grantType = "refresh_token" public var refreshToken: String public var scope: String? // Possibly not part of the standard but specific to certain implementations (e.g.: Feedly). public var clientId: String public var clientSecret: String public init(refreshToken: String, scope: String?, client: OAuthAuthorizationClient) { self.refreshToken = refreshToken self.scope = scope self.clientId = client.id self.clientSecret = client.secret } } /// Conformed to by API callers to provide a consistent interface for `AccountDelegate` types to refresh OAuth Access Tokens. Conformers provide an associated type that models any custom parameters/properties, as well as the standard ones, in the response to a request for an access token. /// https://tools.ietf.org/html/rfc6749#section-6 public protocol OAuthAcessTokenRefreshRequesting { associatedtype AccessTokenResponse: OAuthAccessTokenResponse /// Access tokens expire. Perform a request for a fresh access token given the long life refresh token received when authorization was granted. /// - Parameter refreshRequest: The refresh token and other information the authorization server requires to grant the client fresh access tokens on the user's behalf. /// - Parameter completion: On success, the access token response appropriate for concrete type's service. Both the access and refresh token should be stored, preferably on the Keychain. On failure, possibly a `URLError` or `OAuthAuthorizationErrorResponse` value. func refreshAccessToken(_ refreshRequest: OAuthRefreshAccessTokenRequest, completion: @escaping (Result<AccessTokenResponse, Error>) -> ()) } /// Implemented by concrete types to perform the actual request. protocol OAuthAccessTokenRefreshing: AnyObject { func refreshAccessToken(with refreshToken: String, client: OAuthAuthorizationClient, completion: @escaping (Result<OAuthAuthorizationGrant, Error>) -> ()) }
mit
94782ac6b8087d96685c9d608fd91f5a
48.826087
289
0.787522
4.565737
false
false
false
false
hollance/swift-algorithm-club
Rootish Array Stack/RootishArrayStack.playground/Contents.swift
4
4681
//: Playground - noun: a place where people can play // last checked with Xcode 9.0b4 #if swift(>=4.0) print("Hello, Swift 4!") #endif import Darwin public struct RootishArrayStack<T> { // MARK: - Instance variables fileprivate var blocks = [Array<T?>]() fileprivate var internalCount = 0 // MARK: - Init public init() { } // MARK: - Calculated variables var count: Int { return internalCount } var capacity: Int { return blocks.count * (blocks.count + 1) / 2 } var isEmpty: Bool { return blocks.count == 0 } var first: T? { guard capacity > 0 else { return nil } return blocks[0][0] } var last: T? { guard capacity > 0 else { return nil } let block = self.block(fromIndex: count - 1) let innerBlockIndex = self.innerBlockIndex(fromIndex: count - 1, fromBlock: block) return blocks[block][innerBlockIndex] } // MARK: - Equations fileprivate func block(fromIndex index: Int) -> Int { let block = Int(ceil((-3.0 + sqrt(9.0 + 8.0 * Double(index))) / 2)) return block } fileprivate func innerBlockIndex(fromIndex index: Int, fromBlock block: Int) -> Int { return index - block * (block + 1) / 2 } // MARK: - Behavior fileprivate mutating func growIfNeeded() { if capacity - blocks.count < count + 1 { let newArray = [T?](repeating: nil, count: blocks.count + 1) blocks.append(newArray) } } fileprivate mutating func shrinkIfNeeded() { if capacity + blocks.count >= count { while blocks.count > 0 && (blocks.count - 2) * (blocks.count - 1) / 2 >= count { blocks.remove(at: blocks.count - 1) } } } public subscript(index: Int) -> T { get { let block = self.block(fromIndex: index) let innerBlockIndex = self.innerBlockIndex(fromIndex: index, fromBlock: block) return blocks[block][innerBlockIndex]! } set(newValue) { let block = self.block(fromIndex: index) let innerBlockIndex = self.innerBlockIndex(fromIndex: index, fromBlock: block) blocks[block][innerBlockIndex] = newValue } } public mutating func insert(element: T, atIndex index: Int) { growIfNeeded() internalCount += 1 var i = count - 1 while i > index { self[i] = self[i - 1] i -= 1 } self[index] = element } public mutating func append(element: T) { insert(element: element, atIndex: count) } fileprivate mutating func makeNil(atIndex index: Int) { let block = self.block(fromIndex: index) let innerBlockIndex = self.innerBlockIndex(fromIndex: index, fromBlock: block) blocks[block][innerBlockIndex] = nil } public mutating func remove(atIndex index: Int) -> T { let element = self[index] for i in index..<count - 1 { self[i] = self[i + 1] } internalCount -= 1 makeNil(atIndex: count) shrinkIfNeeded() return element } // MARK: - Struct to string public var memoryDescription: String { var description = "{\n" for block in blocks { description += "\t[" for index in 0..<block.count { description += "\(block[index])" if index + 1 != block.count { description += ", " } } description += "]\n" } return description + "}" } } extension RootishArrayStack: CustomStringConvertible { public var description: String { var description = "[" for index in 0..<count { description += "\(self[index])" if index + 1 != count { description += ", " } } return description + "]" } } var list = RootishArrayStack<String>() list.isEmpty // true list.first // nil list.last // nil list.count // 0 list.capacity // 0 list.memoryDescription // { // } list.append(element: "Hello") list.isEmpty // false list.first // "Hello" list.last // "hello" list.count // 1 list.capacity // 1 list.memoryDescription // { // [Optional("Hello")] // } list.append(element: "World") list.isEmpty // false list.first // "Hello" list.last // "World" list.count // 2 list.capacity // 3 list[0] // "Hello" list[1] // "World" //list[2] // crash! list.memoryDescription // { // [Optional("Hello")] // [Optional("World"), nil] // } list.insert(element: "Swift", atIndex: 1) list.isEmpty // false list.first // "Hello" list.last // "World" list.count // 3 list.capacity // 6 list[0] // "Hello" list[1] // "Swift" list[2] // "World" list.memoryDescription // { // [Optional("Hello")] // [Optional("Swift"), Optional("World")] // [nil, nil, nil] // } list.remove(atIndex: 2) // "World" list.isEmpty // false list.first // "Hello" list.last // "Swift" list.count // 2 list.capacity // 3 list[0] // "Hello" list[1] // "Swift" //list[2] // crash! list[0] = list[1] list[1] = "is awesome" list // ["Swift", "is awesome"]
mit
a0972865a72bf49cff2b385bb6989898
20.085586
86
0.630207
3.089769
false
false
false
false
AshuMishra/PhotoGallery
PhotoGallery/PhotoGallery/Utility/LocationHandler.swift
1
1915
// // LocationManager.swift // PhotoGallery // // Created by Ashutosh Mishra on 27/12/15. // Copyright © 2015 Ashu.com. All rights reserved. // import Foundation import CoreLocation import UIKit typealias LocationFetchCompletionBlock = (CLLocation?,error: NSError?) -> () class LocationHandler: NSObject, CLLocationManagerDelegate, UIAlertViewDelegate { var currentUserLocation = CLLocation() private var locationFetchCompletionBlock : LocationFetchCompletionBlock? static let sharedInstance = LocationHandler() lazy var locationManager: CLLocationManager = { var manager = CLLocationManager() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyBest manager.distanceFilter = 20.0 return manager }() func fetchLocation(completionBlock: LocationFetchCompletionBlock) { locationFetchCompletionBlock = completionBlock updateLocation() } func updateLocation() { locationManager.requestWhenInUseAuthorization() let authorizationDenied: Bool = (CLLocationManager.authorizationStatus().rawValue == CLAuthorizationStatus.Denied.rawValue) if (authorizationDenied) { let error = NSError(domain: "Error", code: 1, userInfo: ["message": "To enable, please go to Settings and turn on Location Service for this app."]) if let locationFetchCompletionBlock = locationFetchCompletionBlock { locationFetchCompletionBlock(nil, error: error) } } else { locationManager.startUpdatingLocation() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { manager.stopUpdatingLocation() currentUserLocation = locations.last! if let locationFetchCompletionBlock = locationFetchCompletionBlock { locationFetchCompletionBlock(currentUserLocation,error: nil) } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { self.locationFetchCompletionBlock!(nil,error: error) } }
mit
0b8981b7d2a5bac57fcca19ab38b9a45
31.440678
150
0.785266
4.796992
false
false
false
false
huangboju/Moots
Examples/UserLocationService/UserLocationService/UserLocationService.swift
1
2916
// // UserLocationService.swift // UserLocationService // // Created by xiAo_Ju on 2019/4/3. // Copyright © 2019 黄伯驹. All rights reserved. // import UIKit import CoreLocation typealias Coordinate = CLLocationCoordinate2D protocol UserLocation { var coordinate: Coordinate { get } } extension CLLocation: UserLocation { } enum UserLocationError: Swift.Error { case canNotBeLocated } typealias UserLocationCompletionBlock = (UserLocation?, UserLocationError?) -> Void protocol UserLocationProvider { func findUserLocation(then: @escaping UserLocationCompletionBlock) } protocol LocationProvider { var isUserAuthorized: Bool { get } func requestWhenInUseAuthorization() func requestLocation() } extension CLLocationManager: LocationProvider { var isUserAuthorized: Bool { return CLLocationManager.authorizationStatus() == .authorizedWhenInUse } } class UserLocationService: NSObject { fileprivate var provider: LocationProvider fileprivate var locationCompletionBlock: UserLocationCompletionBlock? init(with provider: LocationProvider) { self.provider = provider super.init() } func findUserLocation(then: @escaping UserLocationCompletionBlock) { self.locationCompletionBlock = then if provider.isUserAuthorized { provider.requestLocation() } else { provider.requestWhenInUseAuthorization() } } } extension UserLocationService: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { provider.requestLocation() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { manager.stopUpdatingLocation() if let location = locations.last { locationCompletionBlock?(location, nil) } else { locationCompletionBlock?(nil, .canNotBeLocated) } } } struct UserLocationMock: UserLocation { var coordinate: Coordinate { return Coordinate(latitude: 51.509865, longitude: -0.118092) } } class UserLocationProviderMock: UserLocationProvider { var locationBlockLocationValue: UserLocation? var locationBlockErrorValue: UserLocationError? func findUserLocation(then: @escaping UserLocationCompletionBlock) { then(locationBlockLocationValue, locationBlockErrorValue) } } class LocationProviderMock: LocationProvider { var isRequestWhenInUseAuthorizationCalled = false var isRequestLocationCalled = false var isUserAuthorized: Bool = false func requestWhenInUseAuthorization() { isRequestWhenInUseAuthorizationCalled = true } func requestLocation() { isRequestLocationCalled = true } }
mit
322b5b801376acc2194902f16ec04530
25.688073
110
0.713991
5.427239
false
false
false
false
linggaozhen/Living
LivingApplication/LivingApplication/Classess/Main/Model/RoomListModel.swift
1
805
// // RoomListModel.swift // LivingApplication // // Created by ioser on 17/5/19. // Copyright © 2017年 ioser. All rights reserved. // import UIKit class RoomListModel: NSObject { var specific_catalog : String = "" var owner_uid : Int = 0 var vertical_src : String = "" var room_src : String = "" var avatar_small : String = "" var avatar_mid : String = "" var online : Int = 0 var room_id : Int = 0 var nickname : String = "" var game_name : String = "" var room_name : String = "" var anchor_city : String = "" convenience init(dic : [String : AnyObject]) { self.init() setValuesForKeysWithDictionary(dic) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } }
apache-2.0
8b20bcc5481fe422a6f139649ac6cd43
21.277778
76
0.586035
3.893204
false
false
false
false
auth0/Auth0.swift
Auth0/UserPatchAttributes.swift
1
5035
import Foundation /// User attributes that can be updated using the ``Users/patch(_:attributes:)`` method of ``Users``. final public class UserPatchAttributes { private(set) var dictionary: [String: Any] /** Creates a new `UserPatchAttributes` instance. - Parameter dictionary: Default attribute values. */ public init(dictionary: [String: Any] = [:]) { self.dictionary = dictionary } /** Mark/unmark a user as blocked. - Parameter blocked: If the user is blocked. - Returns: The same `UserPatchAttributes` instance to allow method chaining. */ public func blocked(_ blocked: Bool) -> UserPatchAttributes { dictionary["blocked"] = blocked return self } /** Change the email of the user. - Parameters: - email: New email for the user. - verified: If the email is verified. - verify: If the user should verify the email. - connection: Name of the connection. - clientId: Auth0 Client ID. - Returns: The same `UserPatchAttributes` instance to allow method chaining. */ public func email(_ email: String, verified: Bool? = nil, verify: Bool? = nil, connection: String, clientId: String) -> UserPatchAttributes { dictionary["email"] = email dictionary["verify_email"] = verify dictionary["email_verified"] = verified dictionary["connection"] = connection dictionary["client_id"] = clientId return self } /** Set the verified status of the email. - Parameters: - verified: If the email is verified. - connection: Name of the connection. - Returns: The same `UserPatchAttributes` instance to allow method chaining. */ public func emailVerified(_ verified: Bool, connection: String) -> UserPatchAttributes { dictionary["email_verified"] = verified dictionary["connection"] = connection return self } /** Change the phone number of the user (SMS connection only). - Parameters: - phoneNumber: New phone number for the user. - verified: If the phone number is verified. - verify: If the user should verify the phone number. - connection: Name of the connection. - clientId: Auth0 Client ID. - Returns: The same `UserPatchAttributes` instance to allow method chaining. */ public func phoneNumber(_ phoneNumber: String, verified: Bool? = nil, verify: Bool? = nil, connection: String, clientId: String) -> UserPatchAttributes { dictionary["phone_number"] = phoneNumber dictionary["verify_phone_number"] = verify dictionary["phone_verified"] = verified dictionary["connection"] = connection dictionary["client_id"] = clientId return self } /** Set the verified status of the phone number. - Parameters: - verified: If the phone number is verified or not. - connection: Name of the connection. - Returns: The same `UserPatchAttributes` instance to allow method chaining. */ public func phoneVerified(_ verified: Bool, connection: String) -> UserPatchAttributes { dictionary["phone_verified"] = verified dictionary["connection"] = connection return self } /** Change the user's password. - Parameters: - password: New password for the user. - verify: If the password should be verified by the user. - connection: Name of the connection. - Returns: The same `UserPatchAttributes` instance to allow method chaining. */ public func password(_ password: String, verify: Bool? = nil, connection: String) -> UserPatchAttributes { dictionary["password"] = password dictionary["connection"] = connection dictionary["verify_password"] = verify return self } /** Change the username. - Parameters: - username: New username for the user. - connection: Name of the connection. - Returns: The same `UserPatchAttributes` instance to allow method chaining. */ public func username(_ username: String, connection: String) -> UserPatchAttributes { dictionary["username"] = username dictionary["connection"] = connection return self } /** Update user metadata. - Parameter metadata: New user metadata values. - Returns: The same `UserPatchAttributes` instance to allow method chaining. */ public func userMetadata(_ metadata: [String: Any]) -> UserPatchAttributes { dictionary["user_metadata"] = metadata return self } /** Update app metadata. - Parameter metadata: New app metadata values. - Returns: The same `UserPatchAttributes` instance to allow method chaining. */ public func appMetadata(_ metadata: [String: Any]) -> UserPatchAttributes { dictionary["app_metadata"] = metadata return self } }
mit
139c1d1c00997b7a84d06b1a637744c2
33.02027
157
0.638928
4.902629
false
false
false
false
Shark/GlowingRemote
GlowingRemote WatchKit Extension/DeviceSleepTimerController.swift
1
1473
// // DeviceSleepTimerController.swift // GlowingRemote // // Created by Felix Seidel on 28.07.15. // Copyright © 2015 Felix Seidel. All rights reserved. // import WatchKit import Foundation class DeviceSleepTimerController: WKInterfaceController { @IBOutlet weak var picker : WKInterfacePicker! let timerValues: [String] = ["1min", "5min", "10min", "30min", "60min", "120min"] let timerMinutes: [Int] = [1, 5, 10, 30, 60, 120] var currentSelection: Int = 1 override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() let pickerItems : [WKPickerItem] = timerValues.map { let pickerItem = WKPickerItem() pickerItem.title = $0 pickerItem.caption = $0 return pickerItem } picker.setItems(pickerItems) } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func pickerSelectedItemChanged(value: Int) { currentSelection = timerMinutes[value] } @IBAction func createTimerButtonTapped() { print("Choice: \(currentSelection)min") popController() } }
isc
932ff8d503a07a38d4b71ce85494a59e
26.773585
90
0.637228
4.474164
false
false
false
false
Gatada/Bits
Sources/JBits/UIKit/Decorator/UIColor.swift
1
5160
// // UIColor.swift // JBits // // Created by Johan Basberg on 04/08/2016. // import UIKit public extension UIColor { /// Initialize a color from a hex value. Optionally include an alpha value, which defaults /// to 1 (no transparency). /// /// The hexidecimal is not case sensitive. /// /// To instantiate a UIColor using a hex value, you'll need to format the integer as a /// hexidecimal value. You do this by adding the hexidecimal prefix to the number: `0x` /// /// # Examples: /// ```swift /// UIColor(hex: 0xff0000) // Red /// UIColor(hex: 0xCDCDCD) // Gray /// ``` /// /// - Parameters: /// - hex: The integer that will be resolved to the red, green and blue color component. /// - alpha: The alpha value of the color, default is 1 (full opacity, or no transparency). convenience init?(hex: UInt, alpha: CGFloat = 1) { guard hex <= 0xFFFFFF else { // Value is out of range; an invalid color return nil } let red = CGFloat((hex & 0xFF0000) >> 16)/255 let green = CGFloat((hex & 0x00FF00) >> 8)/255 let blue = CGFloat(hex & 0x0000FF)/255 self.init(red: red, green: green, blue: blue, alpha: alpha) } /// Returns a new `UIColor` that will have a brightness /// offset of 1, making it stand out from the source color. /// /// This is quite useful when you need to dynamically find a color that is /// easily readable against a backdrop, while also being easy on the eyes /// when shown next to or on top of the source color. /// /// If the color is not in a compatible color space, the returned color will /// be the same as the source color (i.e. unchanged); additionally an assert /// failure is thrown. func contrastingColor() -> UIColor { var hue: CGFloat = 1 var saturation: CGFloat = 1 var brightness: CGFloat = 1 var alpha: CGFloat = 1 guard getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) else { assertionFailure("Color is not in a compatible color space") return self } return UIColor(hue: hue, saturation: saturation, brightness: ((brightness + 0.5).truncatingRemainder(dividingBy: 1)), alpha: alpha) } /// Returns a color with an adjusted intensity, increasingly darker by a higher shadow value. /// /// If the color is not in a compatible color space, the returned color will /// be the same as the source color (i.e. unchanged); additionally an assert /// failure is thrown. /// /// - Parameter shadow: The darkness level of the shadow, 0 is no shadow and 1 is maximum shadow. /// - Returns: A new color where a shadow of 1 results in a black color, while 0 returns an unchanged color (no shadow). func withShadowComponent(_ shadow: CGFloat) -> UIColor { let shadow = 1 - shadow var current: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) = (0, 0, 0, 0) guard getRed(&current.red, green: &current.green, blue: &current.blue, alpha: &current.alpha) else { assertionFailure("Color is not in a compatible color space") return self } return UIColor(red: current.red * shadow, green: current.green * shadow, blue: current.blue * shadow, alpha: current.alpha) } /// Returns a new `UIColor` with the provided saturation level. /// /// With a new saturation value of 0 the returned color is unchanged. Providing /// a value of 1 will return a fully desaturated color. /// /// If the color is not in a compatible color space, the returned color will /// be the same as the source color (i.e. unchanged); additionally an assert /// failure is thrown. /// /// - Parameter newSaturation: The new saturation level, ranging from 0 (no change) to 1 (full desaturated). func withSaturation(_ newSaturation: CGFloat) -> UIColor { var current: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) = (0, 0, 0, 0) guard getRed(&current.red, green: &current.green, blue: &current.blue, alpha: &current.alpha) else { assertionFailure("Color is not in a compatible color space") return self } let invertedSaturation = 1 - newSaturation let brightnessRed = 0.299 * pow(current.red, 2) let brightnessGreen = 0.587 * pow(current.green, 2) let brightnessBlue = 0.114 * pow(current.blue, 2) let perceivedBrightness = sqrt(brightnessRed + brightnessGreen + brightnessBlue) let newRed = current.red + invertedSaturation * (perceivedBrightness - current.red) let newGreen = current.green + invertedSaturation * (perceivedBrightness - current.green) let newBlue = current.blue + invertedSaturation * (perceivedBrightness - current.blue) return UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: current.alpha) } }
gpl-3.0
b580d785e464342c523f057380cfb6b2
40.28
139
0.625969
4.369179
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/LostFound/Controller/LostFoundPostViewController.swift
1
4910
// // LostFoundPostViewController.swift // WePeiYang // // Created by Qin Yubo on 16/2/15. // Copyright © 2016年 Qin Yubo. All rights reserved. // import UIKit import FXForms import BlocksKit import SwiftyJSON class LostFoundPostViewController: UITableViewController, FXFormControllerDelegate { var postType: Int = 0 var formController: FXFormController! 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() self.navigationController?.navigationBar.tintColor = UIColor(red: 113/255.0, green: 168/255.0, blue: 57/255.0, alpha: 1.0) // self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:113/255.0 green:168/255.0 blue:57/255.0 alpha:1.0]; formController = FXFormController() formController.tableView = self.tableView formController.delegate = self let form = LostFoundPostForm() form.postType = postType formController.form = form if postType == 0 { self.title = "发布丢失" } else { self.title = "发布捡到" } let cancelBtn = UIBarButtonItem().bk_initWithBarButtonSystemItem(.Cancel, handler: {sender in self.navigationController?.dismissViewControllerAnimated(true, completion: nil) }) as! UIBarButtonItem self.navigationItem.leftBarButtonItem = cancelBtn let sendBtn = UIBarButtonItem().bk_initWithTitle(NSLocalizedString("Send", comment: ""), style: .Plain, handler: {sender in self.postInfo() }) as! UIBarButtonItem self.navigationItem.rightBarButtonItem = sendBtn } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func postInfo() { let form = self.formController.form as! LostFoundPostForm if form.title == nil || form.title!.isEmpty || form.name == nil || form.name!.isEmpty || form.phone == nil || form.phone!.isEmpty { MsgDisplay.showErrorMsg("请填写完整具体内容!") } else { MsgDisplay.showLoading() if postType == 0 { // Lost let time = form.time == nil ? NSDate() : form.time let place = form.place == nil ? "" : form.place let content = form.content == nil ? "" : form.content let lostType = form.lostType == nil ? "0" : form.lostType let otherTag = form.otherTag == nil ? "" : form.otherTag twtSDK.postLostInfoWithTitle(form.title!, name: form.name!, time: time!, place: place!, phone: form.phone!, content:content! , lostType: lostType!, otherTag: otherTag!, success: {(task, responseObj) in let responseData = JSON(responseObj) if responseData["error_code"].int == -1 { MsgDisplay.showSuccessMsg("发布成功!") self.navigationController?.dismissViewControllerAnimated(true, completion: nil) } else { MsgDisplay.showErrorMsg("发布失败") } }, failure: {(task, error) in MsgDisplay.showErrorMsg("发布失败\n\(error.localizedDescription)") }) } else { let time = form.time == nil ? NSDate() : form.time let place = form.place == nil ? "" : form.place let content = form.content == nil ? "" : form.content let foundPic = form.foundPic == nil ? "" : form.foundPic twtSDK.postFoundInfoWithTitle(form.title!, name: form.name!, time: time!, place: place!, phone: form.phone!, content: content!, foundPic: foundPic!, success: {(task, responseObj) in let responseData = JSON(responseObj) if responseData["error_code"].int == -1 { MsgDisplay.showSuccessMsg("发布成功!") self.navigationController?.dismissViewControllerAnimated(true, completion: nil) } else { MsgDisplay.showErrorMsg("发布失败") } }, failure: {(task, error) in MsgDisplay.showErrorMsg("发布失败\n\(error.localizedDescription)") }) } } } }
mit
29e9ba23327d7ca4065ea006fd0fc74e
43.62037
217
0.590786
4.912334
false
false
false
false
yaobanglin/viossvc
viossvc/Scenes/User/MarksTableViewController.swift
2
6151
// // MarksTableViewController.swift // viossvc // // Created by 木柳 on 2016/12/2. // Copyright © 2016年 com.yundian. All rights reserved. // Code By BB import UIKit import SVProgressHUD protocol RefreshSkillDelegate: NSObjectProtocol { func refreshUserSkill() } class MarksTableViewController: BaseTableViewController , LayoutStopDelegate{ @IBOutlet weak var selectSkillView: SkillLayoutView! @IBOutlet weak var allSkillView: SkillLayoutView! var selectHeight:CGFloat = 55.0 var allSkillsHeight:CGFloat = 55.0 var currentSkillsArray:Array<SkillsModel>? var allSkillArray:Array<SkillsModel>? var skillDict:Dictionary<Int, SkillsModel> = [:] var delegate:RefreshSkillDelegate? @IBOutlet weak var submitButton: UIButton! override func viewDidLoad() { selectSkillView.delegate = self allSkillView.delegate = self submitButton.enabled = false setData() MobClick.event(AppConst.Event.server_mark) } func setData() { guard currentSkillsArray == nil else { selectSkillView.showDelete = true selectSkillView.dataSouce = currentSkillsArray allSkillView.dataSouce = allSkillArray return } getAllSkills() getUserSkills() } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 1 { return selectHeight } else if indexPath.row == 3 { return allSkillsHeight } return 45 } func getAllSkills() { unowned let weakSelf = self AppAPIHelper.orderAPI().getSkills({ (response) in let array = response as? Array<SkillsModel> weakSelf.allSkillArray = array for skill in array! { let size = skill.skill_name!.boundingRectWithSize(CGSizeMake(0, 21), font: UIFont.systemFontOfSize(15), lineSpacing: 0) skill.labelWidth = size.width + 30 weakSelf.skillDict[skill.skill_id] = skill } weakSelf.allSkillView.dataSouce = weakSelf.allSkillArray if CurrentUserHelper.shared.userInfo.skills != nil { weakSelf.currentSkillsArray = AppAPIHelper.orderAPI().getSKillsWithModel(CurrentUserHelper.shared.userInfo.skills, dict:weakSelf.skillDict ) weakSelf.selectSkillView.dataSouce = weakSelf.currentSkillsArray } }, error: errorBlockFunc()) } func getUserSkills() { unowned let weakSelf = self AppAPIHelper.userAPI().getOrModfyUserSkills(0, skills: "", complete: { (response) in if response != nil { let dict = response as! Dictionary<String, AnyObject> CurrentUserHelper.shared.userInfo.skills = dict["skills_"] as? String if weakSelf.skillDict.count > 0 { weakSelf.currentSkillsArray = AppAPIHelper.orderAPI().getSKillsWithModel(CurrentUserHelper.shared.userInfo.skills, dict:weakSelf.skillDict ) weakSelf.selectSkillView.showDelete = true weakSelf.selectSkillView.dataSouce = weakSelf.currentSkillsArray } } }, error: errorBlockFunc()) } /** 高度回调 - parameter layoutView: 回调的layoutView - parameter height: 高度 */ func layoutStopWithHeight(layoutView: SkillLayoutView, height: CGFloat) { if layoutView == selectSkillView { guard height > 50 else {return} selectHeight = height } else { allSkillsHeight = height } tableView.reloadData() } /** 点击回调 - parameter layoutView: 点所在的layouView - parameter indexPath: indexPath */ func selectedAtIndexPath(layoutView:SkillLayoutView, indexPath:NSIndexPath) { if layoutView == selectSkillView { guard currentSkillsArray?.count > 0 else {return} currentSkillsArray?.removeAtIndex(indexPath.item) } else { guard currentSkillsArray?.count != 8 else { SVProgressHUD.showWainningMessage(WainningMessage: "不能选择更多标签", ForDuration: 1.5, completion: nil) return } let skill = allSkillArray![indexPath.item] if currentSkillsArray == nil { currentSkillsArray = [] } guard !currentSkillsArray!.contains(skill) else { SVProgressHUD.showWainningMessage(WainningMessage: "您已经选择过此标签", ForDuration: 1.5, completion: nil) return } currentSkillsArray?.append(allSkillArray![indexPath.item]) } submitButton.enabled = true submitButton.backgroundColor = UIColor.init(hexString: "131F32") selectSkillView.showDelete = true selectSkillView.dataSouce = currentSkillsArray } @IBAction func modfySkills(sender: AnyObject) { var idString = "" for skill in currentSkillsArray! { if skill.skill_id != 0 { idString = idString + "\(skill.skill_id)," } } unowned let weakSelf = self AppAPIHelper.userAPI().getOrModfyUserSkills(1, skills: idString, complete: { (response) in if response != nil { let dict = response as! Dictionary<String, AnyObject> CurrentUserHelper.shared.userInfo.skills = dict["skills_"] as? String if weakSelf.delegate != nil { weakSelf.delegate?.refreshUserSkill() } weakSelf.navigationController?.popViewControllerAnimated(true) } }, error: errorBlockFunc()) } }
apache-2.0
e7dffa8a29ecb2ef5dd6b7e119e8a15c
31.843243
160
0.590191
5.080268
false
false
false
false
121372288/Refresh
Refresh/Base/RefreshAutoFooter.swift
1
4795
// // RefreshAutoFooter.swift // Refresh // // Created by 马磊 on 2019/1/13. // Copyright © 2019年 MLCode.com. All rights reserved. // import UIKit open class RefreshAutoFooter: RefreshFooter { /** 是否自动刷新(默认为YES) */ open var isAutomaticallyRefresh: Bool = true /** 当底部控件出现多少时就自动刷新(默认为1.0,也就是底部控件完全出现时,才会自动刷新) */ open var triggerAutomaticallyRefreshPercent: CGFloat = 1.0 /** 是否每一次拖拽只发一次请求 */ open var isOnlyRefreshPerDrag: Bool = false /** 一个新的拖拽 */ var isOneNewPan: Bool = false open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if let _ = newSuperview { if !isHidden { scrollView?.mlInset.bottom += frame.size.height } // 设置位置 self.frame.origin.y = scrollView?.contentSize.height ?? 0 } else { if !isHidden { scrollView?.mlInset.bottom -= frame.size.height } } } open override func prepare() { super.prepare() // 默认底部控件100%出现时才会自动刷新 triggerAutomaticallyRefreshPercent = 1.0 // 设置为默认状态 isAutomaticallyRefresh = true // 默认是当offset达到条件就发送请求(可连续) isOnlyRefreshPerDrag = false } open override func scrollView(contentOffset changed: [NSKeyValueChangeKey : Any]?) { super.scrollView(contentSize: changed) guard let changed = changed else { return } if state != .idle || !isAutomaticallyRefresh || frame.origin.y == 0 { return } guard let scrollView = scrollView else { return } if (scrollView.mlInset.top + scrollView.contentSize.height > scrollView.frame.size.height) { // 内容超过一个屏幕 // 这里的_scrollView.mj_contentH替换掉self.mj_y更为合理 if (scrollView.contentOffset.y >= scrollView.contentSize.height - scrollView.frame.size.height + self.frame.size.height * triggerAutomaticallyRefreshPercent + scrollView.mlInset.bottom - self.frame.size.height) { // 防止手松开时连续调用 let old = (changed[NSKeyValueChangeKey.oldKey] as? CGPoint) ?? .zero let new = (changed[NSKeyValueChangeKey.newKey] as? CGPoint) ?? .zero if new.y <= old.y { return } // 当底部刷新控件完全出现时,才刷新 beginRefreshing() } } } open override func scrollView(panState changed: [NSKeyValueChangeKey : Any]?) { super.scrollView(panState: changed) if state != .idle { return } guard let scrollView = scrollView else { return } switch scrollView.panGestureRecognizer.state { case .ended: if scrollView.mlInset.top + scrollView.contentSize.height <= scrollView.frame.size.height { // 不够一个屏幕 if (scrollView.contentOffset.y >= -scrollView.mlInset.top) { // 向上拽 beginRefreshing() } } else { // 超出一个屏幕 if scrollView.contentOffset.y >= scrollView.contentSize.height + scrollView.mlInset.bottom - scrollView.frame.size.height { beginRefreshing() } } case .began: isOneNewPan = true default: break } } open override func beginRefreshing(completion: (() -> ())? = nil) { if !isOneNewPan && isOnlyRefreshPerDrag { return } super.beginRefreshing(completion: completion) isOneNewPan = false } public override var state: RefreshState { didSet { if oldValue == state { return } if state == .refreshing { executeRefreshingCallback() } else if state == .noMoreData || state == .idle { if oldValue == .refreshing { endRefreshingCompletionBlock?() } } } } open override var isHidden: Bool { didSet { if (!oldValue && isHidden) { state = .idle scrollView?.mlInset.bottom -= frame.size.height } else if oldValue && !isHidden { self.scrollView?.mlInset.bottom += frame.size.height // 设置位置 self.frame.origin.y = scrollView?.contentSize.height ?? 0 } } } }
mit
be90c76e52dcecb9cf18af60d43b0ed2
33.703125
224
0.559208
4.631908
false
false
false
false
sgr-ksmt/SUNetworkActivityIndicator
Demo/Demo/ViewController.swift
1
1918
// // ViewController.swift // Demo // // Created by Suguru Kishimoto on 2015/12/17. import UIKit import SUNetworkActivityIndicator class ViewController: UIViewController { @IBOutlet private weak var countLabel: UILabel! @IBOutlet private weak var resetButton: UIButton! { didSet { resetButton.enabled = false } } @IBOutlet private weak var tableView: UITableView! { didSet { tableView.registerNib( UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: "Cell" ) tableView.tableFooterView = UIView() } } override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver( self, selector: "activeCountChanged:", name: NetworkActivityIndicatorActiveCountChangedNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @objc @IBAction private func endAll(sender: AnyObject!) { NetworkActivityIndicator.shared().endAll() tableView.visibleCells.forEach { let cell = $0 as! Cell cell.end() } } @objc private func activeCountChanged(notification: NSNotification) { let count = notification.object as! Int countLabel.text = "Count : \(count)" resetButton.enabled = count > 0 } } private typealias DataSource = ViewController extension DataSource: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: Cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! Cell cell.configureWithNumber(indexPath.row + 1) return cell } } private typealias Delegate = ViewController extension Delegate: UITableViewDelegate { }
mit
e371235fdc7f996fa640991b84691fd5
24.236842
107
0.703858
4.930591
false
false
false
false
iOSMST/CommonCodeReusable
TestLogging/CodeReusability.swift
1
1836
// // CodeReusability.swift // MClub // // Created by mukesh on 29/07/16. // Copyright © 2016 CodersUnlimited. All rights reserved. // import UIKit import SystemConfiguration.CaptiveNetwork public class CodeReusability: NSObject { //get current date and time public func getRefererId() -> NSString { var currentDate:NSString="" let formatter=DateFormatter() formatter.dateFormat="ddMMyyyyhhmm" currentDate=formatter.string(from: Date()) as NSString return currentDate } //to display alert message in common class public func displayAlertView(_ alertMessage:NSString,alertDisplayView:UIViewController) { let alertController = UIAlertController(title: "Eye Drop Reminder Lite", message: alertMessage as String, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in } alertController.addAction(OKAction) alertDisplayView.present(alertController, animated: true, completion:nil) } //to get device wifi ssid public func fetchSSIDInfo() -> String { var currentSSID = "" if let interfaces = CNCopySupportedInterfaces() as NSArray? { if interfaces.count>0 { //if let interfaces = CNCopySupportedInterfaces() as NSArray? { for interface in interfaces { if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? { if let ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? NSString { currentSSID = ssid as String } // break } } //} } } return currentSSID } }
mit
e0cd5d5486359150c9f6a33646a98d8f
35.7
137
0.613624
4.9729
false
false
false
false
ZamzamInc/ZamzamKit
Sources/ZamzamCore/Extensions/FileManager.swift
1
3967
// // FileManager.swift // ZamzamCore // // Created by Basem Emara on 2/17/16. // Copyright © 2016 Zamzam Inc. All rights reserved. // import Foundation.NSFileManager import Foundation.NSURL #if !os(tvOS) public extension FileManager { /// Get URL for the file. /// /// - Parameters: /// - fileName: Name of file. /// - directory: The directory of the file. /// - Returns: File URL from document directory. func url(of fileName: String, from directory: FileManager.SearchPathDirectory = .documentDirectory) -> URL { let root = NSSearchPathForDirectoriesInDomains(directory, .userDomainMask, true)[0] return URL(fileURLWithPath: root).appendingPathComponent(fileName) } /// Get URL's for files. /// /// - Parameters: /// - directory: The directory of the files. /// - filter: Specify filter to apply. /// - Returns: List of file URL's from document directory. func urls(from directory: FileManager.SearchPathDirectory = .documentDirectory, filter: ((URL) -> Bool)? = nil) -> [URL] { let root = urls(for: directory, in: .userDomainMask)[0] // Get the directory contents including folders guard var directoryUrls = try? contentsOfDirectory(at: root, includingPropertiesForKeys: nil) else { return [] } // Filter the directory contents if applicable if let filter = filter { directoryUrls = directoryUrls.filter(filter) } return directoryUrls } } public extension FileManager { /// Get file system path for the file. /// /// - Parameters: /// - fileName: Name of file. /// - directory: The directory of the file. /// - Returns: File URL from document directory. func path(of fileName: String, from directory: FileManager.SearchPathDirectory = .documentDirectory) -> String { url(of: fileName, from: directory).path } /// Get file system paths for files. /// /// - Parameters: /// - directory: The directory of the files. /// - filter: Specify filter to apply. /// - Returns: List of file system paths from document directory. func paths(from directory: FileManager.SearchPathDirectory = .documentDirectory, filter: ((URL) -> Bool)? = nil) -> [String] { urls(from: directory, filter: filter).map { $0.path } } } public extension FileManager { /// Retrieve a file remotely and persist to local disk. /// /// FileManager.default.download(from: "http://example.com/test.pdf") { url, response, error in /// // The `url` parameter represents location on local disk where remote file was downloaded. /// } /// /// - Parameters: /// - url: The HTTP URL to retrieve the file. /// - completion: The completion handler to call when the load request is complete. func download(from url: String, completion: @escaping (URL?, URLResponse?, Error?) -> Void) { guard let nsURL = URL(string: url) else { completion(nil, nil, ZamzamError.invalidData) return } URLSession.shared .downloadTask(with: nsURL) { location, response, error in guard let location, error == nil else { completion(nil, nil, error) return } // Construct file destination let destination = self.url(of: nsURL.lastPathComponent, from: .cachesDirectory) // Delete local file if it exists to overwrite try? self.removeItem(at: destination) // Store remote file locally do { try self.moveItem(at: location, to: destination) } catch { completion(nil, nil, error) return } completion(destination, response, error) } .resume() } } #endif
mit
c7edea36ec012fdbf714b86a60af5cee
35.054545
130
0.601109
4.699052
false
false
false
false
tjw/swift
stdlib/public/core/StringGraphemeBreaking.swift
1
14810
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims /// CR and LF are common special cases in grapheme breaking logic @inlinable // FIXME(sil-serialize-all) internal var _CR: UInt8 { return 0x0d } @inlinable // FIXME(sil-serialize-all) internal var _LF: UInt8 { return 0x0a } extension String.Index { @inlinable // FIXME(sil-serialize-all) internal init(encodedOffset: Int, characterStride stride: Int) { if _slowPath(stride == 0 || stride > UInt16.max) { // Don't store a 0 stride for the endIndex // or a truncated stride for an overlong grapheme cluster. self.init(encodedOffset: encodedOffset) return } self.init( encodedOffset: encodedOffset, .character(stride: UInt16(truncatingIfNeeded: stride))) } } extension _StringVariant { @inlinable internal func _stride(at i: String.Index) -> Int { if case .character(let stride) = i._cache { // TODO: should _fastPath the case somehow _sanityCheck(stride > 0) return Int(stride) } return characterStride(atOffset: i.encodedOffset) } @inlinable internal func characterStride(atOffset offset: Int) -> Int { let slice = self.checkedSlice(from: offset) return slice.measureFirstExtendedGraphemeCluster() } @inlinable internal func characterIndex(atOffset offset: Int) -> String.Index { let stride = self.characterStride(atOffset: offset) return String.Index(encodedOffset: offset, characterStride: stride) } @inlinable internal func characterIndex(after i: String.Index) -> String.Index { let offset = i.encodedOffset _precondition(offset >= 0, "String index is out of bounds") _precondition(offset < count, "Can't advance past endIndex") // Find the current grapheme distance let slice = self[offset..<count] let stride1 = _stride(at: i) // Calculate and cache the next grapheme distance let stride2 = slice.dropFirst(stride1).measureFirstExtendedGraphemeCluster() return String.Index( encodedOffset: offset &+ stride1, characterStride: stride2) } @inlinable internal func characterIndex(before i: String.Index) -> String.Index { let offset = i.encodedOffset _precondition(offset > 0, "Can't move before startIndex") _precondition(offset <= count, "String index is out of bounds") let slice = self[0..<offset] let stride = slice.measureLastExtendedGraphemeCluster() _sanityCheck(stride > 0 && stride <= UInt16.max) return String.Index( encodedOffset: offset &- stride, characterStride: stride) } @inlinable internal func characterIndex( _ i: String.Index, offsetBy n: Int ) -> String.Index { var i = i if n >= 0 { for _ in 0 ..< n { i = characterIndex(after: i) } } else { for _ in n ..< 0 { i = characterIndex(before: i) } } return i } @inlinable internal func characterIndex( _ i: String.Index, offsetBy n: Int, limitedBy limit: String.Index ) -> String.Index? { var i = i if n >= 0 { for _ in 0 ..< n { // Note condition is >=, not ==: we do not want to jump // over limit if it's in the middle of a grapheme cluster. // https://bugs.swift.org/browse/SR-6545 if i >= limit { return nil } i = characterIndex(after: i) } } else { for _ in n ..< 0 { if i <= limit { return nil } // See note above. i = characterIndex(before: i) } } return i } public func characterDistance( from start: String.Index, to end: String.Index ) -> Int { var i = start var count = 0 if start < end { // Note that the loop condition isn't just an equality check: we do not // want to jump over `end` if it's in the middle of a grapheme cluster. // https://bugs.swift.org/browse/SR-6546 while i < end { count += 1 i = characterIndex(after: i) } } else { while i > end { // See note above. count -= 1 i = characterIndex(before: i) } } return count } @inlinable internal func character(at i: String.Index) -> Character { let stride = _stride(at: i) let offset = i.encodedOffset if _slowPath(stride > 1) { return Character(_unverified: self.checkedSlice(offset..<offset + stride)) } let u = self.codeUnit(atCheckedOffset: offset) if _slowPath(!UTF16._isScalar(u)) { return Character(Unicode.Scalar._replacementCharacter) } return Character(_singleCodeUnit: u) } } extension _StringVariant { // NOTE: Because this function is inlineable, it should contain only the fast // paths of grapheme breaking that we have high confidence won't change. /// Returns the length of the first extended grapheme cluster in UTF-16 /// code units. @inlinable internal func measureFirstExtendedGraphemeCluster() -> Int { // No more graphemes at end of string. if count == 0 { return 0 } // If there is a single code unit left, the grapheme length must be 1. if count == 1 { return 1 } if isASCII { _onFastPath() // Please agressively inline // The only multi-scalar ASCII grapheme cluster is CR/LF. if _slowPath(self[0] == _CR && self[1] == _LF) { return 2 } return 1 } if _fastPath( UTF16._quickCheckGraphemeBreakBetween(self[0], self[1])) { return 1 } return self._measureFirstExtendedGraphemeClusterSlow() } // NOTE: Because this function is inlineable, it should contain only the fast // paths of grapheme breaking that we have high confidence won't change. // /// Returns the length of the last extended grapheme cluster in UTF-16 /// code units. @inlinable internal func measureLastExtendedGraphemeCluster() -> Int { let count = self.count // No more graphemes at end of string. if count == 0 { return 0 } // If there is a single code unit left, the grapheme length must be 1. if count == 1 { return 1 } if isASCII { _onFastPath() // Please agressively inline // The only multi-scalar ASCII grapheme cluster is CR/LF. if _slowPath(self[count-1] == _LF && self[count-2] == _CR) { return 2 } return 1 } if _fastPath( UTF16._quickCheckGraphemeBreakBetween(self[count - 2], self[count - 1])) { return 1 } return self._measureLastExtendedGraphemeClusterSlow() } } extension _UnmanagedString { @inline(never) @usableFromInline internal func _measureFirstExtendedGraphemeClusterSlow() -> Int { // ASCII case handled entirely on fast path. // FIXME: Have separate implementations for ASCII & UTF-16 views. _sanityCheck(CodeUnit.self == UInt16.self) return UTF16._measureFirstExtendedGraphemeCluster( in: UnsafeBufferPointer( start: rawStart.assumingMemoryBound(to: UInt16.self), count: count)) } @inline(never) @usableFromInline internal func _measureLastExtendedGraphemeClusterSlow() -> Int { // ASCII case handled entirely on fast path. // FIXME: Have separate implementations for ASCII & UTF-16 views. _sanityCheck(CodeUnit.self == UInt16.self) return UTF16._measureLastExtendedGraphemeCluster( in: UnsafeBufferPointer( start: rawStart.assumingMemoryBound(to: UInt16.self), count: count)) } } extension _UnmanagedOpaqueString { @inline(never) @usableFromInline internal func _measureFirstExtendedGraphemeClusterSlow() -> Int { _sanityCheck(count >= 2, "should have at least two code units") // Pull out some code units into a fixed array and try to perform grapheme // breaking on that. typealias ShortBuffer = _FixedArray16<UInt16> var shortBuffer = ShortBuffer(count: Swift.min(ShortBuffer.capacity, count)) shortBuffer.withUnsafeMutableBufferPointer { buffer in self.prefix(buffer.count)._copy(into: buffer) } let shortLength = shortBuffer.withUnsafeBufferPointer { buffer in UTF16._measureFirstExtendedGraphemeCluster(in: buffer) } if _fastPath(shortLength < shortBuffer.capacity) { return shortLength } // Nuclear option: copy out the rest of the string into a contiguous buffer. let longStart = UnsafeMutablePointer<UInt16>.allocate(capacity: count) defer { longStart.deallocate(capacity: count) } self._copy(into: UnsafeMutableBufferPointer(start: longStart, count: count)) return UTF16._measureFirstExtendedGraphemeCluster( in: UnsafeBufferPointer(start: longStart, count: count)) } @inline(never) @usableFromInline internal func _measureLastExtendedGraphemeClusterSlow() -> Int { _sanityCheck(count >= 2, "should have at least two code units") // Pull out some code units into a fixed array and try to perform grapheme // breaking on that. typealias ShortBuffer = _FixedArray16<UInt16> var shortBuffer = ShortBuffer(count: Swift.min(ShortBuffer.capacity, count)) shortBuffer.withUnsafeMutableBufferPointer { buffer in self.suffix(buffer.count)._copy(into: buffer) } let shortLength = shortBuffer.withUnsafeBufferPointer { buffer in UTF16._measureLastExtendedGraphemeCluster(in: buffer) } if _fastPath(shortLength < shortBuffer.capacity) { return shortLength } // Nuclear option: copy out the rest of the string into a contiguous buffer. let longStart = UnsafeMutablePointer<UInt16>.allocate(capacity: count) defer { longStart.deallocate(capacity: count) } self._copy(into: UnsafeMutableBufferPointer(start: longStart, count: count)) return UTF16._measureLastExtendedGraphemeCluster( in: UnsafeBufferPointer(start: longStart, count: count)) } } extension Unicode.UTF16 { /// Fast check for a (stable) grapheme break between two UInt16 code units @inlinable // Safe to inline internal static func _quickCheckGraphemeBreakBetween( _ lhs: UInt16, _ rhs: UInt16 ) -> Bool { // With the exception of CR-LF, there is always a grapheme break between two // sub-0x300 code units if lhs < 0x300 && rhs < 0x300 { return lhs != UInt16(_CR) && rhs != UInt16(_LF) } return _internalExtraCheckGraphemeBreakBetween(lhs, rhs) } @inline(never) // @inline(resilient_only) @usableFromInline internal static func _internalExtraCheckGraphemeBreakBetween( _ lhs: UInt16, _ rhs: UInt16 ) -> Bool { _sanityCheck( lhs != _CR || rhs != _LF, "CR-LF special case handled by _quickCheckGraphemeBreakBetween") // Whether the given scalar, when it appears paired with another scalar // satisfying this property, has a grapheme break between it and the other // scalar. func hasBreakWhenPaired(_ x: UInt16) -> Bool { // TODO: This doesn't generate optimal code, tune/re-write at a lower // level. // // NOTE: Order of case ranges affects codegen, and thus performance. All // things being equal, keep existing order below. switch x { // Unified CJK Han ideographs, common and some supplemental, amongst // others: // 0x3400-0xA4CF case 0x3400...0xa4cf: return true // Repeat sub-300 check, this is beneficial for common cases of Latin // characters embedded within non-Latin script (e.g. newlines, spaces, // proper nouns and/or jargon, punctuation). // // NOTE: CR-LF special case has already been checked. case 0x0000...0x02ff: return true // Non-combining kana: // 0x3041-0x3096 // 0x30A1-0x30FA case 0x3041...0x3096: return true case 0x30a1...0x30fa: return true // Non-combining modern (and some archaic) Cyrillic: // 0x0400-0x0482 (first half of Cyrillic block) case 0x0400...0x0482: return true // Modern Arabic, excluding extenders and prependers: // 0x061D-0x064A case 0x061d...0x064a: return true // Precomposed Hangul syllables: // 0xAC00–0xD7AF case 0xac00...0xd7af: return true // Common general use punctuation, excluding extenders: // 0x2010-0x2029 case 0x2010...0x2029: return true // CJK punctuation characters, excluding extenders: // 0x3000-0x3029 case 0x3000...0x3029: return true default: return false } } return hasBreakWhenPaired(lhs) && hasBreakWhenPaired(rhs) } // NOT @usableFromInline internal static func _measureFirstExtendedGraphemeCluster( in buffer: UnsafeBufferPointer<CodeUnit> ) -> Int { // ICU can only handle 32-bit offsets; don't feed it more than that. // https://bugs.swift.org/browse/SR-6544 let count: Int32 if _fastPath(buffer.count <= Int(Int32.max)) { count = Int32(truncatingIfNeeded: buffer.count) } else { count = Int32.max } let iterator = _ThreadLocalStorage.getUBreakIterator( start: buffer.baseAddress!, count: count) let offset = __swift_stdlib_ubrk_following(iterator, 0) // ubrk_following returns -1 (UBRK_DONE) when it hits the end of the buffer. if _fastPath(offset != -1) { // The offset into our buffer is the distance. _sanityCheck(offset > 0, "zero-sized grapheme?") return Int(offset) } return Int(count) } // NOT @usableFromInline internal static func _measureLastExtendedGraphemeCluster( in buffer: UnsafeBufferPointer<CodeUnit> ) -> Int { // ICU can only handle 32-bit offsets; don't feed it more than that. // https://bugs.swift.org/browse/SR-6544 let count: Int32 let start: UnsafePointer<CodeUnit> if _fastPath(buffer.count <= Int(Int32.max)) { count = Int32(truncatingIfNeeded: buffer.count) start = buffer.baseAddress! } else { count = Int32.max start = buffer.baseAddress! + buffer.count - Int(Int32.max) } let iterator = _ThreadLocalStorage.getUBreakIterator( start: start, count: count) let offset = __swift_stdlib_ubrk_preceding(iterator, count) // ubrk_following returns -1 (UBRK_DONE) when it hits the end of the buffer. if _fastPath(offset != -1) { // The offset into our buffer is the distance. _sanityCheck(offset < count, "zero-sized grapheme?") return Int(count - offset) } return Int(count) } }
apache-2.0
83176e91c44df49dc896e8e56896a33e
32.578231
80
0.658563
4.104213
false
false
false
false
nyjsl/Hank
RecentArticlesModel.swift
1
3027
// // RecentArticlesModel.swift // Gank // // Created by 魏星 on 16/7/17. // Copyright © 2016年 wx. All rights reserved. // import Foundation import RxSwift import ObjectMapper class RecentArticlesModel: BaseModel<GankIOApi>{ var articleEntities: [ArticleEntity] override init() { articleEntities = [] super.init() } func refresh() -> Observable<[ArticleEntity]>{ page = 1 return getArticlesByPage(page) } func loadMore() -> Observable<[ArticleEntity]>{ return getArticlesByPage(page + 1) } func getArticlesByPage(page: Int) -> Observable<[ArticleEntity]>{ let sourceGirl = requestProvider.request(GankIOApi.ByPageAndKind(kind: "福利", page: page, count: self.offset)) .filterStatusCodes(200...201) .observeOn(backgroundScheduler) .map { (response) -> [ArticleEntity] in if let result = Mapper<BaseEntity<ArticleEntity>>().map(String(data: response.data, encoding: NSUTF8StringEncoding)){ return result.results! }else{ throw NSError(domain: "parse json error", code: -1, userInfo: ["json": response]) } } let sourceVideo = requestProvider.request(GankIOApi.ByPageAndKind(kind: "休息视频", page: page, count: self.offset)) .filterStatusCodes(200...201) .observeOn(backgroundScheduler) .map { (response) -> [ArticleEntity] in if let result = Mapper<BaseEntity<ArticleEntity>>().map(String(data: response.data, encoding: NSUTF8StringEncoding)){ return result.results! }else{ throw NSError(domain: "parse json error", code: -1, userInfo: ["json": response]) } } return Observable.zip(sourceGirl, sourceVideo, resultSelector: { (girls, videos) -> [ArticleEntity] in for item in girls{ item.desc = item.desc! + " " + self.getFirstVideoDescByPublishTime(videos, publishedAt: item.publishedAt!) } return girls }).doOnNext({ (entities) in if !entities.isEmpty { if page == 1{ self.articleEntities = entities }else{ self.articleEntities += entities self.page = page } } }).observeOn(MainScheduler.instance) } private func getFirstVideoDescByPublishTime(videos: [ArticleEntity],publishedAt: NSDate) -> String{ var videoDesc = "" for item in videos{ if item.publishedAt == nil{ item.publishedAt = item.createdAt } let videoPublishedAt = item.publishedAt if DateUtils.areDatesSameDay(videoPublishedAt!, dateTwo: publishedAt){ videoDesc = item.desc! break } } return videoDesc } }
mit
414ccb07debed0ee3aa57f10fa7d09fa
32.808989
129
0.567819
4.641975
false
false
false
false
netguru/inbbbox-ios
Unit Tests/PageableComponentSerializerSpec.swift
1
6605
// // PageableComponentSerializerSpec.swift // Inbbbox // // Created by Patryk Kaczmarek on 04/02/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import Quick import Nimble import Mockingjay @testable import Inbbbox class PageableComponentSerializerSpec: QuickSpec { override func spec() { var component: PageableComponent! afterEach { component = nil } describe("when serializing next component") { context("with proper header") { beforeEach { let header = self.linkHeaderForTypes([.relNext]) component = PageableComponentSerializer.nextPageableComponentWithSentQuery(QueryMock(), receivedHeader: header) } it("serialized component should not be nil") { expect(component).toNot(beNil()) } it("serialized component should have correct path") { expect(component.path).to(equal("/fixture.path.next")) } it("serialized component should have query items") { expect(component.queryItems).toNot(beNil()) } it("serialized component should have 2 query items") { expect(component.queryItems).to(haveCount(2)) } it("first query item of serialized component should have proper value") { expect(component.queryItems!.first!.value).to(equal("3")) } it("first query item of serialized component should have proper name") { expect(component.queryItems!.first!.name).to(equal("page")) } it("second query item of serialized component should have proper value") { expect(component.queryItems![1].value).to(equal("100")) } it("second query item of serialized component should have proper name") { expect(component.queryItems![1].name).to(equal("per_page")) } } context("with invalid header") { beforeEach { let header = ["fixture.header.key": "fixture.header.value"] component = PageableComponentSerializer.nextPageableComponentWithSentQuery(QueryMock(), receivedHeader: header as [String : AnyObject]) } it("serialized component should not be nil") { expect(component).to(beNil()) } } } describe("when serializing previous component") { context("with proper header") { beforeEach { let header = self.linkHeaderForTypes([.relPrev]) component = PageableComponentSerializer.previousPageableComponentWithSentQuery(QueryMock(), receivedHeader: header) } it("serialized component should not be nil") { expect(component).toNot(beNil()) } it("serialized component should have correct path") { expect(component.path).to(equal("/fixture.path.prev")) } it("serialized component should have query items") { expect(component.queryItems).toNot(beNil()) } it("serialized component should have 2 query items") { expect(component.queryItems).to(haveCount(2)) } it("first query item of serialized component should have proper value") { expect(component.queryItems!.first!.value).to(equal("1")) } it("first query item of serialized component should have proper name") { expect(component.queryItems!.first!.name).to(equal("page")) } it("second query item of serialized component should have proper value") { expect(component.queryItems![1].value).to(equal("200")) } it("second query item of serialized component should have proper name") { expect(component.queryItems![1].name).to(equal("per_page")) } } context("with invalid header") { beforeEach { let header = ["fixture.header.key": "fixture.header.value"] component = PageableComponentSerializer.previousPageableComponentWithSentQuery(QueryMock(), receivedHeader: header as [String : AnyObject]) } it("serialized component should not be nil") { expect(component).to(beNil()) } } } } } private struct QueryMock: Query { let path = "/fixture/path" var parameters = Parameters(encoding: .json) let method = Method.POST var service: SecureNetworkService { return ServiceMock() } } private struct ServiceMock: SecureNetworkService { let scheme = "https" let host = "fixture.host" let version = "/v1" func authorizeRequest(_ request: NSMutableURLRequest) { request.setValue("fixture.header", forHTTPHeaderField: "fixture.http.header.field") } } private enum LinkHeaderType { case relNext, relPrev var description: String { switch self { case .relNext: return "<https://fixture.host/v1/fixture.path.next?page=3&per_page=100>; rel=\"next\"" case .relPrev: return "<https://fixture.host/v1/fixture.path.prev?page=1&per_page=200>; rel=\"prev\"" } } } private extension PageableComponentSerializerSpec { func linkHeaderForTypes(_ types: [LinkHeaderType]) -> [String: AnyObject] { var linkValue = [String]() types.forEach { linkValue.append($0.description) } return [ "Link" : linkValue.joined(separator: ",") as AnyObject ] } }
gpl-3.0
593de38834a3dfdb86f156429915636b
34.505376
159
0.513022
5.625213
false
false
false
false
cdtschange/SwiftMKit
SwiftMKit/Data/Image/ImageScout/ImageParser.swift
1
5020
import QuartzCore struct ImageParser { fileprivate enum JPEGHeaderSegment { case nextSegment, sofSegment, skipSegment, parseSegment, eoiSegment } fileprivate struct PNGSize { var width: UInt32 = 0 var height: UInt32 = 0 } fileprivate struct GIFSize { var width: UInt16 = 0 var height: UInt16 = 0 } fileprivate struct JPEGSize { var height: UInt16 = 0 var width: UInt16 = 0 } /// Takes an NSData instance and returns an image type. static func imageTypeFromData(_ data: Data) -> ScoutedImageType { let sampleLength = 2 if (data.count < sampleLength) { return .Unsupported } var length = UInt16(0); (data as NSData).getBytes(&length, range: NSRange(location: 0, length: sampleLength)) switch CFSwapInt16(length) { case 0xFFD8: return .JPEG case 0x8950: return .PNG case 0x4749: return .GIF default: return .Unsupported } } /// Takes an NSData instance and returns an image size (CGSize). static func imageSizeFromData(_ data: Data) -> CGSize { switch self.imageTypeFromData(data) { case .PNG: return self.PNGSizeFromData(data) case .GIF: return self.GIFSizeFromData(data) case .JPEG: return self.JPEGSizeFromData(data) default: return CGSize.zero } } // MARK: PNG static func PNGSizeFromData(_ data: Data) -> CGSize { if (data.count < 25) { return CGSize.zero } var size = PNGSize() (data as NSData).getBytes(&size, range: NSRange(location: 16, length: 8)) return CGSize(width: Int(CFSwapInt32(size.width)), height: Int(CFSwapInt32(size.height))) } // MARK: GIF static func GIFSizeFromData(_ data: Data) -> CGSize { if (data.count < 11) { return CGSize.zero } var size = GIFSize(); (data as NSData).getBytes(&size, range: NSRange(location: 6, length: 4)) return CGSize(width: Int(size.width), height: Int(size.height)) } // MARK: JPEG static func JPEGSizeFromData(_ data: Data) -> CGSize { let offset = 2 var size: CGSize? repeat { if (data.count <= offset) { size = CGSize.zero } size = self.parseJPEGData(data, offset: offset, segment: .nextSegment) } while size == nil return size! } fileprivate typealias JPEGParseTuple = (data: Data, offset: Int, segment: JPEGHeaderSegment) fileprivate enum JPEGParseResult { case size(CGSize) case tuple(JPEGParseTuple) } fileprivate static func parseJPEG(_ tuple: JPEGParseTuple) -> JPEGParseResult { let data = tuple.data let offset = tuple.offset let segment = tuple.segment if segment == .eoiSegment || (data.count <= offset + 1) || (data.count <= offset + 2) && segment == .skipSegment || (data.count <= offset + 7) && segment == .parseSegment { return .size(CGSize.zero) } switch segment { case .nextSegment: let newOffset = offset + 1 var byte = 0x0; (data as NSData).getBytes(&byte, range: NSRange(location: newOffset, length: 1)) if byte == 0xFF { return .tuple(JPEGParseTuple(data, offset: newOffset, segment: .sofSegment)) } else { return .tuple(JPEGParseTuple(data, offset: newOffset, segment: .nextSegment)) } case .sofSegment: let newOffset = offset + 1 var byte = 0x0; (data as NSData).getBytes(&byte, range: NSRange(location: newOffset, length: 1)) switch byte { case 0xE0...0xEF: return .tuple(JPEGParseTuple(data, offset: newOffset, segment: .skipSegment)) case 0xC0...0xC3, 0xC5...0xC7, 0xC9...0xCB, 0xCD...0xCF: return .tuple(JPEGParseTuple(data, offset: newOffset, segment: .parseSegment)) case 0xFF: return .tuple(JPEGParseTuple(data, offset: newOffset, segment: .sofSegment)) case 0xD9: return .tuple(JPEGParseTuple(data, offset: newOffset, segment: .eoiSegment)) default: return .tuple(JPEGParseTuple(data, offset: newOffset, segment: .skipSegment)) } case .skipSegment: var length = UInt16(0) (data as NSData).getBytes(&length, range: NSRange(location: offset + 1, length: 2)) let newOffset = offset + Int(CFSwapInt16(length)) - 1 return .tuple(JPEGParseTuple(data, offset: Int(newOffset), segment: .nextSegment)) case .parseSegment: var size = JPEGSize(); (data as NSData).getBytes(&size, range: NSRange(location: offset + 4, length: 4)) return .size(CGSize(width: Int(CFSwapInt16(size.width)), height: Int(CFSwapInt16(size.height)))) default: return .size(CGSize.zero) } } fileprivate static func parseJPEGData(_ data: Data, offset: Int, segment: JPEGHeaderSegment) -> CGSize { var tuple: JPEGParseResult = .tuple(JPEGParseTuple(data, offset: offset, segment: segment)) while true { switch tuple { case .size(let size): return size case .tuple(let newTuple): tuple = parseJPEG(newTuple) } } } }
mit
f97d5abcec555eb789f54f931fcc8158
29.987654
113
0.642032
3.832061
false
false
false
false
YauheniYarotski/APOD
APOD/Apod.swift
1
2576
// // Apod.swift // APOD // // Created by Yauheni Yarotski on 6/24/16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // class Apod: NSObject, NSCoding { var date:Date var title:String var explanation:String var mediaType: MediaType var copyright: String var url: String var hdUrl: String init(date:Date, title:String, explanation:String, mediaType: MediaType, url:String, hdUrl:String, copyright:String) { self.date = date self.title = title self.explanation = explanation self.mediaType = mediaType self.url = url self.hdUrl = hdUrl self.copyright = copyright super.init() } //MARK: - NSCoding fileprivate struct CodingKeys { static let kTitle = "title" static let kExplanation = "explanation" static let kMediaType = "mediaType" static let kUrl = "url" static let kHdUrl = "hdurl" static let kDate = "date" static let kCopyright = "copyright" } required convenience init?(coder aDecoder: NSCoder) { guard let date = aDecoder.decodeObject(forKey: CodingKeys.kDate) as? Date , let title = aDecoder.decodeObject(forKey: CodingKeys.kTitle) as? String //TODO: define how to use constants before self.init , let explanation = aDecoder.decodeObject(forKey: CodingKeys.kExplanation) as? String , let mediaTypeString = aDecoder.decodeObject(forKey: CodingKeys.kMediaType) as? String , let mediaType = MediaType(rawValue: mediaTypeString) , let url = aDecoder.decodeObject(forKey: CodingKeys.kUrl) as? String , let hdUrl = aDecoder.decodeObject(forKey: CodingKeys.kHdUrl) as? String , let copyright = aDecoder.decodeObject(forKey: CodingKeys.kCopyright) as? String else { return nil } self.init(date: date, title: title, explanation: explanation, mediaType: mediaType, url: url, hdUrl: hdUrl, copyright: copyright) } func encode(with aCoder: NSCoder) { aCoder.encode(date, forKey: CodingKeys.kDate) aCoder.encode(title, forKey: CodingKeys.kTitle) aCoder.encode(explanation, forKey: CodingKeys.kExplanation) aCoder.encode(mediaType.rawValue, forKey: CodingKeys.kMediaType) aCoder.encode(url, forKey: CodingKeys.kUrl) aCoder.encode(hdUrl, forKey: CodingKeys.kHdUrl) aCoder.encode(copyright, forKey: CodingKeys.kCopyright) } }
mit
41eb49efaeea74c7b6cb1807af3d12c2
35.785714
138
0.642718
4.342327
false
false
false
false
FoxerLee/iOS_sitp
tiankeng/ConfirmTableViewController.swift
1
3223
// // ConfirmTableViewController.swift // tiankeng // // Created by 李源 on 2017/4/3. // Copyright © 2017年 foxerlee. All rights reserved. // import UIKit //import LeanCloud import AVOSCloud import os.log class ConfirmTableViewController: UITableViewController { @IBOutlet weak var confirmButton: UIBarButtonItem! var message: Message! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //货物详情的cell if (indexPath.section == 0) { let cell = tableView.dequeueReusableCell(withIdentifier: "PackageConfirmTableViewCell", for: indexPath) as! PackageConfirmTableViewCell cell.packageLabel.text = message?.package cell.describeLabel.text = message?.describe cell.timeLabel.text = message?.time cell.photoImageView.image = message?.photo return cell } //寄货人的cell else if (indexPath.section == 1) { let cell = tableView.dequeueReusableCell(withIdentifier: "FounderConfirmTableViewCell", for: indexPath) as! FounderConfirmTableViewCell let query = AVQuery(className: "_User") query.whereKey("mobilePhoneNumber", equalTo: message.founderPhone) var object = query.findObjects() let founder = object?.popLast() as! AVObject cell.founderNameLabel.text = founder.object(forKey: "username") as? String cell.founderPhoneLabel.text = founder.object(forKey: "mobilePhoneNumber") as? String cell.founderAddressLabel.text = founder.object(forKey: "address") as? String return cell } //收货人的cell else { let cell = tableView.dequeueReusableCell(withIdentifier: "ReceiverConfirmTableViewCell", for: indexPath) as! ReceiverConfirmTableViewCell cell.ReceiverNameLabel.text = message?.name cell.ReceiverPhoneLabel.text = message?.phone cell.ReceiverAddressLabel.text = message?.address return cell } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if (section == 0) { return "货物信息" } else if (section == 1) { return "寄货人信息" } else { return "收货人信息" } } }
mit
b592c32ebf5e5f15f8e962aed9d0043b
30.939394
149
0.611954
5.149837
false
false
false
false
sessuru/AlamofireImage
Source/Request+AlamofireImage.swift
16
14608
// // Request+AlamofireImage.swift // // Copyright (c) 2015-2017 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import Foundation #if os(iOS) || os(tvOS) import UIKit #elseif os(watchOS) import UIKit import WatchKit #elseif os(macOS) import Cocoa #endif extension DataRequest { static var acceptableImageContentTypes: Set<String> = [ "image/tiff", "image/jpeg", "image/gif", "image/png", "image/ico", "image/x-icon", "image/bmp", "image/x-bmp", "image/x-xbitmap", "image/x-ms-bmp", "image/x-win-bitmap" ] static let streamImageInitialBytePattern = Data(bytes: [255, 216]) // 0xffd8 /// Adds the content types specified to the list of acceptable images content types for validation. /// /// - parameter contentTypes: The additional content types. public class func addAcceptableImageContentTypes(_ contentTypes: Set<String>) { DataRequest.acceptableImageContentTypes.formUnion(contentTypes) } // MARK: - iOS, tvOS and watchOS #if os(iOS) || os(tvOS) || os(watchOS) /// Creates a response serializer that returns an image initialized from the response data using the specified /// image options. /// /// - parameter imageScale: The scale factor used when interpreting the image data to construct /// `responseImage`. Specifying a scale factor of 1.0 results in an image whose /// size matches the pixel-based dimensions of the image. Applying a different /// scale factor changes the size of the image as reported by the size property. /// `Screen.scale` by default. /// - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats /// (such as PNG or JPEG). Enabling this can significantly improve drawing /// performance as it allows a bitmap representation to be constructed in the /// background rather than on the main thread. `true` by default. /// /// - returns: An image response serializer. public class func imageResponseSerializer( imageScale: CGFloat = DataRequest.imageScale, inflateResponseImage: Bool = true) -> DataResponseSerializer<Image> { return DataResponseSerializer { request, response, data, error in let result = serializeResponseData(response: response, data: data, error: error) guard case let .success(data) = result else { return .failure(result.error!) } do { try DataRequest.validateContentType(for: request, response: response) let image = try DataRequest.image(from: data, withImageScale: imageScale) if inflateResponseImage { image.af_inflate() } return .success(image) } catch { return .failure(error) } } } /// Adds a response handler to be called once the request has finished. /// /// - parameter imageScale: The scale factor used when interpreting the image data to construct /// `responseImage`. Specifying a scale factor of 1.0 results in an image whose /// size matches the pixel-based dimensions of the image. Applying a different /// scale factor changes the size of the image as reported by the size property. /// This is set to the value of scale of the main screen by default, which /// automatically scales images for retina displays, for instance. /// `Screen.scale` by default. /// - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats /// (such as PNG or JPEG). Enabling this can significantly improve drawing /// performance as it allows a bitmap representation to be constructed in the /// background rather than on the main thread. `true` by default. /// - parameter queue: The queue on which the completion handler is dispatched. `nil` by default, /// which results in using `DispatchQueue.main`. /// - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 /// arguments: the URL request, the URL response, if one was received, the image, /// if one could be created from the URL response and data, and any error produced /// while creating the image. /// /// - returns: The request. @discardableResult public func responseImage( imageScale: CGFloat = DataRequest.imageScale, inflateResponseImage: Bool = true, queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<Image>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.imageResponseSerializer( imageScale: imageScale, inflateResponseImage: inflateResponseImage ), completionHandler: completionHandler ) } /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server /// and converted into images. /// /// - parameter imageScale: The scale factor used when interpreting the image data to construct /// `responseImage`. Specifying a scale factor of 1.0 results in an image whose /// size matches the pixel-based dimensions of the image. Applying a different /// scale factor changes the size of the image as reported by the size property. /// This is set to the value of scale of the main screen by default, which /// automatically scales images for retina displays, for instance. /// `Screen.scale` by default. /// - parameter inflateResponseImage: Whether to automatically inflate response image data for compressed formats /// (such as PNG or JPEG). Enabling this can significantly improve drawing /// performance as it allows a bitmap representation to be constructed in the /// background rather than on the main thread. `true` by default. /// - parameter completionHandler: A closure to be executed when the request has new image. The closure takes 1 /// argument: the image, if one could be created from the data. /// /// - returns: The request. @discardableResult public func streamImage( imageScale: CGFloat = DataRequest.imageScale, inflateResponseImage: Bool = true, completionHandler: @escaping (Image) -> Void) -> Self { var imageData = Data() return stream { chunkData in if chunkData.starts(with: DataRequest.streamImageInitialBytePattern) { imageData = Data() } imageData.append(chunkData) if let image = DataRequest.serializeImage(from: imageData) { completionHandler(image) } } } private class func serializeImage( from data: Data, imageScale: CGFloat = DataRequest.imageScale, inflateResponseImage: Bool = true) -> UIImage? { guard data.count > 0 else { return nil } do { let image = try DataRequest.image(from: data, withImageScale: imageScale) if inflateResponseImage { image.af_inflate() } return image } catch { return nil } } private class func image(from data: Data, withImageScale imageScale: CGFloat) throws -> UIImage { if let image = UIImage.af_threadSafeImage(with: data, scale: imageScale) { return image } throw AFIError.imageSerializationFailed } public class var imageScale: CGFloat { #if os(iOS) || os(tvOS) return UIScreen.main.scale #elseif os(watchOS) return WKInterfaceDevice.current().screenScale #endif } #elseif os(macOS) // MARK: - macOS /// Creates a response serializer that returns an image initialized from the response data. /// /// - returns: An image response serializer. public class func imageResponseSerializer() -> DataResponseSerializer<Image> { return DataResponseSerializer { request, response, data, error in let result = serializeResponseData(response: response, data: data, error: error) guard case let .success(data) = result else { return .failure(result.error!) } do { try DataRequest.validateContentType(for: request, response: response) } catch { return .failure(error) } guard let bitmapImage = NSBitmapImageRep(data: data) else { return .failure(AFIError.imageSerializationFailed) } let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh)) image.addRepresentation(bitmapImage) return .success(image) } } /// Adds a response handler to be called once the request has finished. /// /// - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 4 /// arguments: the URL request, the URL response, if one was received, the image, if /// one could be created from the URL response and data, and any error produced while /// creating the image. /// - parameter queue: The queue on which the completion handler is dispatched. `nil` by default, /// which results in using `DispatchQueue.main`. /// /// - returns: The request. @discardableResult public func responseImage( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<Image>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.imageResponseSerializer(), completionHandler: completionHandler ) } /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server /// and converted into images. /// /// - parameter completionHandler: A closure to be executed when the request has new image. The closure takes 1 /// argument: the image, if one could be created from the data. /// /// - returns: The request. @discardableResult public func streamImage(completionHandler: @escaping (Image) -> Void) -> Self { var imageData = Data() return stream { chunkData in if chunkData.starts(with: DataRequest.streamImageInitialBytePattern) { imageData = Data() } imageData.append(chunkData) if let image = DataRequest.serializeImage(from: imageData) { completionHandler(image) } } } private class func serializeImage(from data: Data) -> NSImage? { guard data.count > 0 else { return nil } guard let bitmapImage = NSBitmapImageRep(data: data) else { return nil } let image = NSImage(size: NSSize(width: bitmapImage.pixelsWide, height: bitmapImage.pixelsHigh)) image.addRepresentation(bitmapImage) return image } #endif // MARK: - Content Type Validation /// Returns whether the content type of the response matches one of the acceptable content types. /// /// - parameter request: The request. /// - parameter response: The server response. /// /// - throws: An `AFError` response validation failure when an error is encountered. public class func validateContentType(for request: URLRequest?, response: HTTPURLResponse?) throws { if let url = request?.url, url.isFileURL { return } guard let mimeType = response?.mimeType else { let contentTypes = Array(DataRequest.acceptableImageContentTypes) throw AFError.responseValidationFailed(reason: .missingContentType(acceptableContentTypes: contentTypes)) } guard DataRequest.acceptableImageContentTypes.contains(mimeType) else { let contentTypes = Array(DataRequest.acceptableImageContentTypes) throw AFError.responseValidationFailed( reason: .unacceptableContentType(acceptableContentTypes: contentTypes, responseContentType: mimeType) ) } } }
mit
34fa8d6eadab1d859e949ce93309d445
43.672783
120
0.607749
5.382461
false
false
false
false
supertommy/yahoo-weather-ios-watchkit-swift
weather/RootViewController.swift
1
3242
// // RootViewController.swift // weather // // Created by Tommy Leung on 3/14/15. // Copyright (c) 2015 Tommy Leung. All rights reserved. // import UIKit class RootViewController: UIViewController, UIPageViewControllerDelegate { var pageViewController: UIPageViewController? var modelController: ModelController { // Return the model controller object, creating it if necessary. // In more complex implementations, the model controller may be passed to the view controller. if _modelController == nil { _modelController = ModelController() } return _modelController! } var _modelController: ModelController? = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Configure the page view controller and add it as a child view controller. self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil) self.pageViewController!.delegate = self let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)! let viewControllers = [startingViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in }) self.pageViewController!.dataSource = self.modelController self.addChildViewController(self.pageViewController!) self.view.addSubview(self.pageViewController!.view) // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages. var pageViewRect = self.view.bounds self.pageViewController!.view.frame = pageViewRect self.pageViewController!.didMoveToParentViewController(self) // Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily. self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UIPageViewController delegate methods func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation { // Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here. let currentViewController = self.pageViewController!.viewControllers[0] as UIViewController let viewControllers = [currentViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) self.pageViewController!.doubleSided = false return .Min } }
mit
6c6740a3a29010d044ed03cc353798b7
40.564103
291
0.729488
5.768683
false
false
false
false
Reggian/IOS-Pods-DFU-Library
iOSDFULibrary/Classes/Implementation/LegacyDFU/Characteristics/DFUVersion.swift
1
4644
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * 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. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 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 CoreBluetooth internal typealias VersionCallback = (_ major:Int, _ minor:Int) -> Void @objc internal class DFUVersion : NSObject, CBPeripheralDelegate { static let UUID = CBUUID(string: "00001534-1212-EFDE-1523-785FEABCD123") static func matches(_ characteristic:CBCharacteristic) -> Bool { return characteristic.uuid.isEqual(UUID) } fileprivate var characteristic:CBCharacteristic fileprivate var logger:LoggerHelper fileprivate var success:VersionCallback? fileprivate var report:ErrorCallback? var valid:Bool { return characteristic.properties.contains(CBCharacteristicProperties.read) } // MARK: - Initialization init(_ characteristic:CBCharacteristic, _ logger:LoggerHelper) { self.characteristic = characteristic self.logger = logger } // MARK: - Characteristic API methods /** Reads the value of the DFU Version characteristic. The value, or an error, will be reported as a callback. - parameter callback: method called when version is read and is supported - parameter error: method called on error of if version is not supported */ func readVersion(onSuccess success:VersionCallback?, onError report:ErrorCallback?) { // Save callbacks self.success = success self.report = report // Get the peripheral object let peripheral = characteristic.service.peripheral // Set the peripheral delegate to self peripheral.delegate = self logger.v("Reading DFU Version number...") logger.d("peripheral.readValueForCharacteristic(\(DFUVersion.UUID.uuidString))") peripheral.readValue(for: characteristic) } // MARK: - Peripheral Delegate callbacks func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if error != nil { logger.e("Reading DFU Version characteristic failed") logger.e(error!) report?(DFUError.readingVersionFailed, "Reading DFU Version characteristic failed") } else { let data = characteristic.value logger.i("Read Response received from \(DFUVersion.UUID.uuidString), \("value (0x):" + (data?.hexString ?? "no value"))") // Validate data length if data == nil || data!.count != 2 { logger.w("Invalid value: 2 bytes expected") report?(DFUError.readingVersionFailed, "Unsupported DFU Version value: \(data != nil ? "0x" + data!.hexString : "nil"))") return } // Read major and minor var minor:Int = 0 var major:Int = 0 (data as NSData?)?.getBytes(&minor, range: NSRange(location: 0, length: 1)) (data as NSData?)?.getBytes(&major, range: NSRange(location: 1, length: 1)) logger.a("Version number read: \(major).\(minor)") success?(major, minor) } } }
mit
1f03cfeaa8ba0af24fc0c2f37ef27ec9
43.653846
144
0.681309
5.080963
false
false
false
false
mlibai/XZKit
Projects/Example/XZKitExample/XZKitExample/XZKitExample/Code/ContentStatus/SampleContentStatusViewController.swift
1
3892
// // SampleContentStatusViewController.swift // Example // // Created by mlibai on 2018/4/3. // Copyright © 2018年 mlibai. All rights reserved. // import UIKit import XZKit class SampleContentStatusView: UIView, ContentStatusRepresentable { } class SampleContentStatusViewController: UIViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.hidesBottomBarWhenPushed = true } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.hidesBottomBarWhenPushed = true } override func loadView() { let view = SampleContentStatusView.init(frame: UIScreen.main.bounds) view.setTitle("Content is empty now", for: .empty) view.setImage(UIImage(named: "ImageEmpty"), for: .empty) view.setTitle("Content is loading now", for: .loading) view.setImage(UIImage(named: "ImageLoading"), for: .loading) view.contentStatus = .loading self.view = view } var contentView: SampleContentStatusView { return view as! SampleContentStatusView } override func viewDidLoad() { super.viewDidLoad() // self.navigationBar.title = "ContentStatusRepresentable" self.contentView.backgroundColor = UIColor.white contentView.setImage(UIImage(named: "img_empty"), for: .empty) contentView.setTitle("没有了...", for: .empty) contentView.setTitleColor(UIColor.gray, for: .empty) contentView.setTitleFont(UIFont.systemFont(ofSize: 12.0), for: .empty) contentView.setTitleInsets(EdgeInsets.init(top: 5, leading: 0, bottom: -5, trailing: 0), for: .empty) let image = UIImage.animatedImageNamed("gif_searching_", duration: 1.2) contentView.setImage(image, for: .loading) contentView.setTitle("加载中...", for: .loading) contentView.setTitleColor(UIColor(0x476eadff), for: .loading) contentView.setTitleFont(UIFont.systemFont(ofSize: 12.0), for: .loading) contentView.setTitleInsets(EdgeInsets.init(top: 10, leading: 0, bottom: -10, trailing: 0), for: .loading) contentView.setImage(UIImage(named: "img_404"), for: .error) contentView.setTitle("找不到...", for: .error) contentView.setTitleColor(UIColor(0xc73420ff), for: .error) contentView.setTitleFont(UIFont.systemFont(ofSize: 12.0), for: .error) contentView.setTitleInsets(EdgeInsets.init(top: 5, leading: 0, bottom: -5, trailing: 0), for: .error) self.contentView.contentStatus = .empty self.contentView.addTarget(self, action: #selector(emptyAction(_:)), for: .empty) self.contentView.addTarget(self, action: #selector(loadingAction(_:)), for: .loading) self.contentView.addTarget(self, action: #selector(errorAction(_:)), for: .error) } @objc private func emptyAction(_ view: UIView) { contentView.contentStatus = .loading } @objc private func loadingAction(_ view: UIView) { contentView.contentStatus = .error } @objc private func errorAction(_ view: UIView) { contentView.contentStatus = .empty } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c0ff5422b0b90cfd76704d0e3500dbef
34.842593
113
0.655386
4.506403
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Elements/Match/MatchSummaryView.swift
1
8498
import Foundation import TBAData import UIKit protocol MatchSummaryViewDelegate: AnyObject { func teamPressed(teamNumber: Int) } class MatchSummaryView: UIView { public weak var delegate: MatchSummaryViewDelegate? var viewModel: MatchViewModel? { didSet { configureView() } } // change this variable so that the teams are shown as buttons private var teamsTappable: Bool = false private let winnerFont = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.bold) private let notWinnerFont = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium) // MARK: - IBOutlet @IBOutlet private var summaryView: UIView! @IBOutlet weak var matchInfoStackView: UIStackView! @IBOutlet private weak var matchNumberLabel: UILabel! @IBOutlet weak private var playIconImageView: UIImageView! @IBOutlet private weak var redStackView: UIStackView! @IBOutlet weak var redContainerView: UIView! { didSet { redContainerView.layer.borderColor = UIColor.systemRed.cgColor } } @IBOutlet weak var redScoreView: UIView! @IBOutlet weak var redScoreLabel: UILabel! @IBOutlet private weak var redRPStackView: UIStackView! @IBOutlet weak private var blueStackView: UIStackView! @IBOutlet weak var blueContainerView: UIView! { didSet { blueContainerView.layer.borderColor = UIColor.systemBlue.cgColor } } @IBOutlet weak var blueScoreView: UIView! @IBOutlet weak var blueScoreLabel: UILabel! @IBOutlet private weak var blueRPStackView: UIStackView! @IBOutlet weak var timeLabel: UILabel! // MARK: - Init init(teamsTappable: Bool = false) { super.init(frame: .zero) self.teamsTappable = teamsTappable initMatchView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initMatchView() } private func initMatchView() { Bundle.main.loadNibNamed(String(describing: MatchSummaryView.self), owner: self, options: nil) summaryView.frame = self.bounds summaryView.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.addSubview(summaryView) styleInterface() } private func styleInterface() { redContainerView.backgroundColor = UIColor.redAllianceBackgroundColor redScoreLabel.backgroundColor = UIColor.redAllianceScoreBackgroundColor blueContainerView.backgroundColor = UIColor.blueAllianceBackgroundColor blueScoreLabel.backgroundColor = UIColor.blueAllianceScoreBackgroundColor } // MARK: - Public Methods func resetView() { redContainerView.layer.borderWidth = 0.0 blueContainerView.layer.borderWidth = 0.0 redScoreLabel.font = notWinnerFont blueScoreLabel.font = notWinnerFont } // MARK: - Private Methods private func removeTeams() { for stackView in [redStackView, blueStackView] as [UIStackView] { for view in stackView.arrangedSubviews { if [redScoreView, blueScoreView].contains(view) { continue } stackView.removeArrangedSubview(view) view.removeFromSuperview() } } } private func removeRPs() { for stackView in [redRPStackView, blueRPStackView] as [UIStackView] { for view in stackView.arrangedSubviews { stackView.removeArrangedSubview(view) view.removeFromSuperview() } } } private func configureView() { guard let viewModel = viewModel else { return } matchNumberLabel.text = viewModel.matchName playIconImageView.isHidden = viewModel.hasVideos removeTeams() removeRPs() let baseTeamKeys = viewModel.baseTeamKeys for (alliance, stackView) in [(viewModel.redAlliance, redStackView!), (viewModel.blueAlliance, blueStackView!)] { for teamKey in alliance { let dq = viewModel.dqs.contains(teamKey) // if teams are tappable, load the team #s as buttons to link to the team page let label = teamsTappable ? teamButton(for: teamKey, baseTeamKeys: baseTeamKeys, dq: dq) : teamLabel(for: teamKey, baseTeamKeys: baseTeamKeys, dq: dq) // Insert each new stack view at the index just before the score view stackView.insertArrangedSubview(label, at: stackView.arrangedSubviews.count - 1) } } // Add red RP to view addRPToView(stackView: redRPStackView, rpCount: viewModel.redRPCount) // Add blue RP to view addRPToView(stackView: blueRPStackView, rpCount: viewModel.blueRPCount) if let redScore = viewModel.redScore { redScoreLabel.text = "\(redScore)" } else { redScoreLabel.text = nil } redScoreView.isHidden = viewModel.redScore == nil if let blueScore = viewModel.blueScore { blueScoreLabel.text = "\(blueScore)" } else { blueScoreLabel.text = nil } blueScoreView.isHidden = viewModel.blueScore == nil timeLabel.text = viewModel.timeString timeLabel.isHidden = viewModel.hasScores if viewModel.redAllianceWon { redContainerView.layer.borderWidth = 2.0 redScoreLabel.font = winnerFont } else if viewModel.blueAllianceWon { blueContainerView.layer.borderWidth = 2.0 blueScoreLabel.font = winnerFont } } private func addRPToView(stackView: UIStackView, rpCount: Int) { for _ in 0..<rpCount { let rpLabel = label(text: "•", isBold: true) stackView.addArrangedSubview(rpLabel) } } private func teamLabel(for teamKey: String, baseTeamKeys: [String], dq: Bool) -> UILabel { let text: String = "\(Team.trimFRCPrefix(teamKey))" let isBold: Bool = baseTeamKeys.contains(teamKey) return label(text: text, isBold: isBold, isStrikethrough: dq) } private func teamButton(for teamKey: String, baseTeamKeys: [String], dq: Bool) -> UIButton { let text: String = "\(Team.trimFRCPrefix(teamKey))" let isBold: Bool = baseTeamKeys.contains(teamKey) return button(text: text, isBold: isBold, isStrikethrough: dq) } private func button(text: String, isBold: Bool, isStrikethrough: Bool = false) -> UIButton { let button = UIButton(type: .system) button.setTitle(text, for: []) button.setTitleColor(UIColor.highlightColor, for: .normal) if let teamNumber = Int(text) { button.tag = teamNumber } button.titleLabel?.attributedText = customAttributedString(text: text, isBold: isBold, isStrikethrough: isStrikethrough) button.addTarget(self, action: #selector(teamPressed(sender:)), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button } private func label(text: String, isBold: Bool, isStrikethrough: Bool = false) -> UILabel { let label = UILabel() label.textAlignment = .center label.attributedText = customAttributedString(text: text, isBold: isBold, isStrikethrough: isStrikethrough) label.translatesAutoresizingMaskIntoConstraints = false label.textColor = UIColor.label return label } @objc private func teamPressed(sender: UIButton) { if sender.tag == 0 { return } delegate?.teamPressed(teamNumber: sender.tag) } private func customAttributedString(text: String, isBold: Bool, isStrikethrough: Bool = false) -> NSMutableAttributedString { let attributeString = NSMutableAttributedString(string: text) let attributedStringRange = NSMakeRange(0, attributeString.length) var font: UIFont = .systemFont(ofSize: 14) if isBold { font = .boldSystemFont(ofSize: 14) } attributeString.addAttribute(.font, value: font, range: attributedStringRange) if isStrikethrough { attributeString.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: attributedStringRange) } return attributeString } }
mit
c84420a38652a0627e8e7d6bda62e1dc
33.819672
132
0.648423
4.936665
false
false
false
false
roambotics/swift
SwiftCompilerSources/Sources/SIL/Argument.swift
2
7454
//===--- Argument.swift - Defines the Argument classes --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basic import SILBridging /// A basic block argument. /// /// Maps to both, SILPhiArgument and SILFunctionArgument. public class Argument : Value, Hashable { public var definingInstruction: Instruction? { nil } public var definingBlock: BasicBlock { block } public var block: BasicBlock { return SILArgument_getParent(bridged).block } var bridged: BridgedArgument { BridgedArgument(obj: SwiftObject(self)) } public var index: Int { return block.arguments.firstIndex(of: self)! } public static func ==(lhs: Argument, rhs: Argument) -> Bool { lhs === rhs } public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } } final public class FunctionArgument : Argument { public var convention: ArgumentConvention { SILArgument_getConvention(bridged).convention } } final public class BlockArgument : Argument { public var isPhiArgument: Bool { block.predecessors.allSatisfy { let term = $0.terminator return term is BranchInst || term is CondBranchInst } } public var incomingPhiOperands: LazyMapSequence<PredecessorList, Operand> { assert(isPhiArgument) let idx = index return block.predecessors.lazy.map { switch $0.terminator { case let br as BranchInst: return br.operands[idx] case let condBr as CondBranchInst: if condBr.trueBlock == self.block { assert(condBr.falseBlock != self.block) return condBr.trueOperands[idx] } else { assert(condBr.falseBlock == self.block) return condBr.falseOperands[idx] } default: fatalError("wrong terminator for phi-argument") } } } public var incomingPhiValues: LazyMapSequence<LazyMapSequence<PredecessorList, Operand>, Value> { incomingPhiOperands.lazy.map { $0.value } } } public enum ArgumentConvention { /// This argument is passed indirectly, i.e. by directly passing the address /// of an object in memory. The callee is responsible for destroying the /// object. The callee may assume that the address does not alias any valid /// object. case indirectIn /// This argument is passed indirectly, i.e. by directly passing the address /// of an object in memory. The callee must treat the object as read-only /// The callee may assume that the address does not alias any valid object. case indirectInConstant /// This argument is passed indirectly, i.e. by directly passing the address /// of an object in memory. The callee may not modify and does not destroy /// the object. case indirectInGuaranteed /// This argument is passed indirectly, i.e. by directly passing the address /// of an object in memory. The object is always valid, but the callee may /// assume that the address does not alias any valid object and reorder loads /// stores to the parameter as long as the whole object remains valid. Invalid /// single-threaded aliasing may produce inconsistent results, but should /// remain memory safe. case indirectInout /// This argument is passed indirectly, i.e. by directly passing the address /// of an object in memory. The object is allowed to be aliased by other /// well-typed references, but is not allowed to be escaped. This is the /// convention used by mutable captures in @noescape closures. case indirectInoutAliasable /// This argument represents an indirect return value address. The callee stores /// the returned value to this argument. At the time when the function is called, /// the memory location referenced by the argument is uninitialized. case indirectOut /// This argument is passed directly. Its type is non-trivial, and the callee /// is responsible for destroying it. case directOwned /// This argument is passed directly. Its type may be trivial, or it may /// simply be that the callee is not responsible for destroying it. Its /// validity is guaranteed only at the instant the call begins. case directUnowned /// This argument is passed directly. Its type is non-trivial, and the caller /// guarantees its validity for the entirety of the call. case directGuaranteed public var isIndirect: Bool { switch self { case .indirectIn, .indirectInConstant, .indirectInGuaranteed, .indirectInout, .indirectInoutAliasable, .indirectOut: return true case .directOwned, .directUnowned, .directGuaranteed: return false } } public var isIndirectIn: Bool { switch self { case .indirectIn, .indirectInConstant, .indirectInGuaranteed: return true case .directOwned, .directUnowned, .directGuaranteed, .indirectInout, .indirectInoutAliasable, .indirectOut: return false } } public var isGuaranteed: Bool { switch self { case .indirectInGuaranteed, .directGuaranteed: return true case .indirectIn, .indirectInConstant, .directOwned, .directUnowned, .indirectInout, .indirectInoutAliasable, .indirectOut: return false } } public var isExclusiveIndirect: Bool { switch self { case .indirectIn, .indirectInConstant, .indirectOut, .indirectInGuaranteed, .indirectInout: return true case .indirectInoutAliasable, .directUnowned, .directGuaranteed, .directOwned: return false } } public var isInout: Bool { switch self { case .indirectInout, .indirectInoutAliasable: return true case .indirectIn, .indirectInConstant, .indirectOut, .indirectInGuaranteed, .directUnowned, .directGuaranteed, .directOwned: return false } } } // Bridging utilities extension BridgedArgument { public var argument: Argument { obj.getAs(Argument.self) } public var blockArgument: BlockArgument { obj.getAs(BlockArgument.self) } public var functionArgument: FunctionArgument { obj.getAs(FunctionArgument.self) } } extension BridgedArgumentConvention { var convention: ArgumentConvention { switch self { case ArgumentConvention_Indirect_In: return .indirectIn case ArgumentConvention_Indirect_In_Constant: return .indirectInConstant case ArgumentConvention_Indirect_In_Guaranteed: return .indirectInGuaranteed case ArgumentConvention_Indirect_Inout: return .indirectInout case ArgumentConvention_Indirect_InoutAliasable: return .indirectInoutAliasable case ArgumentConvention_Indirect_Out: return .indirectOut case ArgumentConvention_Direct_Owned: return .directOwned case ArgumentConvention_Direct_Unowned: return .directUnowned case ArgumentConvention_Direct_Guaranteed: return .directGuaranteed default: fatalError("unsupported argument convention") } } }
apache-2.0
a6a8ea4785b959ac12f7282313593dce
32.881818
99
0.69238
4.772087
false
false
false
false
onekiloparsec/SwiftAA
Tests/SwiftAATests/VenusTests.swift
2
1988
// // VenusTests.swift // SwiftAA // // Created by Cédric Foellmi on 18/06/16. // MIT Licence. See LICENCE file. // import Foundation import XCTest @testable import SwiftAA class VenusTests: XCTestCase { func testAverageColor() { XCTAssertNotEqual(Venus.averageColor, Color.white) } // See AA p.225 func testApparentGeocentricCoordinates() { let venus = Venus(julianDay: JulianDay(year: 1992, month: 12, day: 20)) AssertEqual(Hour(venus.allPlanetaryDetails.ApparentGeocentricRA), Hour(21.078181), accuracy: ArcSecond(0.1).inHours) AssertEqual(Degree(venus.allPlanetaryDetails.ApparentGeocentricDeclination), Degree(-18.88801), accuracy: ArcSecond(0.1).inDegrees) } // See AA p.284 func testIlluminationFraction() { let venus = Venus(julianDay: JulianDay(year: 1992, month: 12, day: 20)) XCTAssertEqual(venus.illuminatedFraction, 0.647, accuracy: 0.005) } // See AA p.225 func testHeliocentricEclipticCoordinates() { let venus = Venus(julianDay: JulianDay(year: 1992, month: 12, day: 20), highPrecision: false) let heliocentricEcliptic = venus.heliocentricEclipticCoordinates AssertEqual(heliocentricEcliptic.celestialLatitude, Degree(-2.62070), accuracy: ArcSecond(0.1).inDegrees) AssertEqual(heliocentricEcliptic.celestialLongitude, Degree(26.11428), accuracy: ArcSecond(0.1).inDegrees) AssertEqual(venus.radiusVector, AstronomicalUnit(0.724603), accuracy: AstronomicalUnit(0.00001)) } // See AA p.103 func testGeocentricEquatorialCoordinates() { let venus = Venus(julianDay: JulianDay(year: 1988, month: 03, day: 20)) let equatorial = venus.apparentGeocentricEquatorialCoordinates AssertEqual(equatorial.rightAscension.inDegrees, Degree(41.73129), accuracy: ArcSecond(0.1).inDegrees) AssertEqual(equatorial.declination, Degree(18.44092), accuracy: ArcSecond(0.1).inDegrees) } }
mit
9402ef60fed2851a5a7926f725fe6b88
40.395833
139
0.709612
3.770398
false
true
false
false
LuAndreCast/iOS_AudioRecordersAndPlayers
recorder_LPCM/LPCMrecorder/Recorders/LPCM_SpeechRecorder.swift
1
14629
import UIKit import CoreAudio import AudioToolbox class SpeechRecorderV2: NSObject { static let sharedInstance = SpeechRecorderV2() // MARK:- properties @objc enum Status: Int { case ready case busy case error } internal struct RecordState { var format: AudioStreamBasicDescription var queue: UnsafeMutablePointer<AudioQueueRef?> var buffers: [AudioQueueBufferRef?] var file: AudioFileID? var currentPacket: Int64 var recording: Bool }; private var recordState: RecordState? private var audioURL:URL? var format: AudioFormatID { get { return recordState!.format.mFormatID } set { recordState!.format.mFormatID = newValue } } var sampleRate: Float64 { get { return recordState!.format.mSampleRate } set { recordState!.format.mSampleRate = newValue } } var formatFlags: AudioFormatFlags { get { return recordState!.format.mFormatFlags } set { recordState!.format.mFormatFlags = newValue } } var channelsPerFrame: UInt32 { get { return recordState!.format.mChannelsPerFrame } set { recordState!.format.mChannelsPerFrame = newValue } } var bitsPerChannel: UInt32 { get { return recordState!.format.mBitsPerChannel } set { recordState!.format.mBitsPerChannel = newValue } } var framesPerPacket: UInt32 { get { return recordState!.format.mFramesPerPacket } set { recordState!.format.mFramesPerPacket = newValue } } var bytesPerFrame: UInt32 { get { return recordState!.format.mBytesPerFrame } set { recordState!.format.mBytesPerFrame = newValue } } var bytesPerPacket: UInt32 { get { return recordState!.format.mBytesPerPacket } set { recordState!.format.mBytesPerPacket = newValue } } //MARK: - Handlers public var handler: ((_ status:Status, _ data:NSData?, _ errorDesc:String?) -> Void)? // MARK:- Init override init() { super.init() self.recordState = RecordState(format: AudioStreamBasicDescription(), queue: UnsafeMutablePointer<AudioQueueRef?>.allocate(capacity: 1), buffers: [AudioQueueBufferRef?](repeating: nil, count: 1), file: nil, currentPacket: 0, recording: false) }//eom // MARK:- OutputFile private func getDocumentsPath()->URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] return documentsDirectory } func setOutputFileNameWithDocumentsDirectory(nameDesired:String) { audioURL = getDocumentsPath().appendingPathComponent(nameDesired) setOutputFile(url: audioURL!) }//eom func setOutputFileNameWithTempDirectory(nameDesired:String) { let tempDir = NSTemporaryDirectory() let tempURLdir = URL(fileURLWithPath: tempDir) audioURL = tempURLdir.appendingPathComponent(nameDesired) setOutputFile(url: audioURL!) }//eom private func setOutputFile(path: String) { setOutputFile(url: URL(fileURLWithPath: path)) }//eom private func setOutputFile(url: URL) { AudioFileCreateWithURL(url as CFURL, kAudioFileWAVEType, &recordState!.format, AudioFileFlags.dontPageAlignAudioData.union(.eraseFile), &recordState!.file) } // MARK:- Start / Stop Recording func start() { handler?(.busy, nil, nil) self.recordState?.currentPacket = 0 let inputAudioQueue: AudioQueueInputCallback = { (userData: UnsafeMutableRawPointer?, audioQueue: AudioQueueRef, bufferQueue: AudioQueueBufferRef, startTime: UnsafePointer<AudioTimeStamp>, packets: UInt32, packetDescription: UnsafePointer<AudioStreamPacketDescription>?) in let internalRSP = unsafeBitCast(userData, to: UnsafeMutablePointer<RecordState>.self) if packets > 0 { var packetsReceived = packets let outputStream:OSStatus = AudioFileWritePackets(internalRSP.pointee.file!, false, bufferQueue.pointee.mAudioDataByteSize, packetDescription, internalRSP.pointee.currentPacket, &packetsReceived, bufferQueue.pointee.mAudioData) if outputStream != 0 { print("Error with AudioFileWritePackets") //<----DEBUG switch outputStream { case kAudioFilePermissionsError: print("kAudioFilePermissionsError") break case kAudioFileNotOptimizedError: print("kAudioFileNotOptimizedError") break case kAudioFileInvalidChunkError: print("kAudioFileInvalidChunkError") break case kAudioFileDoesNotAllow64BitDataSizeError: print("kAudioFileDoesNotAllow64BitDataSizeError") break case kAudioFileInvalidPacketOffsetError: print("kAudioFileInvalidPacketOffsetError") break case kAudioFileInvalidFileError: print("kAudioFileInvalidFileError") break case kAudioFileOperationNotSupportedError: print("kAudioFileOperationNotSupportedError") break case kAudioFileNotOpenError: print("kAudioFileNotOpenError") break case kAudioFileEndOfFileError: print("kAudioFileEndOfFileError") break case kAudioFilePositionError: print("kAudioFilePositionError") break case kAudioFileFileNotFoundError: print("kAudioFileFileNotFoundError") break case kAudioFileUnspecifiedError: print("kAudioFileUnspecifiedError") break case kAudioFileUnsupportedFileTypeError: print("kAudioFileUnsupportedFileTypeError") break case kAudioFileUnsupportedDataFormatError: print("kAudioFileUnsupportedDataFormatError") break case kAudioFileUnsupportedPropertyError: print("kAudioFileUnsupportedPropertyError") break case kAudioFileBadPropertySizeError: print("kAudioFileBadPropertySizeError") break default: print("unknown error") break } //<----DEBUG } internalRSP.pointee.currentPacket += Int64(packetsReceived) } if internalRSP.pointee.recording { let outputStream:OSStatus = AudioQueueEnqueueBuffer(audioQueue, bufferQueue, 0, nil) if outputStream != 0 { print("Error with AudioQueueEnqueueBuffer") //<----DEBUG switch outputStream { case kAudioFilePermissionsError: print("kAudioFilePermissionsError") break case kAudioFileNotOptimizedError: print("kAudioFileNotOptimizedError") break case kAudioFileInvalidChunkError: print("kAudioFileInvalidChunkError") break case kAudioFileDoesNotAllow64BitDataSizeError: print("kAudioFileDoesNotAllow64BitDataSizeError") break case kAudioFileInvalidPacketOffsetError: print("kAudioFileInvalidPacketOffsetError") break case kAudioFileInvalidFileError: print("kAudioFileInvalidFileError") break case kAudioFileOperationNotSupportedError: print("kAudioFileOperationNotSupportedError") break case kAudioFileNotOpenError: print("kAudioFileNotOpenError") break case kAudioFileEndOfFileError: print("kAudioFileEndOfFileError") break case kAudioFilePositionError: print("kAudioFilePositionError") break case kAudioFileFileNotFoundError: print("kAudioFileFileNotFoundError") break case kAudioFileUnspecifiedError: print("kAudioFileUnspecifiedError") break case kAudioFileUnsupportedFileTypeError: print("kAudioFileUnsupportedFileTypeError") break case kAudioFileUnsupportedDataFormatError: print("kAudioFileUnsupportedDataFormatError") break case kAudioFileUnsupportedPropertyError: print("kAudioFileUnsupportedPropertyError") break case kAudioFileBadPropertySizeError: print("kAudioFileBadPropertySizeError") break default: print("unknown error") break } //<----DEBUG } } } let queueResults = AudioQueueNewInput(&recordState!.format, inputAudioQueue, &recordState, nil, nil, 0, recordState!.queue) if queueResults == 0 { let bufferByteSize: Int = calculate(format: recordState!.format, seconds: 0.5) for index in (0..<recordState!.buffers.count) { AudioQueueAllocateBuffer(recordState!.queue.pointee!, UInt32(bufferByteSize), &recordState!.buffers[index]) AudioQueueEnqueueBuffer(recordState!.queue.pointee!, recordState!.buffers[index]!, 0, nil) } AudioQueueStart(recordState!.queue.pointee!, nil) recordState?.recording = true } else { handler?(.error, nil, "Error setting audio input.") } }//eom func stop() { recordState?.recording = false if let recordingState: RecordState = recordState { AudioQueueStop(recordingState.queue.pointee!, true) AudioQueueDispose(recordingState.queue.pointee!, true) AudioFileClose(recordingState.file!) let audioData:NSData? = NSData(contentsOf: audioURL!) handler?(.ready, audioData, nil) } }//eom // MARK:- Helper methods func calculate(format: AudioStreamBasicDescription, seconds: Double) -> Int { let framesRequiredForBufferTime = Int(ceil(seconds * format.mSampleRate)) if framesRequiredForBufferTime > 0 { return (framesRequiredForBufferTime * Int(format.mBytesPerFrame)) } else { var maximumPacketSize = UInt32(0) if format.mBytesPerPacket > 0 { maximumPacketSize = format.mBytesPerPacket } else { audioQueueProperty(propertyId: kAudioQueueProperty_MaximumOutputPacketSize, value: &maximumPacketSize) } var packets = 0 if format.mFramesPerPacket > 0 { packets = (framesRequiredForBufferTime / Int(format.mFramesPerPacket)) } else { packets = framesRequiredForBufferTime } if packets == 0 { packets = 1 } return (packets * Int(maximumPacketSize)) } }//eom func audioQueueProperty<T>(propertyId: AudioQueuePropertyID, value: inout T) { let propertySize = UnsafeMutablePointer<UInt32>.allocate(capacity: 1) propertySize.pointee = UInt32(MemoryLayout<T>.size) let queueResults = AudioQueueGetProperty(recordState!.queue.pointee!, propertyId, &value, propertySize) propertySize.deallocate(capacity: 1) if queueResults != 0 { handler?(.error, nil, "Unable to get audio queue property.") } }//eom }
mit
7ea23c69cb304a66db96afbc97749ff5
39.300275
131
0.498667
6.565978
false
false
false
false
NicholasBusby/UdacityVirtualTourist
UdacityVirtualTourist/UdacityVirtualTourist/Http.swift
1
2846
// // Http.swift // UdacityVirtualTourist // // Created by Nicholas Busby on 7/1/15. // Copyright (c) 2015 CareerBuilder. All rights reserved. // import Foundation class Http { static let JSON = "application/json" static var session = NSURLSession.sharedSession() static func getRequest(url: String, headers: [String: String], queryString: [String: String]) -> NSMutableURLRequest { let request = NSMutableURLRequest(URL: buildURLAndQueryString(url, queryString: queryString)) request.timeoutInterval = 15 request.addValue(JSON, forHTTPHeaderField: "Accept") for (key, value) in headers { request.addValue(value, forHTTPHeaderField: key) } return request } static func buildTask(request: NSMutableURLRequest, completionHandler: (result: NSData!, error: NSError?) -> Void) -> NSURLSessionDataTask{ if !isConnectedToNetwork() { completionHandler(result: nil, error: NSError(domain: "No Network Connection", code: 404, userInfo: nil)) } let task = session.dataTaskWithRequest(request) {data, response, downloadError in if let error = downloadError { completionHandler(result: nil, error: error) } else { completionHandler(result: data, error: nil) } } task.resume() return task } static func buildURLAndQueryString(baseUrl: String, queryString: [String: String]) -> NSURL { var url = NSURL(string: baseUrl + escapedParameters(queryString)) return url! } static func escapedParameters(parameters: [String : AnyObject]) -> String { var urlVars = [String]() for (key, value) in parameters { let stringValue = "\(value)" let escapedValue = stringValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) urlVars += [key + "=" + "\(escapedValue!)"] } return (!urlVars.isEmpty ? "?" : "") + join("&", urlVars) } static func isConnectedToNetwork() -> Bool { var status:Bool = false let url = NSURL(string: "http://careerbuilder.com") let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "HEAD" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData request.timeoutInterval = 10.0 var response:NSURLResponse? var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData? if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode == 200 { status = true } } return status } }
mit
f138221ff76f9279341dc6268c7ab919
36.447368
144
0.625791
5.202925
false
false
false
false
BellAppLab/swift-sodium
Sodium/Box.swift
1
6864
// // Box.swift // Sodium // // Created by Frank Denis on 12/28/14. // Copyright (c) 2014 Frank Denis. All rights reserved. // import Foundation public class Box { public let SeedBytes = Int(crypto_box_seedbytes()) public let PublicKeyBytes = Int(crypto_box_publickeybytes()) public let SecretKeyBytes = Int(crypto_box_secretkeybytes()) public let NonceBytes = Int(crypto_box_noncebytes()) public let MacBytes = Int(crypto_box_macbytes()) public let Primitive = String.fromCString(crypto_box_primitive()) public typealias PublicKey = NSData public typealias SecretKey = NSData public typealias Nonce = NSData public typealias MAC = NSData public struct KeyPair { public let publicKey: PublicKey public let secretKey: SecretKey } public func keyPair() -> KeyPair? { let pk = NSMutableData(length: PublicKeyBytes) if pk == nil { return nil } let sk = NSMutableData(length: SecretKeyBytes) if sk == nil { return nil } if crypto_box_keypair(pk!.mutableBytesPtr, sk!.mutableBytesPtr) != 0 { return nil } return KeyPair(publicKey: PublicKey(data: pk!), secretKey: SecretKey(data: sk!)) } public func keyPair(seed seed: NSData) -> KeyPair? { if seed.length != SeedBytes { return nil } let pk = NSMutableData(length: PublicKeyBytes) if pk == nil { return nil } let sk = NSMutableData(length: SecretKeyBytes) if sk == nil { return nil } if crypto_box_seed_keypair(pk!.mutableBytesPtr, sk!.mutableBytesPtr, seed.bytesPtr) != 0 { return nil } return KeyPair(publicKey: PublicKey(data: pk!), secretKey: SecretKey(data: sk!)) } public func nonce() -> Nonce? { let nonce = NSMutableData(length: NonceBytes) if nonce == nil { return nil } randombytes_buf(nonce!.mutableBytesPtr, nonce!.length) return nonce! as Nonce } public func seal(message: NSData, recipientPublicKey: PublicKey, senderSecretKey: SecretKey) -> NSData? { let sealed: (NSData, Nonce)? = seal(message, recipientPublicKey: recipientPublicKey, senderSecretKey: senderSecretKey) if sealed == nil { return nil } let (authenticatedCipherText, nonce) = sealed! let nonceAndAuthenticatedCipherText = NSMutableData(data: nonce) nonceAndAuthenticatedCipherText.appendData(authenticatedCipherText) return nonceAndAuthenticatedCipherText } public func seal(message: NSData, recipientPublicKey: PublicKey, senderSecretKey: SecretKey) -> (authenticatedCipherText: NSData, nonce: Nonce)? { if recipientPublicKey.length != PublicKeyBytes || senderSecretKey.length != SecretKeyBytes { return nil } let authenticatedCipherText = NSMutableData(length: message.length + MacBytes) if authenticatedCipherText == nil { return nil } let nonce = self.nonce() if nonce == nil { return nil } if crypto_box_easy(authenticatedCipherText!.mutableBytesPtr, message.bytesPtr, CUnsignedLongLong(message.length), nonce!.bytesPtr, recipientPublicKey.bytesPtr, senderSecretKey.bytesPtr) != 0 { return nil } return (authenticatedCipherText: authenticatedCipherText!, nonce: nonce!) } public func seal(message: NSData, recipientPublicKey: PublicKey, senderSecretKey: SecretKey) -> (authenticatedCipherText: NSData, nonce: Nonce, mac: MAC)? { if recipientPublicKey.length != PublicKeyBytes || senderSecretKey.length != SecretKeyBytes { return nil } let authenticatedCipherText = NSMutableData(length: message.length) if authenticatedCipherText == nil { return nil } let mac = NSMutableData(length: MacBytes) if mac == nil { return nil } let nonce = self.nonce() if nonce == nil { return nil } if crypto_box_detached(authenticatedCipherText!.mutableBytesPtr, mac!.mutableBytesPtr, message.bytesPtr, CUnsignedLongLong(message.length), nonce!.bytesPtr, recipientPublicKey.bytesPtr, senderSecretKey.bytesPtr) != 0 { return nil } return (authenticatedCipherText: authenticatedCipherText!, nonce: nonce! as Nonce, mac: mac! as MAC) } public func open(nonceAndAuthenticatedCipherText: NSData, senderPublicKey: PublicKey, recipientSecretKey: SecretKey) -> NSData? { if nonceAndAuthenticatedCipherText.length < NonceBytes + MacBytes { return nil } let nonce = nonceAndAuthenticatedCipherText.subdataWithRange(NSRange(0..<NonceBytes)) as Nonce let authenticatedCipherText = nonceAndAuthenticatedCipherText.subdataWithRange(NSRange(NonceBytes..<nonceAndAuthenticatedCipherText.length)) return open(authenticatedCipherText, senderPublicKey: senderPublicKey, recipientSecretKey: recipientSecretKey, nonce: nonce) } public func open(authenticatedCipherText: NSData, senderPublicKey: PublicKey, recipientSecretKey: SecretKey, nonce: Nonce) -> NSData? { if nonce.length != NonceBytes || authenticatedCipherText.length < MacBytes { return nil } if senderPublicKey.length != PublicKeyBytes || recipientSecretKey.length != SecretKeyBytes { return nil } let message = NSMutableData(length: authenticatedCipherText.length - MacBytes) if message == nil { return nil } if crypto_box_open_easy(message!.mutableBytesPtr, authenticatedCipherText.bytesPtr, CUnsignedLongLong(authenticatedCipherText.length), nonce.bytesPtr, senderPublicKey.bytesPtr, recipientSecretKey.bytesPtr) != 0 { return nil } return message } public func open(authenticatedCipherText: NSData, senderPublicKey: PublicKey, recipientSecretKey: SecretKey, nonce: Nonce, mac: MAC) -> NSData? { if nonce.length != NonceBytes || mac.length != MacBytes { return nil } if senderPublicKey.length != PublicKeyBytes || recipientSecretKey.length != SecretKeyBytes { return nil } let message = NSMutableData(length: authenticatedCipherText.length) if message == nil { return nil } if crypto_box_open_detached(message!.mutableBytesPtr, authenticatedCipherText.bytesPtr, mac.bytesPtr, CUnsignedLongLong(authenticatedCipherText.length), nonce.bytesPtr, senderPublicKey.bytesPtr, recipientSecretKey.bytesPtr) != 0 { return nil } return message } }
isc
e036a9f3e643d9e6045ee9b3a17b6c15
40.853659
238
0.653846
4.878465
false
false
false
false
BurlApps/latch
Framework/Latch.swift
2
4872
// // Latch.swift // Latch // // Created by Brian Vallelunga on 10/25/14. // Copyright (c) 2014 Brian Vallelunga. All rights reserved. // import Foundation import UIKit public protocol LatchDelegate { func latchGranted() func latchSet() func latchDenied(reason: LatchError) func latchCanceled() } public enum LatchError: Printable { case TouchIDAuthFailed, TouchIDSystemCancel, TouchIDPasscodeNotSet, TouchIDNotAvailable, TouchIDNotEnrolled, NoAuthMethodsAvailable, TouchIDNotAvailablePasscodeDisabled, TouchIDCancelledPasscodeDisabled, PasscodeNotSet public var description: String { switch self { case .TouchIDAuthFailed: return "Touch ID authorization failed." case .TouchIDSystemCancel: return "Touch ID system canceled." case .TouchIDPasscodeNotSet: return "Touch ID passcode not set." case .TouchIDNotAvailable: return "Touch ID not available." case .TouchIDNotEnrolled: return "Touch ID not enrolled." case .NoAuthMethodsAvailable: return "No authorization methods available." case .TouchIDNotAvailablePasscodeDisabled: return "Touch ID not available and passcode disabled." case .TouchIDCancelledPasscodeDisabled: return "Touch ID cancelled and passcode disabled." case .PasscodeNotSet: return "Passcode not set." } } } public class Latch: LTTouchIDDelegate, LTPasscodeDelegate { // MARK: Instance Variables public var delegate: LatchDelegate! public var parentController: UIViewController! public var touchReason: String = "We need to make sure it's you!" public var passcodeInstruction: String = NSLocalizedString("Enter Passcode", bundle: FrameworkBundle!, comment: "") public var changePasscodeInstruction: String = NSLocalizedString("Enter your old passcode", bundle: FrameworkBundle!, comment: "") public var enableTouch: Bool = true public var enablePasscode: Bool = true public var enablePasscodeChange: Bool = false public var passcodeTheme: LTPasscodeTheme = LTPasscodeTheme() // MARK: Private Instance Variables private var touchID: LTTouchID! private var passcode: LTPasscode! private var storage: LTStorage! = LTStorage() // MARK: Initializer public init(defaultPasscode: String? = nil) { // Initialize TouchID Module self.touchID = LTTouchID(reason: self.touchReason) self.touchID.delegate = self // Initialize Passcode Module self.passcode = LTPasscode(instructions: self.passcodeInstruction, changeInstructions: self.changePasscodeInstruction) if let passcodeString = defaultPasscode { self.passcode.setDefaultPasscode(passcodeString) } self.passcode.delegate = self self.passcode.theme = self.passcodeTheme } // MARK: Instance Methods public func authorize() { if self.enableTouch == false && self.enablePasscode == false { self.delegate!.latchDenied(LatchError.NoAuthMethodsAvailable) return } if self.enableTouch { self.touchID.authorize() } if self.enablePasscode { self.passcode.parentController = self.parentController self.passcode.theme = self.passcodeTheme self.passcode.enablePasscodeChange = self.enablePasscodeChange self.passcode.updateStyle() self.passcode.authorize() } } public func updatePasscode() { self.passcode.parentController = self.parentController self.passcode.theme = self.passcodeTheme self.passcode.updateStyle() self.passcode.setPasscode() } public func removePasscode() { self.storage.removePasscode() } // MARK: LTPasscode Delegate Methods public func passcodeGranted() { self.delegate!.latchGranted() } public func passcodeFailed(reason: LatchError) { self.delegate!.latchDenied(reason) } public func passcodeSet() { self.delegate.latchSet() } public func passcodeCanceled() { self.delegate.latchCanceled() } // MARK: LTTouchID Delegate Methods internal func touchIDGranted() { self.delegate!.latchGranted() self.passcode.dismiss() } internal func touchIDDenied(reason: LatchError) { self.delegate!.latchDenied(reason) } internal func touchIDCancelled() { if self.enablePasscode == false { self.delegate!.latchDenied(LatchError.TouchIDCancelledPasscodeDisabled) } } internal func touchIDNotAvailable(reason: LatchError) { if self.enablePasscode == false { self.delegate!.latchDenied(LatchError.TouchIDNotAvailablePasscodeDisabled) } } }
gpl-2.0
e67a36573b6a4ffbb3c534a7af1230c7
31.059211
132
0.677545
4.857428
false
false
false
false
PlutoMa/EmployeeCard
EmployeeCard/EmployeeCard/Core/BusVC/BusVC.swift
1
3586
// // BusVC.swift // EmployeeCard // // Created by PlutoMa on 2017/4/7. // Copyright © 2017年 PlutoMa. All rights reserved. // import UIKit class BusVC: UIViewController { var busModelArr = [BusModel]() @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self getBusInfo() } func getBusInfo() -> Void { let hud = MBProgressHUD.showAdded(to: view, animated: true) NetUtil.post(url: busInfoUrl, param: nil, success: { (data) in let dataDic = data as! [String : Any] if let errorCode = dataDic["errorCode"] as? String, errorCode == "0" { hud?.hide(true) self.configBusModelArr(busArr: (dataDic["bus"] as? [[String : Any]]) ?? [[String : Any]](), runtimeArr: (dataDic["runtime"] as? [[String : Any]]) ?? [[String : Any]]()) } else { hud?.mode = .text hud?.labelText = (dataDic["errorText"] as? String) ?? "" hud?.hide(true, afterDelay: 2.5) } }, failure: { (error) in hud?.mode = .text hud?.labelText = "网络出错" hud?.hide(true, afterDelay: 2.5) }) } func configBusModelArr(busArr: [[String : Any]], runtimeArr: [[String : Any]]) -> Void { let newBusArr = busArr.sorted { $1["id"] as! String > $0["id"] as! String } for dic in newBusArr { let id = dic["id"] as? String let name = dic["name"] as? String let number = dic["cph"] as? String var startTime: String? var endTime: String? for runtimeDic in runtimeArr { let vrid = runtimeDic["vrid"] as? String if vrid == id { if runtimeDic["sxh"] as? Int == 1 { startTime = runtimeDic["time"] as? String } if runtimeDic["sxh"] as? Int == 2 { endTime = runtimeDic["time"] as? String } } } let busModel = BusModel(id: id, name: name, number: number, startTime: startTime, endTime: endTime) busModelArr.append(busModel) } tableView.reloadData() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } @IBAction func backAction(_ sender: Any) { _ = navigationController?.popViewController(animated: true) } } extension BusVC: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return busModelArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BusTableCell") as! BusTableCell let model = busModelArr[indexPath.row] cell.nameLabel.text = model.name cell.numberLabel.text = model.number cell.beginTimeLabel.text = model.startTime cell.endTimeLabel.text = model.endTime return cell } }
mit
dcfce6f6aadf4c56b5611704d9140a12
34.39604
196
0.521958
4.735099
false
false
false
false
snark/jumpcut
Jumpcut/Jumpcut/Preferences/PreferenceWindow.swift
1
735
// // PreferenceWindow.swift // Jumpcut // // Created by Steve Cook on 7/21/22. // import Cocoa import Preferences extension Preferences.PaneIdentifier { static let appearance = Self("appearance") static let clippings = Self("clippings") static let general = Self("general") static let hotkey = Self("hotkey") } // Preferences pane var preferences: [PreferencePane] = [ GeneralPreferenceViewController(), HotkeyPreferenceViewController(), ClippingsPreferenceViewController(), AppearancePreferenceViewController() ] var preferencesWindowController = PreferencesWindowController( preferencePanes: preferences, style: .toolbarItems, animated: true, hidesToolbarForSingleItem: true )
mit
84a3cd5d3fb4f0d2f7f9fdb1d2b97d30
22.709677
62
0.738776
4.537037
false
false
false
false
AndrewShmig/Qtty
Qtty/MainScreen.swift
1
4874
// // MainScreen.swift // Qtty // // Created by AndrewShmig on 03/07/14. // Copyright (c) 2014 Non Atomic Games Inc. All rights reserved. // import UIKit import Foundation class MainScreen: UIViewController { let authorizationButton = UIButton() override func loadView() { // настраиваем вьюху var view = UIView(frame:UIScreen.mainScreen().bounds) // устанавливаем фоновое изображение let backgroundImage = UIImage(named:"backgroundImage") let backgroundImageView = UIImageView(image:backgroundImage) backgroundImageView.frame = UIScreen.mainScreen().bounds view.addSubview(backgroundImageView) // накладываем прозрачность let glassView = UIView(frame:UIScreen.mainScreen().bounds) glassView.alpha = 0.65 glassView.backgroundColor = UIColor(red:0.815, green:0.815, blue:0.815, alpha:1.0) let blurEffectView = UIVisualEffectView(effect:UIBlurEffect(style:.Light)) blurEffectView.frame = glassView.frame glassView.addSubview(blurEffectView) view.addSubview(glassView) // добавляем надпись с названием приложения let screenMidX = CGRectGetWidth(UIScreen.mainScreen().bounds) / 2 let screenMidY = CGRectGetHeight(UIScreen.mainScreen().bounds) / 2 let appNameImage = UIImage(named:"logo") let appNameImageView = UIImageView(image:appNameImage) appNameImageView.center = CGPointMake(screenMidX, screenMidY) view.addSubview(appNameImageView) // добавляем кнопку авторизации в ВК let authorizationButtonHeight: Double = 40.0 let authorizationButtonX: Double = 10.0 let authorizationButtonWidth = Double(UIScreen.mainScreen().bounds.size.width) - authorizationButtonX * 2 let authorizationButtonY = Double(UIScreen.mainScreen().bounds.size.height) - 10.0 - authorizationButtonHeight authorizationButton.backgroundColor = UIColor(red:0.439, green:0.286, blue:0.549, alpha:1) authorizationButton.setTitleColor(UIColor(red:0.749, green:0.749, blue:0.749, alpha:1), forState:.Normal) authorizationButton.setTitle("Авторизоваться", forState:.Normal) authorizationButton.titleLabel.font = UIFont(name:"Helvetica Light", size:25) authorizationButton.enabled = false authorizationButton.addTarget(self, action:"authorizationButtonTappedInside:", forControlEvents:.TouchUpInside) // объединяем тень и кнопку в одну вьюху let compoundView = UIView(frame: CGRectMake(CGFloat(authorizationButtonX), CGFloat(authorizationButtonY), CGFloat(authorizationButtonWidth), CGFloat(authorizationButtonHeight))) let shadow = NAGShadowedView(frame: CGRectMake(0, 0, CGRectGetWidth(compoundView.frame), CGRectGetHeight(compoundView.frame))) authorizationButton.frame = shadow.frame authorizationButton.layer.cornerRadius = 6.0 compoundView.addSubview(shadow) compoundView.addSubview(authorizationButton) view.addSubview(compoundView) // устанавливаем текущую сконфигурированную вьюху self.view = view } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if VKUser.currentUser() { authorizationButton.enabled = false if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) { println("We have camera...") let cameraView = NAGImagePickerController() cameraView.delegate = cameraView cameraView.sourceType = UIImagePickerControllerSourceType.Camera cameraView.showsCameraControls = false cameraView.allowsEditing = false cameraView.cameraOverlayView = NAGFirstPhotoOverlayView(frame: UIScreen.mainScreen().bounds) self.presentViewController(cameraView, animated: false, completion: nil) } else { UIAlertView(title: "Ошибка!", message: "Упс! Не можем достучаться до камеры.", delegate: nil, cancelButtonTitle: "OK").show() } } else { authorizationButton.enabled = true println("User is not authorized...") } } func authorizationButtonTappedInside(sender:UIButton) { let vkModal = VKAuthorizationViewController() as UIViewController vkModal.modalPresentationStyle = .FullScreen vkModal.modalTransitionStyle = .CoverVertical self.presentViewController(vkModal, animated:true, completion:nil) } override func supportedInterfaceOrientations() -> Int { return Int(UIInterfaceOrientationMask.Portrait.toRaw() | UIInterfaceOrientationMask.PortraitUpsideDown.toRaw()) } }
mit
61f83826ed4e95265aa03db7835469a4
38.452991
181
0.72487
4.547783
false
false
false
false
apstrand/loggy
LoggyTools/LogTracks.swift
1
3571
// // LogTracks.swift // Loggy // // Created by Peter Strand on 2017-07-12. // Copyright © 2017 Peter Strand. All rights reserved. // import Foundation import CoreLocation public class LogTracks { public typealias LocationLogger = (TrackPoint, Bool) -> Void public typealias TrackLogger = (GPXData.Track?, GPXData.TrackSeg?, TrackPoint?) -> Void public typealias WaypointLogger = (GPXData.Waypoint) -> Void var trackLoggers : [(Int,Filter,TrackLogger)] = [] var waypointLoggers : [(Int,Filter,WaypointLogger)] = [] var loggerId = 0 var regs = TokenRegs() public var gpx: GPXData public var isTracking: Bool = false public init(_ gpx: GPXData) { self.gpx = gpx } public func handleNewLocation(point pt: TrackPoint, isMajor: Bool) { if isTracking { self.gpx.tracks.last!.segments.last!.track.append(TrackPoint(location:pt.location, timestamp: pt.timestamp)) } } public func startNewSegment() { if gpx.tracks.count == 0 { gpx.tracks.append(GPXData.Track(id:gpx.genId())) } gpx.tracks.last!.segments.append(GPXData.TrackSeg(id:gpx.genId())) isTracking = true } public func endSegment(_ pt: TrackPoint?) { isTracking = false } public func storeWaypoint(location pt: TrackPoint) { let waypoint = GPXData.Waypoint(point: pt, id: gpx.genId()) for logger in self.waypointLoggers { logger.2(waypoint) } } public struct Filter { let fullHistory: Bool let majorPoints: Bool let trackingOnly: Bool public init(trackingOnly: Bool, fullHistory: Bool = false, majorPoints: Bool = false) { self.fullHistory = fullHistory self.trackingOnly = trackingOnly self.majorPoints = majorPoints } } public func observeTrackData(_ filter: Filter, _ logger : @escaping TrackLogger) -> Token { loggerId += 1 let removeId = loggerId self.trackLoggers.append((removeId,filter,logger)) if filter.fullHistory { for track in gpx.tracks { for seg in track.segments { logger(track, seg, nil) } } } return TokenImpl { for ix in self.trackLoggers.indices { if self.trackLoggers[ix].0 == removeId { self.trackLoggers.remove(at: ix) break } } } } public func observeWaypoints(_ filter: Filter, _ logger : @escaping WaypointLogger) -> Token { loggerId += 1 let removeId = loggerId self.waypointLoggers.append((removeId,filter,logger)) if filter.fullHistory { for waypoint in gpx.waypoints { logger(waypoint) } } return TokenImpl { for ix in self.waypointLoggers.indices { if self.waypointLoggers[ix].0 == removeId { self.waypointLoggers.remove(at: ix) break } } } } public func load(from other: GPXData) { self.gpx.tracks = other.tracks self.gpx.waypoints = other.waypoints refreshObservers() } func refreshObservers() { for logger in trackLoggers { if logger.1.fullHistory { // clear all logger.2(nil, nil, nil) } } for track in self.gpx.tracks { for seg in track.segments { for logger in trackLoggers { if logger.1.fullHistory { logger.2(track, seg, nil) } } } } for waypoint in self.gpx.waypoints { for logger in waypointLoggers { if logger.1.fullHistory { logger.2(waypoint) } } } } }
mit
a8b76ab940af3c74cc0fa5036cf2ec88
22.959732
114
0.616527
3.966667
false
false
false
false
google/android-auto-companion-ios
Sources/AndroidAutoConnectedDeviceManager/AssociationMessageHelperV4.swift
1
6829
// Copyright 2021 Google LLC // // 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. @_implementationOnly import AndroidAutoCoreBluetoothProtocols import AndroidAutoLogger @_implementationOnly import AndroidAutoMessageStream @_implementationOnly import AndroidAutoSecureChannel import CoreBluetooth import Foundation @_implementationOnly import AndroidAutoCompanionProtos private typealias VerificationCodeState = Com_Google_Companionprotos_VerificationCodeState private typealias VerificationCode = Com_Google_Companionprotos_VerificationCode /// Handles version 4 of the message exchange. /// /// Version 4 Phases are: /// 1) Begin encryption handshake. /// 2) Send verification code for the desired mode (visual pairing or OOB). /// 3) Receive confirmation code. /// 4) Establish encryption. /// 5) Send device ID and receive car ID. /// 6) Complete association. final class AssociationMessageHelperV4 { static let log = Logger(for: AssociationMessageHelperV4.self) private let messageStream: MessageStream private let associator: Associator /// Possible states of the association process. private enum Phase { case none case encryptionInProgress case visualConfirmation case outOfBandConfirmation(SecurityVerificationToken, OutOfBandToken) case encryptionEstablished case done } /// Current association phase. private var phase = Phase.none init(_ associator: Associator, messageStream: MessageStream) { self.associator = associator self.messageStream = messageStream } } // MARK: - AssociationMessageHelper extension AssociationMessageHelperV4: AssociationMessageHelper { func start() { phase = .encryptionInProgress associator.establishEncryption(using: messageStream) } func handleMessage(_ message: Data, params: MessageStreamParams) { switch phase { case .encryptionInProgress: Self.log.error("Invalid state of .encryptionInProgress encountered.") associator.notifyDelegateOfError(.unknown) case .visualConfirmation: do { let code = try VerificationCode(serializedData: message) guard code.state == .visualConfirmation else { Self.log.error("Expecting visual confirmation, but instead received: \(code.state)") associator.notifyDelegateOfError(.unknown) return } try associator.notifyPairingCodeAccepted() } catch { associator.notifyDelegateOfError(.pairingCodeRejected) } case let .outOfBandConfirmation(securityToken, outOfBandToken): do { let code = try VerificationCode(serializedData: message) guard code.state == .oobVerification else { Self.log.error("Expecting Out-Of-Band confirmation, but instead received: \(code.state)") associator.notifyDelegateOfError(.unknown) return } let confirmation = try outOfBandToken.decrypt(code.payload) guard confirmation == securityToken.data else { Self.log.error("Decrypted pairing verification code does not match the security token.") associator.notifyDelegateOfError(.pairingCodeRejected) return } try associator.notifyPairingCodeAccepted() } catch { associator.notifyDelegateOfError(.pairingCodeRejected) } case .encryptionEstablished: guard let carId = try? extractCarId(fromMessage: message) else { Self.log.error("Error extracting carId from message.") associator.notifyDelegateOfError(.malformedCarId) return } associator.carId = carId let authenticator = CarAuthenticatorImpl() guard let _ = try? authenticator.saveKey(forIdentifier: carId) else { associator.notifyDelegateOfError(.authenticationKeyStorageFailed) return } sendDeviceIdPlusAuthenticationKey(keyData: authenticator.keyData, on: messageStream) case .none: Self.log.error("Invalid state of .none encountered.") associator.notifyDelegateOfError(.unknown) case .done: Self.log.error("Invalid state of .done encountered.") associator.notifyDelegateOfError(.unknown) } } func messageDidSendSuccessfully() { guard case .encryptionEstablished = phase else { return } Self.log("Device id and authentication key successfully sent.") guard let carId = associator.carId, let channel = associator.establishSecuredCarChannel( forCarId: carId, messageStream: messageStream) else { associator.notifyDelegateOfError(.cannotStoreAssociation) return } associator.connectionHandle.requestConfiguration(for: channel) { [weak self] in guard let self = self else { return } Self.log("Channel user role: \(channel.userRole.debugDescription)") self.associator.completeAssociation(channel: channel, messageStream: self.messageStream) self.phase = .done } } func onRequiresPairingVerification(_ verificationToken: SecurityVerificationToken) { Self.log("Helper requesting out of band token.") associator.requestOutOfBandToken { [weak self] outOfBandToken in guard let self = self else { return } do { var code = VerificationCode() if let outOfBandToken = outOfBandToken { Self.log("Out of band verification token will be used.") code.state = .oobVerification code.payload = try outOfBandToken.encrypt(verificationToken.data) self.phase = .outOfBandConfirmation(verificationToken, outOfBandToken) } else { Self.log("No out of band verification token. Will perform visual verification.") code.state = .visualVerification self.phase = .visualConfirmation self.associator.displayPairingCode(verificationToken.pairingCode) } let message = try code.serializedData() try self.messageStream.writeMessage(message, params: Self.handshakeMessageParams) } catch { Self.log.error("Error sending pairing verification code.") self.associator.notifyDelegateOfError(.verificationCodeFailed) return } } } func onPairingCodeDisplayed() { // Nothing to do here as we await confirmation from the IHU. } func onEncryptionEstablished() { phase = .encryptionEstablished } }
apache-2.0
ba357ba73ae9c887e90254f198a54aa6
36.11413
99
0.716942
4.706409
false
false
false
false
JGiola/swift-package-manager
Tests/PackageModelTests/SwiftLanguageVersionTests.swift
2
2619
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import Basic import PackageModel class SwiftLanguageVersionTests: XCTestCase { func testBasics() throws { let validVersions = [ "4" : "4", "4.0" : "4.0", "4.2" : "4.2", "1.0.0" : "1.0.0", "3.1.0" : "3.1.0", ] for (version, expected) in validVersions { guard let swiftVersion = SwiftLanguageVersion(string: version) else { return XCTFail("Couldn't form a version with string: \(version)") } XCTAssertEqual(swiftVersion.rawValue, expected) XCTAssertEqual(swiftVersion.description, expected) } let invalidVersions = [ "1.2.3.4", "1.2-al..beta.0+bu.uni.ra", "1.2.33-al..beta.0+bu.uni.ra", ".1.0.0-x.7.z.92", "1.0.0-alpha.beta+", "1.0.0beta", "1.0.0-", "1.-2.3", "1.2.3d", ] for version in invalidVersions { if let swiftVersion = SwiftLanguageVersion(string: version) { XCTFail("Formed an invalid version \(swiftVersion) with string: \(version)") } } } func testComparison() { XCTAssertTrue(SwiftLanguageVersion(string: "4.0.1")! > SwiftLanguageVersion(string: "4")!) XCTAssertTrue(SwiftLanguageVersion(string: "4.0")! == SwiftLanguageVersion(string: "4")!) XCTAssertTrue(SwiftLanguageVersion(string: "4.1")! > SwiftLanguageVersion(string: "4")!) XCTAssertTrue(SwiftLanguageVersion(string: "5")! >= SwiftLanguageVersion(string: "4")!) XCTAssertTrue(SwiftLanguageVersion(string: "4.0.1")! < ToolsVersion(string: "4.1")!) XCTAssertTrue(SwiftLanguageVersion(string: "4")! == ToolsVersion(string: "4.0")!) XCTAssertTrue(SwiftLanguageVersion(string: "4.2")! == ToolsVersion(string: "4.2")!) XCTAssertTrue(SwiftLanguageVersion(string: "4.2")! < ToolsVersion(string: "4.3")!) XCTAssertTrue(SwiftLanguageVersion(string: "4.2")! <= ToolsVersion(string: "4.3")!) XCTAssertTrue(SwiftLanguageVersion(string: "4.2")! <= ToolsVersion(string: "5.0")!) XCTAssertTrue(SwiftLanguageVersion(string: "4")! < ToolsVersion(string: "5.0")!) } }
apache-2.0
1b00e51f28d3405a545f80012048404a
36.414286
98
0.597174
3.885757
false
true
false
false
vladislav-k/VKCheckbox
VKCheckboxExample/VKCheckboxExample/ViewController.swift
1
2627
// // ViewController.swift // VKCheckboxExample // // Created by Vladislav Kovalyov on 8/22/16. // Copyright © 2016 WOOPSS.com http://woopss.com/ All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class ViewController: UIViewController { @IBOutlet weak var checkbox: VKCheckbox! @IBOutlet weak var customCheckbox: VKCheckbox! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Simple checkbox callback checkbox.checkboxValueChangedBlock = { isOn in print("Basic checkbox is \(isOn ? "ON" : "OFF")") } // Customized checkbox customCheckbox.line = .thin customCheckbox.bgColorSelected = UIColor(red: 46/255, green: 119/255, blue: 217/255, alpha: 1) customCheckbox.bgColor = UIColor.gray customCheckbox.color = UIColor.white customCheckbox.borderColor = UIColor.white customCheckbox.borderWidth = 2 customCheckbox.cornerRadius = customCheckbox.frame.height / 2 // Handle custom checkbox callback customCheckbox.checkboxValueChangedBlock = { isOn in print("Custom checkbox is \(isOn ? "ON" : "OFF")") } } } // MARK: - Actions extension ViewController { @IBAction func onReset(_ sender: AnyObject) { self.checkbox.setOn(false) self.customCheckbox.setOn(false, animated: true) } }
mit
3bd09be02ebb554407e39a0906c94610
35.985915
103
0.674791
4.607018
false
false
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/Examples/Examples/BarsPlusMinusAndLinesExample.swift
1
6480
// // BarsPlusMinusAndLinesExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class BarsPlusMinusAndLinesExample: UIViewController { fileprivate var chart: Chart? // arc override func viewDidLoad() { let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let barsData: [(title: String, min: Double, max: Double)] = [ ("A", -65, 40), ("B", -30, 50), ("C", -40, 35), ("D", -50, 40), ("E", -60, 30), ("F", -35, 47), ("G", -30, 60), ("H", -46, 48) ] let lineData: [(title: String, val: Double)] = [ ("A", -10), ("B", 20), ("C", -20), ("D", 10), ("E", -20), ("F", 23), ("G", 10), ("H", 45) ] let alpha: CGFloat = 0.5 let posColor = UIColor.green.withAlphaComponent(alpha) let negColor = UIColor.red.withAlphaComponent(alpha) let zero = ChartAxisValueDouble(0) let bars: [ChartBarModel] = barsData.enumerated().flatMap {index, tuple in [ ChartBarModel(constant: ChartAxisValueDouble(index), axisValue1: zero, axisValue2: ChartAxisValueDouble(tuple.min), bgColor: negColor), ChartBarModel(constant: ChartAxisValueDouble(index), axisValue1: zero, axisValue2: ChartAxisValueDouble(tuple.max), bgColor: posColor) ] } let yValues = stride(from: (-80), through: 80, by: 20).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)} let xValues = [ChartAxisValueString(order: -1)] + barsData.enumerated().map {index, tuple in ChartAxisValueString(tuple.0, order: index, labelSettings: labelSettings)} + [ChartAxisValueString(order: barsData.count)] 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 chartFrame = ExamplesDefaults.chartFrame(self.view.bounds) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let barsLayer = ChartBarsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, bars: bars, horizontal: false, barWidth: Env.iPad ? 40 : 25, animDuration: 0.5) // labels layer // create chartpoints for the top and bottom of the bars, where we will show the labels let labelChartPoints = bars.map {bar in ChartPoint(x: bar.constant, y: bar.axisValue2) } let formatter = NumberFormatter() formatter.maximumFractionDigits = 2 let labelsLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: labelChartPoints, viewGenerator: {(chartPointModel, layer, chart) -> UIView? in let label = HandlingLabel() let posOffset: CGFloat = 10 let pos = chartPointModel.chartPoint.y.scalar > 0 let yOffset = pos ? -posOffset : posOffset label.text = "\(formatter.string(from: NSNumber(value: chartPointModel.chartPoint.y.scalar))!)%" label.font = ExamplesDefaults.labelFont label.sizeToFit() label.center = CGPoint(x: chartPointModel.screenLoc.x, y: pos ? innerFrame.origin.y : innerFrame.origin.y + innerFrame.size.height) label.alpha = 0 label.movedToSuperViewHandler = {[weak label] in UIView.animate(withDuration: 0.3, animations: { label?.alpha = 1 label?.center.y = chartPointModel.screenLoc.y + yOffset }) } return label }, displayDelay: 0.5) // show after bars animation // line layer let lineChartPoints = lineData.enumerated().map {index, tuple in ChartPoint(x: ChartAxisValueDouble(index), y: ChartAxisValueDouble(tuple.val))} let lineModel = ChartLineModel(chartPoints: lineChartPoints, lineColor: UIColor.black, lineWidth: 2, animDuration: 0.5, animDelay: 1) let lineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel]) let circleViewGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in let color = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1) let circleView = ChartPointEllipseView(center: chartPointModel.screenLoc, diameter: 6) circleView.animDuration = 0.5 circleView.fillColor = color return circleView } let lineCirclesLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: lineChartPoints, viewGenerator: circleViewGenerator, displayDelay: 1.5, delayBetweenItems: 0.05) // show a gap between positive and negative bar let dummyZeroYChartPoint = ChartPoint(x: ChartAxisValueDouble(0), y: ChartAxisValueDouble(0)) let yZeroGapLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: [dummyZeroYChartPoint], viewGenerator: {(chartPointModel, layer, chart) -> UIView? in let height: CGFloat = 2 let v = UIView(frame: CGRect(x: innerFrame.origin.x + 2, y: chartPointModel.screenLoc.y - height / 2, width: innerFrame.origin.x + innerFrame.size.height, height: height)) v.backgroundColor = UIColor.white return v }) let chart = Chart( frame: chartFrame, layers: [ xAxis, yAxis, barsLayer, labelsLayer, yZeroGapLayer, lineLayer, lineCirclesLayer ] ) self.view.addSubview(chart.view) self.chart = chart } }
mit
23f05e748191f8234fff2c0a9a3da87c
45.618705
214
0.610802
4.807122
false
false
false
false
HeartRateLearning/HRLApp
HRLApp/Modules/ListHeartRates/View/ListHeartRatesViewController.swift
1
3451
// // ListHeartRatesListHeartRatesViewController.swift // HRLApp // // Created by Enrique de la Torre on 03/02/2017. // Copyright © 2017 Enrique de la Torre. All rights reserved. // import UIKit // MARK: - Main body final class ListHeartRatesViewController: UIViewController { // MARK: - Dependencies var output: ListHeartRatesViewOutput! // MARK: - Outlets @IBOutlet weak var tableView: UITableView! // MARK: - Private properties fileprivate lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .short return formatter }() fileprivate var records = [] as [FoundHeartRateRecord] // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() } // MARK: - Actions @IBAction func save(_ sender: Any) { let workingOuts = records.map { (record) -> Bool in return record.workingOut } output.save(workingOuts: workingOuts) } } // MARK: - UITableViewDataSource methods extension ListHeartRatesViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return records.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: Constants.cellIdentifier, for: indexPath) let record = records[indexPath.row] cell.textLabel?.text = String(record.bpm) cell.detailTextLabel?.text = dateFormatter.string(from: record.date) return cell } } // MARK: - UITableViewDelegate methods extension ListHeartRatesViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let record = records[indexPath.row] if record.workingOut { tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) } else { tableView.deselectRow(at: indexPath, animated: false) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { replaceRecord(at: indexPath.row, withWorkingOut: true) } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { replaceRecord(at: indexPath.row, withWorkingOut: false) } } // MARK: - ListHeartRatesViewInput methods extension ListHeartRatesViewController: ListHeartRatesViewInput { func setup(with records: [FoundHeartRateRecord]) { self.records = records if isViewLoaded { tableView.reloadData() } } } // MARK: - Private body private extension ListHeartRatesViewController { // MARK: - Constants enum Constants { static let cellIdentifier = "HeartRateCell" } // MARK: - Private methods func replaceRecord(at index: Int, withWorkingOut workingOut: Bool) { let oldRecord = records[index] let nextRecord = FoundHeartRateRecord(date: oldRecord.date, bpm: oldRecord.bpm, workingOut: workingOut) records[index] = nextRecord } }
mit
9b4ebce56bf8ca98c629381591c02826
25.953125
90
0.638551
4.978355
false
false
false
false
eugenepavlyuk/swift-algorithm-club
Quicksort/Quicksort.swift
6
6286
import Foundation /* Easy to understand but not very efficient. */ func quicksort<T: Comparable>(_ a: [T]) -> [T] { guard a.count > 1 else { return a } let pivot = a[a.count/2] let less = a.filter { $0 < pivot } let equal = a.filter { $0 == pivot } let greater = a.filter { $0 > pivot } return quicksort(less) + equal + quicksort(greater) } // MARK: - Lomuto /* Lomuto's partitioning algorithm. This is conceptually simpler than Hoare's original scheme but less efficient. The return value is the index of the pivot element in the new array. The left partition is [low...p-1]; the right partition is [p+1...high], where p is the return value. The left partition includes all values smaller than or equal to the pivot, so if the pivot value occurs more than once, its duplicates will be found in the left partition. */ func partitionLomuto<T: Comparable>(_ a: inout [T], low: Int, high: Int) -> Int { // We always use the highest item as the pivot. let pivot = a[high] // This loop partitions the array into four (possibly empty) regions: // [low ... i] contains all values <= pivot, // [i+1 ... j-1] contains all values > pivot, // [j ... high-1] are values we haven't looked at yet, // [high ] is the pivot value. var i = low for j in low..<high { if a[j] <= pivot { (a[i], a[j]) = (a[j], a[i]) i += 1 } } // Swap the pivot element with the first element that is greater than // the pivot. Now the pivot sits between the <= and > regions and the // array is properly partitioned. (a[i], a[high]) = (a[high], a[i]) return i } /* Recursive, in-place version that uses Lomuto's partioning scheme. */ func quicksortLomuto<T: Comparable>(_ a: inout [T], low: Int, high: Int) { if low < high { let p = partitionLomuto(&a, low: low, high: high) quicksortLomuto(&a, low: low, high: p - 1) quicksortLomuto(&a, low: p + 1, high: high) } } // MARK: - Hoare partitioning /* Hoare's partitioning scheme. The return value is NOT necessarily the index of the pivot element in the new array. Instead, the array is partitioned into [low...p] and [p+1...high], where p is the return value. The pivot value is placed somewhere inside one of the two partitions, but the algorithm doesn't tell you which one or where. If the pivot value occurs more than once, then some instances may appear in the left partition and others may appear in the right partition. Hoare scheme is more efficient than Lomuto's partition scheme; it performs fewer swaps. */ func partitionHoare<T: Comparable>(_ a: inout [T], low: Int, high: Int) -> Int { let pivot = a[low] var i = low - 1 var j = high + 1 while true { repeat { j -= 1 } while a[j] > pivot repeat { i += 1 } while a[i] < pivot if i < j { swap(&a[i], &a[j]) } else { return j } } } /* Recursive, in-place version that uses Hoare's partioning scheme. Because of the choice of pivot, this performs badly if the array is already sorted. */ func quicksortHoare<T: Comparable>(_ a: inout [T], low: Int, high: Int) { if low < high { let p = partitionHoare(&a, low: low, high: high) quicksortHoare(&a, low: low, high: p) quicksortHoare(&a, low: p + 1, high: high) } } // MARK: - Randomized sort /* Returns a random integer in the range min...max, inclusive. */ public func random(min: Int, max: Int) -> Int { assert(min < max) return min + Int(arc4random_uniform(UInt32(max - min + 1))) } /* Uses a random pivot index. On average, this results in a well-balanced split of the input array. */ func quicksortRandom<T: Comparable>(_ a: inout [T], low: Int, high: Int) { if low < high { // Create a random pivot index in the range [low...high]. let pivotIndex = random(min: low, max: high) // Because the Lomuto scheme expects a[high] to be the pivot entry, swap // a[pivotIndex] with a[high] to put the pivot element at the end. (a[pivotIndex], a[high]) = (a[high], a[pivotIndex]) let p = partitionLomuto(&a, low: low, high: high) quicksortRandom(&a, low: low, high: p - 1) quicksortRandom(&a, low: p + 1, high: high) } } // MARK: - Dutch national flag partitioning /* Swift's swap() doesn't like it if the items you're trying to swap refer to the same memory location. This little wrapper simply ignores such swaps. */ public func swap<T>(_ a: inout [T], _ i: Int, _ j: Int) { if i != j { swap(&a[i], &a[j]) } } /* Dutch national flag partitioning Partitions the array into three sections: all element smaller than the pivot, all elements equal to the pivot, and all larger elements. This makes for a more efficient Quicksort if the array contains many duplicate elements. Returns a tuple with the start and end index of the middle area. For example, on [0,1,2,3,3,3,4,5] it returns (3, 5). Note: These indices are relative to 0, not to "low"! The number of occurrences of the pivot is: result.1 - result.0 + 1 Time complexity is O(n), space complexity is O(1). */ func partitionDutchFlag<T: Comparable>(_ a: inout [T], low: Int, high: Int, pivotIndex: Int) -> (Int, Int) { let pivot = a[pivotIndex] var smaller = low var equal = low var larger = high // This loop partitions the array into four (possibly empty) regions: // [low ...smaller-1] contains all values < pivot, // [smaller... equal-1] contains all values == pivot, // [equal ... larger] contains all values > pivot, // [larger ... high] are values we haven't looked at yet. while equal <= larger { if a[equal] < pivot { swap(&a, smaller, equal) smaller += 1 equal += 1 } else if a[equal] == pivot { equal += 1 } else { swap(&a, equal, larger) larger -= 1 } } return (smaller, larger) } /* Uses Dutch national flag partitioning and a random pivot index. */ func quicksortDutchFlag<T: Comparable>(_ a: inout [T], low: Int, high: Int) { if low < high { let pivotIndex = random(min: low, max: high) let (p, q) = partitionDutchFlag(&a, low: low, high: high, pivotIndex: pivotIndex) quicksortDutchFlag(&a, low: low, high: p - 1) quicksortDutchFlag(&a, low: q + 1, high: high) } }
mit
8549d0b552cecafcebbd45aa8b53cece
29.663415
108
0.641744
3.366899
false
false
false
false
joostholslag/BNRiOS
iOSProgramming6ed/7 - Localization/Solutions/WorldTrotter/WorldTrotter/MapViewController.swift
1
2116
// // Copyright © 2015 Big Nerd Ranch // import UIKit import MapKit class MapViewController: UIViewController { var mapView: MKMapView! override func loadView() { // Create a map view mapView = MKMapView() // Set it as *the* view of this view controller view = mapView let standardString = NSLocalizedString("Standard", comment: "foobar") let satelliteString = NSLocalizedString("Satellite", comment: "foobar") let hybridString = NSLocalizedString("Hybrid", comment: "foobar") let segmentedControl = UISegmentedControl(items: [standardString, satelliteString, hybridString]) segmentedControl.backgroundColor = UIColor.white.withAlphaComponent(0.5) segmentedControl.selectedSegmentIndex = 0 segmentedControl.addTarget(self, action: #selector(MapViewController.mapTypeChanged(_:)), for: .valueChanged) segmentedControl.translatesAutoresizingMaskIntoConstraints = false view.addSubview(segmentedControl) let topConstraint = segmentedControl.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 8) let margins = view.layoutMarginsGuide let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor) let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor) topConstraint.isActive = true leadingConstraint.isActive = true trailingConstraint.isActive = true } func mapTypeChanged(_ segControl: UISegmentedControl) { switch segControl.selectedSegmentIndex { case 0: mapView.mapType = .standard case 1: mapView.mapType = .hybrid case 2: mapView.mapType = .satellite default: break } } override func viewDidLoad() { super.viewDidLoad() print("MapViewController loaded its view") } }
gpl-3.0
4e7e2030af469430cafab570cd566fa7
31.045455
96
0.642553
5.974576
false
false
false
false
LYM-mg/MGDYZB
MGDYZB/MGDYZB/Class/Live/Controller/FaceScoreViewController.swift
1
4946
// // FaceScoreViewController.swift // MGDYZB // // Created by i-Techsys.com on 17/2/25. // Copyright © 2017年 ming. All rights reserved. // import UIKit import SafariServices class FaceScoreViewController: BaseViewController { fileprivate lazy var faceVM = FaceViewModel() fileprivate lazy var collectionView : UICollectionView = {[weak self] in // 1.创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kNormalItemW, height: kPrettyItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin // layout.headerReferenceSize = CGSizeMake(kScreenW, kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: kItemMargin, left: kItemMargin, bottom: 0, right: kItemMargin) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self!.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.scrollsToTop = false collectionView.dataSource = self collectionView.delegate = self collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // 3.注册 collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - setUpUI extension FaceScoreViewController{ override func setUpMainView() { // 0.给ContentView进行赋值 contentView = collectionView view.addSubview(collectionView) super.setUpMainView() setUpRefresh() } } // MARK: - setUpUI extension FaceScoreViewController{ fileprivate func setUpRefresh() { // MARK: - 下拉 self.collectionView.header = MJRefreshGifHeader(refreshingBlock: { [weak self]() -> Void in self!.faceVM.offset = 0 self?.loadData() self!.collectionView.header.endRefreshing() self?.collectionView.footer.endRefreshing() }) // MARK: - 上拉 self.collectionView.footer = MJRefreshAutoGifFooter(refreshingBlock: {[weak self] () -> Void in self!.faceVM.offset += 20 self?.loadData() self!.collectionView.header.endRefreshing() self?.collectionView.footer.endRefreshing() }) self.collectionView.header.isAutoChangeAlpha = true self.collectionView.header.beginRefreshing() self.collectionView.footer.noticeNoMoreData() } // 加载数据 fileprivate func loadData() { faceVM.loadFaceData { (err) in if err == nil { self.collectionView.reloadData() }else { debugPrint(err) } self.loadDataFinished() } } } // MARK: - UICollectionViewDataSource extension FaceScoreViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return faceVM.faceModels.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.取出Cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell // 2.给cell设置数据 cell.anchor = faceVM.faceModels[(indexPath as NSIndexPath).item] return cell } } // MARK: - UICollectionViewDelegate extension FaceScoreViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let anchor = faceVM.faceModels[indexPath.item] anchor.isVertical == 0 ? pushNormalRoomVc(model: anchor) : presentShowRoomVc(model: anchor) } fileprivate func pushNormalRoomVc(model: AnchorModel) { let webViewVc = WKWebViewController(navigationTitle: model.room_name, urlStr: model.jumpUrl) show(webViewVc, sender: nil) } fileprivate func presentShowRoomVc(model: AnchorModel) { if #available(iOS 9, *) { if let url = URL(string: model.jumpUrl) { let webViewVc = SFSafariViewController(url: url, entersReaderIfAvailable: true) present(webViewVc, animated: true, completion: nil) } } else { let webViewVc = WKWebViewController(navigationTitle: model.room_name, urlStr: model.jumpUrl) present(webViewVc, animated: true, completion: nil) } } }
mit
cb0cb6bc614c4919133e7a62a62094ea
34.18705
130
0.656921
5.380638
false
false
false
false
ACChe/eidolon
Kiosk/App/CardHandler.swift
1
2869
import UIKit import ReactiveCocoa class CardHandler: NSObject, CFTReaderDelegate { let cardSwipedSignal = RACSubject() var card: CFTCard? let APIKey: String let APIToken: String var reader: CFTReader! lazy var sessionManager = CFTSessionManager.sharedInstance() init(apiKey: String, accountToken: String){ APIKey = apiKey APIToken = accountToken super.init() sessionManager.setApiToken(APIKey, accountToken: APIToken) } func startSearching() { sessionManager.setLogging(true) reader = CFTReader(andConnect: ()) reader.delegate = self; reader.swipeTimeoutDuration(0) cardSwipedSignal.sendNext("Started searching"); } func end() { reader.cancelSwipeWithMessage(nil) reader = nil } func readerCardResponse(card: CFTCard?, withError error: NSError?) { if let card = card { self.card = card; cardSwipedSignal.sendNext("Got Card") card.tokenizeCardWithSuccess({ [weak self] () -> Void in self?.cardSwipedSignal.sendCompleted() logger.log("Card was tokenized") }, failure: { [weak self] (error) -> Void in self?.cardSwipedSignal.sendNext("Card Flight Error: \(error)"); logger.log("Card was not tokenizable") }) } else if let error = error { self.cardSwipedSignal.sendNext("response Error \(error)"); logger.log("CardReader got a response it cannot handle") reader.beginSwipeWithMessage(nil); } } // handle other delegate call backs with the status messages func readerIsAttached() { cardSwipedSignal.sendNext("Reader is attatched"); } func readerIsConnecting() { cardSwipedSignal.sendNext("Reader is connecting"); } func readerIsDisconnected() { cardSwipedSignal.sendNext("Reader is disconnected"); logger.log("Card Reader Disconnected") } func readerSwipeDidCancel() { cardSwipedSignal.sendNext("Reader did cancel"); logger.log("Card Reader was Cancelled") } func readerGenericResponse(cardData: String!) { cardSwipedSignal.sendNext("Reader received non-card data: \(cardData) "); reader.beginSwipeWithMessage(nil); } func readerIsConnected(isConnected: Bool, withError error: NSError!) { if isConnected { cardSwipedSignal.sendNext("Reader is connected"); reader.beginSwipeWithMessage(nil); } else { if (error != nil) { cardSwipedSignal.sendNext("Reader is disconnected: \(error.localizedDescription)"); } else { cardSwipedSignal.sendNext("Reader is disconnected"); } } } }
mit
18ee38366634604dc2332094a2e520a8
27.979798
99
0.6145
4.854484
false
false
false
false