repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
squall09s/VegOresto
VegoResto/ColorExtension.swift
1
719
// // ColorExtension.swift // ManageColabApps // // Created by Laurent Nicolas on 21/10/2015. // Copyright © 2015 sopra. All rights reserved. // import UIKit extension UIColor { convenience init(hexString: String) { // Trim leading '#' if needed let cleanedHexString = hexString // String -> UInt32 var rgbValue: UInt32 = 0 Scanner(string: cleanedHexString).scanHexInt32(&rgbValue) // UInt32 -> R,G,B let red = CGFloat((rgbValue >> 16) & 0xff) / 255.0 let green = CGFloat((rgbValue >> 08) & 0xff) / 255.0 let blue = CGFloat((rgbValue >> 00) & 0xff) / 255.0 self.init(red: red, green: green, blue: blue, alpha: 1.0) } }
gpl-3.0
043fa6d7ecd5641d2ae53ee5401a33ff
23.758621
65
0.597493
3.64467
false
false
false
false
ktustanowski/DurationReporter
Playground.playground/Contents.swift
1
1979
//: Playground - noun: a place where people can play import Foundation import DurationReporter DurationReporter.begin(event: "Application Start", action: "Loading", payload: "🚀") sleep(1) DurationReporter.end(event: "Application Start", action: "Loading", payload: "💥") DurationReporter.begin(event: "Application Start", action: "Loading Home") sleep(2) DurationReporter.end(event: "Application Start", action: "Loading Home") DurationReporter.begin(event: "Application Start", action: "Preparing Home") usleep(200000) DurationReporter.end(event: "Application Start", action: "Preparing Home") DurationReporter.begin(event: "Problematic Code", action: "Executing 💥") /* no end event for Problematic Code on purpose */ // Print regular / default report print(":: Default report") print(DurationReporter.generateReport()) print("\n:: Custom report") // Print regular / default report DurationReporter.reportGenerator = { collectedData in var output = "" collectedData.forEach { eventName, reports in reports.enumerated().forEach { index, report in if let reportDuration = report.duration { output += "\(eventName) → \(index). \(report.title) \(reportDuration)s\n" } else { output += "\(eventName) → \(index). 🔴 \(report.title) - ?\n" } } } return output } print(DurationReporter.generateReport()) print(":: Report from raw collected data") // Print regular / default report let collectedData = DurationReporter.reportData() collectedData.forEach { eventName, reports in reports.enumerated().forEach { index, report in if let reportDuration = report.duration { print("\(eventName) → \(index). \(report.title) \(reportDuration)s \((report.beginPayload as? String) ?? "") \((report.endPayload as? String) ?? "")") } else { print("\(eventName) → \(index). 🔴 \(report.title) - ?\n") } } }
mit
2a83777102b44032dce3e9e3ace7d9e0
34.563636
162
0.665133
4.126582
false
false
false
false
zisko/swift
test/SILGen/nested_types_referencing_nested_functions.swift
1
1001
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s do { func foo() { bar(2) } func bar<T>(_: T) { foo() } class Foo { // CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_CACycfc : $@convention(method) (@owned Foo) -> @owned Foo { init() { foo() } // CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_C3zimyyF : $@convention(method) (@guaranteed Foo) -> () func zim() { foo() } // CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_C4zangyyxlF : $@convention(method) <T> (@in T, @guaranteed Foo) -> () func zang<T>(_ x: T) { bar(x) } // CHECK-LABEL: sil private @$S025nested_types_referencing_A10_functions3FooL_CfD : $@convention(method) (@owned Foo) -> () deinit { foo() } } let x = Foo() x.zim() x.zang(1) _ = Foo.zim _ = Foo.zang as (Foo) -> (Int) -> () _ = x.zim _ = x.zang as (Int) -> () }
apache-2.0
98af54618405d2edf573c6f659c1f701
29.333333
151
0.585415
3.01506
false
false
false
false
Pencroff/ai-hackathon-2017
IOS APP/Pods/Cloudinary/Cloudinary/Utils/CLDStringUtils.swift
1
3526
// // CLDStringUtils.swift // // Copyright (c) 2016 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 Foundation //internal extension Int { // func format(f: String) -> String { // return String(format: "%\(f)d", self) // } //} internal extension Double { func cldFormat(f: String) -> String { return String(format: "%\(f)f", self) } } internal extension Float { func cldFloatFormat() -> String { return cldFormat(f: ".1") } func cldFormat(f: String) -> String { return String(format: "%\(f)f", self) } } internal extension String { internal func cldSmartEncodeUrl() -> String? { let customAllowedSet = NSCharacterSet(charactersIn:"!*'\"();@&=+$,?%#[] ").inverted return addingPercentEncoding(withAllowedCharacters: customAllowedSet) } internal subscript (i: Int) -> Character { return self[startIndex.cldAdvance(i, for: self)] } subscript (r: CountableClosedRange<Int>) -> String { get { let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound) let endIndex = self.index(startIndex, offsetBy: r.upperBound - r.lowerBound) return self[startIndex...endIndex] } } internal func cldStringByAppendingPathComponent(str: String) -> String { return self + ("/\(str)") } internal func cldAsBool() -> Bool { if self == "true" { return true } if let intValue = Int(self) { return NSNumber(value: intValue).boolValue } return false } } internal extension String.Index{ // func successor(in string:String)->String.Index{ // return string.index(after: self) // } // // func predecessor(in string:String)->String.Index{ // return string.index(before: self) // } func cldAdvance(_ offset:Int, `for` string:String)->String.Index{ return string.index(self, offsetBy: offset) } } internal func cldParamValueAsString(value: Any) -> String? { if let valueStr = value as? String { if valueStr.isEmpty { return nil } return valueStr } else if let valueNum = value as? NSNumber { return String(describing: valueNum) } else { printLog(.error, text: "The parameter value must ba a String or a Number") return nil } }
mit
a4d46723dbc068b2c277b15be585933c
28.140496
92
0.639535
4.172781
false
false
false
false
skyfe79/SwiftImageProcessing
06_SplitRGBColorSpace_2.playground/Sources/ImageProcess.swift
1
5422
import Foundation public class ImageProcess { public static func grabR(_ image: RGBAImage) -> RGBAImage { var outImage = image outImage.process { (pixel) -> Pixel in var pixel = pixel pixel.R = pixel.R pixel.G = 0 pixel.B = 0 return pixel } return outImage } public static func grabG(_ image: RGBAImage) -> RGBAImage { var outImage = image outImage.process { (pixel) -> Pixel in var pixel = pixel pixel.R = 0 pixel.G = pixel.G pixel.B = 0 return pixel } return outImage } public static func grabB(_ image: RGBAImage) -> RGBAImage { var outImage = image outImage.process { (pixel) -> Pixel in var pixel = pixel pixel.R = 0 pixel.G = 0 pixel.B = pixel.B return pixel } return outImage } public static func composite(_ rgbaImageList: RGBAImage...) -> RGBAImage { let result : RGBAImage = RGBAImage(width:rgbaImageList[0].width, height: rgbaImageList[0].height) for y in 0..<result.height { for x in 0..<result.width { let index = y * result.width + x var pixel = result.pixels[index] for rgba in rgbaImageList { let rgbaPixel = rgba.pixels[index] pixel.R = min(pixel.R + rgbaPixel.R, 255) pixel.G = min(pixel.G + rgbaPixel.G, 255) pixel.B = min(pixel.B + rgbaPixel.B, 255) } result.pixels[index] = pixel } } return result } public static func composite(_ byteImageList: ByteImage...) -> RGBAImage { let result : RGBAImage = RGBAImage(width:byteImageList[0].width, height: byteImageList[0].height) for y in 0..<result.height { for x in 0..<result.width { let index = y * result.width + x var pixel = result.pixels[index] for (imageIndex, byte) in byteImageList.enumerated() { let bytePixel = byte.pixels[index] switch imageIndex % 3 { case 0: pixel.R = min(pixel.R + bytePixel.C, 255) case 1: pixel.G = min(pixel.G + bytePixel.C, 255) case 2: pixel.B = min(pixel.B + bytePixel.C, 255) default: break } } result.pixels[index] = pixel } } return result } public static func gray1(_ image: RGBAImage) -> RGBAImage { var outImage = image outImage.process { (pixel) -> Pixel in var pixel = pixel let result = pixel.Rf*0.2999 + pixel.Gf*0.587 + pixel.Bf*0.114 pixel.Rf = result pixel.Gf = result pixel.Bf = result return pixel } return outImage } public static func gray2(_ image: RGBAImage) -> RGBAImage { var outImage = image outImage.process { (pixel) -> Pixel in var pixel = pixel let result = (pixel.Rf + pixel.Gf + pixel.Bf) / 3.0 pixel.Rf = result pixel.Gf = result pixel.Bf = result return pixel } return outImage } public static func gray3(_ image: RGBAImage) -> RGBAImage { var outImage = image outImage.process { (pixel) -> Pixel in var pixel = pixel pixel.R = pixel.G pixel.G = pixel.G pixel.B = pixel.G return pixel } return outImage } public static func gray4(_ image: RGBAImage) -> RGBAImage { var outImage = image outImage.process { (pixel) -> Pixel in var pixel = pixel let result = pixel.Rf*0.212671 + pixel.Gf*0.715160 + pixel.Bf*0.071169 pixel.Rf = result pixel.Gf = result pixel.Bf = result return pixel } return outImage } public static func gray5(_ image: RGBAImage) -> RGBAImage { var outImage = image outImage.process { (pixel) -> Pixel in var pixel = pixel let result = sqrt(pow(pixel.Rf, 2) + pow(pixel.Rf, 2) + pow(pixel.Rf, 2))/sqrt(3.0) pixel.Rf = result pixel.Gf = result pixel.Bf = result return pixel } return outImage } public static func splitRGB(_ rgba: RGBAImage) -> (ByteImage, ByteImage, ByteImage) { let R = ByteImage(width: rgba.width, height: rgba.height) let G = ByteImage(width: rgba.width, height: rgba.height) let B = ByteImage(width: rgba.width, height: rgba.height) rgba.enumerate { (index, pixel) -> Void in R.pixels[index] = pixel.R.toBytePixel() G.pixels[index] = pixel.G.toBytePixel() B.pixels[index] = pixel.B.toBytePixel() } return (R, G, B) } }
mit
5554cb1a4d4aa086664fcdebce81c164
30.707602
105
0.485983
4.390283
false
false
false
false
krzysztofzablocki/Sourcery
Sourcery/Utils/DryOutputModels.swift
1
1303
import Foundation struct DryOutputType: Codable { enum SubType: String, Codable { case allTemplates case template case path case range } let id: String? let subType: SubType static var allTemplates: DryOutputType { .init(id: nil, subType: .allTemplates) } static func template(_ path: String) -> DryOutputType { .init(id: path, subType: .template) } static func path(_ path: String) -> DryOutputType { .init(id: path, subType: .path) } static func range(_ range: NSRange, in file: String) -> DryOutputType { let startIndex = range.location let endIndex = range.location + range.length if startIndex == endIndex { return .init(id: "\(file):\(startIndex)", subType: .range) } return .init(id: "\(file):\(startIndex)-\(endIndex)", subType: .range) } } struct DryOutputValue: Codable { let type: DryOutputType let outputPath: String let value: String } struct DryOutputSuccess: Codable { let outputs: [DryOutputValue] } public struct DryOutputFailure: Codable { public let error: String public let log: [String] public init(error: String, log: [String]) { self.error = error self.log = log } }
mit
63c693cb8842c35cea344f14619b1bab
23.584906
78
0.615503
4.162939
false
false
false
false
atljeremy/JFCardSelectionViewController
JFCardSelectionViewController/JFCardSelectionViewController+CollectionView.swift
1
3040
/* * JFCardSelectionViewController * * Created by Jeremy Fox on 3/1/16. * Copyright (c) 2016 Jeremy Fox. 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 extension JFCardSelectionViewController: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard indexPath != previouslySelectedIndexPath else { shake() return } guard let card = dataSource?.cardSelectionViewController(self, cardForItemAtIndexPath: indexPath) else { return } updateUIForCard(card, atIndexPath: indexPath) previouslySelectedIndexPath = indexPath } } extension JFCardSelectionViewController: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let _dataSource = dataSource else { return 0 } return _dataSource.numberOfCardsForCardSelectionViewController(self) } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: JFCardSelectionCell.reuseIdentifier, for: indexPath) as? JFCardSelectionCell else { fatalError("Expected to display a `JFCardSelectionCell`.") } guard let _dataSource = dataSource else { return cell } let card = _dataSource.cardSelectionViewController(self, cardForItemAtIndexPath: indexPath) cell.configureForCard(card, inScrollView: collectionView) if (collectionView.indexPathsForSelectedItems?.count ?? 0) == 0 && indexPath.section == 0 && indexPath.row == 0 && focusedView.card == nil && previouslySelectedIndexPath == nil { focusedView.configureForCard(card) previouslySelectedIndexPath = indexPath } return cell } }
mit
866f852f8afde711127cfc64c1d13ca1
45.060606
186
0.730592
5.333333
false
false
false
false
CoderJChen/SWWB
CJWB/CJWB/Classes/Compose/CJComposeTitleView.swift
1
1357
// // CJComposeTitleView.swift // CJWB // // Created by 星驿ios on 2017/9/11. // Copyright © 2017年 CJ. All rights reserved. // import UIKit import SnapKit class CJComposeTitleView: UIView { // MARK:- 懒加载属性 fileprivate lazy var titleLabel : UILabel = UILabel() fileprivate lazy var screenNameLabel : UILabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension CJComposeTitleView{ fileprivate func setUpUI(){ addSubview(titleLabel) addSubview(screenNameLabel) titleLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(self) } screenNameLabel.snp.makeConstraints { (make) in make.centerX.equalTo(titleLabel.snp.centerX) make.top.equalTo(titleLabel.snp.bottom).offset(3) } titleLabel.font = UIFont.systemFont(ofSize: 16) screenNameLabel.font = UIFont.systemFont(ofSize: 14) screenNameLabel.textColor = UIColor.lightGray titleLabel.text = "发微博" screenNameLabel.text = CJUserAccountViewModel.shareInstance.account?.screen_name } }
apache-2.0
15d73752c2a4b1f5587bcb4c1ce44974
25.68
88
0.636432
4.522034
false
false
false
false
nathawes/swift
test/Incremental/PrivateDependencies/private-subscript-fine.swift
15
1127
// REQUIRES: shell // Also uses awk: // XFAIL OS=windows // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD // RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW // RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps struct Wrapper { fileprivate subscript() -> InterestingType { fatalError() } } // CHECK-OLD: sil_global @$s4main1x{{[^ ]+}} : $Int // CHECK-NEW: sil_global @$s4main1x{{[^ ]+}} : $Double public var x = Wrapper()[] + 0 // CHECK-DEPS: topLevel interface '' InterestingType false
apache-2.0
696da728f5deb8cee4596fb78fbff570
52.666667
203
0.71961
3.314706
false
false
false
false
payjp/payjp-ios
Sources/Log.swift
1
640
// // Log.swift // PAYJP // // Created by Tadashi Wakayanagi on 2019/11/26. // Copyright © 2019 PAY, Inc. All rights reserved. // import Foundation /// Debugビルド時のみログ出力する /// - Parameters: /// - debug: debug message /// - function: function name /// - file: file name /// - line: line number func print(debug: Any = "", function: String = #function, file: String = #file, line: Int = #line) { #if DEBUG var filename: NSString = file as NSString filename = filename.lastPathComponent as NSString Swift.print("File: \(filename), Line: \(line), Func: \(function) \n\(debug)") #endif }
mit
5dd52021bbd7772591dea8910d9ab5b8
25.73913
100
0.635772
3.324324
false
false
false
false
Barry-Wang/iOS-Animation-Guide-Swift
AnimationGuide1-circle/AnimationGuide/YMCircleLayer.swift
1
4854
// // YMCircleLayer.swift // AnimationGuide // // Created by barryclass on 15/11/13. // Copyright © 2015年 barry. All rights reserved. // import UIKit enum MovePoint { // 连接点 A B C D 生成一个圆, Move_B 表示向左移动,移动B点 case Move_B, Move_D } let OutSideRectSize:CGFloat = 120 class YMCircleLayer: CALayer { var outSideRect = CGRectZero var movePoint:MovePoint = MovePoint.Move_B var progress:Float = 0.5{ didSet { let paddingWidth:CGFloat = (self.bounds.size.width - OutSideRectSize) / 2 self.outSideRect = CGRectMake( (self.position.x - OutSideRectSize / 2) + CGFloat(progress - 0.5) * paddingWidth, self.position.y - OutSideRectSize / 2, OutSideRectSize, OutSideRectSize) if progress > 0.5 { self.movePoint = MovePoint.Move_B } else { self.movePoint = MovePoint.Move_D } // CALayer在第一次出现的时候不会主动调用 drawInContext self.setNeedsDisplay() } } override func drawInContext(ctx: CGContext) { //画最外面的正方形,在这个正方形里面画圆 CGContextSetLineWidth(ctx, 5) CGContextSetStrokeColorWithColor(ctx, UIColor.greenColor().CGColor) // 设置为虚线模式 CGContextSetLineDash(ctx, 0, [3,3], 2) CGContextStrokeRect(ctx, self.outSideRect) CGContextStrokePath(ctx) CGContextSetStrokeColorWithColor(ctx, UIColor.yellowColor().CGColor) // offset, moveDistance 都是些经验值 let offset = OutSideRectSize / 3.6 let moveDistance = (self.outSideRect.width * 1 / 6) * CGFloat(fabs(self.progress - 0.5) * 2) let rectCenter = CGPointMake(self.outSideRect.origin.x + OutSideRectSize / 2, self.outSideRect.origin.y + OutSideRectSize / 2) let point_A = CGPointMake(rectCenter.x, self.outSideRect.origin.y + moveDistance) // 当向左移动时,使B的x坐标增加,使其成近似椭圆状 let point_B = CGPointMake(self.movePoint == MovePoint.Move_B ? rectCenter.x + OutSideRectSize / 2 + moveDistance * 2 : rectCenter.x + OutSideRectSize / 2, rectCenter.y) let point_C = CGPointMake(rectCenter.x, rectCenter.y + OutSideRectSize / 2 - moveDistance) let point_D = CGPointMake(self.movePoint == MovePoint.Move_D ? self.outSideRect.origin.x - moveDistance * 2 : self.outSideRect.origin.x, rectCenter.y) // let rectBizerpath = UIBezierPath() // rectBizerpath.moveToPoint(point_A) // rectBizerpath.addLineToPoint(point_B) // rectBizerpath.addLineToPoint(point_C) // rectBizerpath.addLineToPoint(point_D) // rectBizerpath.closePath() // CGContextAddPath(ctx, rectBizerpath.CGPath) // CGContextStrokePath(ctx) // 合成贝塞尔曲线所需要的控制点 let point_AB1 = CGPointMake(point_A.x + offset, point_A.y) //判断控制点的位置使其形状变化更加真实 let point_AB2 = CGPointMake(point_B.x, self.movePoint == MovePoint.Move_B ? point_B.y - offset + moveDistance : point_B.y - offset) let point_BC1 = CGPointMake(point_B.x, self.movePoint == MovePoint.Move_B ? point_B.y + offset - moveDistance : point_B.y + offset) let point_BC2 = CGPointMake(point_C.x + offset, point_C.y) let point_CD1 = CGPointMake(point_C.x - offset, point_C.y) let point_CD2 = CGPointMake(point_D.x, self.movePoint == MovePoint.Move_D ? point_D.y + offset - moveDistance : point_D.y + offset) let point_DA1 = CGPointMake(point_D.x, self.movePoint == MovePoint.Move_D ? point_D.y - offset + moveDistance : point_D.y - offset ) let point_DA2 = CGPointMake(point_A.x - offset, point_A.y) let circlePath = UIBezierPath() CGContextSetLineDash(ctx, 0, nil, 0) CGContextSetStrokeColorWithColor(ctx, UIColor.purpleColor().CGColor) circlePath.moveToPoint(point_A) circlePath.addCurveToPoint(point_B, controlPoint1: point_AB1, controlPoint2: point_AB2) circlePath.addCurveToPoint(point_C, controlPoint1: point_BC1, controlPoint2: point_BC2) circlePath.addCurveToPoint(point_D, controlPoint1: point_CD1, controlPoint2: point_CD2) circlePath.addCurveToPoint(point_A, controlPoint1: point_DA1, controlPoint2: point_DA2) CGContextSetStrokeColorWithColor(ctx, UIColor.whiteColor().CGColor) CGContextSetFillColorWithColor(ctx, UIColor.orangeColor().CGColor) CGContextAddPath(ctx, circlePath.CGPath) CGContextDrawPath(ctx, CGPathDrawingMode.EOFillStroke) } }
apache-2.0
239ab211a71f246f27e0f91a56970d4f
40.558559
197
0.643616
3.726171
false
false
false
false
ProsoftEngineering/TimeMachineRemoteStatus
TimeMachineRemoteStatus/Backups.swift
1
5084
// Copyright © 2016-2017, Prosoft Engineering, Inc. (A.K.A "Prosoft") // 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 Prosoft 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 PROSOFT ENGINEERING, INC. 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 Foundation class Backup: NSObject { let volumeName: String let date: Date init(volumeName aVolumeName: String, date aDate: Date) { self.volumeName = aVolumeName self.date = aDate } } class BackupHost: NSObject { var backups: [Backup] = [] var error: String = "" } class BackupsManager: NSObject { var hosts: [String] = [] let regex: NSRegularExpression let cal: NSCalendar override init() { do { // /Volumes/Drive/Backups.backupdb/hostname/2016-11-15-164402 regex = try NSRegularExpression(pattern: "^/Volumes/(.*?)/.*/(\\d{4,4})-(\\d{2,2})-(\\d{2,2})-(\\d{2,2})(\\d{2,2})(\\d{2,2})", options: []) } catch let error as NSError { print("FATAL: Invalid regex: \(error.localizedDescription)") exit(-1) } guard let cal = NSCalendar(calendarIdentifier: .gregorian) else { print("FATAL: Got nil calendar") exit(-1) } self.cal = cal } typealias UpdateHandler = (_ backups: [String: BackupHost]) -> (Void) func update(handler: @escaping UpdateHandler) -> Void { let hostsCopy = hosts DispatchQueue.global().async { var backups = [String: BackupHost]() let backupsQueue = DispatchQueue(label: "com.prosofteng.timemachineremotestatus.backups.update.group") let group = DispatchGroup() for host in hostsCopy { DispatchQueue.global().async(group: group, execute: { let backupHost = self.processHost(host) backupsQueue.sync { backups[host] = backupHost } }) } group.wait() DispatchQueue.main.async { handler(backups) } } } private func processHost(_ host: String) -> BackupHost { let backupHost = BackupHost() let result = Process.run(launchPath: "/usr/bin/ssh", args: [host, "tmutil", "listbackups"]) if result.status != 0 { backupHost.error = result.error return backupHost } for line in result.output.components(separatedBy: "\n") { if line.isEmpty { continue } let txt = line as NSString let results = self.regex.matches(in: line, options: [], range: NSMakeRange(0, txt.length)) for result in results { if result.numberOfRanges == 8 { let volumeName = txt.substring(with: result.rangeAt(1)) var comps = DateComponents() comps.year = Int(txt.substring(with: result.rangeAt(2)))! comps.month = Int(txt.substring(with: result.rangeAt(3)))! comps.day = Int(txt.substring(with: result.rangeAt(4)))! comps.hour = Int(txt.substring(with: result.rangeAt(5)))! comps.minute = Int(txt.substring(with: result.rangeAt(6)))! comps.second = Int(txt.substring(with: result.rangeAt(7)))! let date = self.cal.date(from: comps) backupHost.backups.append(Backup(volumeName: volumeName, date: date!)) } else { print("Unknown line: \(line)") } } } return backupHost } }
bsd-3-clause
a323312ac452ecdebf3042aeff3b4d52
40.663934
151
0.599449
4.506206
false
false
false
false
OrdnanceSurvey/OS-Maps-API
Sample Code/OS API Response -Swift/OSAPIResponse/Fetch.Parsable+Parsing.swift
1
2077
// // Fetch.Parsable+Parsing.swift // OSAPIResponse // // Created by Dave Hardiman on 15/03/2016. // Copyright © 2016 Ordnance Survey. All rights reserved. // import Fetch import OSJSON extension Fetch.Parsable where Self: OSAPIResponse.Parsable { public static func parse(fromData data: NSData?, withStatus status: Int) -> Result<Self> { guard let data = data else { return .Failure(ResponseError.NoDataReceived) } guard let json = JSON(data: data) else { return .Failure(ResponseError.FailedToParseJSON) } switch status { case 200: return parseExpectedResponse(json) case 400: return .Failure(ResponseError.BadRequest(messageFromErrorBody(json))) case 401: return .Failure(ResponseError.Unauthorised(messageFromErrorBody(json))) case 404: return .Failure(ResponseError.NotFound(messageFromErrorBody(json))) case 405: return .Failure(ResponseError.MethodNotAllowed(messageFromErrorBody(json))) case 406: return .Failure(ResponseError.NotAcceptable(messageFromErrorBody(json))) case 500: return .Failure(ResponseError.ServerError(messageFromErrorBody(json))) default: return .Failure(ResponseError.UnknownError) } } private static func parseExpectedResponse(json: JSON) -> Result<Self> { guard let response = Self.create(json) else { return .Failure(ResponseError.FailedToDeserialiseJSON) } return .Success(response) } } private func messageFromErrorBody(json: JSON) -> String { if let error = json.jsonForKey("error"), message = error.stringValueForKey("message") { return message } if let fault = json.jsonForKey("fault"), message = fault.stringValueForKey("faultstring") { return message } if let errorResponse = json.jsonForKey("ErrorResponse") { return messageFromErrorBody(errorResponse) } return "" }
apache-2.0
6b7ee0d60e7c247196cb27c0a052db67
33.032787
94
0.649807
4.644295
false
false
false
false
GenericDataSource/GenericDataSource
Sources/UIKitExtensions.swift
1
1330
// // UIKitExtensions.swift // GenericDataSource // // Created by Mohamed Afifi on 9/16/15. // Copyright © 2016 mohamede1945. All rights reserved. // import UIKit extension UITableView.ScrollPosition { init(scrollPosition: UICollectionView.ScrollPosition) { if scrollPosition.contains(.top) { self = .top } else if scrollPosition.contains(.bottom) { self = .bottom } else if scrollPosition.contains(.centeredVertically) { self = .middle } else { self = .none } } } extension UITableView { /** Use this method to set up a table view with a data source. - parameter dataSource: The data source to set for the table view. */ open func ds_useDataSource(_ dataSource: AbstractDataSource) { self.dataSource = dataSource self.delegate = dataSource dataSource.ds_reusableViewDelegate = self } } extension UICollectionView { /** Use this method to set up a collection view with a data source. - parameter dataSource: The data source to set for the table view. */ open func ds_useDataSource(_ dataSource: AbstractDataSource) { self.dataSource = dataSource self.delegate = dataSource dataSource.ds_reusableViewDelegate = self } }
mit
3acb849c9caa64369e82f0d1a5c39fac
25.058824
71
0.644093
4.712766
false
false
false
false
russbishop/swift
stdlib/public/core/Reverse.swift
1
12927
//===--- Reverse.swift - Sequence and collection reversal -----------------===// // // 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 // //===----------------------------------------------------------------------===// extension MutableCollection where Self : BidirectionalCollection { /// Reverses the elements of the collection in place. /// /// var characters: [Character] = ["C", "a", "f", "é"] /// characters.reverse() /// print(cafe.characters) /// // Prints "["é", "f", "a", "C"] /// /// - Complexity: O(*n*), where *n* is the number of elements in the /// collection. public mutating func reverse() { if isEmpty { return } var f = startIndex var l = index(before: endIndex) while f < l { swap(&self[f], &self[l]) formIndex(after: &f) formIndex(before: &l) } } } // FIXME(ABI)(compiler limitation): we should have just one type, // `ReversedCollection`, that has conditional conformances to // `RandomAccessCollection`, and possibly `MutableCollection` and // `RangeReplaceableCollection`. // FIXME: swift-3-indexing-model - should gyb ReversedXxx & ReversedRandomAccessXxx /// An index that traverses the same positions as an underlying index, /// with inverted traversal direction. public struct ReversedIndex<Base : Collection> : Comparable { public init(_ base: Base.Index) { self.base = base } /// The position corresponding to `self` in the underlying collection. public let base: Base.Index } public func == <Base : Collection>( lhs: ReversedIndex<Base>, rhs: ReversedIndex<Base> ) -> Bool { return lhs.base == rhs.base } public func < <Base : Collection>( lhs: ReversedIndex<Base>, rhs: ReversedIndex<Base> ) -> Bool { // Note ReversedIndex has inverted logic compared to base Base.Index return lhs.base > rhs.base } /// A Collection that presents the elements of its `Base` collection /// in reverse order. /// /// - Note: This type is the result of `x.reversed()` where `x` is a /// collection having bidirectional indices. /// /// The `reversed()` method is always lazy when applied to a collection /// with bidirectional indices, but does not implicitly confer /// laziness on algorithms applied to its result. In other words, for /// ordinary collections `c` having bidirectional indices: /// /// * `c.reversed()` does not create new storage /// * `c.reversed().map(f)` maps eagerly and returns a new array /// * `c.lazy.reversed().map(f)` maps lazily and returns a `LazyMapCollection` /// /// - See also: `ReversedRandomAccessCollection` public struct ReversedCollection< Base : BidirectionalCollection > : BidirectionalCollection { /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) internal init(_base: Base) { self._base = _base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReversedIndex<Base> public typealias IndexDistance = Base.IndexDistance /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. public typealias Iterator = IndexingIterator<ReversedCollection> public var startIndex: Index { return ReversedIndex(_base.endIndex) } public var endIndex: Index { return ReversedIndex(_base.startIndex) } public func index(after i: Index) -> Index { return ReversedIndex(_base.index(before: i.base)) } public func index(before i: Index) -> Index { return ReversedIndex(_base.index(after: i.base)) } public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. return ReversedIndex(_base.index(i.base, offsetBy: -n)) } public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { ReversedIndex($0) } } public func distance(from start: Index, to end: Index) -> IndexDistance { return _base.distance(from: end.base, to: start.base) } public typealias _Element = Base.Iterator.Element public subscript(position: Index) -> Base.Iterator.Element { return _base[_base.index(before: position.base)] } public subscript(bounds: Range<Index>) -> BidirectionalSlice<ReversedCollection> { return BidirectionalSlice(base: self, bounds: bounds) } public let _base: Base } /// An index that traverses the same positions as an underlying index, /// with inverted traversal direction. public struct ReversedRandomAccessIndex< Base : RandomAccessCollection > : Comparable { public init(_ base: Base.Index) { self.base = base } /// The position corresponding to `self` in the underlying collection. public let base: Base.Index } public func == <Base : Collection>( lhs: ReversedRandomAccessIndex<Base>, rhs: ReversedRandomAccessIndex<Base> ) -> Bool { return lhs.base == rhs.base } public func < <Base : Collection>( lhs: ReversedRandomAccessIndex<Base>, rhs: ReversedRandomAccessIndex<Base> ) -> Bool { // Note ReversedRandomAccessIndex has inverted logic compared to base Base.Index return lhs.base > rhs.base } /// A Collection that presents the elements of its `Base` collection /// in reverse order. /// /// - Note: This type is the result of `x.reversed()` where `x` is a /// collection having random access indices. /// - See also: `ReversedCollection` public struct ReversedRandomAccessCollection< Base : RandomAccessCollection > : RandomAccessCollection { // FIXME: swift-3-indexing-model: tests for ReverseRandomAccessIndex and // ReverseRandomAccessCollection. /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) internal init(_base: Base) { self._base = _base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReversedRandomAccessIndex<Base> public typealias IndexDistance = Base.IndexDistance /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. public typealias Iterator = IndexingIterator< ReversedRandomAccessCollection > public var startIndex: Index { return ReversedRandomAccessIndex(_base.endIndex) } public var endIndex: Index { return ReversedRandomAccessIndex(_base.startIndex) } public func index(after i: Index) -> Index { return ReversedRandomAccessIndex(_base.index(before: i.base)) } public func index(before i: Index) -> Index { return ReversedRandomAccessIndex(_base.index(after: i.base)) } public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. // FIXME: swift-3-indexing-model: tests. return ReversedRandomAccessIndex(_base.index(i.base, offsetBy: -n)) } public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. // FIXME: swift-3-indexing-model: tests. return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { Index($0) } } public func distance(from start: Index, to end: Index) -> IndexDistance { // FIXME: swift-3-indexing-model: tests. return _base.distance(from: end.base, to: start.base) } public typealias _Element = Base.Iterator.Element // FIXME(compiler limitation): this typealias should be inferred. public subscript(position: Index) -> Base.Iterator.Element { return _base[_base.index(before: position.base)] } // FIXME: swift-3-indexing-model: the rest of methods. public let _base: Base } extension BidirectionalCollection { /// Returns a view presenting the elements of the collection in reverse /// order. /// /// You can reverse a collection without allocating new space for its /// elements by calling this `reversed()` method. A `ReverseCollection` /// instance wraps an underlying collection and provides access to its /// elements in reverse order. This example prints the characters of a /// string in reverse order: /// /// let word = "Backwards" /// for char in word.characters.reversed() { /// print(char, terminator="") /// } /// // Prints "sdrawkcaB" /// /// If you need a reversed collection of the same type, you may be able to /// use the collection's sequence-based or collection-based initializer. For /// example, to get the reversed version of a string, reverse its /// characters and initialize a new `String` instance from the result. /// /// let reversedWord = String(word.characters.reversed()) /// print(reversedWord) /// // Prints "sdrawkcaB" /// /// - Complexity: O(1) public func reversed() -> ReversedCollection<Self> { return ReversedCollection(_base: self) } } extension RandomAccessCollection { /// Returns a view presenting the elements of the collection in reverse /// order. /// /// You can reverse a collection without allocating new space for its /// elements by calling this `reversed()` method. A /// `ReverseRandomAccessCollection` instance wraps an underlying collection /// and provides access to its elements in reverse order. This example /// prints the elements of an array in reverse order: /// /// let numbers = [3, 5, 7] /// for number in numbers.reversed() { /// print(number) /// } /// // Prints "7" /// // Prints "5" /// // Prints "3" /// /// If you need a reversed collection of the same type, you may be able to /// use the collection's sequence-based or collection-based initializer. For /// example, to get the reversed version of an array, initialize a new /// `Array` instance from the result of this `reversed()` method. /// /// let reversedNumbers = Array(numbers.reversed()) /// print(reversedNumbers) /// // Prints "[7, 5, 3]" /// /// - Complexity: O(1) public func reversed() -> ReversedRandomAccessCollection<Self> { return ReversedRandomAccessCollection(_base: self) } } extension LazyCollectionProtocol where Self : BidirectionalCollection, Elements : BidirectionalCollection { /// Returns the elements of `self` in reverse order. /// /// - Complexity: O(1) public func reversed() -> LazyBidirectionalCollection< ReversedCollection<Elements> > { return ReversedCollection(_base: elements).lazy } } extension LazyCollectionProtocol where Self : RandomAccessCollection, Elements : RandomAccessCollection { /// Returns the elements of `self` in reverse order. /// /// - Complexity: O(1) public func reversed() -> LazyRandomAccessCollection< ReversedRandomAccessCollection<Elements> > { return ReversedRandomAccessCollection(_base: elements).lazy } } extension ReversedCollection { @available(*, unavailable, message: "use the 'reversed()' method on the collection") public init(_ base: Base) { Builtin.unreachable() } } extension ReversedRandomAccessCollection { @available(*, unavailable, message: "use the 'reversed()' method on the collection") public init(_ base: Base) { Builtin.unreachable() } } extension BidirectionalCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> ReversedCollection<Self> { Builtin.unreachable() } } extension RandomAccessCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> ReversedRandomAccessCollection<Self> { Builtin.unreachable() } } extension LazyCollectionProtocol where Self : BidirectionalCollection, Elements : BidirectionalCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> LazyCollection< ReversedCollection<Elements> > { Builtin.unreachable() } } extension LazyCollectionProtocol where Self : RandomAccessCollection, Elements : RandomAccessCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> LazyCollection< ReversedRandomAccessCollection<Elements> > { Builtin.unreachable() } } // ${'Local Variables'}: // eval: (read-only-mode 1) // End:
apache-2.0
3e6875ee3bfa12d95dcbd92032be4a3e
30.447689
93
0.686112
4.341619
false
false
false
false
shahen94/react-native-video-processing
ios/GPUImage/examples/Mac/FilterShowcaseSwift/FilterShowcaseSwift/FilterShowcaseWindowController.swift
129
3832
import Cocoa import GPUImage class FilterShowcaseWindowController: NSWindowController { @IBOutlet var filterView: GPUImageView! @IBOutlet weak var filterSlider: NSSlider! var enableSlider:Bool = false var minimumSliderValue:CGFloat = 0.0, maximumSliderValue:CGFloat = 1.0 var currentSliderValue:CGFloat = 0.5 { willSet(newSliderValue) { switch (currentFilterOperation!.sliderConfiguration) { case let .Enabled(_, _, _): currentFilterOperation!.updateBasedOnSliderValue(newSliderValue) case .Disabled: break } } } var currentFilterOperation: FilterOperationInterface? var videoCamera: GPUImageAVCamera? lazy var blendImage: GPUImagePicture = { let inputImage = NSImage(named:"Lambeau.jpg") return GPUImagePicture(image: inputImage) }() var currentlySelectedRow = 1 override func windowDidLoad() { super.windowDidLoad() videoCamera = GPUImageAVCamera(sessionPreset: AVCaptureSessionPreset640x480, cameraDevice:nil) self.changeSelectedRow(0) } func changeSelectedRow(row:Int) { if (currentlySelectedRow == row) { return } // Clean up everything from the previous filter selection first videoCamera!.stopCameraCapture() videoCamera!.removeAllTargets() // blendImage?.removeAllTargets() currentFilterOperation?.filter.removeAllTargets() currentFilterOperation = filterOperations[row] switch currentFilterOperation!.filterOperationType { case .SingleInput: videoCamera!.addTarget((currentFilterOperation!.filter as! GPUImageInput)) currentFilterOperation!.filter.addTarget(filterView!) case .Blend: videoCamera!.addTarget((currentFilterOperation!.filter as! GPUImageInput)) self.blendImage.addTarget((currentFilterOperation!.filter as! GPUImageInput)) currentFilterOperation!.filter.addTarget(filterView!) self.blendImage.processImage() case let .Custom(filterSetupFunction:setupFunction): let inputToFunction:(GPUImageOutput, GPUImageOutput?) = setupFunction(camera:videoCamera!, outputView:filterView!) // Type inference falls down, for now needs this hard cast currentFilterOperation!.configureCustomFilter(inputToFunction) } switch currentFilterOperation!.sliderConfiguration { case .Disabled: filterSlider.enabled = false // case let .Enabled(minimumValue, initialValue, maximumValue, filterSliderCallback): case let .Enabled(minimumValue, maximumValue, initialValue): filterSlider.minValue = Double(minimumValue) filterSlider.maxValue = Double(maximumValue) filterSlider.enabled = true currentSliderValue = CGFloat(initialValue) } videoCamera!.startCameraCapture() } // MARK: - // MARK: Table view delegate and datasource methods func numberOfRowsInTableView(aTableView:NSTableView!) -> Int { return filterOperations.count } func tableView(aTableView:NSTableView!, objectValueForTableColumn aTableColumn:NSTableColumn!, row rowIndex:Int) -> AnyObject! { let filterInList:FilterOperationInterface = filterOperations[rowIndex] return filterInList.listName } func tableViewSelectionDidChange(aNotification: NSNotification!) { if let currentTableView = aNotification.object as? NSTableView { let rowIndex = currentTableView.selectedRow self.changeSelectedRow(rowIndex) } } }
mit
aec22dad6ba65b0f336bfbda7f6ccf41
38.515464
189
0.662578
5.841463
false
false
false
false
sarvex/SwiftRecepies
Basics/Picking Values with the UIPickerView/Picking Values with the UIPickerView/ViewController.swift
1
3778
// // ViewController.swift // Picking Values with the UIPickerView // // Created by Vandad Nahavandipoor on 6/27/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 /* 1 */ //import UIKit // //class ViewController: UIViewController { // // var picker: UIPickerView! // //} /* 2 */ //import UIKit // //class ViewController: UIViewController { // // var picker: UIPickerView! // // override func viewDidLoad() { // super.viewDidLoad() // // picker = UIPickerView() // picker.center = view.center // view.addSubview(picker) // } // //} /* 3 */ //import UIKit // //class ViewController: UIViewController, UIPickerViewDataSource { // // var picker: UIPickerView! // // func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { // if pickerView == picker{ // return 1 // } // return 0 // } // // func pickerView(pickerView: UIPickerView, // numberOfRowsInComponent component: Int) -> Int { // if pickerView == picker{ // return 10 // } // return 0 // } // // override func viewDidLoad() { // super.viewDidLoad() // // picker = UIPickerView() // picker.dataSource = self // picker.center = view.center // view.addSubview(picker) // } // //} /* 4 */ //import UIKit // //class ViewController: UIViewController, //UIPickerViewDataSource, UIPickerViewDelegate { // // var picker: UIPickerView! // // func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { // if pickerView == picker{ // return 1 // } // return 0 // } // // func pickerView(pickerView: UIPickerView, // numberOfRowsInComponent component: Int) -> Int { // if pickerView == picker{ // return 10 // } // return 0 // } // // func pickerView(pickerView: UIPickerView, // titleForRow row: Int, // forComponent component: Int) -> String!{ // return "\(row + 1)" // } // // override func viewDidLoad() { // super.viewDidLoad() // // picker = UIPickerView() // picker.dataSource = self // picker.delegate = self // picker.center = view.center // view.addSubview(picker) // } // //} /* 5 */ import UIKit class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate { var picker: UIPickerView! func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { if pickerView == picker{ return 1 } return 0 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView == picker{ return 10 } return 0 } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!{ return "\(row + 1)" } override func viewDidLoad() { super.viewDidLoad() picker = UIPickerView() picker.dataSource = self picker.delegate = self picker.center = view.center view.addSubview(picker) } }
isc
ec82ae57d0ab3a50faeda3678d07c73e
22.184049
83
0.639756
3.927235
false
false
false
false
jigneshsheth/Datastructures
DataStructure/DataStructureTests/ArrayOperations/SortingAlgorithmsTest.swift
1
5749
// // SortingAlogrithmsTest.swift // DataStructure // // Created by Jigs Sheth on 4/11/16. // Copyright © 2016 jigneshsheth.com. All rights reserved. // import XCTest @testable import DataStructure class SortingAlgorithmsTest: XCTestCase { var operations:SortingAlgorithms? override func setUp() { super.setUp() operations = SortingAlgorithms() } override func tearDown() { super.tearDown() operations = nil } func testInsert() { operations?.insert(position:0, num: 10) operations?.insert(position:1, num: 11) operations?.insert(position:2, num: 12) operations?.insert(position:3, num: 13) operations?.insert(position:4, num: 14) operations?.insert(position:5, num: 15) operations?.insert(position:6, num: 16) operations?.display() XCTAssertEqual([10, 11, 12, 13, 14, 15, 16], (operations?.arrayOutput)!, "Insertion failed into an Array operation") } func testDelete() { operations?.insert(position:0, num: 10) operations?.insert(position:1, num: 11) operations?.insert(position:2, num: 12) operations?.insert(position:3, num: 13) operations?.insert(position:4, num: 14) operations?.insert(position:5, num: 15) operations?.insert(position:6, num: 16) operations?.display() operations?.delete(position:1) XCTAssertEqual([10, 12, 13, 14, 15, 16], (operations?.arrayOutput)!, "Deletion failed into an Array operation") operations?.display() operations?.delete(position:0) XCTAssertEqual([12, 13, 14, 15, 16], (operations?.arrayOutput)!, "Deletion failed into an Array operation") operations?.display() operations?.delete(position:4) XCTAssertEqual([12, 13, 14, 15], (operations?.arrayOutput)!, "Deletion failed into an Array operation") operations?.display() operations?.delete(position:2) XCTAssertEqual([12, 13,15], (operations?.arrayOutput)!, "Deletion failed into an Array operation") operations?.display() operations?.delete(position:2) XCTAssertEqual([12, 13], (operations?.arrayOutput)!, "Deletion failed into an Array operation") operations?.display() operations?.delete(position: 0) XCTAssertEqual([13], (operations?.arrayOutput)!, "Deletion failed into an Array operation") } func testReverse() { operations?.insert(position:0, num: 10) operations?.insert(position:1, num: 11) operations?.insert(position:2, num: 12) operations?.insert(position:3, num: 13) operations?.insert(position:4, num: 14) operations?.insert(position:5, num: 15) operations?.insert(position:6, num: 16) operations?.display() operations?.delete(position: 1) operations?.reverse() XCTAssertEqual([10,12, 13, 14, 15, 16].reversed(), (operations?.arrayOutput)!, "Reverse failed into an Array operation") operations?.display() operations?.delete(position: 0) operations?.reverse() XCTAssertEqual([10, 12, 13, 14, 15], (operations?.arrayOutput)!, "Reverse failed into an Array operation") operations?.display() operations?.delete(position: 4) operations?.reverse() XCTAssertEqual([14, 13, 12, 10], (operations?.arrayOutput)!, "Reverse failed into an Array operation") operations?.display() } func testSelectionSort(){ let array = SortingAlgorithms(input: [25,17,31,13,2]) array.selectionSort() XCTAssertEqual([2, 13, 17, 25, 31], array.arrayOutput, "Selection sort failed \(#function)") } func testBubleSort(){ let array = SortingAlgorithms(input: [25,17,31,13,2]) array.bubbleSort() XCTAssertEqual([2, 13, 17, 25, 31], array.arrayOutput, "BubleSort failed \(#function)") } func test_BubleSort() throws{ var array = [25,17,31,13,2] SortingAlgorithms().bubbleSort(&array) XCTAssertEqual([2, 13, 17, 25, 31], array, "BubleSort failed \(#function)") var array1 = [25] SortingAlgorithms().bubbleSort(&array1) XCTAssertEqual([25], array1, "BubleSort failed \(#function)") var array2 = [25,45,2,4,65] SortingAlgorithms().bubbleSort(&array2) XCTAssertEqual([2,4,25,45,65], array2, "BubleSort failed \(#function)") } func test_SelectionSort() throws{ var array = [25,17,31,13,2] SortingAlgorithms().selectionSort(&array) XCTAssertEqual([2, 13, 17, 25, 31], array, "selectionSort failed \(#function)") var array1 = [25] SortingAlgorithms().selectionSort(&array1) XCTAssertEqual([25], array1, "selectionSort failed \(#function)") var array2 = [25,45,2,4,65] SortingAlgorithms().selectionSort(&array2) XCTAssertEqual([2,4,25,45,65], array2, "selectionSort failed \(#function)") } func test_InsertionSort() throws{ var array = [25,17,31,13,2] SortingAlgorithms().insertionSort(&array) XCTAssertEqual([2, 13, 17, 25, 31], array, "insertionSort failed \(#function)") var array1 = [25] SortingAlgorithms().insertionSort(&array1) XCTAssertEqual([25], array1, "insertionSort failed \(#function)") var array2 = [25,45,2,4,65] SortingAlgorithms().insertionSort(&array2) XCTAssertEqual([2,4,25,45,65], array2, "insertionSort failed \(#function)") } func testInsertionSort(){ let array = SortingAlgorithms(input: [25,17,31,13,2]) array.insertionSort() XCTAssertEqual([2, 13, 17, 25, 31], array.arrayOutput, "BubleSort failed \(#function)") } func testSecondLargestElementInArray(){ XCTAssertEqual(51, try! findSecondLargestElement(input: [45, 51, 28, 75, 49, 42])) XCTAssertEqual(975, try! findSecondLargestElement(input: [985, 521, 975, 831, 479, 861])) XCTAssertEqual(9459, try! findSecondLargestElement(input: [9459, 9575, 5692, 1305, 1942, 9012])) XCTAssertEqual(74562, try! findSecondLargestElement(input: [47498, 14526, 74562, 42681, 75283, 45796])) } }
mit
48c25baca235ec7ed29f189cd27ec5ac
32.418605
124
0.688065
3.559133
false
true
false
false
magnetsystems/message-ios
Source/PushMessage/MMXPushMessage.swift
5
8334
/* * Copyright (c) 2015 Magnet Systems, Inc. * 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 MagnetMaxCore import UIKit @objc public class MMXPushMessage : NSObject { //******************************************************************************** // MARK: Public Properies //******************************************************************************** public var recipients : Set<MMUser>? //******************************************************************************** // MARK: Read-only Properies //******************************************************************************** // message content dictionary contains the actual values that will be sent via push private(set) public var messageContent : Dictionary<String, String>? // the following properties reflect the values stored in message content private(set) public var body : String? private(set) public var title : String? private(set) public var badge : String? private(set) public var sound : String? private(set) public var userDefinedObjects : Dictionary<String, String>? //******************************************************************************** // MARK: Initializers //******************************************************************************** /** The designated initializer. */ public override init() { super.init() } /** Convience initializer. - parameter Dictionary: The Remote Dictionary is the UserInfo recieved from a push notification. */ convenience public init(pushUserInfo : NSDictionary) { self.init() let mmxDictionary : Dictionary? = pushUserInfo["_mmx"] as? Dictionary<String, AnyObject>; let apsDictionary : AnyObject? = pushUserInfo["aps"]; var messageContent : Dictionary = [String : String]() if let mmx = mmxDictionary { if let mmxCustom : Dictionary<String, AnyObject> = mmx["custom"] as? Dictionary<String, AnyObject> { for ( key, value ) in mmxCustom { messageContent[key] = "\(value)" } } let userObjects = messageContent self.userDefinedObjects = userObjects } else { return } if let aps = apsDictionary as? Dictionary<String, AnyObject> { if let alert : String = aps["alert"] as? String { self.body = alert messageContent["body"] = alert } else { if let body : String = aps["alert"]?["body"] as? String { self.body = body messageContent["body"] = body } if let title : String = aps["alert"]?["title"] as? String { self.title = title messageContent["title"] = title if self.body == nil { self.body = self.title } } } if let badge : Int = aps["badge"] as? Int { self.badge = "\(badge)" messageContent["badge"] = self.badge! } if let sound : String = aps["sound"] as? String { self.sound = sound messageContent["sound"] = sound } } self.messageContent = messageContent } //******************************************************************************** // MARK: Factory Methods //******************************************************************************** /** Factory Methods for generating a push message. - parameter Dictionary: The Remote Dictionary is the UserInfo recieved from a push notification. - Returns: a new MMXPushMessage object */ public class func pushMessageWithRecipients(recipients : Set <MMUser>, body : String) -> MMXPushMessage { return pushMessageWithRecipients(recipients, body: body, title : nil, sound: nil, badge: nil, userDefinedObjects: nil) } public class func pushMessageWithRecipients(recipients : Set <MMUser>, body : String, title : String?, sound : String?, badge : NSNumber?) -> MMXPushMessage { return pushMessageWithRecipients(recipients, body: body, title : title, sound: sound, badge: badge, userDefinedObjects: nil) } public class func pushMessageWithRecipients(recipients : Set <MMUser>, body : String, title : String?, sound : String?, badge : NSNumber?, userDefinedObjects : Dictionary<String, String>?) -> MMXPushMessage { var messageContent : Dictionary = [String : String]() let msg: MMXPushMessage = MMXPushMessage.init() msg.userDefinedObjects = userDefinedObjects if let userObjects = userDefinedObjects { for ( key, value ) in userObjects { messageContent[key] = value } } messageContent["body"] = body msg.body = body if let _ = title { messageContent["title"] = title msg.title = title } if let _ = sound { messageContent["sound"] = sound msg.sound = sound } if let _ = badge { messageContent["badge"] = badge?.stringValue msg.badge = badge?.stringValue } msg.messageContent = messageContent msg.recipients = recipients return msg } public class func pushMessageWithRecipient(recipient : MMUser, body : String) -> MMXPushMessage { return pushMessageWithRecipients([recipient], body: body) } public class func pushMessageWithRecipient(recipient : MMUser, body : String, title : String, sound : String?, badge : NSNumber?) -> MMXPushMessage { return pushMessageWithRecipients([recipient], body: body, title : title, sound: sound, badge: badge) } public class func pushMessageWithRecipient(recipient : MMUser, body : String, title : String, sound : String?, badge : NSNumber?, userDefinedObjects : Dictionary<String, String>?) -> MMXPushMessage { return pushMessageWithRecipients([recipient], body: body, title : title, sound: sound, badge: badge, userDefinedObjects: userDefinedObjects) } //******************************************************************************** // MARK: Public Methods //******************************************************************************** /** Sends the push message. - parameters: - success: a closure to run upon success - failure: a closure to run upon failure - Returns: a new MMXPushMessage object */ public func sendPushMessage(success : (() -> Void)?, failure : ((error : NSError) -> Void)?) { if MMXMessageUtils.isValidMetaData(self.messageContent) == false { let error : NSError = MMXClient.errorWithTitle("Not Valid", message: "All values must be strings.", code: 401) failure?(error : error) } if MMUser.currentUser() == nil { let error : NSError = MMXClient.errorWithTitle("Not Logged In", message: "You must be logged in to send a message.", code: 401) failure?(error : error) } MagnetDelegate.sharedDelegate().sendPushMessage(self, success: { (invalidDevices : Set<NSObject>!) -> Void in success?() }, failure: { error in failure?(error: error) }); } }
apache-2.0
9f4b8585c7bdb6e555ab0d0e43c63be3
36.205357
212
0.524238
5.515553
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Playgrounds/Basics.playground/Pages/Splitting Nodes.xcplaygroundpage/Contents.swift
1
1188
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Splitting Nodes //: ### All nodes in AudioKit can have multiple destinations, the only //: ### caveat is that all of the destinations do have to eventually be mixed //: ### back together and none of the parallel signal paths can have any time stretching. import XCPlayground import AudioKit //: Prepare the source audio player let file = try AKAudioFile(readFileName: "drumloop.wav", baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true //: The following nodes are both acting on the original player node var ringMod = AKRingModulator(player) var delay = AKDelay(player) delay.time = 0.01 delay.feedback = 0.8 delay.dryWetMix = 1 //: Any number of inputs can be equally summed into one output, including the //: original player, allowing us to create dry/wet mixes even for effects that //: don't have that property by default let mixer = AKMixer(player, delay) AudioKit.output = mixer AudioKit.start() player.play() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
55b2ff2b1738ecc482f58ef3cdd3e0b7
31.108108
89
0.733165
3.920792
false
false
false
false
sagittarius-90/-t-tracker
microtime.tracker/Controllers/MainPageViewController.swift
1
5811
// // MainPageViewController.swift // microtime.tracker // // Created by Eni Sinanaj on 29/10/2016. // Copyright © 2016 Eni Sinanaj. All rights reserved. // import UIKit import AVFoundation import Foundation class MainPageViewController: UIViewController { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var minutesHand: UILabel! @IBOutlet weak var secondsHand: UILabel! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var stopButton: UIButton! weak var allEntriesDelegate: AllEntriesViewController? var minutes = 0 var seconds = 0 var hours = 0 var timer: Timer! var timeKeeper: Double = 0.0 var startSeconds: Double = 0.0 var sectionSeconds: Double = 0.0 var differenceInSecconds: Double = 0.0 var running: Bool! func startTime(_ sender: AnyObject) { running = true self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) self.startSeconds = CACurrentMediaTime() self.differenceInSecconds = 0.0 self.resetTimerCounters() startButton.isHidden = true stopButton.isHidden = false } func stopTime(_ sender: AnyObject) { timer.invalidate() running = false let saveEntryDialog = SaveEntryViewController(nibName: "SaveEntryViewController", bundle: nil) saveEntryDialog.time = sectionSeconds saveEntryDialog.timeAsText = (timeLabel!.text ?? "").appending("H ") .appending(minutesHand!.text ?? "").appending("M ") .appending(secondsHand?.text ?? "").appending("S") saveEntryDialog.allEntriesDelegate = self.allEntriesDelegate self.resetTimerCounters() sectionSeconds = getIntervalFromStartTime() self.present(saveEntryDialog, animated: true, completion: nil) stopButton.isHidden = true startButton.isHidden = false } func resetTimerCounters() { minutes = 0 seconds = 0 hours = 0 timeLabel.text = "00" minutesHand.text = "00" secondsHand.text = "00" } @IBAction func stopTimerAction(_ sender: AnyObject) { stopTime(sender) } @IBAction func startTimerAction(_ sender: AnyObject) { startTime(sender) } func update() { self.timeKeeper += 1 incrementSeconds() playBeep() timeLabel.text = getAsString(timePart: hours) minutesHand.text = getAsString(timePart: minutes) secondsHand.text = getAsString(timePart: seconds) } func playBeep() { let interval: Double = getIntervalFromStartTime() print("interval in seconds: " + String(interval)) if (interval == 5) { //TODO: play notification aufio every half an hour? } } func getIntervalFromStartTime() -> Double { return CACurrentMediaTime() - startSeconds } func incrementMinutes() { if (minutes == 59) { minutes = 0 incrementHours() } else { minutes += 1 } } func incrementHours() { if (hours == 23) { hours = 0 } else { hours += 1 } } func incrementSeconds() { if (seconds == 59) { seconds = 0 incrementMinutes() } else { seconds += 1 } } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationDidBecomeActive, object: nil, queue: OperationQueue.main, using: self.reloadTimer) stopButton.isHidden = true } func reloadTimer(notification: Notification) { differenceInSecconds = CACurrentMediaTime() - self.startSeconds let hoursD = floor(differenceInSecconds / (60.0 * 60.0)) let divisorForMinutes = differenceInSecconds.truncatingRemainder(dividingBy: (60.0 * 60.0)) let minutesD = floor(divisorForMinutes / 60.0) let divisorForSeconds = divisorForMinutes.truncatingRemainder(dividingBy: 60.0) let secondsD = ceil(divisorForSeconds) print ("application restored at: " + String(CACurrentMediaTime())) print ("startTime: " + String(self.startSeconds)) print ("differenceInSeconds: " + String(CACurrentMediaTime() - self.startSeconds)) print ("hoursD: " + String(hoursD)) print ("minutesD: " + String(minutesD)) print ("secondsD: " + String(secondsD)) if self.startSeconds > 0.0 { self.seconds = Int(secondsD) self.minutes = minutesD > 1 ? Int(minutesD) : self.minutes self.hours = hoursD > 1 ? Int(hoursD) : self.hours } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getAsString(timePart: NSInteger) -> String { if (timePart == 0) { return "00" } else if (timePart > 0 && timePart < 10) { return "0" + String(timePart) } else { return String(timePart) } } /* // 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
348de01ea614a1386d422961b576b8ad
29.103627
171
0.596213
4.693053
false
false
false
false
loudnate/Loop
Learn/Configuration/NumberRangeEntry.swift
1
1723
// // NumberRangeEntry.swift // Learn // // Copyright © 2019 LoopKit Authors. All rights reserved. // import UIKit class NumberRangeEntry: LessonSectionProviding { let headerTitle: String? var cells: [LessonCellProviding] { return numberCells } var minValue: NSNumber? { return numberCells.compactMap({ $0.number }).min() } var maxValue: NSNumber? { return numberCells.compactMap({ $0.number }).max() } var range: Range<NSNumber>? { guard let minValue = minValue, let maxValue = maxValue else { return nil } return minValue..<maxValue } var closedRange: ClosedRange<NSNumber>? { guard let minValue = minValue, let maxValue = maxValue else { return nil } return minValue...maxValue } private var numberCells: [NumberEntry] init(headerTitle: String?, minValue: NSNumber?, maxValue: NSNumber?, formatter: NumberFormatter, unitString: String?, keyboardType: UIKeyboardType) { self.headerTitle = headerTitle self.numberCells = [ NumberEntry( number: minValue, formatter: formatter, placeholder: NSLocalizedString("Minimum", comment: "Placeholder for lower range entry"), unitString: unitString, keyboardType: keyboardType ), NumberEntry( number: maxValue, formatter: formatter, placeholder: NSLocalizedString("Maximum", comment: "Placeholder for upper range entry"), unitString: unitString, keyboardType: keyboardType ), ] } }
apache-2.0
8abf96d2214ca01369d5db225378e131
25.90625
153
0.591173
5.364486
false
false
false
false
gregomni/swift
test/ModuleInterface/access-filter.swift
2
10439
// RUN: %target-swift-frontend -typecheck -emit-module-interface-path %t.swiftinterface %s -module-name AccessFilter -requirement-machine-inferred-signatures=on // RUN: %FileCheck %s < %t.swiftinterface // RUN: %FileCheck -check-prefix NEGATIVE %s < %t.swiftinterface // NEGATIVE-NOT: BAD // CHECK: public func publicFn(){{$}} public func publicFn() {} internal func internalFn_BAD() {} private func privateFn_BAD() {} // CHECK: @usableFromInline // CHECK-NEXT: internal func ufiFn(){{$}} @usableFromInline internal func ufiFn() {} // CHECK: public struct PublicStruct {{[{]$}} public struct PublicStruct { // CHECK: public func publicMethod(){{$}} public func publicMethod() {} internal func internalMethod_BAD() {} // CHECK: @usableFromInline // CHECK-NEXT: internal func ufiMethod(){{$}} @usableFromInline internal func ufiMethod() {} } // CHECK: {{^[}]$}} internal struct InternalStruct_BAD { public func publicMethod_BAD() {} internal func internalMethod_BAD() {} @usableFromInline internal func ufiMethod_BAD() {} } // CHECK: @usableFromInline // CHECK-NEXT: internal struct UFIStruct {{[{]$}} @usableFromInline internal struct UFIStruct { // FIXME: Arguably this should be downgraded to "@usableFromInline internal". // CHECK: public func publicMethod(){{$}} public func publicMethod() {} internal func internalMethod_BAD() {} // CHECK: @usableFromInline // CHECK-NEXT: internal func ufiMethod(){{$}} @usableFromInline internal func ufiMethod() {} } // CHECK: {{^[}]$}} // CHECK: public protocol PublicProto {{[{]$}} public protocol PublicProto { // CHECK-NEXT: associatedtype Assoc = Swift.Int associatedtype Assoc = Int // CHECK-NEXT: func requirement() func requirement() } // CHECK-NEXT: {{^[}]$}} // CHECK: extension AccessFilter.PublicProto {{[{]$}} extension PublicProto { // CHECK: public func publicMethod(){{$}} public func publicMethod() {} internal func internalMethod_BAD() {} // CHECK: @usableFromInline // CHECK-NEXT: internal func ufiMethod(){{$}} @usableFromInline internal func ufiMethod() {} } // CHECK: {{^[}]$}} // CHECK: {{^}}extension AccessFilter.PublicProto {{[{]$}} public extension PublicProto { // CHECK: public func publicExtPublicMethod(){{$}} func publicExtPublicMethod() {} internal func publicExtInternalMethod_BAD() {} // CHECK: @usableFromInline // CHECK-NEXT: internal func publicExtUFIMethod(){{$}} @usableFromInline internal func publicExtUFIMethod() {} } internal protocol InternalProto_BAD { associatedtype AssocBAD = Int func requirementBAD() } extension InternalProto_BAD { public func publicMethod_BAD() {} internal func internalMethod_BAD() {} @usableFromInline internal func ufiMethod_BAD() {} } // CHECK: @usableFromInline // CHECK-NEXT: internal protocol UFIProto {{[{]$}} @usableFromInline internal protocol UFIProto { // CHECK-NEXT: associatedtype Assoc = Swift.Int associatedtype Assoc = Int // CHECK-NEXT: func requirement() func requirement() } // CHECK-NEXT: {{^[}]$}} // CHECK: extension AccessFilter.UFIProto {{[{]$}} extension UFIProto { // CHECK: public func publicMethod(){{$}} public func publicMethod() {} internal func internalMethod_BAD() {} // CHECK: @usableFromInline // CHECK-NEXT: internal func ufiMethod(){{$}} @usableFromInline internal func ufiMethod() {} } // CHECK: {{^[}]$}} // CHECK: extension AccessFilter.PublicStruct {{[{]$}} extension PublicStruct { // CHECK: @_hasInitialValue public static var secretlySettable: Swift.Int { // CHECK-NEXT: get // CHECK-NEXT: } public private(set) static var secretlySettable: Int = 0 } // CHECK: {{^[}]$}} extension InternalStruct_BAD: PublicProto { func requirement() {} internal static var dummy: Int { return 0 } } // CHECK: extension AccessFilter.UFIStruct : AccessFilter.PublicProto {{[{]$}} extension UFIStruct: PublicProto { // CHECK-NEXT: @usableFromInline // CHECK-NEXT: internal typealias Assoc = Swift.Int // FIXME: Is it okay for this non-@usableFromInline implementation to satisfy // the protocol? func requirement() {} internal static var dummy: Int { return 0 } } // CHECK-NEXT: {{^[}]$}} // CHECK: public enum PublicEnum {{[{]$}} public enum PublicEnum { // CHECK-NEXT: case x case x // CHECK-NEXT: case y(Swift.Int) case y(Int) } // CHECK-NEXT: {{^[}]$}} enum InternalEnum_BAD { case xBAD } // CHECK: @usableFromInline // CHECK-NEXT: internal enum UFIEnum {{[{]$}} @usableFromInline enum UFIEnum { // CHECK-NEXT: case x case x // CHECK-NEXT: case y(Swift.Int) case y(Int) } // CHECK-NEXT: {{^[}]$}} // CHECK: public class PublicClass {{[{]$}} public class PublicClass { } // CHECK: {{^[}]$}} class InternalClass_BAD { } // CHECK: @usableFromInline // CHECK-NEXT: internal class UFIClass {{[{]$}} @usableFromInline class UFIClass { } // CHECK: {{^[}]$}} // CHECK: public struct GenericStruct<T> public struct GenericStruct<T> {} // CHECK: extension AccessFilter.GenericStruct where T == AccessFilter.PublicStruct {{[{]$}} extension GenericStruct where T == AccessFilter.PublicStruct { // CHECK-NEXT: public func constrainedToPublicStruct(){{$}} public func constrainedToPublicStruct() {} } // CHECK-NEXT: {{^[}]$}} // CHECK: extension AccessFilter.GenericStruct where T == AccessFilter.UFIStruct {{[{]$}} extension GenericStruct where T == AccessFilter.UFIStruct { // CHECK-NEXT: @usableFromInline{{$}} // CHECK-NEXT: internal func constrainedToUFIStruct(){{$}} @usableFromInline internal func constrainedToUFIStruct() {} } // CHECK-NEXT: {{^[}]$}} extension GenericStruct where T == InternalStruct_BAD { @usableFromInline internal func constrainedToInternalStruct_BAD() {} } // CHECK: extension AccessFilter.GenericStruct where T == AccessFilter.PublicStruct {{[{]$}} extension GenericStruct where PublicStruct == T { // CHECK-NEXT: public func constrainedToPublicStruct2(){{$}} public func constrainedToPublicStruct2() {} } // CHECK-NEXT: {{^[}]$}} // CHECK: extension AccessFilter.GenericStruct where T == AccessFilter.UFIStruct {{[{]$}} extension GenericStruct where UFIStruct == T { // CHECK-NEXT: @usableFromInline{{$}} // CHECK-NEXT: internal func constrainedToUFIStruct2(){{$}} @usableFromInline internal func constrainedToUFIStruct2() {} } // CHECK-NEXT: {{^[}]$}} extension GenericStruct where InternalStruct_BAD == T { @usableFromInline internal func constrainedToInternalStruct2_BAD() {} } // CHECK: extension AccessFilter.GenericStruct where T : AccessFilter.PublicProto {{[{]$}} extension GenericStruct where T: PublicProto { // CHECK-NEXT: public func constrainedToPublicProto(){{$}} public func constrainedToPublicProto() {} } // CHECK-NEXT: {{^[}]$}} // CHECK: extension AccessFilter.GenericStruct where T : AccessFilter.UFIProto {{[{]$}} extension GenericStruct where T: UFIProto { // CHECK-NEXT: @usableFromInline{{$}} // CHECK-NEXT: internal func constrainedToUFIProto(){{$}} @usableFromInline internal func constrainedToUFIProto() {} } // CHECK-NEXT: {{^[}]$}} extension GenericStruct where T: InternalProto_BAD { @usableFromInline internal func constrainedToInternalProto_BAD() {} } // CHECK: extension AccessFilter.GenericStruct where T : AccessFilter.PublicClass {{[{]$}} extension GenericStruct where T: PublicClass { // CHECK-NEXT: public func constrainedToPublicClass(){{$}} public func constrainedToPublicClass() {} } // CHECK-NEXT: {{^[}]$}} // CHECK: extension AccessFilter.GenericStruct where T : AccessFilter.UFIClass {{[{]$}} extension GenericStruct where T: UFIClass { // CHECK-NEXT: @usableFromInline{{$}} // CHECK-NEXT: internal func constrainedToUFIClass(){{$}} @usableFromInline internal func constrainedToUFIClass() {} } // CHECK-NEXT: {{^[}]$}} extension GenericStruct where T: InternalClass_BAD { @usableFromInline internal func constrainedToInternalClass_BAD() {} } // CHECK: extension AccessFilter.GenericStruct where T : AnyObject {{[{]$}} extension GenericStruct where T: AnyObject { // CHECK-NEXT: public func constrainedToAnyObject(){{$}} public func constrainedToAnyObject() {} } // CHECK-NEXT: {{^[}]$}} public struct PublicAliasBase {} internal struct ReallyInternalAliasBase_BAD {} // CHECK: public typealias PublicAlias = AccessFilter.PublicAliasBase public typealias PublicAlias = PublicAliasBase internal typealias InternalAlias_BAD = PublicAliasBase // CHECK: @usableFromInline // CHECK-NEXT: internal typealias UFIAlias = AccessFilter.PublicAliasBase @usableFromInline internal typealias UFIAlias = PublicAliasBase internal typealias ReallyInternalAlias_BAD = ReallyInternalAliasBase_BAD // CHECK: extension AccessFilter.GenericStruct where T == AccessFilter.PublicAliasBase {{[{]$}} extension GenericStruct where T == PublicAlias { // CHECK-NEXT: public func constrainedToPublicAlias(){{$}} public func constrainedToPublicAlias() {} } // CHECK-NEXT: {{^[}]$}} // CHECK: extension AccessFilter.GenericStruct where T == AccessFilter.PublicAliasBase {{[{]$}} extension GenericStruct where T == UFIAlias { // CHECK-NEXT: @usableFromInline{{$}} // CHECK-NEXT: internal func constrainedToUFIAlias(){{$}} @usableFromInline internal func constrainedToUFIAlias() {} } // CHECK-NEXT: {{^[}]$}} extension GenericStruct where T == InternalAlias_BAD { // FIXME: We could print this one by desugaring; it is indeed public. @usableFromInline internal func constrainedToInternalAlias() {} } extension GenericStruct where T == ReallyInternalAlias_BAD { @usableFromInline internal func constrainedToPrivateAlias() {} } extension GenericStruct { // For the next extension's test. public func requirement() {} } extension GenericStruct: PublicProto where T: InternalProto_BAD { @usableFromInline internal func conformance_BAD() {} } public struct MultiGenericStruct<First, Second> {} // CHECK: extension AccessFilter.MultiGenericStruct where First == AccessFilter.PublicStruct, Second == AccessFilter.PublicStruct {{[{]$}} extension MultiGenericStruct where First == PublicStruct, Second == PublicStruct { // CHECK-NEXT: public func publicPublic(){{$}} public func publicPublic() {} } // CHECK-NEXT: {{^[}]$}} extension MultiGenericStruct where First == PublicStruct, Second == InternalStruct_BAD { @usableFromInline internal func publicInternal_BAD() {} } extension MultiGenericStruct where First == InternalStruct_BAD, Second == PublicStruct { @usableFromInline internal func internalPublic_BAD() {} }
apache-2.0
980dcdcbdc32aafbee5e3d761a768d75
35.121107
160
0.713287
4.294118
false
false
false
false
sharkspeed/dororis
platforms/iOS/FoodTracker/FoodTracker/Meal.swift
1
690
// // Meal.swift // FoodTracker // // Created by liuxiangyu on 8/30/17. // Copyright © 2017 42vision. All rights reserved. // import Foundation import UIKit class Meal { // MARK: Properties var name: String var photo: UIImage? var rating: Int init?(name: String, photo: UIImage?, rating: Int) { // if name.isEmpty || rating < 0 { // return nil // } // 改进 guard !name.isEmpty else { return nil } guard (rating >= 0 ) && (rating <= 5) else { return nil } self.name = name self.photo = photo self.rating = rating } }
bsd-2-clause
7f7988b2b74533f84cd87e317cf875fd
18.027778
55
0.50073
3.959538
false
false
false
false
OscarSwanros/swift
stdlib/public/core/SliceBuffer.swift
2
12650
//===--- SliceBuffer.swift - Backing storage for ArraySlice<Element> ------===// // // 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 // //===----------------------------------------------------------------------===// /// Buffer type for `ArraySlice<Element>`. @_fixed_layout @_versioned internal struct _SliceBuffer<Element> : _ArrayBufferProtocol, RandomAccessCollection { internal typealias NativeStorage = _ContiguousArrayStorage<Element> internal typealias NativeBuffer = _ContiguousArrayBuffer<Element> @_inlineable @_versioned internal init( owner: AnyObject, subscriptBaseAddress: UnsafeMutablePointer<Element>, indices: Range<Int>, hasNativeBuffer: Bool ) { self.owner = owner self.subscriptBaseAddress = subscriptBaseAddress self.startIndex = indices.lowerBound let bufferFlag = UInt(hasNativeBuffer ? 1 : 0) self.endIndexAndFlags = (UInt(indices.upperBound) << 1) | bufferFlag _invariantCheck() } @_inlineable @_versioned internal init() { let empty = _ContiguousArrayBuffer<Element>() self.owner = empty.owner self.subscriptBaseAddress = empty.firstElementAddress self.startIndex = empty.startIndex self.endIndexAndFlags = 1 _invariantCheck() } @_inlineable @_versioned internal init(_buffer buffer: NativeBuffer, shiftedToStartIndex: Int) { let shift = buffer.startIndex - shiftedToStartIndex self.init( owner: buffer.owner, subscriptBaseAddress: buffer.subscriptBaseAddress + shift, indices: shiftedToStartIndex..<shiftedToStartIndex + buffer.count, hasNativeBuffer: true) } @_inlineable // FIXME(sil-serialize-all) @_versioned internal func _invariantCheck() { let isNative = _hasNativeBuffer let isNativeStorage: Bool = owner is _ContiguousArrayStorageBase _sanityCheck(isNativeStorage == isNative) if isNative { _sanityCheck(count <= nativeBuffer.count) } } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var _hasNativeBuffer: Bool { return (endIndexAndFlags & 1) != 0 } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var nativeBuffer: NativeBuffer { _sanityCheck(_hasNativeBuffer) return NativeBuffer( owner as? _ContiguousArrayStorageBase ?? _emptyArrayStorage) } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var nativeOwner: AnyObject { _sanityCheck(_hasNativeBuffer, "Expect a native array") return owner } /// Replace the given subRange with the first newCount elements of /// the given collection. /// /// - Precondition: This buffer is backed by a uniquely-referenced /// `_ContiguousArrayBuffer` and /// `insertCount <= numericCast(newValues.count)`. @_inlineable // FIXME(sil-serialize-all) @_versioned internal mutating func replaceSubrange<C>( _ subrange: Range<Int>, with insertCount: Int, elementsOf newValues: C ) where C : Collection, C.Element == Element { _invariantCheck() _sanityCheck(insertCount <= numericCast(newValues.count)) _sanityCheck(_hasNativeBuffer && isUniquelyReferenced()) let eraseCount = subrange.count let growth = insertCount - eraseCount let oldCount = count var native = nativeBuffer let hiddenElementCount = firstElementAddress - native.firstElementAddress _sanityCheck(native.count + growth <= native.capacity) let start = subrange.lowerBound - startIndex + hiddenElementCount let end = subrange.upperBound - startIndex + hiddenElementCount native.replaceSubrange( start..<end, with: insertCount, elementsOf: newValues) self.endIndex = self.startIndex + oldCount + growth _invariantCheck() } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. @_inlineable // FIXME(sil-serialize-all) @_versioned internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } /// An object that keeps the elements stored in this buffer alive. @_versioned internal var owner: AnyObject @_versioned internal let subscriptBaseAddress: UnsafeMutablePointer<Element> @_inlineable // FIXME(sil-serialize-all) @_versioned internal var firstElementAddress: UnsafeMutablePointer<Element> { return subscriptBaseAddress + startIndex } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } /// [63:1: 63-bit index][0: has a native buffer] @_versioned internal var endIndexAndFlags: UInt //===--- Non-essential bits ---------------------------------------------===// @_inlineable // FIXME(sil-serialize-all) @_versioned internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> NativeBuffer? { _invariantCheck() if _fastPath(_hasNativeBuffer && isUniquelyReferenced()) { if capacity >= minimumCapacity { // Since we have the last reference, drop any inaccessible // trailing elements in the underlying storage. That will // tend to reduce shuffling of later elements. Since this // function isn't called for subscripting, this won't slow // down that case. var native = nativeBuffer let offset = self.firstElementAddress - native.firstElementAddress let backingCount = native.count let myCount = count if _slowPath(backingCount > myCount + offset) { native.replaceSubrange( (myCount+offset)..<backingCount, with: 0, elementsOf: EmptyCollection()) } _invariantCheck() return native } } return nil } @_inlineable @_versioned internal mutating func isMutableAndUniquelyReferenced() -> Bool { return _hasNativeBuffer && isUniquelyReferenced() } @_inlineable @_versioned internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { return _hasNativeBuffer && isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @_inlineable // FIXME(sil-serialize-all) @_versioned internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { _invariantCheck() if _fastPath(_hasNativeBuffer && nativeBuffer.count == count) { return nativeBuffer } return nil } @_inlineable // FIXME(sil-serialize-all) @_versioned @discardableResult internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _invariantCheck() _sanityCheck(bounds.lowerBound >= startIndex) _sanityCheck(bounds.upperBound >= bounds.lowerBound) _sanityCheck(bounds.upperBound <= endIndex) let c = bounds.count target.initialize(from: subscriptBaseAddress + bounds.lowerBound, count: c) return target + c } /// True, if the array is native and does not need a deferred type check. @_inlineable // FIXME(sil-serialize-all) @_versioned internal var arrayPropertyIsNativeTypeChecked: Bool { return _hasNativeBuffer } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var count: Int { get { return endIndex - startIndex } set { let growth = newValue - count if growth != 0 { nativeBuffer.count += growth self.endIndex += growth } _invariantCheck() } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `startIndex ≤ index < endIndex` @_inlineable // FIXME(sil-serialize-all) @_versioned internal func _checkValidSubscript(_ index : Int) { _precondition( index >= startIndex && index < endIndex, "Index out of bounds") } @_inlineable // FIXME(sil-serialize-all) @_versioned internal var capacity: Int { let count = self.count if _slowPath(!_hasNativeBuffer) { return count } let n = nativeBuffer let nativeEnd = n.firstElementAddress + n.count if (firstElementAddress + count) == nativeEnd { return count + (n.capacity - n.count) } return count } @_inlineable // FIXME(sil-serialize-all) @_versioned internal mutating func isUniquelyReferenced() -> Bool { return isKnownUniquelyReferenced(&owner) } @_inlineable // FIXME(sil-serialize-all) @_versioned internal mutating func isUniquelyReferencedOrPinned() -> Bool { return _isKnownUniquelyReferencedOrPinned(&owner) } @_inlineable // FIXME(sil-serialize-all) @_versioned internal func getElement(_ i: Int) -> Element { _sanityCheck(i >= startIndex, "slice index is out of range (before startIndex)") _sanityCheck(i < endIndex, "slice index is out of range") return subscriptBaseAddress[i] } /// Access the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal subscript(position: Int) -> Element { get { return getElement(position) } nonmutating set { _sanityCheck(position >= startIndex, "slice index is out of range (before startIndex)") _sanityCheck(position < endIndex, "slice index is out of range") subscriptBaseAddress[position] = newValue } } @_inlineable // FIXME(sil-serialize-all) @_versioned internal subscript(bounds: Range<Int>) -> _SliceBuffer { get { _sanityCheck(bounds.lowerBound >= startIndex) _sanityCheck(bounds.upperBound >= bounds.lowerBound) _sanityCheck(bounds.upperBound <= endIndex) return _SliceBuffer( owner: owner, subscriptBaseAddress: subscriptBaseAddress, indices: bounds, hasNativeBuffer: _hasNativeBuffer) } set { fatalError("not implemented") } } //===--- Collection conformance -------------------------------------===// /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @_versioned internal var startIndex: Int /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// `endIndex` is always reachable from `startIndex` by zero or more /// applications of `index(after:)`. @_inlineable // FIXME(sil-serialize-all) @_versioned internal var endIndex: Int { get { return Int(endIndexAndFlags >> 1) } set { endIndexAndFlags = (UInt(newValue) << 1) | (_hasNativeBuffer ? 1 : 0) } } internal typealias Indices = CountableRange<Int> //===--- misc -----------------------------------------------------------===// /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. @_inlineable @_versioned internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. @_inlineable @_versioned internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } } extension _SliceBuffer { @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _copyToContiguousArray() -> ContiguousArray<Element> { if _hasNativeBuffer { let n = nativeBuffer if count == n.count { return ContiguousArray(_buffer: n) } } let result = _ContiguousArrayBuffer<Element>( _uninitializedCount: count, minimumCapacity: 0) result.firstElementAddress.initialize( from: firstElementAddress, count: count) return ContiguousArray(_buffer: result) } }
apache-2.0
509de9b74ce2260c3fa9c4f899c64303
30.076167
93
0.673703
4.859009
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Config/External/3DSecure/PXThreeDSConfig.swift
1
915
import Foundation /** Whe use this object to store properties related to ESC module. Check PXESCProtocol methods. */ @objcMembers open class PXThreeDSConfig: NSObject { public let flowIdentifier: String public let sessionId: String public let privateKey: String? init(flowIdentifier: String, sessionId: String, privateKey: String?) { self.flowIdentifier = flowIdentifier self.sessionId = sessionId self.privateKey = privateKey } } // MARK: Internals (Only PX) extension PXThreeDSConfig { static func createConfig(privateKey: String? = nil) -> PXThreeDSConfig { let flowIdentifier = MPXTracker.sharedInstance.getFlowName() ?? "PX" let sessionId = MPXTracker.sharedInstance.getSessionID() let defaultConfig = PXThreeDSConfig(flowIdentifier: flowIdentifier, sessionId: sessionId, privateKey: privateKey) return defaultConfig } }
mit
c6a24b630346bcc5575edc6cf46c8d8b
31.678571
121
0.72459
4.42029
false
true
false
false
mathewsanders/Mustard
Playgrounds/Source/CharacterSet Tokenizers.playground/Contents.swift
1
1529
/** Note: To use framework in a playground, the playground must be opened in a workspace that has the framework. If you recieve the error *"Playground execution failed: error: no such module 'Mustard'"* then run Project -> Build (⌘B). */ import Swift import Mustard //: ## Example 1 //: Match with just letters. let str = "Hello, playground 2017" let words = str.components(matchedWith: .letters) // words.count -> 2 // words = ["hello", "playground"] //: ## Example 2 //: Match with decimals digits or letters let tokens = "123Hello world&^45.67".tokens(matchedWith: .decimalDigits, .letters) for token in tokens { switch token.set { case CharacterSet.decimalDigits: print("- digits:", token.text) case CharacterSet.letters: print("- letters:", token.text) default: break } } // Pull the decimal tokens out by themselves. let numberTokens = tokens .filter { $0.set == .decimalDigits } .map { $0.text } numberTokens.count // -> 3 numberTokens // -> ["123", "45", "67"] //: ## Example 3 //: Use a custom tokenizer to get numbers with commas and decimals. struct NumberTokenizer: TokenizerType { let unicodeScalars = Set("0123456789.,".unicodeScalars) func tokenCanTake(_ scalar: UnicodeScalar) -> Bool { return unicodeScalars.contains(scalar) } } let customNumberTokens = "10,123hello456.789".tokens(matchedWith: NumberTokenizer()).map { $0.text } customNumberTokens.count // -> 2 customNumberTokens // -> ["10,123", "456.789"]
mit
632a1a179fbbf082a9e6c2a0ddb6f9c0
25.789474
122
0.671906
3.865823
false
false
false
false
david1mdavis/IOS-nRF-Toolbox
nRF Toolbox/BGM/ContinuousGlucoseMonitoring/NORCGMDetailsViewController.swift
2
5625
/* * Copyright (c) 2015, 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 UIKit class NORCGMDetailsViewController : UIViewController { //MARK: - Class Properties var reading : NORCGMReading? var dateFormat : DateFormatter? //MARK: - View Outlets/Actions @IBOutlet weak var backgroundImage: UIImageView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var sequenceNumber: UILabel! @IBOutlet weak var timestamp: UILabel! @IBOutlet weak var type: UILabel! @IBOutlet weak var location: UILabel! @IBOutlet weak var concentration: UILabel! @IBOutlet weak var unit: UILabel! @IBOutlet weak var lowBatteryStatus: UILabel! @IBOutlet weak var sensorMalfunctionStatus: UILabel! @IBOutlet weak var insufficienSampleStatus: UILabel! @IBOutlet weak var stripInsertionStatus: UILabel! @IBOutlet weak var stripTypeStatus: UILabel! @IBOutlet weak var resultTooHighStatus: UILabel! @IBOutlet weak var resultTooLowStatus: UILabel! @IBOutlet weak var tempTooHighStatus: UILabel! @IBOutlet weak var tempTooLowStatus: UILabel! @IBOutlet weak var stripPulledTooSoonStatus: UILabel! @IBOutlet weak var deviceFaultStatus: UILabel! @IBOutlet weak var timeStatus: UILabel! @IBOutlet weak var contextPresentStatus: UILabel! @IBOutlet weak var carbohydrateId: UILabel! @IBOutlet weak var carbohydrate: UILabel! @IBOutlet weak var meal: UILabel! @IBOutlet weak var tester: UILabel! @IBOutlet weak var health: UILabel! @IBOutlet weak var exerciseDuration: UILabel! @IBOutlet weak var exerciseIntensity: UILabel! @IBOutlet weak var medication: UILabel! @IBOutlet weak var medicationUnit: UILabel! @IBOutlet weak var medicationId: UILabel! @IBOutlet weak var HbA1c: UILabel! //MARK: - Initializer required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) dateFormat = DateFormatter() dateFormat?.dateFormat = "dd.MM.yyy, hh:mm:ss" } //MARK: - UIViewController methods override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) timestamp.text = dateFormat?.string(from: reading!.timeStamp! as Date) self.type.text = reading?.typeAsString() self.location.text = reading?.locationAsSting() self.concentration.text = String(format:"%.1f", reading!.glucoseConcentration) self.unit.text = "mg/dL"; if (reading?.sensorStatusAnnunciationPresent)! { print("Sensor annuciation is not fully implemented, updates will be ignored") // UInt16 status = reading.sensorStatusAnnunciation; // [self updateView:self.lowBatteryStatus withStatus:(status & 0x0001) > 0]; // [self updateView:self.sensorMalfunctionStatus withStatus:(status & 0x0002) > 0]; // [self updateView:self.insufficienSampleStatus withStatus:(status & 0x0004) > 0]; // [self updateView:self.stripInsertionStatus withStatus:(status & 0x0008) > 0]; // [self updateView:self.stripTypeStatus withStatus:(status & 0x0010) > 0]; // [self updateView:self.resultTooHighStatus withStatus:(status & 0x0020) > 0]; // [self updateView:self.resultTooLowStatus withStatus:(status & 0x0040) > 0]; // [self updateView:self.tempTooHighStatus withStatus:(status & 0x0080) > 0]; // [self updateView:self.tempTooLowStatus withStatus:(status & 0x0100) > 0]; // [self updateView:self.stripPulledTooSoonStatus withStatus:(status & 0x0200) > 0]; // [self updateView:self.deviceFaultStatus withStatus:(status & 0x0400) > 0]; // [self updateView:self.timeStatus withStatus:(status & 0x0800) > 0]; } } func updateView(withLabel aLabel : UILabel, andStatus status : Bool) { if status == true { aLabel.text = "YES" aLabel.textColor = UIColor.red }else{ aLabel.text = "NO" } } }
bsd-3-clause
5c5b4228a2bf4baf7f36bec467a5319b
50.605505
145
0.694933
4.550971
false
false
false
false
iscriptology/swamp
Swamp/Messages/PubSub/Publisher/PublishSwampMessage.swift
2
1515
// // PublishSwampMessage.swift // Pods // // Created by Yossi Abraham on 01/09/2016. // // import Foundation /// [PUBLISH, requestId|number, options|dict, topic|String, args|list?, kwargs|dict?] class PublishSwampMessage: SwampMessage { let requestId: Int let options: [String: Any] let topic: String let args: [Any]? let kwargs: [String: Any]? init(requestId: Int, options: [String: Any], topic: String, args: [Any]?=nil, kwargs: [String: Any]?=nil) { self.requestId = requestId self.options = options self.topic = topic self.args = args self.kwargs = kwargs } // MARK: SwampMessage protocol required init(payload: [Any]) { self.requestId = payload[0] as! Int self.options = payload[1] as! [String: Any] self.topic = payload[2] as! String self.args = payload[safe: 3] as? [Any] self.kwargs = payload[safe: 4] as? [String: Any] } func marshal() -> [Any] { var marshalled: [Any] = [SwampMessages.publish.rawValue, self.requestId, self.options, self.topic] if let args = self.args { marshalled.append(args) if let kwargs = self.kwargs { marshalled.append(kwargs) } } else { if let kwargs = self.kwargs { marshalled.append([]) marshalled.append(kwargs) } } return marshalled } }
mit
a98b6f375e2dcd188563f77131bd1f09
25.578947
111
0.552475
3.759305
false
false
false
false
grandiere/box
box/Model/Help/Basic/MHelpBasicIntro.swift
1
1353
import UIKit class MHelpBasicIntro:MHelpProtocol { private let attributedString:NSAttributedString init() { let attributesTitle:[String:AnyObject] = [ NSFontAttributeName:UIFont.bold(size:20), NSForegroundColorAttributeName:UIColor.white] let attributesDescription:[String:AnyObject] = [ NSFontAttributeName:UIFont.regular(size:18), NSForegroundColorAttributeName:UIColor(white:1, alpha:0.8)] let stringTitle:NSAttributedString = NSAttributedString( string:NSLocalizedString("MHelpBasicIntro_title", comment:""), attributes:attributesTitle) let stringDescription:NSAttributedString = NSAttributedString( string:NSLocalizedString("MHelpBasicIntro_description", comment:""), attributes:attributesDescription) let mutableString:NSMutableAttributedString = NSMutableAttributedString() mutableString.append(stringTitle) mutableString.append(stringDescription) attributedString = mutableString } var message:NSAttributedString { get { return attributedString } } var image:UIImage { get { return #imageLiteral(resourceName: "assetHelpBasicIntro") } } }
mit
ab7153379dfddf570458d16ca2ac9b64
29.75
81
0.648928
6.013333
false
false
false
false
Vaseltior/SFCoreDataOneWaySynchronization
Sources/NSManagedObject+OneWaySynchronization.swift
1
10677
/* Copyright 2011-present Samuel GRAU 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. */ // // NSManagedObject+OneWaySynchronization.swift // SFCoreDataOneWaySynchronization // import Foundation import CoreData extension NSManagedObject { /** Sets the object priority - parameter priority: the priority of the object - parameter object: the object for which to set the priority - parameter key: the key used to set the priority of the object */ public func sfSetObjectPriority(priority: NSNumber, object: AnyObject, key: String) { } /** Do the unique comparison between the source object and the destination object. Objects should be unique in a certain way. It means that a key exist that identifies them uniquely, event if the content of each object is different. - parameter srcObject: the source object - parameter dstObject: the destination object - parameter context: a context, if needed for the comparison - returns: `true` if the keys that identify the objects are equal, otherwise returns `false`. */ public class func sfCompareUniqueKeyFrom( srcObject: AnyObject, with dstObject: AnyObject, context: AnyObject?) -> Bool { return true } /** Insert the object referenced by data - parameter data: the object involved in the operation - parameter moc: the managed object context associated to the operation - parameter context: a context, if needed for the operation - returns: the newly inserted managed object */ public class func sfCreateObjectWithData( data: AnyObject, managedObjectContext moc: NSManagedObjectContext, context: AnyObject? ) -> NSManagedObject? { fatalError("createObjectWithData(data:managedObjectContext:context:) has not been implemented") } /** Updates the object referenced by data - parameter data: the object involved in the operation - parameter moc: the managed object context associated to the operation - parameter context: a context, if needed for the operation - returns: the updated managed object */ public class func sfUpdateObjectWithData( data: AnyObject, updatedObject: AnyObject, managedObjectContext moc: NSManagedObjectContext, context: AnyObject? ) -> NSManagedObject? { fatalError("updateObjectWithData(data:managedObjectContext:context:) has not been implemented") } /** Deletes the object referenced by data - parameter data: the object involved in the operation - parameter moc: the managed object context associated to the operation - parameter context: a context, if needed for the operation - returns: the deleted managed object */ public class func sfDeleteObjectWithData( data: AnyObject, managedObjectContext moc: NSManagedObjectContext, context: AnyObject? ) -> NSManagedObject? { fatalError("deleteObjectWithData(data:managedObjectContext:context:) has not been implemented") } /** do the whole synchronization - parameter inputObjects: source (master) - parameter existingData: destination (slave) - parameter key: the priority key - parameter moc: the managed object context in which to operate the synchronization - parameter context: the context if any needed - returns: the resulting set */ public class func sfSynchronizeSortedInputData( inputObjects: [AnyObject], withSortedExistingData existingData: [AnyObject], priorityKey key: String, managedObjectContext moc: NSManagedObjectContext, context: AnyObject? = nil) -> NSSet { var srcIndex = 0 // Source index var dstIndex = 0 // Destination index var resultSet = NSMutableSet() // While source index does not reach the upper bound of the existing data count while srcIndex < inputObjects.count { // We treat the current source object let srcMO: AnyObject = inputObjects[srcIndex] // Have we reached yet the end of the source array? if (dstIndex >= existingData.count) || (dstIndex < 0) { // There we are out of bounds, so this is an insertion --> Create the object self.owsInsertObject(object: srcMO, resultSet: &resultSet, key: key, managedObjectContext: moc, syncContext: context) // Mark as treated, and go to the next element srcIndex += 1 } else { // Get the existing current element for comparison let dstMO: AnyObject = existingData[dstIndex] // If the elements are equal this means that we already have the object, and it is an update. if self.sfCompareUniqueKeyFrom(srcMO, with: dstMO, context: context) == true { // We should update self.owsUpdateObject( object: srcMO, updatedObject: dstMO, resultSet: &resultSet, key: key, managedObjectContext: moc, syncContext: context ) // We progress on both indexes dstIndex += 1 srcIndex += 1 } else { // // If there is a difference this means that it could be an // insertion or a deletion // But we should find out which one it is. // - We should delete from Core Data if the next element is equal. // - We should insert an element into the Core Data if both the // current and the following element are different // - We should delete any object // // So we try to get the next Core Data identifier let dstIndexPlusOne = dstIndex + 1 // Do this element exist ? if (dstIndexPlusOne >= existingData.count) || (dstIndexPlusOne < 0) { // There we are out of bounds, so this is an insertion self.owsInsertObject(object: srcMO, resultSet: &resultSet, key: key, managedObjectContext: moc, syncContext: context) srcIndex += 1 } else { // We should compare to know if it is an insertion or a // deletion let dstMOPlusOne = existingData[dstIndexPlusOne] as! NSManagedObject if self.sfCompareUniqueKeyFrom(srcMO, with:dstMOPlusOne, context:context) == true { // If objects at this point are identical, // it is a deletion of the Core Data object self.sfDeleteObjectWithData(dstMO, managedObjectContext:moc, context:context) dstIndex += 1 } else { self.owsInsertObject(object: srcMO, resultSet: &resultSet, key: key, managedObjectContext: moc, syncContext: context) srcIndex += 1 } } } } } // The last step consist in deleting all the objects of the core data // that have not been deleted yet if any is remaining. self.owsDeleteRemainingObjects(existingData, destinationIndex: dstIndex, managedObjectContext: moc, syncContext: context) return resultSet } // MARK: - Private /** Update the result set with a given object - parameter srcMO: the object to insert in the results - parameter resultSet: the result set - parameter key: a user key comparison - parameter moc: the context in which the operation should occur - parameter context: a user context */ private static func owsUpdateObject( object srcMO: AnyObject, updatedObject: AnyObject, inout resultSet: NSMutableSet, key: String, managedObjectContext moc: NSManagedObjectContext, syncContext context: AnyObject?) { if let updated = self.sfUpdateObjectWithData(srcMO, updatedObject: updatedObject, managedObjectContext:moc, context:context) { updated.sfSetObjectPriority(resultSet.count, object:updated, key:key) resultSet.addObject(updated) } } /** Insert in the result set a new inserted object - parameter srcMO: the object to insert in the results - parameter resultSet: the result set - parameter key: a user key comparison - parameter moc: the context in which the operation should occur - parameter context: a user context */ private static func owsInsertObject( object srcMO: AnyObject, inout resultSet: NSMutableSet, key: String, managedObjectContext moc: NSManagedObjectContext, syncContext context: AnyObject?) { if let created: NSManagedObject = self.sfCreateObjectWithData(srcMO, managedObjectContext: moc, context: context) { created.sfSetObjectPriority(resultSet.count, object:created, key:key) /*if resultSet.containsObject(created) { oneWaySwellLogger.trace { return "duplicate created" } }*/ resultSet.addObject(created) } } /** Do the last operation of the one way synchronization process - parameter existingData: Here is the array of the destination data we target to synchronize - parameter dstIndex: The current index in the existingData array - parameter moc: The context in which the operation should be executed - parameter context: a user context, if any */ private static func owsDeleteRemainingObjects( existingData: [AnyObject], destinationIndex dstIndex: Int, managedObjectContext moc: NSManagedObjectContext, syncContext context: AnyObject?) { // The last step consist in deleting all the objects of the core data // that have not been deleted yet if any is remaining. if !((dstIndex >= existingData.count) || (dstIndex < 0)) { for i in dstIndex..<existingData.count { self.sfDeleteObjectWithData(existingData[i], managedObjectContext: moc, context: context) } } } }
apache-2.0
5e0b8df83af72004839703419ea43401
36.069444
133
0.653616
5.074144
false
false
false
false
bingoogolapple/SwiftNote-PartOne
TableViewController/TableViewController/ProvinceViewController.swift
1
1753
// // MainTableViewController.swift // TableViewController // // Created by bingoogol on 14-6-21. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ProvinceViewController:UITableViewController { var provinces:NSArray! var cities:NSDictionary! override func viewDidLoad() { super.viewDidLoad() let bundle = NSBundle.mainBundle() provinces = NSArray(contentsOfFile:bundle.pathForResource("provinces", ofType:"plist")!) cities = NSDictionary(contentsOfFile:bundle.pathForResource("cities",ofType:"plist")!) } override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return provinces.count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cellIdentifier = "myProvince" var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier:cellIdentifier) } cell?.textLabel.text = provinces[indexPath.row] as String return cell } override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { let cityController = segue.destinationViewController as CityViewController let index = self.tableView.indexPathForSelectedRow().row let provinceName = provinces[index] as String cityController.cities = cities[provinceName] as NSArray } override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { } }
apache-2.0
b55d1eb7886fe46e454fa63254cde8e1
35.5
121
0.699029
5.594249
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/ExplicitInitRule.swift
1
4614
import Foundation import SourceKittenFramework public struct ExplicitInitRule: ASTRule, ConfigurationProviderRule, CorrectableRule, OptInRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "explicit_init", name: "Explicit Init", description: "Explicitly calling .init() should be avoided.", kind: .idiomatic, nonTriggeringExamples: [ "import Foundation; class C: NSObject { override init() { super.init() }}", // super "struct S { let n: Int }; extension S { init() { self.init(n: 1) } }", // self "[1].flatMap(String.init)", // pass init as closure "[String.self].map { $0.init(1) }", // initialize from a metatype value "[String.self].map { type in type.init(1) }" // initialize from a metatype value ], triggeringExamples: [ "[1].flatMap{String↓.init($0)}", "[String.self].map { Type in Type↓.init(1) }", // starting with capital assumes as type, "func foo() -> [String] {\n return [1].flatMap { String↓.init($0) }\n}" ], corrections: [ "[1].flatMap{String↓.init($0)}": "[1].flatMap{String($0)}", "func foo() -> [String] {\n return [1].flatMap { String↓.init($0) }\n}": "func foo() -> [String] {\n return [1].flatMap { String($0) }\n}", "class C {\n#if true\nfunc f() {\n[1].flatMap{String.init($0)}\n}\n#endif\n}": "class C {\n#if true\nfunc f() {\n[1].flatMap{String($0)}\n}\n#endif\n}" ] ) public func validate(file: File, kind: SwiftExpressionKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { return violationRanges(in: file, kind: kind, dictionary: dictionary).map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } private let initializerWithType = regex("^[A-Z].*\\.init$") private func violationRanges(in file: File, kind: SwiftExpressionKind, dictionary: [String: SourceKitRepresentable]) -> [NSRange] { func isExpected(_ name: String) -> Bool { let range = NSRange(location: 0, length: name.utf16.count) return !["super.init", "self.init"].contains(name) && initializerWithType.numberOfMatches(in: name, options: [], range: range) != 0 } let length = ".init".utf8.count guard kind == .call, let name = dictionary.name, isExpected(name), let nameOffset = dictionary.nameOffset, let nameLength = dictionary.nameLength, let range = file.contents.bridge() .byteRangeToNSRange(start: nameOffset + nameLength - length, length: length) else { return [] } return [range] } private func violationRanges(in file: File, dictionary: [String: SourceKitRepresentable]) -> [NSRange] { let ranges = dictionary.substructure.flatMap { subDict -> [NSRange] in var ranges = violationRanges(in: file, dictionary: subDict) if let kind = subDict.kind.flatMap(SwiftExpressionKind.init(rawValue:)) { ranges += violationRanges(in: file, kind: kind, dictionary: subDict) } return ranges } return ranges.unique } private func violationRanges(in file: File) -> [NSRange] { return violationRanges(in: file, dictionary: file.structure.dictionary).sorted { lhs, rhs in lhs.location > rhs.location } } public func correct(file: File) -> [Correction] { let matches = violationRanges(in: file) .filter { !file.ruleEnabled(violatingRanges: [$0], for: self).isEmpty } guard !matches.isEmpty else { return [] } let description = type(of: self).description var corrections = [Correction]() var contents = file.contents for range in matches { contents = contents.bridge().replacingCharacters(in: range, with: "") let location = Location(file: file, characterOffset: range.location) corrections.append(Correction(ruleDescription: description, location: location)) } file.write(contents) return corrections } }
mit
47ff1883e26afc3336fcd879591166e3
43.699029
108
0.583406
4.465567
false
false
false
false
jason-wong-9/iOSLetsChill
iOS Lets Chill/PhoneVerficationViewController.swift
1
10909
// // PhoneVerficationViewController.swift // iOS Lets Chill // // Created by Jason Wong on 2016-02-03. // Copyright © 2016 Jason Wong. All rights reserved. // import UIKit import Firebase import SwiftRequest import CoreData class PhoneVerficationViewController: UIViewController, UITextFieldDelegate { @IBOutlet var enterLabel: UILabel! @IBOutlet var phoneTextField: UITextField! @IBOutlet var confirmButton: UIButton! @IBOutlet var spinnerActivity: UIActivityIndicatorView! let code = arc4random_uniform(8999) + 1000 var numberTo = "" @IBAction func confirmAction(sender: AnyObject) { if self.confirmButton.titleLabel!.text == "Confirm" { if self.phoneTextField.text?.characters.count == 0 { let alertController = UIAlertController(title: "Phone Verifcation Required", message: "Missing Phone Number for verifcation!", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } else if self.phoneTextField.text?.characters.count == 14{ self.phoneTextField.enabled = false self.confirmButton.hidden = true self.confirmButton.userInteractionEnabled = false spinnerActivity.startAnimating() numberTo = self.phoneFormatToString(self.phoneTextField.text!) print(code) let data = [ "To" : numberTo, "From" : "+17786550640", "Body" : String(code) as String ] print(numberTo) let swiftRequest = SwiftRequest() swiftRequest.post("https://api.twilio.com/2010-04-01/Accounts/ACd49f32975885a2d612c8e32598197df7/Messages", auth: ["username" : "ACd49f32975885a2d612c8e32598197df7", "password" : "8100a9c8b51620a1e769013d91101401"], data: data, callback: {err, response, body in if err == nil { print("Success: (response)") } else { print("Error: (err)") let alertController = UIAlertController(title: "Problem with SMS", message: "Validation messsage was not successfully sent.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) self.confirmButton.hidden = false self.confirmButton.userInteractionEnabled = true self.phoneTextField.enabled = true } }) self.spinnerActivity.stopAnimating() self.confirmButton.hidden = false self.confirmButton.userInteractionEnabled = true // self.phoneTextField.enabled = true self.confirmButton.setTitle("Next", forState: .Normal) } else { let alertController = UIAlertController(title: "Phone Verifcation Error", message: "Phone Number is invalid.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } else if self.confirmButton.titleLabel!.text == "Next"{ self.phoneTextField.placeholder = "XXXX" self.phoneTextField.text = "" self.phoneTextField.enabled = true self.enterLabel.text = "Enter Validation Code" self.confirmButton.setTitle("OK", forState: .Normal) view.endEditing(true) } else { if self.phoneTextField.text == "" { let alertController = UIAlertController(title: "Phone Verifcation Required", message: "Missing Verification Code!", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } else if self.phoneTextField.text == String(code){ // create firebase user let ref = Firebase(url: "https://letschill.firebaseio.com") let index = numberTo.startIndex.advancedBy(2) var email: String = numberTo.substringFromIndex(index) print(email) email += "@jasonkcwong.com" print(email) ref.createUser(email, password: String(code), withValueCompletionBlock: { error, result in if error != nil { // There was an error creating the account print(error) } else { let uid = result["uid"] as? String print("Successfully created user account with uid: \(uid)") self.view.endEditing(true) ref.authUser(email, password: String(self.code), withCompletionBlock: { error, authData in if error != nil { // There was an error logging in to this account print(error) } else { print("LogIn") //self.performSegueWithIdentifier("DBSegue", sender: nil) // We are now logged in } }) } }) } else { let alertController = UIAlertController(title: "Invalid", message: "You have entered an invalid code for verifcation", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } } func phoneFormatToString(string: String) -> String{ var str = "+1" for char in string.characters{ if char != "(" && char != ")" && char != "-" && char != " " { str.append(char) } } return str } override func viewDidLoad() { super.viewDidLoad() phoneTextField.delegate = self // Do any additional setup after loading the view. } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // Prevent invalid character input, if keyboard is numberpad if textField.keyboardType == UIKeyboardType.PhonePad { if ((string.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)) != nil) { return false; } } if (textField.placeholder == "(XXX) XXX-XXXX") { let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) let components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) let decimalString = components.joinWithSeparator("") as NSString let length = decimalString.length let hasLeadingOne = length > 0 && decimalString.characterAtIndex(0) == (1 as unichar) if length == 0 || (length > 10 && !hasLeadingOne) || length > 11 { let newLength = (textField.text! as NSString).length + (string as NSString).length - range.length as Int return (newLength > 10) ? false : true } var index = 0 as Int let formattedString = NSMutableString() if hasLeadingOne { formattedString.appendString("1 ") index += 1 } if (length - index) > 3 { let areaCode = decimalString.substringWithRange(NSMakeRange(index, 3)) formattedString.appendFormat("(%@) ", areaCode) index += 3 } if length - index > 3 { let prefix = decimalString.substringWithRange(NSMakeRange(index, 3)) formattedString.appendFormat("%@-", prefix) index += 3 } let remainder = decimalString.substringFromIndex(index) formattedString.appendString(remainder) textField.text = formattedString as String return false } else if textField.placeholder == "XXXX"{ let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) let components = newString.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) let decimalString = components.joinWithSeparator("") as NSString let length = decimalString.length if (length > 4) { return false } return true } else { return true } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?){ view.endEditing(true) super.touchesBegan(touches, withEvent: event) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
9b38b1ac3503139bd9ef9971ee545a72
42.458167
130
0.531261
6.039867
false
false
false
false
DataArt/SmartSlides
PresentatorS/Model/BrowsingHandler.swift
1
10438
// // BrowsingHandler.swift // PresentatorS // // Created by Igor Litvinenko on 12/24/14. // Copyright (c) 2014 Igor Litvinenko. All rights reserved. // import MultipeerConnectivity extension MCSessionState { func readableRawValue() -> String { switch (self) { case .Connected: return "Connected" case .Connecting: return "Connecting" case .NotConnected: return "Not connected" } } } protocol BrowsingHandlerDelegate : NSObjectProtocol { func browsingHandlerDidDetermineAdvertiser(peerID: MCPeerID, withState state: MCSessionState) } protocol BrowsingConnectivityDelegate : NSObjectProtocol { func browsingHandlerDidDisconnectedFromPeer(peerID: MCPeerID) func browsingHandlerDidStartDownloadingPresentation(progress: NSProgress, presentationName : String) func browsingHandlerDidReceiveActiveSlideCommand(command : BrowserCommandsHelper.CommandReceiveActiveSlide) func browsingHandlerDidUpdateActiveSlideCommand(command : BrowserCommandsHelper.CommandUpdatePresentationSlide) func browsingHandlerDidReceiveStopPresentationCommand(command : BrowserCommandsHelper.CommandStopCurrentPresentation) } class BrowsingHandler: SessionHandler { weak var browsingDelegate : BrowsingHandlerDelegate? weak var connectivityDelegate : BrowsingConnectivityDelegate? override func setup() { self.commandFactory = BrowserCommandsHelper() } init(browsingDelegate : BrowsingHandlerDelegate?){ self.browsingDelegate = browsingDelegate super.init() } override func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState) { if peerID.displayName.containsString(".pptx") || peerID.displayName.containsString(".key") { Logger.printLine("\(peerID.displayName) state: \(state.rawValue) (2-connected)") browsingDelegate?.browsingHandlerDidDetermineAdvertiser(peerID, withState: state) if state == .Connected { var error: NSError? do { try session.sendData(SessionHandler.dataRequestForCommandType(.GetSharedMaterialsList, parameters: nil), toPeers: [peerID], withMode: MCSessionSendDataMode.Reliable) } catch let error1 as NSError { error = error1 } if let err = error { Logger.printLine("\(__FUNCTION__), \(err.localizedDescription)") } } else if state == .NotConnected { dispatch_async(dispatch_get_main_queue(), { () -> Void in Logger.printLine("ATT: \(peerID.displayName) is disconnected") self.connectivityDelegate?.browsingHandlerDidDisconnectedFromPeer(peerID) AppDelegate.shared.browsingManager.stopPinging() }) } } else { Logger.printLine("\(peerID.displayName) state: \(state.rawValue) (2-connected) found, but is not advertiser") } } override func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID) { self.commandFactory?.commandWithType(SessionHandler.parseResponseToDictionary(data)).execute(session, peers: [peerID]) } override func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress) { connectivityDelegate?.browsingHandlerDidStartDownloadingPresentation(progress, presentationName: resourceName) } override func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError!) { var summaryError: NSError? do { if error == nil { try NSFileManager.defaultManager().moveItemAtURL(localURL, toURL: NSURL.CM_fileURLToSharedPresentationDirectory().URLByAppendingPathComponent(resourceName)) } } catch let excError as NSError { summaryError = excError } if let err = summaryError { Logger.printLine("Get Error on saving presentation \(err.localizedDescription)") } else { Logger.printLine("Saved presentation with name \(NSURL.CM_pathForPresentationWithName(resourceName))") do { try session.sendData(SessionHandler.dataRequestForCommandType(.GetPresentationActiveSlide, parameters: nil), toPeers: [peerID], withMode: MCSessionSendDataMode.Reliable) } catch let excError as NSError { summaryError = excError } } } } class BrowserCommandsHelper: SessionCommandFactory { class CommandGetSharedMaterials: SessionCommand { var items: [String]? required init(parameters: [String : String]) { self.items = parameters["items"]?.componentsSeparatedByString(",") } func execute(session: MCSession, peers: [MCPeerID]) -> (Bool) { var result = true if let items = self.items{ for presentation in items { var error: NSError? var array : [String] = presentation.componentsSeparatedByString("/md5Hex=") let presentationFilename = array[0] as String if !ContentManager.sharedInstance.isResourceAvailable(presentation, directoryType: .Imported){ do { try session.sendData(SessionHandler.dataRequestForCommandType(.GetPresentationWithNameAndCrc, parameters: ["name": presentationFilename]), toPeers: peers, withMode: .Reliable) } catch { result = result && false } if let err = error{ Logger.printLine("Sending request erre \(err.localizedDescription)") } } else { do { try session.sendData(SessionHandler.dataRequestForCommandType(.GetPresentationActiveSlide, parameters: nil), toPeers: peers, withMode: MCSessionSendDataMode.Reliable) } catch let error1 as NSError { error = error1 } } } } return result } } class CommandReceiveActiveSlide: SessionCommand { let presentationName: String let pageNumber: Int? let slidesAmount : Int? required init(parameters: [String : String]) { let name = parameters["name"]! presentationName = NSURL.CM_pathForPresentationWithName((name as NSString).lastPathComponent)!.path! if let page : String? = parameters["page"] { pageNumber = Int(page!) } else { pageNumber = 0 } if let slidesAmount : String? = parameters["slides_amount"] { self.slidesAmount = Int(slidesAmount!) } else { self.slidesAmount = 0 } } func execute(session: MCSession, peers: [MCPeerID]) -> (Bool) { Logger.printLine("Active presentation\(presentationName) and slide \(pageNumber!)") if !presentationName.isEmpty { AppDelegate.shared.browsingManager.stopHeartbeat() AppDelegate.shared.browsingManager.connectivityDelegate?.browsingHandlerDidReceiveActiveSlideCommand(self) AppDelegate.shared.browsingManager.startHeartbeat() } return true } } class CommandUpdatePresentationSlide: SessionCommand { let pageNumber: Int? required init(parameters: [String : String]) { if let page : String? = parameters["page"] { pageNumber = Int(page!) } else { pageNumber = 0 } } func execute(session: MCSession, peers: [MCPeerID]) -> (Bool) { AppDelegate.shared.browsingManager.stopHeartbeat() AppDelegate.shared.browsingManager.connectivityDelegate?.browsingHandlerDidUpdateActiveSlideCommand(self) AppDelegate.shared.browsingManager.startHeartbeat() return true } } class CommandPing: SessionCommand { required init(parameters: [String : String]) {} func execute(session: MCSession, peers: [MCPeerID]) -> (Bool) { AppDelegate.shared.browsingManager.backPingMessageReceived() return true } } class CommandStopCurrentPresentation: SessionCommand { let parameters: [String: String]? required init(parameters: [String : String]) { self.parameters = parameters } func execute(session: MCSession, peers: [MCPeerID]) -> (Bool) { AppDelegate.shared.browsingManager.connectivityDelegate?.browsingHandlerDidReceiveStopPresentationCommand(self) AppDelegate.shared.browsingManager.stopPinging() return true } } func commandWithType(response: [String : String]) -> SessionCommand { var result : SessionCommand = CommandUnknown(parameters: response) let type = CommantType(rawValue: response["type"]!) if let type_local = type { switch type_local { case .GetSharedMaterialsList, .UpdateActivePresentation: result = CommandGetSharedMaterials(parameters: response) case .GetPresentationActiveSlide: result = CommandReceiveActiveSlide(parameters: response) case .UpdatePresentationActiveSlide: result = CommandUpdatePresentationSlide(parameters: response) case .StopPresentation: result = CommandStopCurrentPresentation(parameters: response) case .PingServer: result = CommandPing(parameters: response) default: result = CommandUnknown(parameters: response) } } return result } }
mit
c57ee8e9b36252203d2893812d889acd
41.954733
203
0.614965
5.596783
false
false
false
false
luanlzsn/pos
pos/Classes/pos/Login/Controller/LoginController.swift
1
3174
// // LoginController.swift // pos // // Created by luan on 2017/5/7. // Copyright © 2017年 luan. All rights reserved. // import UIKit class LoginController: AntController { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var userName: UITextField! @IBOutlet weak var passWord: UITextField! override func viewDidLoad() { super.viewDidLoad() navigationController?.isNavigationBarHidden = true if (UserDefaults.standard.object(forKey: kUserName) != nil) { userName.text = UserDefaults.standard.object(forKey: kUserName) as? String passWord.text = UserDefaults.standard.object(forKey: kPassWord) as? String loginClick() } } @IBAction func loginClick() { UIApplication.shared.keyWindow?.endEditing(true) if !Common.isValidateEmail(email: userName.text!) { AntManage.showDelayToast(message: NSLocalizedString("请输入正确的邮箱地址!", comment: "")) return } if (passWord.text?.isEmpty)! { AntManage.showDelayToast(message: NSLocalizedString("请输入密码", comment: "")) return } weak var weakSelf = self AntManage.postRequest(path: "access/generateToken", params: ["email":userName.text!,"password":passWord.text!], successResult: { (response) in AntManage.userModel = UserModel.mj_object(withKeyValues: response["Api"]) AntManage.isLogin = true UserDefaults.standard.set(weakSelf?.userName.text, forKey: kUserName) UserDefaults.standard.set(weakSelf?.passWord.text, forKey: kPassWord) UserDefaults.standard.synchronize() AntManage.showDelayToast(message: NSLocalizedString("登录成功!", comment: "")) weakSelf?.dismiss(animated: true, completion: nil) }, failureResult: { AntManage.showDelayToast(message: NSLocalizedString("用户名或密码错误", comment: "")) }) } @IBAction func checkInClick(_ sender: UIButton) { let alert = UIAlertController(title: NSLocalizedString("签入", comment: ""), message: nil, preferredStyle: .alert) alert.addTextField(configurationHandler: nil) alert.addAction(UIAlertAction(title: NSLocalizedString("确定", comment: ""), style: .default, handler: { (_) in AntLog(message: alert.textFields?.first?.text) })) alert.addAction(UIAlertAction(title: NSLocalizedString("取消", comment: ""), style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } 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
2a99e126fb74fb998e24ffc02f176baa
38.75641
150
0.652693
4.77812
false
false
false
false
frootloops/swift
validation-test/Reflection/inherits_Swift.swift
5
3677
// RUN: %empty-directory(%t) // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/inherits_Swift // RUN: %target-run %target-swift-reflection-test %t/inherits_Swift | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // REQUIRES: executable_test import SwiftReflectionTest class BaseClass { var w: Int = 0 var x: Bool = false } class DerivedClass : BaseClass { var y: Bool = false var z: Int = 0 } // CHECK-64: Reflecting an object. // CHECK-64: Type reference: // CHECK-64: (class inherits_Swift.BaseClass) // CHECK-64: Type info: // CHECK-64-NEXT: (class_instance size=25 alignment=8 stride=32 num_extra_inhabitants=0 // CHECK-64-NEXT: (field name=w offset=16 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0)))) // CHECK-64-NEXT: (field name=x offset=24 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254))))) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class inherits_Swift.BaseClass) // CHECK-32: Type info: // CHECK-32-NEXT: (class_instance size=13 alignment=4 stride=16 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=w offset=8 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))) // CHECK-32-NEXT: (field name=x offset=12 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254))))) let baseObject = BaseClass() reflect(object: baseObject) let derivedObject = DerivedClass() reflect(object: derivedObject) // CHECK-64: Reflecting an object. // CHECK-64: Type reference: // CHECK-64: (class inherits_Swift.DerivedClass) // CHECK-64: Type info: // CHECK-64-NEXT: (class_instance size=40 alignment=8 stride=40 num_extra_inhabitants=0 // CHECK-64-NEXT: (field name=y offset=25 // CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254)))) // CHECK-64-NEXT: (field name=z offset=32 // CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64-NEXT: (field name=_value offset=0 // CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))) // CHECK-32: Reflecting an object. // CHECK-32: Type reference: // CHECK-32: (class inherits_Swift.DerivedClass) // CHECK-32: Type info: // CHECK-32-NEXT: (class_instance size=20 alignment=4 stride=20 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=y offset=13 // CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=254 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=254)))) // CHECK-32-NEXT: (field name=z offset=16 // CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 // CHECK-32-NEXT: (field name=_value offset=0 // CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))) doneReflecting()
apache-2.0
0c967ddefb472889a24548b910727cee
41.755814
141
0.694588
3.134697
false
false
false
false
adrfer/swift
test/PlaygroundTransform/init.swift
20
695
// RUN: rm -rf %t // RUN: mkdir %t // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift // RUN: %target-run %t/main | FileCheck %s // REQUIRES: executable_test class B { init() { } } class C : B { var i : Int var j : Int override init() { i = 3 j = 5 i + j } } let c = C() // CHECK: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='8'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log[c='main.C']
apache-2.0
dca39657e425e09eeb82734b7023be6b
23.821429
139
0.574101
2.90795
false
false
false
false
marcoarment/FCModel
FCModel/FCModel+ObservableObject.swift
1
3794
// // FCModel+BindableObject.swift // // Created by Marco Arment on 10/28/20. // Copyright © 2020 Marco Arment. See included LICENSE file. // import Foundation import Combine import ObjectiveC extension FCModel : ObservableObject, Identifiable { public var objectWillChange: ObservableObjectPublisher { get { let key = UnsafeRawPointer(method(for: #selector(__observableObjectPropertiesWillChange)))! if let obj = objc_getAssociatedObject(self, key) as? ObservableObjectPublisher { return obj } let obj = ObservableObjectPublisher() objc_setAssociatedObject(self, key, obj, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return obj } } // Called from FCModel::observableObjectPropertiesWillChange @objc private func __observableObjectPropertiesWillChange() { objectWillChange.send() } } class FCModelCollection<T: FCModel> : ObservableObject { @Published var instances: [T] private var fetcher: (() -> [T]) private var ignoreChangedFields: Set<String>? private var onlyIfChangedFields: Set<String>? init() { self.fetcher = { T.allInstances() as! [T] } instances = fetcher() NotificationCenter.default.addObserver(self, selector: #selector(fcModelChanged), name: NSNotification.Name.FCModelChange, object: T.self) } init(where whereClause: String?, arguments: [Any]?) { fetcher = { return T.instancesWhere(whereClause ?? "", arguments: arguments ?? []) as! [T] } instances = fetcher() NotificationCenter.default.addObserver(self, selector: #selector(fcModelChanged), name: NSNotification.Name.FCModelChange, object: T.self) } init(_ fetcher: @escaping (() -> [T])) { self.fetcher = fetcher instances = fetcher() NotificationCenter.default.addObserver(self, selector: #selector(fcModelChanged), name: NSNotification.Name.FCModelChange, object: T.self) } init(onlyIfChangedFields: [String]) { self.fetcher = { T.allInstances() as! [T] } self.onlyIfChangedFields = Set(onlyIfChangedFields); instances = fetcher() NotificationCenter.default.addObserver(self, selector: #selector(fcModelChanged), name: NSNotification.Name.FCModelChange, object: T.self) } init(onlyIfChangedFields: [String], _ fetcher: @escaping (() -> [T])) { self.fetcher = fetcher self.onlyIfChangedFields = Set(onlyIfChangedFields); instances = fetcher() NotificationCenter.default.addObserver(self, selector: #selector(fcModelChanged), name: NSNotification.Name.FCModelChange, object: T.self) } init(ignoringChangesInFields: [String]) { self.fetcher = { T.allInstances() as! [T] } self.ignoreChangedFields = Set(ignoringChangesInFields); instances = fetcher() NotificationCenter.default.addObserver(self, selector: #selector(fcModelChanged), name: NSNotification.Name.FCModelChange, object: T.self) } init(ignoringChangesInFields: [String], _ fetcher: @escaping (() -> [T])) { self.fetcher = fetcher self.ignoreChangedFields = Set(ignoringChangesInFields); instances = fetcher() NotificationCenter.default.addObserver(self, selector: #selector(fcModelChanged), name: NSNotification.Name.FCModelChange, object: T.self) } @objc func fcModelChanged(_ notification: Notification) { if let changedFields = notification.userInfo?[FCModelChangedFieldsKey] as? Set<String> { if let ignored = ignoreChangedFields, changedFields.subtracting(ignored).count == 0 { return } if let only = onlyIfChangedFields, changedFields.intersection(only).count == 0 { return } } self.instances = fetcher() } }
mit
336baeb71d53edaf62299401862d90e8
41.144444
146
0.681782
4.457109
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/Store.swift
1
568
// // Store.swift // Wuakup // // Created by Guillermo Gutiérrez on 10/12/14. // Copyright (c) 2014 Yellow Pineapple. All rights reserved. // import Foundation open class Store { public let id: Int public let name: String? public let address: String? public let latitude, longitude: Float? public init(id: Int, name: String?, address: String?, latitude: Float?, longitude: Float?) { self.id = id self.name = name self.address = address self.latitude = latitude self.longitude = longitude } }
mit
d759dfbe603c5155ae1767f80285533e
22.625
96
0.631393
3.9375
false
false
false
false
skywinder/Sync
Examples/AppNet/AppNet/ViewController.swift
1
2059
import UIKit class ViewController: UITableViewController { struct Constanst { static let SYNCCellIdentifier = "CellID" static let SYNCReloadTableNotification = "SYNCReloadTableNotification" } let dataStack: DATAStack lazy var networking: Networking = { [unowned self] in Networking(dataStack: self.dataStack) }() var items = [Data]() // MARK: Initializers required init(dataStack: DATAStack) { self.dataStack = dataStack super.init(nibName: nil, bundle: nil); } required init(coder aDecoder: NSCoder) { assertionFailure("Must use init(dataStack: DATAStack) "); } // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() title = "AppNet" tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: Constanst.SYNCCellIdentifier) fetchCurrentObjects() fetchNewData() } // MARK: Networking methods func fetchNewData() { networking.fetchNewContent { [unowned self] in self.fetchCurrentObjects() } } // MARK: Model methods func fetchCurrentObjects() { let request = NSFetchRequest(entityName: "Data") request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)] items = dataStack.mainContext.executeFetchRequest(request, error: nil) as [Data] tableView.reloadData() } } extension ViewController: UITableViewDataSource { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = self.tableView.dequeueReusableCellWithIdentifier(Constanst.SYNCCellIdentifier) as UITableViewCell let data = self.items[indexPath.row] cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: Constanst.SYNCCellIdentifier) cell.textLabel?.text = data.text cell.textLabel?.numberOfLines = 0 cell.detailTextLabel?.text = data.user.username return cell } }
mit
11049d59b9cf9adcbd65bd67ebc84a36
27.205479
116
0.733851
4.833333
false
false
false
false
material-foundation/material-automation
Sources/ProjectAnalysis.swift
1
10716
/* Copyright 2018 the Material Automation 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import PerfectLib import Foundation import PerfectLogger import PerfectCURL class ProjectAnalysis { class func didMoveCard(githubData: GithubData, githubAPI: GithubAPI) { guard let fromColumn = githubData.changes?.column_from, let toColumn = githubData.projectCard?.column_id, let fromColumnName = githubAPI.getProjectColumnName(columnID: fromColumn), let toColumnName = githubAPI.getProjectColumnName(columnID: toColumn) else { LogFile.error("Couldn't fetch the column ids or column names") return } guard let contentURL = githubData.projectCard?.content_url else { LogFile.info("The moved card isn't an issue, won't do any action to it.") return } if let sender = githubData.sender, fromColumnName == "Backlog" && (toColumnName == "In progress" || toColumnName == "Done") { //assign issue to user let object = githubAPI.getObject(objectURL: contentURL) if let assignees = object?["assignees"] as? [[String: Any]] { if assignees.count == 0 { // Only assign if we can confirm that nobody is already assigned. githubAPI.editIssue(url: contentURL, issueEdit: ["assignees": [sender]]) } } } // Any time a card moves to an in progress column in any project, add it to the current sprint. if toColumnName.lowercased() == "in progress" { if let project = githubAPI.getProjectFromColumn(columnID: toColumn), let projectName = project["name"] as? String, !projectIsSprint(projectName: projectName), let movedObject = githubAPI.getObject(objectURL: contentURL), let contentID = movedObject["id"] as? Int { let contentType = (movedObject["pull_request"] != nil) ? "PullRequest" : "Issue" addContentIDToCurrentSprint(githubData: githubData, githubAPI: githubAPI, contentID: contentID, contentType: contentType, targetColumnName: "In progress") } } if toColumnName == "Done" { //close issue githubAPI.editIssue(url: contentURL, issueEdit: ["state": "closed"]) } if fromColumnName == "Done" && (toColumnName == "Backlog" || toColumnName == "In progress") { //reopen issue githubAPI.editIssue(url: contentURL, issueEdit: ["state": "open"]) } } class func didCloseProject(githubData: GithubData, githubAPI: GithubAPI) { guard let projectName = githubData.project?.name, let url = githubData.url else { LogFile.error("No project name or github url") return } guard projectIsSprint(projectName: projectName), let endDate = projectName.components(separatedBy: " - ").last else { LogFile.info("The project closed didn't fit the regex") return } // Update project name, reopen project guard let projectURL = githubData.project?.url else { LogFile.error("couldn't fetch the project URL") return } let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" guard let lastSprintEndDate = formatter.date(from: endDate), let nextSprintStartDate = Calendar.current.date(byAdding: .day, value: 1, to: lastSprintEndDate), let nextSprintEndDate = Calendar.current.date(byAdding: .day, value: 13, to: nextSprintStartDate) else { LogFile.error("couldn't parse the project date") return } // Rename existing sprint's name to next sprint date and re-open it. let nextSprint = formatter.string(from: nextSprintStartDate) + " - " + formatter.string(from: nextSprintEndDate) githubAPI.updateProject(projectURL: projectURL, projectUpdate: ["name": nextSprint, "state": "open"]) // Create a new project to save last sprint's history guard let projectID = githubAPI.createNewProject(url: url, name: "New Project") else { LogFile.error("The project could not be created") return } githubAPI.updateProject(projectURL: config.githubAPIBaseURL + "/projects/" + projectID, projectUpdate: ["name": projectName, "state": "closed"]) // Create columns for the new sprint project. let backlogID = githubAPI.createProjectColumn(name: "Backlog", projectID: projectID) let inProgressID = githubAPI.createProjectColumn(name: "In progress", projectID: projectID) let doneID = githubAPI.createProjectColumn(name: "Done", projectID: projectID) // Get last sprint's columns. guard let columnsURL = githubData.project?.columns_url else { LogFile.error("couldn't get the columns URL of the previous sprint") return } let projectColumns = githubAPI.getProjectColumnsCardsURLs(columnsURL: columnsURL) for (columnName, cardsURL) in projectColumns { if columnName == "In progress" { for card in githubAPI.listProjectCards(cardsURL: cardsURL) { createCardFromCard(with: card, and: inProgressID, githubAPI: githubAPI) } } else if columnName == "Backlog" { for card in githubAPI.listProjectCards(cardsURL: cardsURL) { createCardFromCard(with: card, and: backlogID, githubAPI: githubAPI) } } else if columnName == "Done" { for card in githubAPI.listProjectCards(cardsURL: cardsURL) { createCardFromCard(with: card, and: doneID, githubAPI: githubAPI) if let cardID = card["id"] as? Int { // Remove Done cards from the sprint githubAPI.deleteProjectCard(cardID: String(cardID)) } } } } } class func addPullRequestToCurrentSprint(githubData: GithubData, githubAPI: GithubAPI) { guard let contentID = githubData.PRData?.id else { LogFile.error("couldn't get the pull request identifier") return } addContentIDToCurrentSprint(githubData: githubData, githubAPI: githubAPI, contentID: contentID, contentType: "PullRequest", targetColumnName: "In progress") } class func addIssueToCurrentSprint(githubData: GithubData, githubAPI: GithubAPI) { guard let contentID = githubData.issueData?.id else { LogFile.error("couldn't get the pull request identifier") return } addContentIDToCurrentSprint(githubData: githubData, githubAPI: githubAPI, contentID: contentID, contentType: "Issue", targetColumnName: "Backlog") } class func addContentIDToCurrentSprint(githubData: GithubData, githubAPI: GithubAPI, contentID: Int, contentType: String, targetColumnName: String) { guard let sprintProject = sprintProjectForRepo(githubData: githubData, githubAPI: githubAPI), let columnsURL = sprintProject["columns_url"] as? String else { LogFile.error("couldn't get the current sprint project") return } let projectColumns = githubAPI.getProjectColumns(columnsURL: columnsURL) for column in projectColumns { guard let columnName = column["name"] as? String else { continue } if columnName != targetColumnName { continue } guard let cardsURL = column["cards_url"] as? String else { continue } // Add the PR to the column. githubAPI.createProjectCard(cardsURL: cardsURL, contentID: contentID, contentType: contentType, note: nil) break } } class func sprintProjectForRepo(githubData: GithubData, githubAPI: GithubAPI) -> [String: Any]? { guard let repoURL = githubData.url else { return nil } let projects = githubAPI.getProjectsForRepo(repoURL: repoURL) return projects.first(where: { project in if let projectName = project["name"] as? String, projectIsSprint(projectName: projectName) { return true } return false }) } private class func projectIsSprint(projectName: String) -> Bool { // Example of regex match: "2018-06-05 - 2018-06-18". let regex = "^[\\d]{4}-[\\d]{2}-[\\d]{2} - [\\d]{4}-[\\d]{2}-[\\d]{2}$" guard projectName.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil else { return false } return true } private class func parseCardContentURL(card: [String: Any], githubAPI: GithubAPI) -> (Int?, String?) { var (contentID, contentType): (Int, String) guard let contentURL = card["content_url"] as? String else { return (nil, nil) } if let issueID = githubAPI.getIssueID(issueURL: contentURL) { contentID = issueID } else { return (nil, nil) } if contentURL.contains(string: "/issues/") { contentType = "Issue" } else if contentURL.contains(string: "/pull/") { contentType = "PullRequest" } else { return (nil, nil) } return (contentID, contentType) } private class func createCardFromCard(with card: [String: Any], and columnID: String?, githubAPI: GithubAPI) { if let columnID = columnID { let note = card["note"] as? String let cardsURL = config.githubAPIBaseURL + "/projects/columns/" + columnID + "/cards" let (contentID, contentType) = parseCardContentURL(card: card, githubAPI: githubAPI) githubAPI.createProjectCard(cardsURL: cardsURL, contentID: contentID, contentType: contentType, note: note) } } }
apache-2.0
faf3cca7df033c8227b0f9513073ec6f
39.590909
116
0.619354
4.624946
false
false
false
false
yskamoona/a-ds
Playground/w2/DSPlayground/DSPlayground/DSClasses/LinkedList/SinglyLinkedList.swift
1
4397
// // SinglyLinkedList.swift // DSPlayground // // Created by Yousra Kamoona on 6/17/17. // Copyright © 2017 ysk. All rights reserved. // import Foundation class SinglyLinkedList: NSObject { var head:SinglyNode? func addNodeAtBegnning(value:Int) { let node = SinglyNode(value:value) if (self.head == nil) { self.head = node } else { node.next = self.head self.head = node } } func addNodeAtEnd(value:Int) { let node = SinglyNode(value: value) guard var currentNode = self.head else { self.head = node return } while (currentNode.next != nil) { currentNode = currentNode.next! } currentNode.next = node } func addNode(value:Int, afterNodeWithValue val:Int) { let addedNode = SinglyNode(value: value) guard let afterNode = findNodeWithValue(value: val) else { print("Couldn't add node. Prev node was not found") return } if afterNode.next == nil { afterNode.next = addedNode } else { addedNode.next = afterNode.next afterNode.next = addedNode } } func addNode(value:Int, beforeNodeWithValue val:Int) { guard let beforeNode = findNodeWithValue(value: val) else { print("couldn't add node. Next node was not found.") return } let addedNode = SinglyNode(value: value) if let prevNode = self.findPrevious(node: beforeNode) { addedNode.next = prevNode.next prevNode.next = addedNode } else { self.head = addedNode addedNode.next = beforeNode } } func removeNodeAtBeginning() { guard let head = self.head else { return } self.head = head.next } func removeNodeAtEnd() { guard var currentNode = self.head else { return } if currentNode.next == nil { self.head = nil } while currentNode.next?.next != nil { currentNode = currentNode.next! } currentNode.next = nil } // Helper methods func findPrevious(node:SinglyNode) -> SinglyNode? { guard var currentNode = self.head else { return nil } while currentNode.next != nil { if currentNode.next === node { return currentNode } currentNode = currentNode.next! } return nil } func contains(node:SinglyNode) -> Bool { guard let head = self.head else { return false } var currentNode = head while currentNode.value != node.value { if (currentNode.next != nil) { currentNode = currentNode.next! } else { return false } } return true } func findNodeWithValue(value:Int) -> SinglyNode? { guard let head = self.head else { return nil } var currentNode = head while currentNode.value != value { if (currentNode.next != nil) { currentNode = currentNode.next! } else { return nil } } return currentNode } func inspectLinkedList() { var linkedListValues:String = "" guard var currentNode = self.head else { print("Linked List Empty") return } if let value = currentNode.value { linkedListValues += "\(value)"} while currentNode.next != nil { currentNode = currentNode.next! if let value = currentNode.value { linkedListValues += ", " + "\(value)" } } print(linkedListValues) } func inspectHead() { guard let headValue = self.head?.value else { print("No Head value was set") return } print("Head value is: \(headValue)") } }
mit
0cdaccc4da12def074b0e5b53ae294e9
21.54359
65
0.490901
4.928251
false
false
false
false
Estimote/iOS-SDK
Examples/swift/Configuration/Configuration/BeaconSetupViewController.swift
1
6380
// // Please report any problems with this app template to [email protected] // import UIKit /** This view controller allows the user to tweak the configuration of the beacon, before the deployment app continues to applying the configuration. Applying the configuration usually means two things: 1. Upload the beacon configuration to Estimote Cloud and/or your own backend. Since beacons only broadcast their identifiers, you usually need to keep extra metadata about them in a remote database. For example, the `BeaconSetupViewController` might allow the user to input the message associated with the beacon. Or just tag the beacon's location (entrance, lobby area, etc.) 2. Writing settings to the beacon hardware. You usually want all your beacons to be set to your custom UUID, tweak power and their advertising interval, etc. Some settings could be derived from the configuration choices made on this screen--e.g., entrance beacons could be set to higher transmit power, etc. The model behind this view controller is `BeaconConfig`, and you will usually want to keep the two in sync. See also: `prepareForSegue` below. **WHAT TO CUSTOMIZE HERE?** Pretty much everything. This is where you will usually want to start. Remember to tweak the `BeaconConfig` struct as well. */ class BeaconSetupViewController: UIViewController, GeoLocatorDelegate { @objc var beacon: ESTDeviceLocationBeacon! @objc var selectedTag: String? { didSet { validate() } } @objc var geoLocator: GeoLocator! @objc var geoLocation: CLLocation? @objc var appBecomeActiveObserver: AnyObject! // MARK: User Interface @IBOutlet weak var saveButton: UIBarButtonItem! @IBOutlet weak var beaconIDLabel: UILabel! @IBOutlet weak var tagsLabel: UILabel! @IBOutlet weak var pickTagButton: UIButton! @IBOutlet weak var aisleNumberTextField: UITextField! @IBOutlet weak var placementSegmentedControl: UISegmentedControl! @IBOutlet weak var geoLocationLabel: UILabel! @IBOutlet weak var geoLocationSpinner: UIActivityIndicatorView! @IBAction func handleTapGesture(_ sender: UITapGestureRecognizer) { view.endEditing(true) } @IBAction func handleAisleNumberChanged(_ sender: UITextField) { validate() } @IBAction func handlePlacementChanged(_ sender: UISegmentedControl) { validate() } override func viewDidLoad() { super.viewDidLoad() geoLocator = GeoLocator(delegate: self) geoLocator.requestLocation() appBecomeActiveObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil) { notification in // when we're coming back from the Settings app (because we asked the user to allow Location Services access), let's retry obtaining geolocation if self.geoLocation == nil && !self.geoLocator.requestInProgress { self.geoLocator.requestLocation() } } } deinit { NotificationCenter.default.removeObserver(appBecomeActiveObserver) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) beaconIDLabel.text = beacon.identifier tagsLabel.text = selectedTag ?? "(no tag)" } // MARK: Config validation & creation @objc func validate() { saveButton.isEnabled = selectedTag != nil && geoLocation != nil && placementSegmentedControl.selectedSegmentIndex != UISegmentedControlNoSegment } func createConfig() -> BeaconConfig { return BeaconConfig( tag: selectedTag!, aisleNumber: aisleNumberTextField.text!.isEmpty ? nil : Int(aisleNumberTextField.text!), placement: Placement(rawValue: placementSegmentedControl.selectedSegmentIndex)!, geoLocation: geoLocation!.coordinate ) } // MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "PerformSetup" { let setupVC = segue.destination as! PerformSetupViewController setupVC.beacon = beacon setupVC.beaconConfig = createConfig() } else if segue.identifier == "ShowTagsPicker" { let tagsVC = (segue.destination as! UINavigationController).topViewController as! TagsViewController tagsVC.selectedTag = selectedTag } else if segue.identifier == "CancelSetup" { beacon.disconnect() } } @IBAction func backToBeaconSetup(_ segue: UIStoryboardSegue) { if segue.identifier == "SaveTags" { let tagsVC = segue.source as! TagsViewController selectedTag = tagsVC.selectedTag } } // MARK: GeoLocator delegate @objc func geoLocator(_ geoLocator: GeoLocator, didDetermineLocation location: CLLocation) { geoLocation = location geoLocationLabel.text = String(format: "%.2f, %.2f, ± %.0f m", geoLocation!.coordinate.latitude, geoLocation!.coordinate.longitude, geoLocation!.horizontalAccuracy) geoLocationSpinner.stopAnimating() validate() } func geoLocator(_ geoLocator: GeoLocator, didFailWithError error: GeoLocatorError) { switch error { case .noLocationFound: let alert = UIAlertController(title: "Couldn't obtain geolocation", message: "Try moving to a slightly different spot, for better GPS or WiFi coverage.", preferredStyle: .alert) let action = UIAlertAction(title: "Retry", style: .default) { action in geoLocator.requestLocation() } alert.addAction(action) self.present(alert, animated: true, completion: nil) case .insufficientPermissions: let alert = UIAlertController(title: "Couldn't obtain geolocation", message: "This app is not authorized to access Location Services. Go to Settings and set Location access to While Using the App.", preferredStyle: .alert) let action = UIAlertAction(title: "Go to Settings", style: .default) { action in UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) } alert.addAction(action) self.present(alert, animated: true, completion: nil) } } }
mit
54585ff9c6e0784dbf5d1bf8178ba06f
40.967105
379
0.694466
5.062698
false
true
false
false
iDurian/KGFloatingDrawer
Example/KGFloatingDrawer-Example/KGDrawerSettingsTableViewController.swift
5
4649
// // KGDrawerSettingsTableViewController.swift // KGDrawerViewController // // Created by Kyle Goddard on 2015-02-16. // Copyright (c) 2015 Kyle Goddard. All rights reserved. // import UIKit import KGFloatingDrawer class KGDrawerSettingsTableViewController: UITableViewController { let resetRowIndex:Int = 4 @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var delayLabel: UILabel! @IBOutlet weak var springVelocityLabel: UILabel! @IBOutlet weak var springDampingLabel: UILabel! var animator: KGDrawerSpringAnimator? var defaultDuration: NSTimeInterval? var defaultDelay: NSTimeInterval? var defaultSpringVelocity: CGFloat? var defaultSpringDamping: CGFloat? @IBOutlet weak var durationSlider: UISlider! @IBOutlet weak var delaySlider: UISlider! @IBOutlet weak var springVelocitySlider: UISlider! @IBOutlet weak var springDampingSlider: UISlider! 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() if let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { animator = appDelegate.drawerViewController.animator captureDefaultValues(animator!) reset() } } func captureDefaultValues(animator:KGDrawerSpringAnimator) { defaultDuration = animator.animationDuration defaultDelay = animator.animationDelay defaultSpringVelocity = animator.initialSpringVelocity defaultSpringDamping = animator.springDamping } func reset() { updateAnimator() updateSliders() updateLabels() } func updateAnimator() { if let currentAnimator = animator { currentAnimator.animationDuration = NSTimeInterval(defaultDuration!) currentAnimator.animationDelay = NSTimeInterval(defaultDelay!) currentAnimator.initialSpringVelocity = defaultSpringVelocity! currentAnimator.springDamping = defaultSpringDamping! } } func updateSliders() { durationSlider.value = Float(defaultDuration!) delaySlider.value = Float(defaultDelay!) springVelocitySlider.value = Float(defaultSpringVelocity!) springDampingSlider.value = Float(defaultSpringDamping!) } func updateLabels() { durationLabel.text = String(format: "%.2f", durationSlider.value) delayLabel.text = String(format: "%.2f", delaySlider.value) springVelocityLabel.text = String(format: "%.2f", springVelocitySlider.value) springDampingLabel.text = String(format: "%.2f", springDampingSlider.value) } @IBAction func durationSliderChanged(sender: UISlider) { durationLabel.text = String(format: "%.2f", sender.value) animator?.animationDuration = NSTimeInterval(sender.value) } @IBAction func delaySliderChanged(sender: UISlider) { delayLabel.text = String(format: "%.2f", sender.value) animator?.animationDelay = NSTimeInterval(sender.value) } @IBAction func springVelocitySliderChanged(sender: UISlider) { springVelocityLabel.text = String(format: "%.2f", sender.value) animator?.initialSpringVelocity = CGFloat(sender.value) } @IBAction func springDampingSliderChanged(sender: UISlider) { springDampingLabel.text = String(format: "%.2f", sender.value) animator?.springDamping = CGFloat(sender.value) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func toggleLeftDrawer(sender: AnyObject) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.toggleLeftDrawer(sender, animated: false) } @IBAction func toggleRightDrawer(sender: AnyObject) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.toggleRightDrawer(sender, animated: true) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var selectedRowIndex:Int = indexPath.section if selectedRowIndex == resetRowIndex { reset() } } }
mit
4841ac7bfc55f00f37bf345d903c8d15
35.896825
113
0.693913
5.450176
false
false
false
false
uacaps/PageMenu
Demos/Demo6/PageMenuConfigurationDemo/PageMenuConfigurationDemo/ViewController.swift
4
1459
// // ViewController.swift // PageMenuConfigurationDemo // // Created by Matthew York on 3/5/17. // Copyright © 2017 Aeron. All rights reserved. // import UIKit import PageMenu class ViewController: UIViewController { var pageMenu: CAPSPageMenu? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setupPageMenu() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setupPageMenu() { //Create controllers let colors = [UIColor.black, UIColor.blue, UIColor.red, UIColor.gray, UIColor.green, UIColor.purple, UIColor.orange, UIColor.brown, UIColor.cyan] let controllers = colors.map { (color: UIColor) -> UIViewController in let controller = UIViewController() controller.view.backgroundColor = color return controller } //Create page menu self.pageMenu = CAPSPageMenu(viewControllers: controllers, in: self, with: dummyConfiguration(), usingStoryboards: true) } func dummyConfiguration() -> CAPSPageMenuConfiguration { let configuration = CAPSPageMenuConfiguration() return configuration } }
bsd-3-clause
b5f3c1d077b1c11b20197b3d60371254
28.16
153
0.658436
5.151943
false
true
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
source/RSTBSupport/Classes/RSRedirectStepGenerator.swift
1
1556
// // RSRedirectStepGenerator.swift // Pods // // Created by James Kizer on 7/29/17. // // import UIKit import ResearchSuiteTaskBuilder import ResearchKit import Gloss open class RSRedirectStepGenerator: RSTBBaseStepGenerator { public init(){} open var supportedTypes: [String]! { return nil } open func getDelegate(helper: RSTBTaskBuilderHelper) -> RSRedirectStepDelegate? { return nil } open func generateStep(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ORKStep? { guard let stepDescriptor = RSRedirectStepDescriptor(json:jsonObject), let delegate = self.getDelegate(helper: helper) else { return nil } let buttonText: String = helper.localizationHelper.localizedString(stepDescriptor.buttonText) let step = RSRedirectStep( identifier: stepDescriptor.identifier, title: helper.localizationHelper.localizedString(stepDescriptor.title), text: helper.localizationHelper.localizedString(stepDescriptor.text), buttonText: buttonText, delegate: delegate ) step.isOptional = stepDescriptor.optional return step } open func processStepResult(type: String, jsonObject: JsonObject, result: ORKStepResult, helper: RSTBTaskBuilderHelper) -> JSON? { return nil } }
apache-2.0
98fe6fe7de9c6ef0d7731dff35d253ba
27.290909
103
0.609897
5.421603
false
false
false
false
icecrystal23/ios-charts
Source/Charts/Renderers/ChartDataRendererBase.swift
2
3727
// // DataRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(ChartDataRendererBase) open class DataRenderer: Renderer { /// An array of accessibility elements that are presented to the ChartViewBase accessibility methods. /// /// Note that the order of elements in this array determines the order in which they are presented and navigated by /// Accessibility clients such as VoiceOver. /// /// Renderers should ensure that the order of elements makes sense to a client presenting an audio-only interface to a user. /// Subclasses should populate this array in drawData() or drawDataSet() to make the chart accessible. @objc final var accessibleChartElements: [NSUIAccessibilityElement] = [] @objc public let animator: Animator @objc public init(animator: Animator, viewPortHandler: ViewPortHandler) { self.animator = animator super.init(viewPortHandler: viewPortHandler) } @objc open func drawData(context: CGContext) { fatalError("drawData() cannot be called on DataRenderer") } @objc open func drawValues(context: CGContext) { fatalError("drawValues() cannot be called on DataRenderer") } @objc open func drawExtras(context: CGContext) { fatalError("drawExtras() cannot be called on DataRenderer") } /// Draws all highlight indicators for the values that are currently highlighted. /// /// - parameter indices: the highlighted values @objc open func drawHighlighted(context: CGContext, indices: [Highlight]) { fatalError("drawHighlighted() cannot be called on DataRenderer") } /// An opportunity for initializing internal buffers used for rendering with a new size. /// Since this might do memory allocations, it should only be called if necessary. @objc open func initBuffers() { } @objc open func isDrawingValuesAllowed(dataProvider: ChartDataProvider?) -> Bool { guard let data = dataProvider?.data else { return false } return data.entryCount < Int(CGFloat(dataProvider?.maxVisibleCount ?? 0) * viewPortHandler.scaleX) } /// Creates an ```NSUIAccessibilityElement``` that acts as the first and primary header describing a chart view. /// /// - Parameters: /// - chart: The chartView object being described /// - data: A non optional data source about the chart /// - defaultDescription: A simple string describing the type/design of Chart. /// - Returns: A header ```NSUIAccessibilityElement``` that can be added to accessibleChartElements. @objc internal func createAccessibleHeader(usingChart chart: ChartViewBase, andData data: ChartData, withDefaultDescription defaultDescription: String = "Chart") -> NSUIAccessibilityElement { let chartDescriptionText = chart.chartDescription?.text ?? defaultDescription let dataSetDescriptions = data.dataSets.map { $0.label ?? "" } let dataSetDescriptionText = dataSetDescriptions.joined(separator: ", ") let dataSetCount = data.dataSets.count let element = NSUIAccessibilityElement(accessibilityContainer: chart) element.accessibilityLabel = chartDescriptionText + ". \(dataSetCount) dataset\(dataSetCount == 1 ? "" : "s"). \(dataSetDescriptionText)" element.accessibilityFrame = chart.bounds element.isHeader = true return element } }
apache-2.0
57648cc2fb4725db007f663a9bcb90a4
39.075269
145
0.684733
5.219888
false
false
false
false
ChrisStayte/Pokedex
Pokedex/MoveCell.swift
1
782
// // MoveCell.swift // Pokedex // // Created by ChrisStayte on 1/24/16. // Copyright © 2016 ChrisStayte. All rights reserved. // import UIKit class MoveCell: UITableViewCell { @IBOutlet weak var nameLbl: UILabel! @IBOutlet weak var learnTypeLabel: UILabel! @IBOutlet weak var levelLbl: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configureCell(move: Move) { print (move.name) nameLbl.text = move.name.capitalizedString learnTypeLabel.text = "Learn Type: \(move.learnType.capitalizedString)" if move.level != "" { levelLbl.text = "Level: \(move.level)" } else { levelLbl.text = move.level } } }
mit
b73de30be441880aa5b7ddec81a7eb05
21.970588
79
0.606914
4.110526
false
false
false
false
kjantzer/FolioReaderKit
Source/Models/Highlight+Helper.swift
1
10320
// // Highlight+Helper.swift // FolioReaderKit // // Created by Heberti Almeida on 06/07/16. // Copyright (c) 2015 Folio Reader. All rights reserved. // import Foundation import RealmSwift /** HighlightStyle type, default is .Yellow. */ public enum HighlightStyle: Int { case Yellow case Green case Blue case Pink case Underline public init () { self = .Yellow } /** Return HighlightStyle for CSS class. */ public static func styleForClass(className: String) -> HighlightStyle { switch className { case "highlight-yellow": return .Yellow case "highlight-green": return .Green case "highlight-blue": return .Blue case "highlight-pink": return .Pink case "highlight-underline": return .Underline default: return .Yellow } } /** Return CSS class for HighlightStyle. */ public static func classForStyle(style: Int) -> String { switch style { case HighlightStyle.Yellow.rawValue: return "highlight-yellow" case HighlightStyle.Green.rawValue: return "highlight-green" case HighlightStyle.Blue.rawValue: return "highlight-blue" case HighlightStyle.Pink.rawValue: return "highlight-pink" case HighlightStyle.Underline.rawValue: return "highlight-underline" default: return "highlight-yellow" } } /** Return CSS class for HighlightStyle. */ public static func colorForStyle(style: Int, nightMode: Bool = false) -> UIColor { switch style { case HighlightStyle.Yellow.rawValue: return UIColor(red: 255/255, green: 235/255, blue: 107/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.Green.rawValue: return UIColor(red: 192/255, green: 237/255, blue: 114/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.Blue.rawValue: return UIColor(red: 173/255, green: 216/255, blue: 255/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.Pink.rawValue: return UIColor(red: 255/255, green: 176/255, blue: 202/255, alpha: nightMode ? 0.9 : 1) case HighlightStyle.Underline.rawValue: return UIColor(red: 240/255, green: 40/255, blue: 20/255, alpha: nightMode ? 0.6 : 1) default: return UIColor(red: 255/255, green: 235/255, blue: 107/255, alpha: nightMode ? 0.9 : 1) } } } /// Completion block public typealias Completion = (error: NSError?) -> () extension Highlight { /** Save a Highlight with completion block - parameter completion: Completion block */ public func persist(completion: Completion? = nil) { do { let realm = try! Realm() realm.beginWrite() realm.add(self, update: true) try realm.commitWrite() completion?(error: nil) } catch let error as NSError { print("Error on persist highlight: \(error)") completion?(error: error) } } /** Remove a Highlight */ public func remove() { do { let realm = try! Realm() realm.beginWrite() realm.delete(self) try realm.commitWrite() } catch let error as NSError { print("Error on remove highlight: \(error)") } } /** Remove a Highlight by ID - parameter highlightId: The ID to be removed */ public static func removeById(highlightId: String) { var highlight: Highlight? let predicate = NSPredicate(format:"highlightId = %@", highlightId) let realm = try! Realm() highlight = realm.objects(Highlight).filter(predicate).toArray(Highlight).first highlight?.remove() } /** Update a Highlight by ID - parameter highlightId: The ID to be removed - parameter type: The `HighlightStyle` */ public static func updateById(highlightId: String, type: HighlightStyle) { var highlight: Highlight? let predicate = NSPredicate(format:"highlightId = %@", highlightId) do { let realm = try! Realm() highlight = realm.objects(Highlight).filter(predicate).toArray(Highlight).first realm.beginWrite() highlight?.type = type.hashValue try realm.commitWrite() } catch let error as NSError { print("Error on updateById : \(error)") } } /** Return a list of Highlights with a given ID - parameter bookId: Book ID - parameter page: Page number - returns: Return a list of Highlights */ public static func allByBookId(bookId: String, andPage page: NSNumber? = nil) -> [Highlight] { var highlights: [Highlight]? let predicate = (page != nil) ? NSPredicate(format: "bookId = %@ && page = %@", bookId, page!) : NSPredicate(format: "bookId = %@", bookId) let realm = try! Realm() highlights = realm.objects(Highlight).filter(predicate).toArray(Highlight) ?? [Highlight]() return highlights! } /** Return all Highlights - returns: Return all Highlights */ public static func all() -> [Highlight] { var highlights: [Highlight]? let realm = try! Realm() highlights = realm.objects(Highlight).toArray(Highlight) ?? [Highlight]() return highlights! } // MARK: HTML Methods /** Match a highlight on string. */ public static func matchHighlight(text: String!, andId id: String, startOffset: String, endOffset: String) -> Highlight? { let pattern = "<highlight id=\"\(id)\" onclick=\".*?\" class=\"(.*?)\">((.|\\s)*?)</highlight>" let regex = try! NSRegularExpression(pattern: pattern, options: []) let matches = regex.matchesInString(text, options: [], range: NSRange(location: 0, length: text.utf16.count)) let str = (text as NSString) let mapped = matches.map { (match) -> Highlight in var contentPre = str.substringWithRange(NSRange(location: match.range.location-kHighlightRange, length: kHighlightRange)) var contentPost = str.substringWithRange(NSRange(location: match.range.location + match.range.length, length: kHighlightRange)) // Normalize string before save if contentPre.rangeOfString(">") != nil { let regex = try! NSRegularExpression(pattern: "((?=[^>]*$)(.|\\s)*$)", options: []) let searchString = regex.firstMatchInString(contentPre, options: .ReportProgress, range: NSRange(location: 0, length: contentPre.characters.count)) if searchString!.range.location != NSNotFound { contentPre = (contentPre as NSString).substringWithRange(searchString!.range) } } if contentPost.rangeOfString("<") != nil { let regex = try! NSRegularExpression(pattern: "^((.|\\s)*?)(?=<)", options: []) let searchString = regex.firstMatchInString(contentPost, options: .ReportProgress, range: NSRange(location: 0, length: contentPost.characters.count)) if searchString!.range.location != NSNotFound { contentPost = (contentPost as NSString).substringWithRange(searchString!.range) } } let highlight = Highlight() highlight.highlightId = id highlight.type = HighlightStyle.styleForClass(str.substringWithRange(match.rangeAtIndex(1))).rawValue highlight.date = NSDate() highlight.content = Highlight.removeSentenceSpam(str.substringWithRange(match.rangeAtIndex(2))) highlight.contentPre = Highlight.removeSentenceSpam(contentPre) highlight.contentPost = Highlight.removeSentenceSpam(contentPost) highlight.page = currentPageNumber highlight.bookId = (kBookId as NSString).stringByDeletingPathExtension highlight.startOffset = Int(startOffset) ?? -1 highlight.endOffset = Int(endOffset) ?? -1 return highlight } return mapped.first } /** Remove a Highlight from HTML by ID - parameter highlightId: The ID to be removed - returns: The removed id */ public static func removeFromHTMLById(highlightId: String) -> String? { guard let currentPage = FolioReader.sharedInstance.readerCenter.currentPage else { return nil } if let removedId = currentPage.webView.js("removeHighlightById('\(highlightId)')") { return removedId } else { print("Error removing Higlight from page") return nil } } /** Remove span tag before store the highlight, this span is added on JavaScript. <span class=\"sentence\"></span> - parameter text: Text to analise - returns: Striped text */ public static func removeSentenceSpam(text: String) -> String { // Remove from text func removeFrom(text: String, withPattern pattern: String) -> String { var locator = text let regex = try! NSRegularExpression(pattern: pattern, options: []) let matches = regex.matchesInString(locator, options: [], range: NSRange(location: 0, length: locator.utf16.count)) let str = (locator as NSString) var newLocator = "" for match in matches { newLocator += str.substringWithRange(match.rangeAtIndex(1)) } if matches.count > 0 && !newLocator.isEmpty { locator = newLocator } return locator } let pattern = "<span class=\"sentence\">((.|\\s)*?)</span>" let cleanText = removeFrom(text, withPattern: pattern) return cleanText } }
bsd-3-clause
af33f2c9f2289b47accba02739e7035c
34.712803
165
0.583333
4.930721
false
false
false
false
opfeffer/swift-sodium
SodiumTests/SodiumTests.swift
1
14911
// // SodiumTests.swift // SodiumTests // // Created by Frank Denis on 12/27/14. // Copyright (c) 2014 Frank Denis. All rights reserved. // import XCTest import Sodium extension String { func toData() -> Data? { return self.data(using: .utf8, allowLossyConversion: false) } } extension Data { func toString() -> String? { return String(data: self, encoding: .utf8) } } class SodiumTests: XCTestCase { let sodium = Sodium(())! override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testBox() { let message = "My Test Message".toData()! let aliceKeyPair = sodium.box.keyPair()! let bobKeyPair = sodium.box.keyPair()! let encryptedMessageFromAliceToBob: Data = sodium.box.seal(message: message, recipientPublicKey: bobKeyPair.publicKey, senderSecretKey: aliceKeyPair.secretKey)! let decrypted = sodium.box.open(nonceAndAuthenticatedCipherText: encryptedMessageFromAliceToBob, senderPublicKey: bobKeyPair.publicKey, recipientSecretKey: aliceKeyPair.secretKey) XCTAssertEqual(decrypted, message) let (encryptedMessageFromAliceToBob2, nonce): (Data, Box.Nonce) = sodium.box.seal(message: message, recipientPublicKey: bobKeyPair.publicKey, senderSecretKey: aliceKeyPair.secretKey)! let decrypted2 = sodium.box.open(authenticatedCipherText: encryptedMessageFromAliceToBob2, senderPublicKey: aliceKeyPair.publicKey, recipientSecretKey: bobKeyPair.secretKey, nonce: nonce) XCTAssertEqual(decrypted2, message) let (encryptedMessageFromAliceToBob3, nonce2, mac): (Data, Box.Nonce, Box.MAC) = sodium.box.seal(message: message, recipientPublicKey: bobKeyPair.publicKey, senderSecretKey: aliceKeyPair.secretKey)! let decrypted3 = sodium.box.open(authenticatedCipherText: encryptedMessageFromAliceToBob3, senderPublicKey: aliceKeyPair.publicKey, recipientSecretKey: bobKeyPair.secretKey, nonce: nonce2, mac: mac) XCTAssertEqual(decrypted3, message) let userNonce = sodium.randomBytes.buf(length: sodium.box.NonceBytes)! let encryptedMessageFromAliceToBob4: Data = sodium.box.seal(message: message, recipientPublicKey: bobKeyPair.publicKey, senderSecretKey: aliceKeyPair.secretKey, nonce: userNonce)! let decrypted4 = sodium.box.open(authenticatedCipherText: encryptedMessageFromAliceToBob4, senderPublicKey: bobKeyPair.publicKey, recipientSecretKey: aliceKeyPair.secretKey, nonce: userNonce) XCTAssertEqual(message, decrypted4) let encryptedMessageToBob: Data = sodium.box.seal(message: message, recipientPublicKey: bobKeyPair.publicKey)! let decrypted5 = sodium.box.open(anonymousCipherText: encryptedMessageToBob, recipientPublicKey: bobKeyPair.publicKey, recipientSecretKey: bobKeyPair.secretKey) XCTAssertEqual(decrypted5, message) // beforenm tests // The two beforenm keys calculated by Alice and Bob separately should be identical let aliceBeforenm = sodium.box.beforenm(recipientPublicKey: bobKeyPair.publicKey, senderSecretKey: aliceKeyPair.secretKey)! let bobBeforenm = sodium.box.beforenm(recipientPublicKey: aliceKeyPair.publicKey, senderSecretKey: bobKeyPair.secretKey)! XCTAssertEqual(aliceBeforenm, bobBeforenm) // Make sure the encryption using beforenm works let encryptedMessageBeforenm: Data = sodium.box.seal(message: message, beforenm: aliceBeforenm)! let decryptedBeforenm = sodium.box.open(nonceAndAuthenticatedCipherText: encryptedMessageBeforenm, beforenm: aliceBeforenm) XCTAssertEqual(decryptedBeforenm, message) let (encryptedMessageBeforenm2, nonceBeforenm): (Data, Box.Nonce) = sodium.box.seal(message: message, beforenm: aliceBeforenm)! let decryptedBeforenm2 = sodium.box.open(authenticatedCipherText: encryptedMessageBeforenm2, beforenm: aliceBeforenm, nonce: nonceBeforenm) XCTAssertEqual(decryptedBeforenm2, message) } func testSecretBox() { let message = "My Test Message".toData()! let secretKey = sodium.secretBox.key()! // test simple nonce + mac + message box let encrypted: Data = sodium.secretBox.seal(message: message, secretKey: secretKey)! let decrypted = sodium.secretBox.open(nonceAndAuthenticatedCipherText: encrypted, secretKey: secretKey)! XCTAssertEqual(decrypted, message) XCTAssertNotEqual(sodium.secretBox.seal(message: message, secretKey: secretKey), encrypted, "Ciphertext of two encryption operations on the same plaintext shouldn't be equal. Make sure the nonce was used only once!") XCTAssertNil(sodium.secretBox.open(nonceAndAuthenticatedCipherText: encrypted, secretKey: sodium.secretBox.key()!), "Shouldn't be able to decrypt with a bad key") // test (mac + message, nonce) box let (encrypted2, nonce2) = sodium.secretBox.seal(message: message, secretKey: secretKey)! let decrypted2 = sodium.secretBox.open(authenticatedCipherText: encrypted2, secretKey: secretKey, nonce: nonce2) XCTAssertEqual(decrypted2, message) XCTAssertNil(sodium.secretBox.open(authenticatedCipherText: encrypted2, secretKey: secretKey, nonce: sodium.secretBox.nonce()), "Shouldn't be able to decrypt with an invalid nonce") // test (message, nonce, mac) box let (encrypted3, nonce3, mac3) = sodium.secretBox.seal(message: message, secretKey: secretKey)! let decrypted3 = sodium.secretBox.open(cipherText: encrypted3, secretKey: secretKey, nonce: nonce3, mac: mac3) XCTAssertEqual(decrypted3, message) let (encrypted4, nonce4, mac4) = sodium.secretBox.seal(message: message, secretKey: secretKey)! XCTAssertNil(sodium.secretBox.open(cipherText: encrypted4, secretKey: secretKey, nonce: nonce3, mac: mac4), "Shouldn't be able to decrypt with an invalid MAC") XCTAssertNil(sodium.secretBox.open(cipherText: encrypted4, secretKey: secretKey, nonce: nonce4, mac: mac3), "Shouldn't be able to decrypt with an invalid nonce") } func testGenericHash() { let message = "My Test Message".toData()! let h1 = sodium.utils.bin2hex(sodium.genericHash.hash(message: message)!)! XCTAssertEqual(h1, "64a9026fca646c31df54426ad15a341e2444d8a1863d57eb27abecf239609f75") let key = sodium.utils.hex2bin("64 a9 02 6f ca 64 6c 31 df 54", ignore: " ") let h2 = sodium.utils.bin2hex(sodium.genericHash.hash(message: message, key: key)!)! XCTAssertEqual(h2, "1773f324cba2e7b0017e32d7e44f7afd1036c5d4ef9a80ae0e52e95a629844cd") let h3 = sodium.utils.bin2hex(sodium.genericHash.hash(message: message, key: key, outputLength: sodium.genericHash.BytesMax)!)! XCTAssertEqual(h3, "cba85e39f2d03923b2f66aba99b204333edc34a8443ab1700f7920c7abcc6639963a953f35162a520b21072ab906457d21f1645e6e3985858ee95a84d0771f07") let s1 = sodium.genericHash.initStream()! XCTAssertTrue(s1.update(input: message)) let h4 = sodium.utils.bin2hex(s1.final()!)! XCTAssertEqual(h4, h1) let s2 = sodium.genericHash.initStream(key: key, outputLength: sodium.genericHash.Bytes)! XCTAssertTrue(s2.update(input: message)) let h5 = sodium.utils.bin2hex(s2.final()!)! XCTAssertEqual(h5, h2) let s3 = sodium.genericHash.initStream(key: key, outputLength: sodium.genericHash.BytesMax)! XCTAssertTrue(s3.update(input: message)) let h6 = sodium.utils.bin2hex(s3.final()!)! XCTAssertEqual(h6, h3) } func testRandomBytes() { let randomLen = 100 + Int(sodium.randomBytes.uniform(upperBound: 100)) let random1 = sodium.randomBytes.buf(length: randomLen)! let random2 = sodium.randomBytes.buf(length: randomLen)! XCTAssertEqual(random1.count, randomLen) XCTAssertEqual(random2.count, randomLen) XCTAssertNotEqual(random1, random2) var c1 = 0 let ref1 = self.sodium.randomBytes.random() for _ in (0..<100) { if sodium.randomBytes.random() == ref1 { c1 += 1 } } XCTAssert(c1 < 10) var c2 = 0 let ref2 = self.sodium.randomBytes.uniform(upperBound: 100_000) for _ in (0..<100) { if sodium.randomBytes.uniform(upperBound: 100_000) == ref2 { c2 += 1 } } XCTAssert(c2 < 10) let seed = sodium.utils.hex2bin("00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff", ignore: " ")! let randomd = sodium.utils.bin2hex(sodium.randomBytes.deterministic(length: 10, seed: seed)!)!; XCTAssertEqual(randomd, "444dc0602207c270b93f"); } func testShortHash() { let message = "My Test Message".toData()! let key = sodium.utils.hex2bin("00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff", ignore: " ")! let h = sodium.utils.bin2hex(sodium.shortHash.hash(message: message, key: key)!)! XCTAssertEqual(h, "bb9be85c918015ea") } func testSignature() { let message = "My Test Message".toData()! let keyPair = sodium.sign.keyPair(seed: sodium.utils.hex2bin("00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff", ignore: " ")!)! let signedMessage = sodium.sign.sign(message: message, secretKey: keyPair.secretKey)! XCTAssertEqual(sodium.utils.bin2hex(signedMessage)!, "ce8437d58a27c4d91426d35b24cfaf1e49f95b213c15eddb198f4a8d24c0fdd0df3e7f7a894f60ec15cff25b5f6f27399ce01db0e2649fc54c91cafb8dd48a094d792054657374204d657373616765") let signature = sodium.sign.signature(message: message, secretKey: keyPair.secretKey)! XCTAssertEqual(sodium.utils.bin2hex(signature)!, "ce8437d58a27c4d91426d35b24cfaf1e49f95b213c15eddb198f4a8d24c0fdd0df3e7f7a894f60ec15cff25b5f6f27399ce01db0e2649fc54c91cafb8dd48a09") XCTAssertTrue(sodium.sign.verify(signedMessage: signedMessage, publicKey: keyPair.publicKey)) XCTAssertTrue(sodium.sign.verify(message: message, publicKey: keyPair.publicKey, signature: signature)) let unsignedMessage = sodium.sign.open(signedMessage: signedMessage, publicKey: keyPair.publicKey)! XCTAssertEqual(unsignedMessage, message) } func testUtils() { var dataToZero = Data(bytes: [1, 2, 3, 4] as [UInt8]) sodium.utils.zero(&dataToZero) XCTAssert(dataToZero == Data(bytes: [0, 0, 0, 0] as [UInt8])) var dataToZero2 = Data(bytes: [1, 2, 3, 4] as [UInt8]) sodium.utils.zero(&dataToZero2) XCTAssert(dataToZero2 == Data(bytes: [0, 0, 0, 0,] as [UInt8])) let eq1 = Data(bytes: [1, 2, 3, 4] as [UInt8]) let eq2 = Data(bytes: [1, 2, 3, 4] as [UInt8]) let eq3 = Data(bytes: [1, 2, 3, 5] as [UInt8]) let eq4 = Data(bytes: [1, 2, 3] as [UInt8]) XCTAssertTrue(sodium.utils.equals(eq1, eq2)) XCTAssertFalse(sodium.utils.equals(eq1, eq3)) XCTAssertFalse(sodium.utils.equals(eq1, eq4)) XCTAssertEqual(sodium.utils.compare(eq1, eq2)!, 0) XCTAssertEqual(sodium.utils.compare(eq1, eq3)!, -1) XCTAssertEqual(sodium.utils.compare(eq3, eq2)!, 1) XCTAssertNil(sodium.utils.compare(eq1, eq4)) let bin = sodium.utils.hex2bin("deadbeef")! let hex = sodium.utils.bin2hex(bin) XCTAssertEqual(hex, "deadbeef") let bin2 = sodium.utils.hex2bin("de-ad be:ef", ignore: ":- ")! XCTAssertEqual(bin2, bin) } func testScrypt() { let passwordLen = Int(sodium.randomBytes.uniform(upperBound: 64)) let password = sodium.randomBytes.buf(length: passwordLen)! let hash = sodium.pwHash.scrypt.str(passwd: password, opsLimit: sodium.pwHash.scrypt.OpsLimitInteractive, memLimit: sodium.pwHash.scrypt.MemLimitInteractive) XCTAssertEqual(hash?.lengthOfBytes(using: String.Encoding.utf8), sodium.pwHash.scrypt.StrBytes) let verify = sodium.pwHash.scrypt.strVerify(hash: hash!, passwd: password) XCTAssertTrue(verify) let password2 = sodium.randomBytes.buf(length: passwordLen)! let verify2 = sodium.pwHash.scrypt.strVerify(hash: hash!, passwd: password2) XCTAssertFalse(verify2) let password3 = "My Test Message".toData()! let salt = Data(bytes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32] as [UInt8]) let hash2 = sodium.pwHash.scrypt.hash(outputLength: 64, passwd: password3, salt: salt, opsLimit: sodium.pwHash.scrypt.OpsLimitInteractive, memLimit: sodium.pwHash.scrypt.MemLimitInteractive) NSLog(sodium.utils.bin2hex(hash2!)!) XCTAssertEqual(sodium.utils.bin2hex(hash2!)!, "6f00c5630b0a113be73721d2bab7800c0fce4b4e7a74451704b53afcded3d9e85fbe1acea7d2aa0fecb3027e35d745547b1041d6c51f731bd0aa934da89f7adf") } func testPwHash() { let passwordLen = Int(sodium.randomBytes.uniform(upperBound: 64)) let password = sodium.randomBytes.buf(length: passwordLen)! let hash = sodium.pwHash.str(passwd: password, opsLimit: sodium.pwHash.OpsLimitInteractive, memLimit: sodium.pwHash.MemLimitInteractive) XCTAssertEqual(hash?.lengthOfBytes(using: String.Encoding.utf8), sodium.pwHash.StrBytes) let verify = sodium.pwHash.strVerify(hash: hash!, passwd: password) XCTAssertTrue(verify) let password2 = sodium.randomBytes.buf(length: passwordLen)! let verify2 = sodium.pwHash.strVerify(hash: hash!, passwd: password2) XCTAssertFalse(verify2) let password3 = "My Test Message".toData()! let salt = Data(bytes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] as [UInt8]) let hash2 = sodium.pwHash.hash(outputLength: 64, passwd: password3, salt: salt, opsLimit: sodium.pwHash.OpsLimitInteractive, memLimit: sodium.pwHash.MemLimitInteractive) XCTAssertEqual(sodium.utils.bin2hex(hash2!)!, "51d659ee6f8790042688274c5bc8a6296390cdc786d2341c3553b01a5c3f7ff1190e04b86a878538b17ef10e74baa19295479f3e3ee587ce571f366fc66e2fdc") } func testKeyExchange() { let aliceKeyPair = sodium.keyExchange.keyPair()! let bobKeyPair = sodium.keyExchange.keyPair()! let sessionKeyPairForAlice = sodium.keyExchange.sessionKeyPair(publicKey: aliceKeyPair.publicKey, secretKey: aliceKeyPair.secretKey, otherPublicKey: bobKeyPair.publicKey, side: .client)! let sessionKeyPairForBob = sodium.keyExchange.sessionKeyPair(publicKey: bobKeyPair.publicKey, secretKey: bobKeyPair.secretKey, otherPublicKey: aliceKeyPair.publicKey, side: .server)! XCTAssertEqual(sessionKeyPairForAlice.rx, sessionKeyPairForBob.tx) XCTAssertEqual(sessionKeyPairForAlice.tx, sessionKeyPairForBob.rx) } }
isc
bd51fa0eba54edb3455a2c2a3e322ea5
55.056391
224
0.707531
3.542647
false
true
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/ImageCodec/Encoder/WEBPEncoder.swift
1
9587
// // WEBPEncoder.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. 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. // struct WEBPEncoder: ImageRepEncoder { let width: Int let height: Int let bytesPerRow: Int let format: PixelFormat let pixels: Data let iccData: Data? var quality: Double? } extension WEBPEncoder { static func encode(image: AnyImage, properties: [ImageRep.PropertyKey: Any]) -> Data? { let pixels: Data let bytesPerRow: Int let format: PixelFormat let iccData: Data switch image.base { case let image as Image<RGBA32ColorPixel>: guard let _iccData = image.colorSpace.iccData else { return encode(image: image.convert(to: .sRGB), properties: properties) } pixels = image.pixels.data bytesPerRow = 4 * image.width format = image.isOpaque ? .RGBX : .RGBA iccData = _iccData case let image as Image<BGRA32ColorPixel>: guard let _iccData = image.colorSpace.iccData else { return encode(image: image.convert(to: .sRGB), properties: properties) } pixels = image.pixels.data bytesPerRow = 4 * image.width format = image.isOpaque ? .BGRX : .BGRA iccData = _iccData default: let image = Image<RGBA32ColorPixel>(image) ?? image.convert(to: .sRGB) guard let _iccData = image.colorSpace.iccData else { return encode(image: image.convert(to: .sRGB), properties: properties) } pixels = image.pixels.data bytesPerRow = 4 * image.width format = image.isOpaque ? .RGBX : .RGBA iccData = _iccData } var encoder = WEBPEncoder(width: image.width, height: image.height, bytesPerRow: bytesPerRow, format: format, pixels: pixels, iccData: iccData) if let quality = properties[.compressionQuality] as? Double { encoder.quality = (quality * 100).clamped(to: 0...100) } return encoder.encode() } } #if canImport(CoreGraphics) extension WEBPEncoder { static func encode(image: CGImage, properties: [ImageRep.PropertyKey: Any]) -> Data? { var image = image let format: PixelFormat switch (image.bitmapInfo.intersection(.byteOrderMask), image.alphaInfo) { case (.byteOrder32Big, .last): format = .RGBA case (.byteOrder32Little, .first): format = .BGRA case (.byteOrder32Big, .noneSkipLast): format = .RGBX case (.byteOrder32Little, .noneSkipFirst): format = .BGRX default: if image.alphaInfo == .none || image.alphaInfo == .noneSkipLast || image.alphaInfo == .noneSkipFirst { let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.noneSkipLast.rawValue) guard let _image = image.createCGImage( bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: 4 * image.width, space: image.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo, decode: image.decode, intent: image.renderingIntent ) else { return nil } image = _image format = .RGBX } else { let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.last.rawValue) guard let _image = image.createCGImage( bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: 4 * image.width, space: image.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo, decode: image.decode, intent: image.renderingIntent ) else { return nil } image = _image format = .RGBA } } let bytesPerRow = image.bytesPerRow let iccData = image.colorSpace?.copyICCData() as Data? guard let pixels = image.dataProvider?.data as Data? else { return nil } var encoder = WEBPEncoder(width: image.width, height: image.height, bytesPerRow: bytesPerRow, format: format, pixels: pixels, iccData: iccData) if let quality = properties[.compressionQuality] as? Double { encoder.quality = (quality * 100).clamped(to: 0...100) } return encoder.encode() } } #endif extension WEBPEncoder { enum PixelFormat: Int32 { case RGBA case BGRA case RGBX case BGRX case RGB case BGR } func encode() -> Data? { return pixels.withUnsafeBytes { guard let pixels = $0.baseAddress else { return nil } guard let mux = WebPMuxNew() else { return nil } defer { WebPMuxDelete(mux) } let importer: Importer switch format { case .RGBA: importer = WebPPictureImportRGBA case .BGRA: importer = WebPPictureImportBGRA case .RGBX: importer = WebPPictureImportRGBX case .BGRX: importer = WebPPictureImportBGRX case .RGB: importer = WebPPictureImportRGB case .BGR: importer = WebPPictureImportBGR } var buffer: UnsafeMutablePointer<UInt8>? let size = webp_encode(pixels, width, height, bytesPerRow, importer, quality ?? 100, quality == nil, &buffer) guard buffer != nil && size != 0 else { return nil } defer { WebPFree(buffer) } var image = WebPData(bytes: buffer, size: size) guard WebPMuxSetImage(mux, &image, 1) == WEBP_MUX_OK else { return nil } if let iccData = iccData { let status: WebPMuxError = iccData.withUnsafeBytes { data in var _data = WebPData(bytes: data.baseAddress?.assumingMemoryBound(to: UInt8.self), size: data.count) return WebPMuxSetChunk(mux, "ICCP", &_data, 1) } guard status == WEBP_MUX_OK else { return nil } } var output = WebPData() guard WebPMuxAssemble(mux, &output) == WEBP_MUX_OK else { return nil } defer { WebPDataClear(&output) } return Data(bytes: output.bytes, count: output.size) } } } private typealias Importer = (UnsafeMutablePointer<WebPPicture>?, UnsafePointer<UInt8>?, Int32) -> Int32 private func webp_encode(_ rgba: UnsafeRawPointer, _ width: Int, _ height: Int, _ stride: Int, _ importer: Importer, _ quality: Double, _ lossless: Bool, _ output: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>) -> Int { var wrt = WebPMemoryWriter() return withUnsafeMutablePointer(to: &wrt) { wrt in var pic = WebPPicture() var config = WebPConfig() if WebPConfigPreset(&config, WEBP_PRESET_DEFAULT, Float(quality)) == 0 || WebPPictureInit(&pic) == 0 { return 0 // shouldn't happen, except if system installation is broken } config.lossless = lossless ? 1 : 0 pic.use_argb = lossless ? 1 : 0 pic.width = Int32(width) pic.height = Int32(height) pic.writer = WebPMemoryWrite pic.custom_ptr = UnsafeMutableRawPointer(wrt) WebPMemoryWriterInit(wrt) let ok = importer(&pic, rgba.assumingMemoryBound(to: UInt8.self), Int32(stride)) != 0 && WebPEncode(&config, &pic) != 0 WebPPictureFree(&pic) if !ok { WebPMemoryWriterClear(wrt) output.pointee = nil return 0 } output.pointee = wrt.pointee.mem return wrt.pointee.size } }
mit
2a7059e0018181f217786da5d6f6ce5e
35.731801
151
0.565453
4.772026
false
false
false
false
yeziahehe/Gank
Pods/SKPhotoBrowser/SKPhotoBrowser/SKToolbar.swift
2
1860
// // SKToolbar.swift // SKPhotoBrowser // // Created by keishi_suzuki on 2017/12/20. // Copyright © 2017年 suzuki_keishi. All rights reserved. // import Foundation // helpers which often used private let bundle = Bundle(for: SKPhotoBrowser.self) class SKToolbar: UIToolbar { var toolActionButton: UIBarButtonItem! fileprivate weak var browser: SKPhotoBrowser? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } convenience init(frame: CGRect, browser: SKPhotoBrowser) { self.init(frame: frame) self.browser = browser setupApperance() setupToolbar() } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if let view = super.hitTest(point, with: event) { if SKMesurement.screenWidth - point.x < 50 { // FIXME: not good idea return view } } return nil } } private extension SKToolbar { func setupApperance() { backgroundColor = .clear clipsToBounds = true isTranslucent = true setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default) } func setupToolbar() { toolActionButton = UIBarButtonItem(barButtonSystemItem: .action, target: browser, action: #selector(SKPhotoBrowser.actionButtonPressed)) toolActionButton.tintColor = UIColor.white var items = [UIBarButtonItem]() items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil)) if SKPhotoBrowserOptions.displayAction { items.append(toolActionButton) } setItems(items, animated: false) } func setupActionButton() { } }
gpl-3.0
cbbc0b757c26fa46288a7d5fd888491a
26.716418
144
0.634356
4.761538
false
false
false
false
jindulys/GitPocket
_site/GitPocket/Utilities/PullToRefresh/PullToRefresh.swift
1
7067
// // PullToRefresh.swift // GitPocket // // Created by yansong li on 2015-07-29. // Copyright © 2015 yansong li. All rights reserved. // import Foundation import UIKit protocol RefreshViewAnimator { func animateState(state: RefreshState) } class PullToRefresh: NSObject { let refreshView: UIView var action: (() -> ())? let animator: RefreshViewAnimator var KVOContext = "PullToRefreshKVOContext" let contentOffsetKeyPath = "contentOffset" var scrollViewDefaultInsets = UIEdgeInsetsZero weak var scrollView: UIScrollView? { didSet { oldValue?.removeObserver(self, forKeyPath: contentOffsetKeyPath) if let scrollView = scrollView { scrollViewDefaultInsets = scrollView.contentInset scrollView.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .Initial, context: &KVOContext) } } } var previousContentOffset: CGPoint = CGPointZero var state: RefreshState = .Initial { didSet{ animator.animateState(state) switch state { case .Loading: if let scrollView = scrollView where oldValue != .Loading { scrollView.contentOffset = previousContentOffset scrollView.bounces = false UIView.animateWithDuration(0.3, animations: { () -> Void in let insets = self.refreshView.frame.height + self.scrollViewDefaultInsets.top scrollView.contentInset.top = insets scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, -insets) }, completion: { finished in scrollView.bounces = true }) action?() } case .Finished: UIView.animateWithDuration(0.3, animations: { () -> Void in self.scrollView?.contentInset = self.scrollViewDefaultInsets self.scrollView?.contentOffset.y = -self.scrollViewDefaultInsets.top }, completion: nil) default: break } } } init(refreshView: UIView, animator: RefreshViewAnimator) { self.refreshView = refreshView self.animator = animator } override convenience init() { let refreshView = DefaultRefreshView() self.init(refreshView: refreshView, animator: DefaultViewAnimator(refreshView: refreshView)) } deinit { scrollView?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if (context == &KVOContext && keyPath == contentOffsetKeyPath && object as? UIScrollView == scrollView) { let offset = previousContentOffset.y + scrollViewDefaultInsets.top let refreshViewHeight = refreshView.frame.height switch offset{ case 0 where state != .Loading: state = .Initial case -refreshViewHeight..<0 where (state != .Loading && state != .Finished): state = .Releasing(progress:-offset / refreshViewHeight) case -1000..<(-refreshViewHeight): if state == RefreshState.Releasing(progress:1.0) && (scrollView?.dragging == false) { state = RefreshState.Loading } else if state != RefreshState.Loading && state != RefreshState.Finished { state = .Releasing(progress:1.0) } default: break } } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } previousContentOffset.y = scrollView!.contentOffset.y } func startRefreshing() { if self.state != RefreshState.Initial { return } scrollView?.setContentOffset(CGPointMake(0, -refreshView.frame.height - scrollViewDefaultInsets.top), animated: true) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.27 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue(), { self.state = RefreshState.Loading }) } func endRefreshing() { if state == .Loading { state = .Finished } } } class DefaultRefreshView: UIView { var activityIndicator: UIActivityIndicatorView! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { frame = CGRectMake(frame.origin.x, frame.origin.y, frame.width, 40) activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) activityIndicator.hidesWhenStopped = false addSubview(activityIndicator) } override func layoutSubviews() { super.layoutSubviews() activityIndicator.center = convertPoint(center, fromView: superview) } override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) if let superview = newSuperview { frame = CGRectMake(frame.origin.x, frame.origin.y, superview.frame.width, 40) } } } class DefaultViewAnimator: RefreshViewAnimator { let animateView: DefaultRefreshView init(refreshView:DefaultRefreshView) { animateView = refreshView } func animateState(state: RefreshState) { switch state { case .Initial: animateView.activityIndicator.stopAnimating() case .Releasing(let progress): var transform = CGAffineTransformIdentity transform = CGAffineTransformScale(transform, progress, progress); transform = CGAffineTransformRotate(transform, 3.14 * progress * 2); animateView.activityIndicator.transform = transform case .Loading: animateView.activityIndicator.startAnimating() default: break } } } enum RefreshState:Equatable, CustomStringConvertible { case Initial, Loading, Finished case Releasing(progress: CGFloat) var description: String { switch self { case .Initial: return "Initial" case .Loading: return "Loading" case .Finished: return "Finished" case .Releasing(let progress): return "Releasing:\(progress)" } } } func ==(a: RefreshState, b: RefreshState) -> Bool { switch(a, b) { case (.Initial, .Initial) : return true case (.Loading, .Loading) : return true case (.Releasing, .Releasing) : return true case (.Finished, .Finished) : return true default: return false } }
mit
1c64cf1b3b7dce0a2aceabbff2781010
33.980198
157
0.612652
5.389779
false
false
false
false
lerocha/ios-bootcamp-TwitterRedux
TwitterRedux/AppDelegate.swift
1
2886
// // AppDelegate.swift // TwitterRedux // // Created by Luis Rocha on 4/20/17. // Copyright © 2017 Luis Rocha. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let hamburguerViewController = window!.rootViewController as! HamburgerViewController let storyboard = UIStoryboard(name: "Main", bundle: nil) let menuViewController = storyboard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController menuViewController.hamburguerViewController = hamburguerViewController hamburguerViewController.menuViewController = menuViewController 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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active 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:. } open func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { // Called to handle OAuth callback URL. TwitterClient.sharedInstance.handleOpenUrl(open: url) return true; } }
apache-2.0
efaa7d4416437905266e075d7fc6fac0
49.614035
285
0.74974
5.735586
false
false
false
false
wibosco/WhiteBoardCodingChallenges
WhiteBoardCodingChallenges/Challenges/HackerRank/BFSShortReach/BFSShortReach.swift
1
2177
// // BFSShortReach.swift // WhiteBoardCodingChallenges // // Created by William Boles on 24/06/2016. // Copyright © 2016 Boles. All rights reserved. // import Foundation //https://www.hackerrank.com/challenges/bfsshortreach class BFSShortReach: NSObject { // MARK: Distance class func distanceFromSourceToAllOtherNodes(sourceIndex: Int, totalNodes: Int, edges: [[Int]]) -> [BFSSearchReachNode] { let nodes = buildNodes(totalNodes: totalNodes) connectNodes(nodes: nodes, edges: edges) let source = nodes[sourceIndex] findDistanceFromSourceToAllOtherNodes(source: source) return nodes } class func findDistanceFromSourceToAllOtherNodes(source: BFSSearchReachNode) { source.visted = true source.distanceFromSource = 0 var queue = [BFSSearchReachNode]() queue.append(source) while queue.count > 0 { let node = queue.removeFirst() for connectedNode in node.nodes { if !connectedNode.visted { queue.append(connectedNode) connectedNode.visted = true connectedNode.distanceFromSource = (node.distanceFromSource + 6) } } } } // MARK: Build class func buildNodes(totalNodes: Int) -> [BFSSearchReachNode] { var nodes = [BFSSearchReachNode]() for _ in 0..<totalNodes { let node = BFSSearchReachNode() nodes.append(node) } return nodes } class func connectNodes(nodes: [BFSSearchReachNode], edges: [[Int]]) { for edge in edges { let sourceNodeIndex = edge[0] let destinationNodeIndex = edge[1] let sourceNode = nodes[sourceNodeIndex] let destinationNode = nodes[destinationNodeIndex] sourceNode.addRelationshipWithNode(node: destinationNode) } } }
mit
1eaeeb73449c9344fd860ce8932fe2ff
25.864198
125
0.550092
4.923077
false
false
false
false
boxenjim/SwiftyFaker
SwiftyFaker.playground/Contents.swift
1
379
//: Playground - noun: a place where people can play import UIKit //import SwiftyFaker // //let digits = 10 //let afterDigits = 10 //let rand = Double.random() //let digitRand = rand * pow(Double(10), Double(digits + afterDigits)) //let floorRand = floor(digitRand) //let afterDigitRand = floorRand / pow(Double(10), Double(afterDigits)) //let val = pow(Double(10), Double(3))
mit
ea8bb41a711dc275cde5400f3e6a4364
28.153846
71
0.701847
3.295652
false
false
false
false
grigaci/RateMyTalkAtMobOS
RateMyTalkAtMobOS/Classes/Helpers/Starters/RMTStarterFactory.swift
1
1234
// // RMTStarterFactory.swift // RateMyTalkAtMobOS // // Created by bogdan on 03/10/14. // Copyright (c) 2014 Grigaci. All rights reserved. // import Foundation @objc(RMTStarterItem) protocol RMTStarterItem { func start(); } class RMTStarterFactory { var allStarters: [NSString] init () { self.allStarters = [] self.addStarter(NSStringFromClass(RMTStarterCoreData.self)) self.addStarter(NSStringFromClass(RMTStarterDataImporter.self)) self.addStarter(NSStringFromClass(RMTStarterUICustomization.self)) } func addStarter(starter: NSString) { allStarters += [starter] } func runStarters() { for starterClassString in allStarters { // With this type of reflection, the class MUST be inherited from NSObject var anyobjectype : AnyObject.Type = NSClassFromString(starterClassString) var nsobjectype : NSObject.Type = anyobjectype as NSObject.Type var object: AnyObject = nsobjectype() assert(object.conformsToProtocol(RMTStarterItem), "Doesn't conform to RMTStarterItem") var starterItem: RMTStarterItem = object as RMTStarterItem starterItem.start() } } }
bsd-3-clause
b7e32dfca7f47f6742ee8733ac17314f
29.097561
98
0.677472
4.197279
false
false
false
false
BalestraPatrick/TweetsCounter
Tweetometer/AppCoordinator.swift
2
1647
// // AppCoordinator.swift // TweetsCounter // // Created by Patrick Balestra on 3/11/16. // Copyright © 2016 Patrick Balestra. All rights reserved. // import UIKit protocol Coordinator: class { func presentSafari(_ url: URL) } class AppCoordinator: Coordinator & DependencyInitializer { let window: UIWindow let linkOpener = LinkOpener() var childCoordinators = [AnyObject]() let services: AppServices lazy var rootViewController: UINavigationController = { return self.window.rootViewController as! UINavigationController }() init(window: UIWindow, services: AppServices) { // Grab the initial view controller from Storyboard let initialViewController = StoryboardScene.Main.initialScene.instantiate() window.rootViewController = initialViewController self.window = window self.childCoordinators = [] self.services = services linkOpener.coordinator = self } func start() { // Grab view controller instance already instantiated by Storyboard from the hierarchy if let visible = rootViewController.visibleViewController, let homeViewController = visible as? HomeViewController { let homeCoordinator = HomeCoordinator(controller: homeViewController, twitterService: services.twitterSession) childCoordinators.append(homeCoordinator) homeCoordinator.start() } } // MARK: Coordinator func presentSafari(_ url: URL) { let safari = linkOpener.openInSafari(url) rootViewController.present(safari, animated: true, completion: nil) } }
mit
3ff7dab7d1c650879e1074101abf3e45
30.653846
124
0.698056
5.361564
false
false
false
false
igiu1988/XiaoBai
XiaoBai/3rd/SwiftyTimer/SwiftyTimer.swift
1
3564
// // SwiftyTimer // // Copyright (c) 2015 Radosław Pietruszewski // // 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 private class NSTimerActor { let block: () -> Void init(_ block: () -> Void) { self.block = block } @objc func fire() { block() } } extension NSTimer { // NOTE: `new` class functions are a workaround for a crashing bug when using convenience initializers (18720947) /// Create a timer that will call `block` once after the specified time. /// /// **Note:** the timer won't fire until it's scheduled on the run loop. /// Use `NSTimer.after` to create and schedule a timer in one step. public class func new(after interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { let actor = NSTimerActor(block) return self.init(timeInterval: interval, target: actor, selector: "fire", userInfo: nil, repeats: false) } /// Create a timer that will call `block` repeatedly in specified time intervals. /// /// **Note:** the timer won't fire until it's scheduled on the run loop. /// Use `NSTimer.every` to create and schedule a timer in one step. public class func new(every interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { let actor = NSTimerActor(block) return self.init(timeInterval: interval, target: actor, selector: "fire", userInfo: nil, repeats: true) } /// Create and schedule a timer that will call `block` once after the specified time. public class func after(interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { let timer = NSTimer.new(after: interval, block) timer.start() return timer } /// Create and schedule a timer that will call `block` repeatedly in specified time intervals. public class func every(interval: NSTimeInterval, _ block: () -> Void) -> NSTimer { let timer = NSTimer.new(every: interval, block) timer.start() return timer } /// Schedule this timer on the run loop /// /// By default, the timer is scheduled on the current run loop for the default mode. /// Specify `runLoop` or `modes` to override these defaults. public func start(runLoop runLoop: NSRunLoop = NSRunLoop.currentRunLoop(), modes: String...) { let modes = modes.isEmpty ? [NSDefaultRunLoopMode] : modes for mode in modes { runLoop.addTimer(self, forMode: mode) } } }
mit
970a4dbb339aa363757f90c8db3c412c
37.728261
117
0.66938
4.533079
false
false
false
false
GrandCentralBoard/GrandCentralBoard
GrandCentralBoardTests/Widgets/Slack/MessageBubbleViewSnapshotTests.swift
2
1491
// // MessageBubbleViewSnapshotTests.swift // GrandCentralBoard // // Created by Michał Laskowski on 25.05.2016. // Copyright © 2016 Macoscope. All rights reserved. // import FBSnapshotTestCase @testable import GrandCentralBoard final class MessageBubbleViewSnapshotTests: FBSnapshotTestCase { override func setUp() { super.setUp() recordMode = false } func testMessageBubbleShortText() { let view = MessageBubbleView() view.frame = CGRect(x: 0, y:0, width: 520, height: 400) view.backgroundColor = .blackColor() view.text = "Short text" FBSnapshotVerifyView(view) } func testMessageBubbleMediumText() { let view = MessageBubbleView() view.frame = CGRect(x: 0, y:0, width: 520, height: 400) view.backgroundColor = .blackColor() view.text = "Hi, I just wanted to say I love GrandCentralBoard, it is the nicest thing to happen on TV since color TV" FBSnapshotVerifyView(view) } func testMessageBubbleLongText() { let view = MessageBubbleView() view.frame = CGRect(x: 0, y:0, width: 520, height: 400) view.backgroundColor = .blackColor() view.text = "Hi, this is just a message from our developers with a long long long long long long long long long " + "long long long long long long long long long long long long long long long long long long long text" FBSnapshotVerifyView(view) } }
gpl-3.0
ab532ba9e4469bdec15036fa77dba99d
28.78
126
0.659503
4.431548
false
true
false
false
mddub/G4ShareSpy
G4ShareSpy/Messages/MessageHeader.swift
1
590
// // MessageHeader.swift // G4ShareSpy // // Created by Mark Wilson on 7/10/16. // Copyright © 2016 Mark Wilson. All rights reserved. // import Foundation struct MessageHeader { // 0...0 indicates start of header (1) // 1...2 total bytes // 3...3 ACK (1) static let length = 4 let totalBytes: UInt16 init?(data: Data) { guard data.count == type(of: self).length else { return nil } guard data[0] as UInt8 == 1 && data[3] as UInt8 == 1 else { return nil } totalBytes = data[1..<3] } }
mit
cb956fa706e724f385a51d4e9f6382ed
17.40625
67
0.546689
3.569697
false
false
false
false
mohitathwani/swift-corelibs-foundation
TestFoundation/TestNSPredicate.swift
1
4129
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestNSPredicate: XCTestCase { static var allTests : [(String, (TestNSPredicate) -> () throws -> Void)] { return [ ("test_BooleanPredicate", test_BooleanPredicate), ("test_BlockPredicateWithoutVariableBindings", test_BlockPredicateWithoutVariableBindings), ("test_filterNSArray", test_filterNSArray), ("test_filterNSMutableArray", test_filterNSMutableArray), ("test_filterNSSet", test_filterNSSet), ("test_filterNSMutableSet", test_filterNSMutableSet), ("test_filterNSOrderedSet", test_filterNSOrderedSet), ("test_filterNSMutableOrderedSet", test_filterNSMutableOrderedSet), ("test_NSCoding", test_NSCoding), ("test_copy", test_copy), ] } func test_BooleanPredicate() { let truePredicate = NSPredicate(value: true) let falsePredicate = NSPredicate(value: false) XCTAssertTrue(truePredicate.evaluate(with: NSObject())) XCTAssertFalse(falsePredicate.evaluate(with: NSObject())) } func test_BlockPredicateWithoutVariableBindings() { let isNSStringPredicate = NSPredicate { (object, bindings) -> Bool in return object is NSString } XCTAssertTrue(isNSStringPredicate.evaluate(with: NSString())) XCTAssertFalse(isNSStringPredicate.evaluate(with: NSArray())) } let lengthLessThanThreePredicate = NSPredicate { (obj, bindings) -> Bool in return (obj as! String).utf16.count < 3 } let startArray = ["1", "12", "123", "1234"] let expectedArray = ["1", "12"] func test_filterNSArray() { let filteredArray = NSArray(array: startArray).filtered(using: lengthLessThanThreePredicate).map { $0 as! String } XCTAssertEqual(expectedArray, filteredArray) } func test_filterNSMutableArray() { let array = NSMutableArray(array: startArray) array.filter(using: lengthLessThanThreePredicate) XCTAssertEqual(NSArray(array: expectedArray), array) } func test_filterNSSet() { let set = NSSet(array: startArray) let filteredSet = set.filtered(using: lengthLessThanThreePredicate) XCTAssertEqual(Set(expectedArray), filteredSet) } func test_filterNSMutableSet() { let set = NSMutableSet(array: ["1", "12", "123", "1234"]) set.filter(using: lengthLessThanThreePredicate) XCTAssertEqual(Set(expectedArray), Set(set.allObjects.map { $0 as! String })) } func test_filterNSOrderedSet() { let orderedSet = NSOrderedSet(array: startArray) let filteredOrderedSet = orderedSet.filtered(using: lengthLessThanThreePredicate) XCTAssertEqual(NSOrderedSet(array: expectedArray), filteredOrderedSet) } func test_filterNSMutableOrderedSet() { let orderedSet = NSMutableOrderedSet() orderedSet.addObjects(from: startArray) orderedSet.filter(using: lengthLessThanThreePredicate) let expectedOrderedSet = NSMutableOrderedSet() expectedOrderedSet.addObjects(from: expectedArray) XCTAssertEqual(expectedOrderedSet, orderedSet) } func test_NSCoding() { let predicateA = NSPredicate(value: true) let predicateB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: predicateA)) as! NSPredicate XCTAssertEqual(predicateA, predicateB, "Archived then unarchived uuid must be equal.") } func test_copy() { let predicate = NSPredicate(value: true) XCTAssert(predicate.isEqual(predicate.copy())) } }
apache-2.0
09ca9279df227d72e26d628b9a12da57
36.536364
138
0.682005
4.9807
false
true
false
false
practicalswift/swift
test/stdlib/NSStringAPI+Substring.swift
35
4737
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/a.out4 -swift-version 4 && %target-codesign %t/a.out4 && %target-run %t/a.out4 // REQUIRES: executable_test // REQUIRES: objc_interop // // Tests for the NSString APIs on Substring // import StdlibUnittest import Foundation extension String { func range(fromStart: Int, fromEnd: Int) -> Range<String.Index> { return index(startIndex, offsetBy: fromStart) ..< index(endIndex, offsetBy: fromEnd) } subscript(fromStart: Int, fromEnd: Int) -> SubSequence { return self[range(fromStart: fromStart, fromEnd: fromEnd)] } } var tests = TestSuite("NSStringAPIs/Substring") tests.test("range(of:)/NilRange") { let ss = "aabcdd"[1, -1] let range = ss.range(of: "bc") expectEqual("bc", range.map { ss[$0] }) } tests.test("range(of:)/NonNilRange") { let s = "aabcdd" let ss = s[1, -1] let searchRange = s.range(fromStart: 2, fromEnd: -2) let range = ss.range(of: "bc", range: searchRange) expectEqual("bc", range.map { ss[$0] }) } tests.test("rangeOfCharacter") { let ss = "__hello__"[2, -2] let range = ss.rangeOfCharacter(from: CharacterSet.alphanumerics) expectEqual("h", range.map { ss[$0] }) } tests.test("compare(_:options:range:locale:)/NilRange") { let needle = "hello" let haystack = "__hello__"[2, -2] expectEqual(.orderedSame, haystack.compare(needle)) } tests.test("compare(_:options:range:locale:)/NonNilRange") { let needle = "hello" let haystack = "__hello__" let range = haystack.range(fromStart: 2, fromEnd: -2) expectEqual(.orderedSame, haystack[range].compare(needle, range: range)) } tests.test("replacingCharacters(in:with:)") { let s = "__hello, world" let range = s.range(fromStart: 2, fromEnd: -7) let expected = "__goodbye, world" let replacement = "goodbye" expectEqual(expected, s.replacingCharacters(in: range, with: replacement)) expectEqual(expected[2, 0], s[2, 0].replacingCharacters(in: range, with: replacement)) expectEqual(replacement, s.replacingCharacters(in: s.startIndex..., with: replacement)) expectEqual(replacement, s.replacingCharacters(in: ..<s.endIndex, with: replacement)) expectEqual(expected[2, 0], s[2, 0].replacingCharacters(in: range, with: replacement[...])) } tests.test("replacingOccurrences(of:with:options:range:)/NilRange") { let s = "hello" expectEqual("he11o", s.replacingOccurrences(of: "l", with: "1")) expectEqual("he11o", s.replacingOccurrences(of: "l"[...], with: "1")) expectEqual("he11o", s.replacingOccurrences(of: "l", with: "1"[...])) expectEqual("he11o", s.replacingOccurrences(of: "l"[...], with: "1"[...])) expectEqual("he11o", s[...].replacingOccurrences(of: "l", with: "1")) expectEqual("he11o", s[...].replacingOccurrences(of: "l"[...], with: "1")) expectEqual("he11o", s[...].replacingOccurrences(of: "l", with: "1"[...])) expectEqual("he11o", s[...].replacingOccurrences(of: "l"[...], with: "1"[...])) } tests.test("replacingOccurrences(of:with:options:range:)/NonNilRange") { let s = "hello" let r = s.range(fromStart: 1, fromEnd: -2) expectEqual("he1lo", s.replacingOccurrences(of: "l", with: "1", range: r)) expectEqual("he1lo", s.replacingOccurrences(of: "l"[...], with: "1", range: r)) expectEqual("he1lo", s.replacingOccurrences(of: "l", with: "1"[...], range: r)) expectEqual("he1lo", s.replacingOccurrences(of: "l"[...], with: "1"[...], range: r)) expectEqual("he1lo", s[...].replacingOccurrences(of: "l", with: "1", range: r)) expectEqual("he1lo", s[...].replacingOccurrences(of: "l"[...], with: "1", range: r)) expectEqual("he1lo", s[...].replacingOccurrences(of: "l", with: "1"[...], range: r)) expectEqual("he1lo", s[...].replacingOccurrences(of: "l"[...], with: "1"[...], range: r)) let ss = s[1, -1] expectEqual("e1l", ss.replacingOccurrences(of: "l", with: "1", range: r)) expectEqual("e1l", ss.replacingOccurrences(of: "l"[...], with: "1", range: r)) expectEqual("e1l", ss.replacingOccurrences(of: "l", with: "1"[...], range: r)) expectEqual("e1l", ss.replacingOccurrences(of: "l"[...], with: "1"[...], range: r)) } tests.test("substring(with:)") { let s = "hello, world" let r = s.range(fromStart: 7, fromEnd: 0) expectEqual("world", s.substring(with: r)) expectEqual("world", s[...].substring(with: r)) expectEqual("world", s[1, 0].substring(with: r)) } tests.test("substring(with:)/SubscriptEquivalence") { let s = "hello, world" let r = s.range(fromStart: 7, fromEnd: 0) expectEqual(s[r], s.substring(with: r)) expectEqual(s[...][r], s[...].substring(with: r)) expectEqual(s[1, 0][r], s[1, 0].substring(with: r)) } runAllTests()
apache-2.0
6733af56456101f9ef69624f7b8608a1
31.445205
115
0.636479
3.20284
false
true
false
false
toshiapp/toshi-ios-client
Toshi/Controllers/Wallet/Views/SendConfirmationSection.swift
1
3098
// // SendConfirmationSection.swift // Toshi // // Created by Ellen Shapiro (Work) on 2/15/18. // Copyright © 2018 Bakken&Baeck. All rights reserved. // import UIKit final class SendConfirmationSection: UIStackView { private lazy var sectionTitleLabel: UILabel = { let label = UILabel() label.textAlignment = .left label.textColor = Theme.darkTextHalfAlpha label.font = Theme.preferredRegular() return label }() private lazy var primaryCurrencyLabel: UILabel = { let label = UILabel() label.textAlignment = .right label.textColor = Theme.darkTextColor return label }() private lazy var secondaryCurrencyLabel: UILabel = { let label = UILabel() label.textAlignment = .right label.textColor = Theme.darkTextHalfAlpha label.font = Theme.preferredFootnote() return label }() // MARK: Initialization /// A section in the confirmation screen which can optionally show a secondary currency. /// /// - Parameters: /// - sectionTitle: The title of the section to display /// - primaryCurrencyString: The string to display for the primary currency /// - secondaryCurrencyString: [optional] The string to show for the secondary currency. The secondary currency label will not be added if this value is nil. /// - primaryCurrencyBold: Whether the primary currency label should be bold or not. Defaults to false. init(sectionTitle: String, primaryCurrencyBold: Bool = false) { super.init(frame: .zero) self.axis = .horizontal self.alignment = .top self.spacing = .smallInterItemSpacing setPrimaryCurrencyFont(bold: primaryCurrencyBold) sectionTitleLabel.text = sectionTitle addArrangedSubview(sectionTitleLabel) } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupWith(primaryCurrencyString: String, secondaryCurrencyString: String?) { primaryCurrencyLabel.text = primaryCurrencyString if let secondaryString = secondaryCurrencyString { secondaryCurrencyLabel.text = secondaryString addCurrencyStackView(to: self) } else { addArrangedSubview(primaryCurrencyLabel) } } // MARK: View Setup private func setPrimaryCurrencyFont(bold: Bool) { if bold { primaryCurrencyLabel.font = Theme.preferredRegularBold() } else { primaryCurrencyLabel.font = Theme.preferredRegular() } } private func addCurrencyStackView(to stackView: UIStackView) { let currencyStackView = UIStackView() currencyStackView.axis = .vertical currencyStackView.alignment = .trailing currencyStackView.spacing = .smallInterItemSpacing stackView.addArrangedSubview(currencyStackView) currencyStackView.addArrangedSubview(primaryCurrencyLabel) currencyStackView.addArrangedSubview(secondaryCurrencyLabel) } }
gpl-3.0
3d6f1e96b7b850fa77493ffcba3823e6
29.362745
163
0.672263
5.019449
false
false
false
false
lerigos/music-service
iOS_9/Pods/SwiftyVK/Source/VK.swift
2
5975
import Foundation #if os(iOS) import UIKit #endif #if os(OSX) import Cocoa #endif ///Delegate to the SwiftyVK public protocol VKDelegate { /**Called when SwiftyVK need autorization permissions - returns: permissions as VK.Scope type*/ func vkWillAutorize() -> [VK.Scope] ///Called when SwiftyVK did autorize and receive token func vkDidAutorize(parameters: Dictionary<String, String>) ///Called when SwiftyVK did unautorize and remove token func vkDidUnautorize() ///Called when SwiftyVK did failed autorization func vkAutorizationFailed(_: VK.Error) /**Called when SwiftyVK need know where a token is located - returns: Bool value that indicates whether to save token to user defaults or not, and alternative save path*/ func vkTokenPath() -> (useUserDefaults: Bool, alternativePath: String) #if os(iOS) /**Called when need to display a view from SwiftyVK - returns: UIViewController that should present autorization view controller*/ func vkWillPresentView() -> UIViewController #elseif os(OSX) /**Called when need to display a window from SwiftyVK - returns: Bool value that indicates whether to display the window as modal or not, and parent window for modal presentation.*/ func vkWillPresentWindow() -> (isSheet: Bool, inWindow: NSWindow?) #endif } // // // // // // // // // // /** Library to connect to the social network "VKontakte" * To use, you must call start() specifying the application ID and a delegate * For user authentication you must call autorize() */ public struct VK { internal static var delegate : VKDelegate! { set{delegateInstance = newValue} get{assert(VK.state != .Unknown, "At first initialize VK with start() method") return delegateInstance} } public private(set) static var appID : String! { set{appIDInstance = newValue} get{assert(VK.state != .Unknown, "At first initialize VK with start() method") return appIDInstance} } private static var delegateInstance : VKDelegate? private static var appIDInstance : String? /** Initialize library with identifier and application delegate - parameter appID: application ID - parameter delegate: Delegate corresponding protocol VKDelegate */ public static func start(appID id: String, delegate owner: VKDelegate) { delegate = owner appID = id Token.get() VK.Log.put("Global", "SwiftyVK INIT") } private static var started : Bool { return VK.delegateInstance != nil && VK.appIDInstance != nil } /** Getting authenticate token. * If the token is already stored in the file, then the authentication takes place in the background * If not, shows a pop-up notification with authorization request */ public static func autorize() { Authorizator.autorize(nil); } #if os(iOS) @available(iOS 9.0, *) public static func processURL(url: NSURL, options: [String: AnyObject]) { Authorizator.recieveTokenURL(url, fromApp: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String); } @available(iOS, introduced=4.2, deprecated=9.0, message="Please use url:options:") public static func processURL_old(url: NSURL, sourceApplication app: String?) { Authorizator.recieveTokenURL(url, fromApp: app); } #endif public static func logOut() { LP.stop() Token.remove() } } // // // // // // // // // // private typealias VK_Defaults = VK extension VK_Defaults { public struct defaults { //Returns used VK API version public static let apiVersion = "5.52" //Returns used VK SDK version public static let sdkVersion = "1.3.1" ///Requests timeout public static var timeOut : Int = 10 ///Maximum number of attempts to send requests public static var maxAttempts : Int = 3 ///Whether to allow automatic processing of some API error public static var catchErrors : Bool = true //Similarly request sendAsynchronous property public static var sendAsynchronous : Bool = true ///Maximum number of requests per second public static var maxRequestsPerSec : Int = 3 ///Allows print log messages to console public static var allowLogToConsole : Bool = false public static var language : String? { get { if useSystemLanguage { let syslemLang = NSBundle.preferredLocalizationsFromArray(supportedLanguages).first if syslemLang == "uk" { return "ua" } return syslemLang } return self.privateLanguage } set { guard newValue == nil || supportedLanguages.contains(newValue!) else {return} self.privateLanguage = newValue useSystemLanguage = (newValue == nil) } } internal static var sleepTime : NSTimeInterval {return NSTimeInterval(1/Double(maxRequestsPerSec))} internal static let successBlock : VK.SuccessBlock = {success in} internal static let errorBlock : VK.ErrorBlock = {error in} internal static let progressBlock : VK.ProgressBlock = {int in} internal static let supportedLanguages = ["ru", "uk", "be", "en", "es", "fi", "de", "it"] internal static var useSystemLanguage = true private static var privateLanguage : String? } } // // // // // // // // // // public typealias VK_States = VK extension VK_States { public enum States { case Unknown case Started case inAutorization case Authorized } public static var state : States { guard VK.started else { return .Unknown } guard Token.exist else { return .Started } return .Authorized } } // // // // // // // // // // private typealias VK_Extensions = VK extension VK_Extensions { ///Access to the API methods public typealias API = _VKAPI public typealias Error = _VKError public typealias SuccessBlock = (response: JSON) -> Void public typealias ErrorBlock = (error: VK.Error) -> Void public typealias ProgressBlock = (done: Int, total: Int) -> Void }
apache-2.0
44aae3a8a4340fa794f1650841dd574a
26.539171
130
0.688368
4.252669
false
false
false
false
WE-St0r/SwiftyVK
Library/Sources/Utils/Reflecting.swift
2
762
import Foundation func associatedValue<T>(of maybeEnum: Any) -> T? { let enumMirror = Mirror(reflecting: maybeEnum) guard enumMirror.displayStyle == .enum, let enumChild = enumMirror.children.first else { return nil } if let enumChildValue = enumChild.value as? T { return enumChildValue } let enumSubchildMirror = Mirror(reflecting: enumChild.value) return enumSubchildMirror.children.first?.value as? T } func caseName(of maybeEnum: Any) -> String { let enumMirror = Mirror(reflecting: maybeEnum) guard enumMirror.displayStyle == .enum, let enumChild = enumMirror.children.first else { return String() } return enumChild.label ?? String() }
mit
a76c5f0493a176be3c8b9ab22658e271
26.214286
64
0.653543
4.280899
false
false
false
false
YifengBai/YuDou
YuDou/YuDou/Classes/Main/View/GradientView.swift
1
2836
// // GradientView.swift // YuDou // // Created by Bemagine on 2017/2/10. // Copyright © 2017年 bemagine. All rights reserved. // import UIKit class GradientView: UIView { fileprivate var startRGBColor: UIColor = UIColor(red: CGFloat(200.0/255.0), green: CGFloat(200.0/255.0), blue: CGFloat(200.0/255.0), alpha: 0) fileprivate var endRGBColor: UIColor = UIColor(r: 200, g: 200, b: 200) // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // 1.获取图形上下文 guard let currentContext = UIGraphicsGetCurrentContext() else { return } // 2.图形上下文将被存储,以便于之后的存储操作 currentContext.saveGState() // 3.CGColorSpace 描述的是颜色的域值范围。大多情况下你会使用到 RGB 模式来描述颜色。 let colorSpace = CGColorSpaceCreateDeviceRGB() // 4.这里我们定义一个渐变样式的起始颜色和结束颜色。CGColor 对象是底层颜色接口的定义。这个接口方法会从 CGColor 中获取指定颜色。 let startColor = startRGBColor guard let startColorComponents = startColor.cgColor.components else { return } let endColor = endRGBColor guard let endColorComponents = endColor.cgColor.components else { return } // 5.在这个数组中,将 RGB 颜色分量和 alpha 值写入。 let colorComponents: [CGFloat] = [startColorComponents[0], startColorComponents[1], startColorComponents[2], startColorComponents[3], endColorComponents[0], endColorComponents[1], endColorComponents[2], endColorComponents[3]] // 6.在此处可以定义各种颜色的相对位置。 let locations: [CGFloat] = [0.0, 1.0] // 7.CGGradient 用来描述渐变信息。 guard let gradient = CGGradient(colorSpace: colorSpace, colorComponents: colorComponents, locations: locations, count: 2) else { return } let startPoint = CGPoint(x: 0, y: self.bounds.height) let endPoint = CGPoint(x: self.bounds.width, y: self.bounds.height) // 8.这里渐变将沿纵轴 (vertical axis) 方向绘制。 currentContext.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: UInt32(0))) // 9存储图形上下文。 currentContext.restoreGState() } func drawGradientColorViewWith(startColor: UIColor, endColor: UIColor) { self.startRGBColor = startColor self.endRGBColor = endColor self.setNeedsDisplay() } }
mit
83a2cfbe7c352bf8bda51d260c7eaf5c
34.528571
233
0.646964
4.265866
false
false
false
false
robertherdzik/RHPreviewCell
RHPReviewCell/RHPreviewCellSource/RHPreviewTableViewCell.swift
1
3438
// // RHPreviewTableViewCell.swift // RHPreviewCell // // Created by Robert Herdzik on 25/09/2016. // Copyright © 2016 Robert. All rights reserved. // import UIKit open class RHPreviewTableViewCell: UITableViewCell { fileprivate var tilesManagerView: RHPreviewTilesContainerView! open weak var delegate: RHPreviewCellDelegate? open weak var dataSource: RHPreviewCellDataSource? var pressDuration = CFTimeInterval(0.4) override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addGesture() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func fulfilTilesContent() { guard let numberOfTiles = dataSource?.previewCellNumberOfTiles(self) else { assertionFailure("previewCellNumberOfTiles not implemented 😥") return } var newTiles = [RHPreviewTileView]() for index in 0...numberOfTiles - 1 { if let tile = dataSource?.previewCell(self, tileForIndex: index) { newTiles.append(tile) } } tilesManagerView.reloadTiles(withNew: newTiles) } @objc func triggerLongPress(with recognizer: UILongPressGestureRecognizer) { creteTilesPresenterIfNecessary() switch recognizer.state { case .began: showTiles { [weak self] in self?.passFingerPositionToPresenter(from: recognizer) } case .changed: passFingerPositionToPresenter(from: recognizer) case .cancelled, .ended, .failed: delegate?.previewCell(self, didSelectTileAtIndex: getSelectedTileIndexValue()) hideTiles() default: print("default") } } } private extension RHPreviewTableViewCell { func addGesture() { let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(triggerLongPress)) longPressGesture.minimumPressDuration = pressDuration contentView.addGestureRecognizer(longPressGesture) } func creteTilesPresenterIfNecessary() { if tilesManagerView != nil { return } tilesManagerView = RHPreviewTilesContainerView(frame: bounds) tilesManagerView.backgroundColor = UIColor.black.withAlphaComponent(0.15) contentView.addSubview(tilesManagerView!) fulfilTilesContent() } func showTiles(with completion: @escaping RHTilesAnimationComplitionBlock) { tilesManagerView.isHidden = false tilesManagerView.showElements(with: completion) } func hideTiles() { tilesManagerView.hideElements { [weak self] in self?.tilesManagerView.isHidden = true } } func passFingerPositionToPresenter(from recognizer: UILongPressGestureRecognizer) { let fingerPosition = recognizer.location(in: contentView) tilesManagerView.gestureOffset(fingerPosition) } func getSelectedTileIndexValue() -> RHTappedTileIndexValue { if tilesManagerView.selectedTileIndex < 0 { return RHTappedTileIndexValue.fingerReleased } else { return RHTappedTileIndexValue.tileTapped(tilesManagerView.selectedTileIndex) } } }
mit
c1afa45bed097c52237c84ddfafe77ed
32.019231
110
0.663366
5.05
false
false
false
false
coach-plus/ios
Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift
6
3111
// // DisposeBag.swift // RxSwift // // Created by Krunoslav Zaher on 3/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension Disposable { /// Adds `self` to `bag` /// /// - parameter bag: `DisposeBag` to add `self` to. public func disposed(by bag: DisposeBag) { bag.insert(self) } } /** Thread safe bag that disposes added disposables on `deinit`. This returns ARC (RAII) like resource management to `RxSwift`. In case contained disposables need to be disposed, just put a different dispose bag or create a new one in its place. self.existingDisposeBag = DisposeBag() In case explicit disposal is necessary, there is also `CompositeDisposable`. */ public final class DisposeBag: DisposeBase { private var _lock = SpinLock() // state private var _disposables = [Disposable]() private var _isDisposed = false /// Constructs new empty dispose bag. public override init() { super.init() } /// Adds `disposable` to be disposed when dispose bag is being deinited. /// /// - parameter disposable: Disposable to add. public func insert(_ disposable: Disposable) { self._insert(disposable)?.dispose() } private func _insert(_ disposable: Disposable) -> Disposable? { self._lock.lock(); defer { self._lock.unlock() } if self._isDisposed { return disposable } self._disposables.append(disposable) return nil } /// This is internal on purpose, take a look at `CompositeDisposable` instead. private func dispose() { let oldDisposables = self._dispose() for disposable in oldDisposables { disposable.dispose() } } private func _dispose() -> [Disposable] { self._lock.lock(); defer { self._lock.unlock() } let disposables = self._disposables self._disposables.removeAll(keepingCapacity: false) self._isDisposed = true return disposables } deinit { self.dispose() } } extension DisposeBag { /// Convenience init allows a list of disposables to be gathered for disposal. public convenience init(disposing disposables: Disposable...) { self.init() self._disposables += disposables } /// Convenience init allows an array of disposables to be gathered for disposal. public convenience init(disposing disposables: [Disposable]) { self.init() self._disposables += disposables } /// Convenience function allows a list of disposables to be gathered for disposal. public func insert(_ disposables: Disposable...) { self.insert(disposables) } /// Convenience function allows an array of disposables to be gathered for disposal. public func insert(_ disposables: [Disposable]) { self._lock.lock(); defer { self._lock.unlock() } if self._isDisposed { disposables.forEach { $0.dispose() } } else { self._disposables += disposables } } }
mit
8882b35fb10afa49e5e0e2d737b765d3
26.280702
88
0.628296
4.755352
false
false
false
false
rluftw/Meetup
MeetupDemo/Model/Meetup/Meetup.swift
2
1373
// // Meetup.swift // MeetupDemo // // Created by Xing Hui Lu on 12/19/15. // Copyright © 2015 Xing Hui Lu. All rights reserved. // import Foundation class Meetup { let timeInMillisec: Int? let durationInMillisec: Int? var meetupDescription: String? let eventURL: URL? let yesRSVPCount: Int? let id: String? let status: String? let name: String? let group: MeetupGroup let venue: MeetupVenue var duration: Int? { get { guard let millisecTime = durationInMillisec else { return nil } return millisecTime/1000 } } var startTime: Int? { get { guard let millisecTime = timeInMillisec else { return nil } return millisecTime/1000 } } init(eventName: String?, meetupDescription: String?, eventURL: URL?, yesRSVPCount: Int?, durationInMillisec: Int?, id: String?, timeInMillisec: Int?, status: String?, group: MeetupGroup, venue: MeetupVenue) { self.name = eventName self.meetupDescription = meetupDescription self.eventURL = eventURL self.yesRSVPCount = yesRSVPCount self.durationInMillisec = durationInMillisec self.id = id self.timeInMillisec = timeInMillisec self.status = status self.group = group self.venue = venue } }
mit
90caa34c83031bc4b43c774e4cafbb71
26.44
127
0.622449
3.875706
false
false
false
false
meninsilicium/apple-swifty
tests/Result-tests.swift
1
2780
// // author: fabrice truillot de chambrier // // © 2015-2015, men in silicium sàrl // import XCTest class ResultsTests : XCTestCase { func test_Result() { XCTAssert( Result().succeeded, "Result().succeeded" ) XCTAssert( Result( error: nil ).failed, "Result( error: nil ).failed" ) } func test_ResultOf() { let yes = ResultOf<Boolean>( true ) let no = ResultOf<Boolean>( false ) let error = ResultOf<Boolean>( error: Error( name: "Error", domain: "Results Tests" ) ) XCTAssert( yes.succeeded, "yes.succeeded" ) XCTAssert( yes.value == true, "yes.value == true" ) XCTAssert( no.succeeded, "no.succeeded" ) XCTAssert( no.value == false, "no.value == false" ) XCTAssert( !error.succeeded, "!error.succeeded" ) XCTAssert( error.failed, "error.failed" ) } func test_ResultOf_Iterable() { let yes = ResultOf<Boolean>( true ) let no = ResultOf<Boolean>( false ) let error = ResultOf<Boolean>( error: Error( name: "Error", domain: "Results Tests" ) ) var pass₁ = false yes.foreach { ( value: Boolean ) in if value { pass₁ = true } } XCTAssert( pass₁, "yes.foreach" ) var pass₂ = false no.foreach { ( index: Int, value: Boolean ) in if index == 0 && !value.boolValue { pass₂ = true } } XCTAssert( pass₂, "no.foreach" ) } func test_ResultOf_Monad() { let yes = ResultOf<Boolean>( true ) let no = ResultOf<Boolean>( false ) var success = yes.fmap { ( value: Boolean ) -> ResultOf<Boolean> in return value ? ResultOf( value ) : ResultOf<Boolean>( error: Error( name: "Error", domain: "Results Tests" ) ) } XCTAssert( success.succeeded, "success.succeeded" ) XCTAssert( success.value == true, "success.value == true" ) var error = no.fmap { ( value: Boolean ) -> ResultOf<Boolean> in return value ? ResultOf( value ) : ResultOf<Boolean>( error: Error( name: "Error", domain: "Results Tests" ) ) } XCTAssert( error.failed, "error.failed" ) XCTAssert( error.value == nil, "error.value == nil" ) } func test_ResultOf_Chaining() { let yes = ResultOf<Boolean>( true ) let no = ResultOf<Boolean>( false ) let error = ResultOf<Boolean>( error: Error( name: "Error", domain: "Results Tests" ) ) var pass₁ = false yes.onSuccess { ( value ) in if value { pass₁ = true } } .onFailure { ( error ) in pass₁ = false } XCTAssert( pass₁, "yes.onSuccess" ) var pass₂ = false no.onSuccess { ( value ) in if !value { pass₂ = true } } .onFailure { ( error ) in pass₂ = false } XCTAssert( pass₂, "no.onSuccess" ) var pass₃ = false error.onSuccess { ( value ) in pass₃ = false } .onFailure { ( error ) in pass₃ = true } XCTAssert( pass₃, "error.onFailure" ) } }
mpl-2.0
eb384293153164e60bdf5186ab26d8c7
21.47541
113
0.627279
2.980435
false
true
false
false
KarlWarfel/nutshell-ios
Nutshell/DataModel/CoreData/User.swift
1
1143
// // User.swift // // // Created by Brian King on 9/14/15. // // import Foundation import CoreData import SwiftyJSON class User: NSManagedObject { class func fromJSON(json: JSON, moc: NSManagedObjectContext) -> User? { if let entityDescription = NSEntityDescription.entityForName("User", inManagedObjectContext: moc) { let me = User(entity: entityDescription, insertIntoManagedObjectContext: nil) me.userid = json["userid"].string me.username = json["username"].string me.fullName = json["fullName"].string me.token = json["token"].string return me } return nil } func processProfileJSON(json: JSON) { NSLog("profile json: \(json)") fullName = json["fullName"].string if fullName != nil { self.managedObjectContext?.refreshObject(self, mergeChanges: true) NSLog("Added full name from profile: \(fullName)") } let patient = json["patient"] let isDSA = patient != nil accountIsDSA = NSNumber.init(bool: isDSA) } }
bsd-2-clause
ebe54ce17310b367f54a8d4b993c4a5c
27.575
107
0.594926
4.742739
false
false
false
false
Performador/Pickery
Pickery/Amazon.swift
1
11733
// // AWS.swift // Pickery // // Created by Okan Arikan on 6/13/16. // // import Foundation import AWSDynamoDB import AWSS3 import ReactiveSwift import Result import Photos /// AWS specialization for the backend class Amazon : Backend { /// Helper struct to hold AWS data struct Region { let regionEnum: AWSRegionType let name: String let regionString: String let coordinate: CLLocationCoordinate2D } /// Constants struct Constants { static let kPrefix = "pickery" ///< The prefix to use for the S3 and DynamoDB static let kUseTransferUtility = true ///< Are we using transfer utility for S3 or not static let kDynamoDBReadCapacityUnits = 25 ///< The default DynamoDB throughput static let kDynamoDBWriteCapacityUnits = 25 ///< The default DynamoDB throughput static let kRefreshPadding = TimeInterval(60) ///< The padding we apply to the date while fetching changes // The regions we present to the user and their locations for locating the closest one static let kAllRegions : [ Region ] = [ Region(regionEnum:.USEast1, name:"US East (N. Virginia)", regionString:"us-east-1", coordinate:CLLocationCoordinate2D(latitude: 37.478397, longitude: -76.453077)), Region(regionEnum:.USWest1, name:"US West (N. California)", regionString:"us-west-1", coordinate:CLLocationCoordinate2D(latitude: 36.778261, longitude: -119.417932)), Region(regionEnum:.USWest2, name:"US West (Oregon)", regionString:"us-west-2", coordinate:CLLocationCoordinate2D(latitude: 43.804133, longitude: -120.554201)), Region(regionEnum:.EUWest1, name:"EU (Ireland)", regionString:"eu-west-1", coordinate:CLLocationCoordinate2D(latitude: 53.412910, longitude: -8.243890)), Region(regionEnum:.EUCentral1, name:"EU (Frankfurt)", regionString:"eu-central-1", coordinate:CLLocationCoordinate2D(latitude: 50.110922, longitude: 8.682127)), Region(regionEnum:.APSoutheast1, name:"Asia Pacific (Singapore)", regionString:"ap-southeast-1", coordinate:CLLocationCoordinate2D(latitude: 1.352083, longitude: 103.819836)), Region(regionEnum:.APNortheast1, name:"Asia Pacific (Tokyo)", regionString:"ap-northeast-1", coordinate:CLLocationCoordinate2D(latitude: 35.689487, longitude: 139.691706)), Region(regionEnum:.APNortheast2, name:"Asia Pacific (Seoul)", regionString:"ap-northeast-2", coordinate:CLLocationCoordinate2D(latitude: 37.566535, longitude: 126.977969)), Region(regionEnum:.APSoutheast2, name:"Asia Pacific (Sydney)", regionString:"ap-southeast-2", coordinate:CLLocationCoordinate2D(latitude: -33.868820, longitude: 151.209296)), Region(regionEnum:.APSouth1, name:"Asia Pacific (Mumbai)", regionString:"sa-east-1", coordinate:CLLocationCoordinate2D(latitude: 19.075984, longitude: 72.877656)), Region(regionEnum:.SAEast1, name:"South America (Sao Paulo)", regionString:"sa-east-1", coordinate:CLLocationCoordinate2D(latitude: -23.550520, longitude: -46.633309)), Region(regionEnum:.CNNorth1, name:"China (Beijing)", regionString:"cn-north-1", coordinate:CLLocationCoordinate2D(latitude: 39.904211, longitude: 116.407395)), ] } /// The unique identifier for the account var identifier : String { return accessKey } /// The disposibles we are listenning let disposibles = ScopedDisposable(CompositeDisposable()) /// AWS: Access ID let accessKey : String /// AWS: Secret Key let secretKey : String /// The default region to use let region : AWSRegionType /// The bucket name to use let bucketName : String /// The queue responsible for running tasks let taskQueue = AmazonTaskQueue() /// Ctor /// /// - parameter accessKey : AWS access key /// - parameter secretKey : AWS secret key /// - parameter defaultRegion : The region to use to create AWS resources in private init(accessKey: String, secretKey: String, region: AWSRegionType, S3UUID: UUID) { // Save the parameters self.accessKey = accessKey self.secretKey = secretKey self.region = region self.bucketName = Constants.kPrefix + "-" + S3UUID.uuidString.lowercased() // Listen to the background URL stuff so we can do // backgound uploads using AWS SDK disposibles += ApplicationState .sharedInstance .backgroundURLHandle .signal .observeValues { (application: UIApplication, identifier: String, completion: @escaping CompletionHandler) in // Deliver the callback to AWS SDK AWSS3TransferUtility.interceptApplication(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completion) } } /// Figure out the region for a given region string /// /// - parameter string: The region string like us-west-2 /// - returns: The region struct that contains information about this region class func region(for string: String) -> Region? { return Constants.kAllRegions.filter { $0.name == string }.first } /// Remove all backend stuff /// /// - returns: A signal producer that will remove the backend func removeBackend() -> SignalProducer<(), NSError> { return Amazon .deleteDynamoDBTable(queue: taskQueue, tableName: AmazonModel.dynamoDBTableName()) .concat(Amazon.deleteS3(queue: taskQueue, bucketName: bucketName)) } /// Create an initializer for given credentials /// /// The initializer will (try) creating the Pickery bucket and the DynamoDB table /// /// - parameter accessKey: The user's access key /// - parameter secretKey: The user's secret key /// - parameter region: The region we want to operate in /// - returns: A signal provider that will do the initialization static func initialize(accessKey: String, secretKey: String, region: AWSRegionType) -> SignalProducer<Backend,NSError> { // The queue we will use for the initialization only let taskQueue = AmazonTaskQueue() // Do the initialization return SignalProducer<(), NSError> { sink,disposible in // First, set the credentials let credentialsProvider = AWSStaticCredentialsProvider(accessKey: accessKey, secretKey: secretKey) let serviceProvider = AWSServiceConfiguration(region: region, credentialsProvider: credentialsProvider) // Setup the log level AWSDDLog.sharedInstance.logLevel = .error // Set these credentials as the default credentials to use AWSServiceManager.default().defaultServiceConfiguration = serviceProvider // Done with the initialization sink.sendCompleted() }.then( // Initialize the S3 bucket Amazon.initializeDynamoDBTable(queue: taskQueue, tableName: AmazonModel.dynamoDBTableName()) // Initialize S3 bucket .then(Amazon.initializeS3(queue: taskQueue).map { return Amazon(accessKey: accessKey, secretKey: secretKey, region: region, S3UUID: $0) }) ) } /// Create a presigned URL for a key func signedURL(for key: String) -> SignalProducer<URL, NSError> { return Amazon.signedURLFor(queue: taskQueue, bucketName: bucketName, key: key) } /// Download a remote key /// /// When the download is done, the uploaded signal will be triggered with /// the downloaded key and it's location on disk /// /// - parameter key: The remote object key to fetch /// - parameter byteRange: The byte range to fetch func download(key: String, to file: URL) -> SignalProducer<(String, URL),NSError> { return Amazon.download(queue: taskQueue, bucketName: bucketName, key: key, to: file) } /// Refresh the local cache /// /// - parameter since: The last modification date /// - returns: A signal source that will emit the set of changed assets func changes(since: Date) -> SignalProducer<[(String,Double,String?)],NSError> { // Capture these let queue = self.taskQueue return SignalProducer< [ AmazonModel ], NSError> { sink, disposible in // Ask for the changes Amazon.refresh(queue: queue, timeStateChanged: (GlobalConstants.double(from: since) - Constants.kRefreshPadding), startKey: nil, sink: sink) // Extract the meta data from AmazonModel }.map { models in return models.map { model in (model.signature,model.timeStateChanged.doubleValue,model.metaData) } } } /// Upload a particular asset /// /// - parameter file: The resource to upload /// - returns: The producer that will execute the task func upload(file: PendingUploadResource) -> SignalProducer<UploadResourceReceipt,NSError> { // Upload the individual resources return Amazon.uploadResource(queue: taskQueue, bucketName: bucketName, fileToUpload: file) } /// Record an asset in DynamoDB /// /// - parameter metaData: The asset meta data to record /// - parameter resources: The resource receipts to go into this asset /// - returns: The producer that will execute the task func record(asset metaData: [ String : Any ], resources: [ UploadResourceReceipt ]) -> SignalProducer<UploadAssetReceipt,NSError> { // Record it return Amazon.record(asset: metaData, using: taskQueue, with: resources) } /// Remove the assets from DynamoDB /// /// - parameter assets: The asset signatures to remove /// - returns: The producer that will execute the task func remove(assets: [ String ]) -> SignalProducer<String, NSError> { // Capture the queue let queue = taskQueue // Produce signatures to delete return SignalProducer<String, NSError>(assets) // This is where we delete a single asset .flatMap(.merge) { signature in Amazon.recordAssetDeletion(queue: queue, signature: signature) } } /// Remove keys from S3 /// /// - parameter resources: The resource signatures to remove /// - returns: The producer that will execute the task func remove(resources: [ String ]) -> SignalProducer<String, NSError> { return Amazon.removeKeys(queue: taskQueue, bucketName: bucketName, keys: resources) } }
mit
b12e54573ea74f6c2a2c4cccdb05f1e0
45.74502
196
0.605301
4.896912
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Sources/EurofurenceModel/Private/Services/ConcretePrivateMessagesService.swift
1
7090
class ConcretePrivateMessagesService: PrivateMessagesService { private let eventBus: EventBus private let api: API private var subscriptions = Set<AnyHashable>() private lazy var state: State = UnauthenticatedState(service: self) private var observers = [PrivateMessagesObserver]() private var localMessages: [MessageImpl] = .empty { didSet { observers.forEach({ $0.privateMessagesServiceDidFinishRefreshingMessages(messages: localMessages) }) } } private struct MarkMessageAsReadHandler: EventConsumer { private unowned let service: ConcretePrivateMessagesService init(service: ConcretePrivateMessagesService) { self.service = service } func consume(event: MessageImpl.ReadEvent) { service.state.markMessageAsRead(event.message) } } private struct EnterAuthenticatedStateWhenLoggedIn: EventConsumer { private unowned let service: ConcretePrivateMessagesService init(service: ConcretePrivateMessagesService) { self.service = service } func consume(event: DomainEvent.LoggedIn) { service.userLoggedIn(event) } } private struct ExitAuthenticatedStateWhenLoggedOut: EventConsumer { private unowned let service: ConcretePrivateMessagesService init(service: ConcretePrivateMessagesService) { self.service = service } func consume(event: DomainEvent.LoggedOut) { service.userLoggedOut(event) } } init(eventBus: EventBus, api: API) { self.eventBus = eventBus self.api = api subscriptions.insert(eventBus.subscribe(consumer: EnterAuthenticatedStateWhenLoggedIn(service: self))) subscriptions.insert(eventBus.subscribe(consumer: ExitAuthenticatedStateWhenLoggedOut(service: self))) subscriptions.insert(eventBus.subscribe(consumer: MarkMessageAsReadHandler(service: self))) } func add(_ observer: PrivateMessagesObserver) { observers.append(observer) observer.privateMessagesServiceDidUpdateUnreadMessageCount(to: determineUnreadMessageCount()) observer.privateMessagesServiceDidFinishRefreshingMessages(messages: localMessages) } func removeObserver(_ observer: PrivateMessagesObserver) { if let index = observers.firstIndex(where: { $0 === observer }) { observers.remove(at: index) } } func refreshMessages() { refreshMessages(completionHandler: nil) } func fetchMessage( identifiedBy identifier: MessageIdentifier, completionHandler: @escaping (Result<Message, PrivateMessageError>) -> Void ) { if let message = findMessage(identifiedBy: identifier) { completionHandler(.success(message)) } else { refreshMessagesWithIntentToAcquireMessage(identifiedBy: identifier, completionHandler: completionHandler) } } private func findMessage(identifiedBy identifier: MessageIdentifier) -> Message? { localMessages.first(where: { $0.identifier == identifier }) } private func refreshMessagesWithIntentToAcquireMessage( identifiedBy identifier: MessageIdentifier, completionHandler: @escaping (Result<Message, PrivateMessageError>) -> Void ) { refreshMessages(completionHandler: { (result) in if result == nil { completionHandler(.failure(.loadingMessagesFailed)) } else { if let message = self.findMessage(identifiedBy: identifier) { completionHandler(.success(message)) } else { completionHandler(.failure(.noMessageFound)) } } }) } func refreshMessages(completionHandler: (([MessageCharacteristics]?) -> Void)? = nil) { state.refreshMessages(completionHandler: completionHandler) } private func updateEntities(from messages: [MessageCharacteristics]) { localMessages = messages.map(makeMessage).sorted() updateObserversWithUnreadMessageCount() } private func notifyDidFailToLoadMessages() { observers.forEach({ $0.privateMessagesServiceDidFailToLoadMessages() }) } private func updateObserversWithUnreadMessageCount() { let unreadCount = determineUnreadMessageCount() observers.forEach({ $0.privateMessagesServiceDidUpdateUnreadMessageCount(to: unreadCount) }) } private func determineUnreadMessageCount() -> Int { return localMessages.filter({ $0.isRead == false }).count } private func makeMessage(from characteristics: MessageCharacteristics) -> MessageImpl { return MessageImpl(eventBus: eventBus, characteristics: characteristics) } private func userLoggedIn(_ event: DomainEvent.LoggedIn) { state = AuthenticatedState(service: self, token: event.authenticationToken) } private func userLoggedOut(_ event: DomainEvent.LoggedOut) { localMessages.removeAll() state = UnauthenticatedState(service: self) } // MARK: State Machine private class State { unowned let service: ConcretePrivateMessagesService init(service: ConcretePrivateMessagesService) { self.service = service } func refreshMessages(completionHandler: (([MessageCharacteristics]?) -> Void)? = nil) { } func markMessageAsRead(_ message: Message) { } } private class UnauthenticatedState: State { override func refreshMessages(completionHandler: (([MessageCharacteristics]?) -> Void)?) { service.notifyDidFailToLoadMessages() completionHandler?(nil) } } private class AuthenticatedState: State { private let token: String init(service: ConcretePrivateMessagesService, token: String) { self.token = token super.init(service: service) refreshMessages(completionHandler: nil) } override func refreshMessages(completionHandler: (([MessageCharacteristics]?) -> Void)?) { service.api.loadPrivateMessages(authorizationToken: token) { (messages) in if let messages = messages { self.service.updateEntities(from: messages) } else { self.service.notifyDidFailToLoadMessages() } completionHandler?(messages) } } override func markMessageAsRead(_ message: Message) { service.api.markMessageWithIdentifierAsRead(message.identifier.rawValue, authorizationToken: token) service.updateObserversWithUnreadMessageCount() } } }
mit
0c050e3d76aae0d636651b1acd35eab3
33.926108
117
0.63921
5.726979
false
false
false
false
paulofaria/HTTP-Server
JSON Parser Middleware/JSONParserMiddleware.swift
3
2012
// JSONParserMiddleware.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. extension Middleware { static func parseJSON(key key: String)(var request: HTTPRequest) throws -> RequestMiddlewareResult<HTTPRequest, HTTPResponse> { // TODO: put contenty type as computed property on httprequest guard let contentType = request.headers["content-type"] where MediaType(contentType).type == "application/json" else { return .Request(request) } let json = try JSONParser.parse(request.body) request.data = request.data + [key: json] return .Request(request) } static func parseJSON(request: HTTPRequest) throws -> RequestMiddlewareResult<HTTPRequest, HTTPResponse> { return try parseJSON(key: "JSON")(request: request) } } extension HTTPRequest { var json: JSON? { return try? getData("JSON") } }
mit
ec519a4d3c2ba62cd6beee983dc59288
33.101695
131
0.712724
4.593607
false
false
false
false
ohadh123/MuscleUp-
Pods/LionheartExtensions/Pod/Classes/Core/UIWindow+LionheartExtensions.swift
1
1859
// // Copyright 2016 Lionheart Software 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. // // import Foundation /** Helper methods for `UIWindow`. */ public extension UIWindow { /** Take a screenshot and save to the specified file path. Helpful for creating screenshots via automated tests. - parameter path: The path on the local filesystem to save the screenshot to. - returns: A bool indicating whether the save was successful. - author: Daniel Loewenherz - copyright: ©2016 Lionheart Software LLC - date: February 17, 2016 */ class func takeScreenshotAndSaveToPath(_ path: String) -> Bool { guard let window = UIApplication.shared.keyWindow else { return false } let bounds = window.bounds UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0) window.drawHierarchy(in: bounds, afterScreenUpdates: true) let _image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let image = _image, let data = UIImagePNGRepresentation(image) else { return false } let url = URL(fileURLWithPath: path) guard let _ = try? data.write(to: url, options: []) else { return false } return true } }
apache-2.0
de354f07715f39f1856f9c1519cc4699
31.596491
113
0.669537
4.715736
false
false
false
false
back2mach/OAuthSwift
Sources/OAuthSwiftMultipartData.swift
17
1460
// // OAuthSwiftMultipartData.swift // OAuthSwift // // Created by Tomohiro Kawaji on 12/18/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import Foundation public struct OAuthSwiftMultipartData { public var name: String public var data: Data public var fileName: String? public var mimeType: String? public init(name: String, data: Data, fileName: String?, mimeType: String?) { self.name = name self.data = data self.fileName = fileName self.mimeType = mimeType } } extension Data { public mutating func append(_ multipartData: OAuthSwiftMultipartData, encoding: String.Encoding, separatorData: Data) { var filenameClause = "" if let filename = multipartData.fileName { filenameClause = " filename=\"\(filename)\"" } let contentDispositionString = "Content-Disposition: form-data; name=\"\(multipartData.name)\";\(filenameClause)\r\n" let contentDispositionData = contentDispositionString.data(using: encoding)! self.append(contentDispositionData) if let mimeType = multipartData.mimeType { let contentTypeString = "Content-Type: \(mimeType)\r\n" let contentTypeData = contentTypeString.data(using: encoding)! self.append(contentTypeData) } self.append(separatorData) self.append(multipartData.data) self.append(separatorData) } }
mit
5db29650ee8124f228f8e2c79e4b8164
29.416667
125
0.663014
4.534161
false
false
false
false
ChristianKienle/highway
Tests/TaskTests/SystemExecutableProviderTests.swift
1
1942
import XCTest import Task import ZFile import Url /// Tests the SystemExecutableProvider with a custom FileSystem final class SystemExecutableProviderTests: XCTestCase { // MARK: - Properties private var finder = SystemExecutableProvider(searchedUrls: [], fileSystem: InMemoryFileSystem()) private var fs: FileSystem { return finder.fileSystem } // MARK: - XCTest override func setUp() { super.setUp() finder = SystemExecutableProvider(searchedUrls: [], fileSystem: InMemoryFileSystem()) } // MARK: - Tests func testWithEmptyFileSystem() { XCTAssertNil(finder.urlForExecuable("hello")) XCTAssertNil(finder.urlForExecuable("/hello")) XCTAssertNil(finder.urlForExecuable("/local")) XCTAssertNil(finder.urlForExecuable("local")) XCTAssertNil(finder.urlForExecuable("")) finder.searchedUrls = ["/usr/bin", "/hello", "/usr/local"] XCTAssertNil(finder.urlForExecuable("hello")) XCTAssertNil(finder.urlForExecuable("/hello")) XCTAssertNil(finder.urlForExecuable("/local")) XCTAssertNil(finder.urlForExecuable("local")) XCTAssertNil(finder.urlForExecuable("")) } func testSimple() { XCTAssertNoThrow(try fs.createDirectory(at: "/usr/bin")) XCTAssertNoThrow(try fs.writeData(Data(), to: "/usr/bin/bash")) finder.searchedUrls = ["/usr/bin"] XCTAssertEqual(finder.urlForExecuable("bash"), "/usr/bin/bash") } func testThatOrderIsOK() { XCTAssertNoThrow(try fs.createDirectory(at: "/usr/bin")) XCTAssertNoThrow(try fs.createDirectory(at: "/local/bin")) XCTAssertNoThrow(try fs.writeData(Data(), to: "/usr/bin/bash")) XCTAssertNoThrow(try fs.writeData(Data(), to: "/local/bin/bash")) finder.searchedUrls = ["/local/bin", "/usr/bin"] XCTAssertEqual(finder.urlForExecuable("bash"), "/local/bin/bash") } }
mit
a37f0fbd3dcbd9840e0a90bc687e8fb3
39.458333
101
0.667868
4.43379
false
true
false
false
CD1212/Doughnut
Doughnut/Library/Library.swift
1
14063
/* * Doughnut Podcast Client * Copyright (C) 2017 Chris Dyer * * 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 FeedKit import GRDB #if DEBUG let INITIAL_RELOAD_WAIT: TimeInterval = 60.0 #else let INITIAL_RELOAD_WAIT: TimeInterval = 10.0 #endif protocol LibraryDelegate { func librarySubscribedToPodcast(subscribed: Podcast) func libraryUnsubscribedFromPodcast(unsubscribed: Podcast) func libraryUpdatingPodcast(podcast: Podcast) func libraryUpdatedPodcast(podcast: Podcast) func libraryUpdatedEpisode(episode: Episode) func libraryReloaded() } class Library: NSObject { static var global = Library() static let databaseFilename = "Doughnut Library.dnl" enum Events:String { case Subscribed = "Subscribed" case Unsubscribed = "Unsubscribed" case Loaded = "Loaded" case Reloaded = "Reloaded" case PodcastUpdated = "PodcastUpdated" case Downloading = "Downloading" var notification: Notification.Name { return Notification.Name(rawValue: self.rawValue) } } let path: URL var dbQueue: DatabaseQueue? var delegate: LibraryDelegate? let taskQueue = DispatchQueue(label: "com.doughnut.Library") let backgroundQueue = DispatchQueue(label: "com.doughnut.Background") let tasks = TaskQueue() var podcasts = [Podcast]() let downloadManager = DownloadManager() var unplayedCount: Int { get { return podcasts.reduce(0) { $0 + $1.unplayedCount } } } var minutesSinceLastScheduledReload = 0 override init() { let libraryPath = Preference.libraryPath() var isDir = ObjCBool(true) if FileManager.default.fileExists(atPath: libraryPath.path, isDirectory: &isDir) { self.path = libraryPath } else { self.path = Library.locate() } } func connect() -> Bool { do { dbQueue = try DatabaseQueue(path: databaseFile().path) if let dbQueue = dbQueue { try LibraryMigrations.migrate(db: dbQueue) if !Preference.testEnv() { print("Connected to Doughnut library at \(path.path)") } try dbQueue.inDatabase({ db in podcasts = try Podcast.fetchAll(db) for podcast in podcasts { podcast.loadEpisodes(db: db) #if DEBUG print("Loading \(podcast.title) with \(podcast.episodes.count) episodes") #endif } delegate?.libraryReloaded() }) // After an initial delay, schedule auto-reload Timer.scheduledTimer(withTimeInterval: INITIAL_RELOAD_WAIT, repeats: false, block: { _ in // Perform an initial reload for podcast in Library.global.podcasts { if !podcast.manualReload { self.reload(podcast: podcast) } } // Schedule following reloads Timer.scheduledTimer(withTimeInterval: 60.0, repeats: true, block: { timer in Library.global.minutesSinceLastScheduledReload += 1 Library.global.scheduledReload() }) }) return true } else { return false } } catch let error { let alert = NSAlert() alert.messageText = "Failed to connect to library" alert.informativeText = "\(databaseFile().path)\n\nError: \(error)" alert.runModal() return false } } func databaseFile() -> URL { return self.path.appendingPathComponent(Library.databaseFilename) } static private func databaseFile(inPath: URL) -> URL { return inPath.appendingPathComponent(Library.databaseFilename) } static private func locate() -> URL { let alert = NSAlert() alert.addButton(withTitle: "Locate Library") alert.addButton(withTitle: "Default Library") alert.addButton(withTitle: "Quit") alert.messageText = "Doughnut Library Not Found" alert.informativeText = "Your Doughnut library could not be found. If you have an existing library, choose to locate it or create a blank new podcast library in the default location." let result = alert.runModal() if result == .alertFirstButtonReturn { let panel = NSOpenPanel() panel.canChooseFiles = false panel.canChooseDirectories = true panel.runModal() if let url = panel.url { Preference.set(url, for: Preference.Key.libraryPath) return url } else { return Library.locate() } } else if result == .alertSecondButtonReturn { // Reset library preference to default Preference.set(Preference.defaultLibraryPath, for: Preference.Key.libraryPath) return Preference.defaultLibraryPath } else { exit(0) } } static func handleDatabaseError(_ error: Error) { print("Library error \(error)") // let alert = NSAlert() } static func sanitizePath(_ path: String) -> String { let illegal = CharacterSet(charactersIn: "/\\%:|\"<>") return path.components(separatedBy: illegal).joined(separator: "") } // // General library methods func detectedNewEpisodes(podcast: Podcast, episodes: [Episode]) { guard let firstEpisode = episodes.first else { return } let notification = NSUserNotification() notification.soundName = NSUserNotificationDefaultSoundName if let artwork = podcast.image { notification.contentImage = artwork } if episodes.count > 1 { notification.title = "New Episodes of \(podcast.title)" notification.informativeText = "\(firstEpisode.title) + \(episodes.count - 1) more" } else { notification.title = "New Episode of \(podcast.title)" notification.informativeText = firstEpisode.title } if podcast.autoDownload { if let latestEpisode = episodes.first { latestEpisode.download() } } NSUserNotificationCenter.default.deliver(notification) } func subscribe(url: String) { guard let dbQueue = self.dbQueue else { return } guard let feedUrl = URL(string: url) else { return } taskQueue.async { do { // Check if the podcast is already subscribed to let existing = try dbQueue.inDatabase({ db -> Podcast? in return try Podcast.filter(Column("feed") == feedUrl.absoluteString).fetchOne(db) }) if existing != nil { return } } catch { Library.handleDatabaseError(error) return } if let podcast = Podcast.subscribe(feedUrl: feedUrl) { self.save(podcast: podcast, completion: { (podcast, error) in guard error == nil else { return } // Don't notify newly detected episodes for a new subscription, maybe change in future? // self.detectedNewEpisodes(podcast: podcast, episodes: podcast.episodes) DispatchQueue.main.async { self.podcasts.append(podcast) self.delegate?.librarySubscribedToPodcast(subscribed: podcast) } }) } } } func subscribe(podcast: Podcast) { guard let dbQueue = self.dbQueue else { return } taskQueue.async { do { // Check if the podcast is already subscribed to let existing = try dbQueue.inDatabase({ db -> Podcast? in return try Podcast.filter(Column("feed") == podcast.feed).fetchOne(db) }) if existing != nil { return } } catch { Library.handleDatabaseError(error) return } self.save(podcast: podcast, completion: { (podcast, error) in guard error == nil else { return } DispatchQueue.main.async { self.podcasts.append(podcast) self.delegate?.librarySubscribedToPodcast(subscribed: podcast) } }) } } func unsubscribe(podcast: Podcast, removeFiles: Bool = false) { guard let storedIndex = podcasts.index(where: { p -> Bool in p.id == podcast.id }) else { return } podcasts.remove(at: storedIndex) self.delegate?.libraryReloaded() taskQueue.async { if removeFiles { if let storagePath = podcast.storagePath() { NSWorkspace.shared.recycle([storagePath], completionHandler: { (trashedFiles, error) in if let error = error { print("Failed to move podcast data to trash: \(error.localizedDescription)") let alert = NSAlert() alert.messageText = "Failed to trash data" alert.informativeText = error.localizedDescription } else { print("Moved podcast data stored at \(trashedFiles) to trash") } }) } } do { _ = try self.dbQueue?.inDatabase { db in try podcast.delete(db) } DispatchQueue.main.async { self.delegate?.libraryUnsubscribedFromPodcast(unsubscribed: podcast) } } catch let error as DatabaseError { Library.handleDatabaseError(error) } catch {} } } func podcast(id: Int64) -> Podcast? { return podcasts.first { (podcast) -> Bool in podcast.id == id } } func episode(id: Int64) -> Episode? { for p in podcasts { for e in p.episodes { if e.id == id { return e } } } return nil } func scheduledReload() { let reloadFrequency = Preference.integer(for: Preference.Key.reloadFrequency) // Reload podcasts on custom schedules for podcast in podcasts { if !podcast.manualReload && !podcast.defaultReload { if (minutesSinceLastScheduledReload >= podcast.reloadFrequency) && (podcast.reloadFrequency % minutesSinceLastScheduledReload == 0) { reload(podcast: podcast, onQueue: backgroundQueue) } } } // Reload podcasts on the default schedule if (minutesSinceLastScheduledReload >= reloadFrequency) { for podcast in podcasts { if podcast.defaultReload { reload(podcast: podcast, onQueue: backgroundQueue) } } minutesSinceLastScheduledReload = 0 } } func reloadAll() { for podcast in podcasts { reload(podcast: podcast) } } func reload(podcast: Podcast, onQueue: DispatchQueue? = nil) { let workerQueue = onQueue ?? taskQueue workerQueue.async { // Mark as loading podcast.loading = true DispatchQueue.main.async { self.delegate?.libraryUpdatingPodcast(podcast: podcast) } let newEpisodes = podcast.fetch() podcast.loading = false self.save(podcast: podcast) DispatchQueue.main.async { if newEpisodes.count > 0 { self.detectedNewEpisodes(podcast: podcast, episodes: newEpisodes) } } } } // Synchronous episode save func save(episode: Episode, completion: (_ result: Episode, _ error: Error?) -> Void) { do { try self.dbQueue?.inDatabase { db in if episode.id != nil { try episode.updateChanges(db) } else { try episode.save(db) } } completion(episode, nil) } catch let error as DatabaseError { Library.handleDatabaseError(error) completion(episode, error) } catch { completion(episode, error) } } // Async episode save and event emission func save(episode: Episode) { taskQueue.async { self.save(episode: episode, completion: { (episode, error) in guard error == nil else { return } DispatchQueue.main.async { self.delegate?.libraryUpdatedEpisode(episode: episode) if let parent = episode.podcast { self.delegate?.libraryUpdatedPodcast(podcast: parent) } } }) } } func delete(episode: Episode) { guard let podcast = episode.podcast else { return } taskQueue.async { do { _ = try self.dbQueue?.inDatabase { db in try episode.delete(db) } DispatchQueue.main.async { self.delegate?.libraryUpdatedPodcast(podcast: podcast) } } catch let error as DatabaseError { Library.handleDatabaseError(error) } catch {} } } // Synchronous podcast save func save(podcast: Podcast, completion: (_ result: Podcast, _ error: Error?) -> Void) { do { try self.dbQueue?.inDatabase { db in try podcast.save(db) for episode in podcast.episodes { if episode.id != nil { try episode.updateChanges(db) } else { try episode.save(db) } } } completion(podcast, nil) } catch let error as DatabaseError { Library.handleDatabaseError(error) completion(podcast, nil) } catch { completion(podcast, nil) } } // Async podcast save and event emission func save(podcast: Podcast) { taskQueue.async { self.save(podcast: podcast, completion: { (podcast, error) in guard error == nil else { return } podcast.loading = false DispatchQueue.main.async { self.delegate?.libraryUpdatedPodcast(podcast: podcast) } }) } } }
gpl-3.0
289f4ffa6adb2f05c6133f74437aac95
27.995876
187
0.61324
4.664345
false
false
false
false
masters3d/xswift
exercises/palindrome-products/Sources/PalindromeProductsExample.swift
1
2351
import Foundation import Dispatch private extension String { var length: Int { return self.characters.count } func reverse() -> String { return characters.reversed().map { String($0) }.joined() } } struct PalindromeProducts { typealias Palindrome = (value: Int, factor: [Int]) private let maxFactor: Int private let minFactor: Int var largest: Palindrome { return calculate(.max) } var smallest: Palindrome { return calculate(.min) } init(maxFactor: Int, minFactor: Int = 1) { self.maxFactor = maxFactor self.minFactor = minFactor } private enum Mode { case max, min } private func calculate(_ upTo: Mode) -> Palindrome { let rangeOuter = minFactor...maxFactor //Multithreaded code var results = [[Palindrome]](repeating: [Palindrome](), count: rangeOuter.count) // use this queue to read and write from results let resultsRWQueue = DispatchQueue.init(label: "exercism.resultsRWQueue") DispatchQueue.concurrentPerform(iterations: rangeOuter.count) { advanceByIndex in var multiplicationsTemp = [Palindrome]() let each = rangeOuter.lowerBound + advanceByIndex let innerRangeCustom = each...rangeOuter.upperBound for eaInside in innerRangeCustom { let multiplied = each * eaInside let number = String(multiplied) if number == number.reverse() { multiplicationsTemp.append((multiplied, [each, eaInside])) } } // prevent data race conditions resultsRWQueue.async { results[advanceByIndex] = multiplicationsTemp } } var multiplications = [Palindrome]() // prevent data race conditions resultsRWQueue.sync { multiplications = results.joined().sorted(by: { $0.value > $1.value }) } if let large = multiplications.first, let small = multiplications.last { switch upTo { case .max: return large case .min: return small } } else { switch upTo { case .max: return (maxFactor, [maxFactor, 1]) case .min: return (minFactor, [minFactor, 1]) } } } }
mit
ca3c74694ac11b6c3422d8c606be6b7b
31.652778
88
0.589536
4.720884
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/OEXFonts.swift
3
2481
// // OEXFonts.swift // edX // // Created by José Antonio González on 11/2/16. // Copyright © 2016 edX. All rights reserved. // import UIKit public class OEXFonts: NSObject { //MARK: - Shared Instance public static let sharedInstance = OEXFonts() @objc public enum FontIdentifiers: Int { case Regular = 1, Italic, SemiBold, SemiBoldItalic, Bold, BoldItalic, Light, LightItalic, ExtraBold, ExtraBoldItalic, Irregular } public var fontsDictionary = [String: AnyObject]() private override init() { super.init() fontsDictionary = initializeFontsDictionary() } private func initializeFontsDictionary() -> [String: AnyObject] { guard let filePath = NSBundle.mainBundle().pathForResource("fonts", ofType: "json") else { return fallbackFonts() } if let data = NSData(contentsOfFile: filePath) { var error : NSError? if let json = JSON(data: data, error: &error).dictionaryObject{ return json } } return fallbackFonts() } public func fallbackFonts() -> [String: AnyObject] { return OEXFontsDataFactory.fonts } public func fontForIdentifier(identifier: FontIdentifiers, size: CGFloat) -> UIFont { if let fontName = fontsDictionary[getIdentifier(identifier)] as? String { return UIFont(name: fontName, size: size)! } return UIFont(name:getIdentifier(FontIdentifiers.Irregular), size: size)! } private func getIdentifier(identifier: FontIdentifiers) -> String { switch identifier { case .Regular: return "regular" case .Italic: return "italic" case .SemiBold: return "semiBold" case .SemiBoldItalic: return "semiBoldItalic" case .Bold: return "bold" case .BoldItalic: return "boldItalic" case .Light: return "light" case .LightItalic: return "lightItalic" case .ExtraBold: return "extraBold" case .ExtraBoldItalic: return "extraBoldItalic" case .Irregular: fallthrough default: //Assert to crash on development, and return Zapfino font assert(false, "Could not find the required font in fonts.json") return "Zapfino" } } }
apache-2.0
f93d749614e4298d61e3a73db79ccf9d
29.219512
135
0.589992
4.81165
false
false
false
false
okerivy/AlgorithmLeetCode
AlgorithmLeetCode/AlgorithmLeetCode/E_108_ConvertSortedArrayToBinarySearchTree.swift
1
1796
// // E_108_ConvertSortedArrayToBinarySearchTree.swift // AlgorithmLeetCode // // Created by okerivy on 2017/3/20. // Copyright © 2017年 okerivy. All rights reserved. // https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree import Foundation // MARK: - 题目名称: 108. Convert Sorted Array to Binary Search Tree /* MARK: - 所属类别: 标签: Tree, Depth-first Search 相关题目: (M) Convert Sorted List to Binary Search Tree */ /* MARK: - 题目英文: Given an array where elements are sorted in ascending order, convert it to a height balanced BST. */ /* MARK: - 题目翻译: 给定一个数组,其中的元素按升序排序,将它转换成一个高度平衡的二叉查找树。 */ /* MARK: - 解题思路: 二分法 */ /* MARK: - 复杂度分析: 二分法,时间复杂度O(n),空间复杂度O(logn) */ // MARK: - 代码: private class Solution { func sortedArrayToBST(_ nums: [Int]) -> TreeNode? { return build(nums, 0, nums.count) } private func build(_ nums: [Int], _ start: Int, _ end: Int) -> TreeNode? { // 终止条件 if start >= end { return nil } // 获取中间节点 let mid = start + (end - start)/2 // 根据中间节点生成 根节点 let root: TreeNode? = CreateBinaryTree().convertNumberToTree(nums[mid]) root?.left = build(nums, start, mid) root?.right = build(nums, mid + 1, end) return root } } // MARK: - 测试代码: // MARK: - 测试代码: func ConvertSortedArrayToBinarySearchTree() { // 单链表 let root = Solution().sortedArrayToBST([1, 2, 3, 4, 5, 6, 7, 8]) print(root ?? "构建失败") }
mit
76eb31f54fa774ec0dd9a03b486cb6c5
16.781609
98
0.585003
3.176591
false
false
false
false
ashfurrow/pragma-2015-rx-workshop
Session 4/Signup Demo/Signup Demo/ViewModel.swift
1
1934
import Foundation import Moya import RxSwift typealias ErrorHandler = ErrorType -> Observable<UIImage!> protocol ViewModelType { init( email: Observable<String>, password: Observable<String>, enabled: ObserverOf<Bool>, submit: Observable<Void>, errorHandler: ErrorHandler) var image: Observable<UIImage!> { get } } class ViewModel: NSObject, ViewModelType { let disposeBag = DisposeBag() private let _povider: RxMoyaProvider<MyAPI> private var imageVariable = Variable<UIImage!>(nil) var image: Observable<UIImage!> { return self.imageVariable.asObservable() } convenience required init( email: Observable<String>, password: Observable<String>, enabled: ObserverOf<Bool>, submit: Observable<Void>, errorHandler: ErrorHandler) { self.init( email: email, password: password, enabled: enabled, submit: submit, errorHandler: errorHandler, provider: provider ) } init( email: Observable<String>, password: Observable<String>, enabled: ObserverOf<Bool>, submit: Observable<Void>, errorHandler: ErrorHandler, provider: RxMoyaProvider<MyAPI>) { _povider = provider super.init() let validEmail = email.map(isEmail) let validPassword = password.map(isPassword) combineLatest(validEmail, validPassword, and).bindTo(enabled) submit.take(1).map { _ -> Observable<MoyaResponse> in return provider.request(.Image) }.switchLatest() .filterSuccessfulStatusCodes() .mapImage() .catchError(errorHandler) .subscribeNext { [weak self] (receivedImage) -> Void in self?.imageVariable.value = receivedImage } .addDisposableTo(disposeBag) } }
mit
cad2661da4e4f2211d576bcccc90fff1
25.493151
69
0.616339
5.049608
false
false
false
false
lorentey/swift
test/Reflection/typeref_decoding_imported.swift
3
4888
// XFAIL: OS=windows-msvc // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ImportedTypes.swift %S/Inputs/ImportedTypesOther.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/%target-library-name(TypesToReflect) -I %S/Inputs // RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu // ... now, test single-frontend mode with multi-threaded LLVM emission: // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ImportedTypes.swift %S/Inputs/ImportedTypesOther.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/%target-library-name(TypesToReflect) -I %S/Inputs -whole-module-optimization -num-threads 2 // RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-cpu // CHECK-32: FIELDS: // CHECK-32: ======= // CHECK-32: TypesToReflect.HasCTypes // CHECK-32: ------------------------ // CHECK-32: mcs: __C.MyCStruct // CHECK-32: (struct __C.MyCStruct) // CHECK-32: mce: __C.MyCEnum // CHECK-32: (struct __C.MyCEnum) // CHECK-32: __C.MyCStruct // CHECK-32: ------------- // CHECK-32: i: Swift.Int32 // CHECK-32: (struct Swift.Int32) // CHECK-32: ip: Swift.Optional<Swift.UnsafeMutablePointer<Swift.Int32>> // CHECK-32: (bound_generic_enum Swift.Optional // CHECK-32: (bound_generic_struct Swift.UnsafeMutablePointer // CHECK-32: (struct Swift.Int32))) // CHECK-32: c: Swift.Int8 // CHECK-32: (struct Swift.Int8) // CHECK-32: TypesToReflect.AlsoHasCTypes // CHECK-32: ---------------------------- // CHECK-32: mcu: __C.MyCUnion // CHECK-32: (struct __C.MyCUnion) // CHECK-32: mcsbf: __C.MyCStructWithBitfields // CHECK-32: (struct __C.MyCStructWithBitfields) // CHECK-32: ASSOCIATED TYPES: // CHECK-32: ================= // CHECK-32: BUILTIN TYPES: // CHECK-32: ============== // CHECK-32-LABEL: - __C.MyCStruct: // CHECK-32: Size: 12 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 12 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32: BitwiseTakable: 1 // CHECK-32-LABEL: - __C.MyCEnum: // CHECK-32: Size: 4 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 4 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32: BitwiseTakable: 1 // CHECK-32-LABEL: - __C.MyCUnion: // CHECK-32: Size: 4 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 4 // CHECK-32: NumExtraInhabitants: 0 // CHECK-32: BitwiseTakable: 1 // CHECK-i386-LABEL: - __C.MyCStructWithBitfields: // CHECK-i386: Size: 4 // CHECK-i386: Alignment: 4 // CHECK-i386: Stride: 4 // CHECK-i386: NumExtraInhabitants: 0 // CHECK-i386: BitwiseTakable: 1 // CHECK-arm-LABEL: - __C.MyCStructWithBitfields: // CHECK-arm: Size: 2 // CHECK-arm: Alignment: 1 // CHECK-arm: Stride: 2 // CHECK-arm: NumExtraInhabitants: 0 // CHECK-arm: BitwiseTakable: 1 // CHECK-32: CAPTURE DESCRIPTORS: // CHECK-32: ==================== // CHECK-64: FIELDS: // CHECK-64: ======= // CHECK-64: TypesToReflect.HasCTypes // CHECK-64: ------------------------ // CHECK-64: mcs: __C.MyCStruct // CHECK-64: (struct __C.MyCStruct) // CHECK-64: mce: __C.MyCEnum // CHECK-64: (struct __C.MyCEnum) // CHECK-64: mcu: __C.MyCUnion // CHECK-64: (struct __C.MyCUnion) // CHECK-64: __C.MyCStruct // CHECK-64: ------------- // CHECK-64: i: Swift.Int32 // CHECK-64: (struct Swift.Int32) // CHECK-64: ip: Swift.Optional<Swift.UnsafeMutablePointer<Swift.Int32>> // CHECK-64: (bound_generic_enum Swift.Optional // CHECK-64: (bound_generic_struct Swift.UnsafeMutablePointer // CHECK-64: (struct Swift.Int32))) // CHECK-64: c: Swift.Int8 // CHECK-64: (struct Swift.Int8) // CHECK-64: TypesToReflect.AlsoHasCTypes // CHECK-64: ---------------------------- // CHECK-64: mcu: __C.MyCUnion // CHECK-64: (struct __C.MyCUnion) // CHECK-64: mcsbf: __C.MyCStructWithBitfields // CHECK-64: (struct __C.MyCStructWithBitfields) // CHECK-64: ASSOCIATED TYPES: // CHECK-64: ================= // CHECK-64: BUILTIN TYPES: // CHECK-64: ============== // CHECK-64-LABEL: - __C.MyCStruct: // CHECK-64: Size: 24 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 24 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: BitwiseTakable: 1 // CHECK-64-LABEL: - __C.MyCEnum: // CHECK-64: Size: 4 // CHECK-64: Alignment: 4 // CHECK-64: Stride: 4 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: BitwiseTakable: 1 // CHECK-64-LABEL: - __C.MyCUnion: // CHECK-64: Size: 8 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 8 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: BitwiseTakable: 1 // CHECK-64-LABEL: - __C.MyCStructWithBitfields: // CHECK-64: Size: 4 // CHECK-64: Alignment: 4 // CHECK-64: Stride: 4 // CHECK-64: NumExtraInhabitants: 0 // CHECK-64: BitwiseTakable: 1 // CHECK-64: CAPTURE DESCRIPTORS: // CHECK-64: ====================
apache-2.0
1c03e7a09182e44e5dcdc4cf7ab5f2fb
28.98773
263
0.6518
3.064577
false
false
false
false
King-Wizard/GTNotification
SampleNotifcations/SampleNotifcations/AppFonts.swift
1
4895
// // AppFonts.swift // SampleNotifcations // // Created by King-Wizard on 2015-09-05. // Copyright (c) 2015 King Wizard. All rights reserved. // import UIKit class AppFonts: NSObject { private static let proximaNovaItalicFont = UIFont(name: SampleNotificationsFontName.ProximaNovaItalic.rawValue, size: 15)! class func proximaNovaItalic(let fontSize: CGFloat) -> UIFont { return self.proximaNovaItalicFont.fontWithSize(fontSize) } private static let proximaNovaExtraBoldItalicFont = UIFont(name: SampleNotificationsFontName.ProximaNovaExtraBoldItalic.rawValue, size: 15)! class func proximaNovaExtraBoldItalic(let fontSize: CGFloat) -> UIFont { return self.proximaNovaExtraBoldItalicFont.fontWithSize(fontSize) } private static let proximaNovaBlackFont = UIFont(name: SampleNotificationsFontName.ProximaNovaBlack.rawValue, size: 15)! class func proximaNovaBlack(let fontSize: CGFloat) -> UIFont { return self.proximaNovaBlackFont.fontWithSize(fontSize) } private static let proximaNovaExtraBoldFont = UIFont(name: SampleNotificationsFontName.ProximaNovaExtraBold.rawValue, size: 15)! class func ProximaNovaExtraBold(let fontSize: CGFloat) -> UIFont { return self.proximaNovaExtraBoldFont.fontWithSize(fontSize) } private static let proximaNovaBoldItalicFont = UIFont(name: SampleNotificationsFontName.ProximaNovaBoldItalic.rawValue, size: 15)! class func proximaNovaBoldItalic(let fontSize: CGFloat) -> UIFont { return self.proximaNovaBoldItalicFont.fontWithSize(fontSize) } private static let proximaNovaRegularFont = UIFont(name: SampleNotificationsFontName.ProximaNovaRegular.rawValue, size: 15)! class func proximaNovaRegular(let fontSize: CGFloat) -> UIFont { return self.proximaNovaRegularFont.fontWithSize(fontSize) } private static let proximaNovaBlackItalicFont = UIFont(name: SampleNotificationsFontName.ProximaNovaBlackItalic.rawValue, size: 15)! class func proximaNovaBlackItalic(let fontSize: CGFloat) -> UIFont { return self.proximaNovaBlackItalicFont.fontWithSize(fontSize) } private static let proximaNovaThinFont = UIFont(name: SampleNotificationsFontName.ProximaNovaThin.rawValue, size: 15)! class func proximaNovaThin(let fontSize: CGFloat) -> UIFont { return self.proximaNovaThinFont.fontWithSize(fontSize) } private static let proximaNovaBoldFont = UIFont(name: SampleNotificationsFontName.ProximaNovaBold.rawValue, size: 15)! class func proximaNovaBold(let fontSize: CGFloat) -> UIFont { return self.proximaNovaBoldFont.fontWithSize(fontSize) } private static let proximaNovaSemiBoldItalicFont = UIFont(name: SampleNotificationsFontName.ProximaNovaSemiBoldItalic.rawValue, size: 15)! class func proximaNovaSemiBoldItalic(let fontSize: CGFloat) -> UIFont { return self.proximaNovaSemiBoldItalicFont.fontWithSize(fontSize) } private static let proximaNovaSemiBoldFont = UIFont(name: SampleNotificationsFontName.ProximaNovaSemiBold.rawValue, size: 15)! class func proximaNovaSemiBold(let fontSize: CGFloat) -> UIFont { return self.proximaNovaSemiBoldFont.fontWithSize(fontSize) } private static let zocialFont = UIFont(name: SampleNotificationsFontName.Zocial.rawValue, size: 15)! class func zocial(let fontSize: CGFloat) -> UIFont { return self.zocialFont.fontWithSize(fontSize) } private static let fontAwesomeFont = UIFont(name: SampleNotificationsFontName.FontAwesome.rawValue, size: 15)! class func fontAwesome(let fontSize: CGFloat) -> UIFont { return self.fontAwesomeFont.fontWithSize(fontSize) } private static let foundationIconsFont = UIFont(name: SampleNotificationsFontName.FoundationIcons.rawValue, size: 15)! class func foundationIcons(let fontSize: CGFloat) -> UIFont { return self.foundationIconsFont.fontWithSize(fontSize) } private static let ionIconsFont = UIFont(name: SampleNotificationsFontName.IonIcons.rawValue, size: 15)! class func ionIcons(let fontSize: CGFloat) -> UIFont { return self.ionIconsFont.fontWithSize(fontSize) } private static let glyphIconsFont = UIFont(name: SampleNotificationsFontName.GlyphIcons.rawValue, size: 15)! class func glyphIcons(let fontSize: CGFloat) -> UIFont { return self.glyphIconsFont.fontWithSize(fontSize) } /* Print the names of all fonts available for this app. */ class func printAllFontNames() { for fontFamilyName: String in UIFont.familyNames() { print("\(getVaList([fontFamilyName]))") for fontName: String in UIFont.fontNamesForFamilyName(fontFamilyName) { print("\t\(getVaList([fontName]))") } } } }
mit
114f8e0826c0b67cf950f3ade19d556b
45.619048
144
0.739326
4.366637
false
false
false
false
apple/swift-nio
Sources/NIOCore/IPProtocol.swift
1
7926
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// /// In the Internet Protocol version 4 (IPv4) [RFC791] there is a field /// called "Protocol" to identify the next level protocol. This is an 8 /// bit field. In Internet Protocol version 6 (IPv6) [RFC8200], this field /// is called the "Next Header" field. public struct NIOIPProtocol: RawRepresentable, Hashable { public typealias RawValue = UInt8 public var rawValue: RawValue @inlinable public init(rawValue: RawValue) { self.rawValue = rawValue } } extension NIOIPProtocol { /// - precondition: `rawValue` must fit into an `UInt8` public init(_ rawValue: Int) { self.init(rawValue: UInt8(rawValue)) } } // Subset of https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml with an RFC extension NIOIPProtocol { /// IPv6 Hop-by-Hop Option - [RFC8200] public static let hopopt = Self(rawValue: 0) /// Internet Control Message - [RFC792] public static let icmp = Self(rawValue: 1) /// Internet Group Management - [RFC1112] public static let igmp = Self(rawValue: 2) /// Gateway-to-Gateway - [RFC823] public static let ggp = Self(rawValue: 3) /// IPv4 encapsulation - [RFC2003] public static let ipv4 = Self(rawValue: 4) /// Stream - [RFC1190][RFC1819] public static let st = Self(rawValue: 5) /// Transmission Control - [RFC9293] public static let tcp = Self(rawValue: 6) /// Exterior Gateway Protocol - [RFC888][David_Mills] public static let egp = Self(rawValue: 8) /// Network Voice Protocol - [RFC741][Steve_Casner] public static let nvpIi = Self(rawValue: 11) /// User Datagram - [RFC768][Jon_Postel] public static let udp = Self(rawValue: 17) /// Host Monitoring - [RFC869][Bob_Hinden] public static let hmp = Self(rawValue: 20) /// Reliable Data Protocol - [RFC908][Bob_Hinden] public static let rdp = Self(rawValue: 27) /// Internet Reliable Transaction - [RFC938][Trudy_Miller] public static let irtp = Self(rawValue: 28) /// ISO Transport Protocol Class 4 - [RFC905][<mystery contact>] public static let isoTp4 = Self(rawValue: 29) /// Bulk Data Transfer Protocol - [RFC969][David_Clark] public static let netblt = Self(rawValue: 30) /// Datagram Congestion Control Protocol - [RFC4340] public static let dccp = Self(rawValue: 33) /// IPv6 encapsulation - [RFC2473] public static let ipv6 = Self(rawValue: 41) /// Reservation Protocol - [RFC2205][RFC3209][Bob_Braden] public static let rsvp = Self(rawValue: 46) /// Generic Routing Encapsulation - [RFC2784][Tony_Li] public static let gre = Self(rawValue: 47) /// Dynamic Source Routing Protocol - [RFC4728] public static let dsr = Self(rawValue: 48) /// Encap Security Payload - [RFC4303] public static let esp = Self(rawValue: 50) /// Authentication Header - [RFC4302] public static let ah = Self(rawValue: 51) /// NBMA Address Resolution Protocol - [RFC1735] public static let narp = Self(rawValue: 54) /// ICMP for IPv6 - [RFC8200] public static let ipv6Icmp = Self(rawValue: 58) /// No Next Header for IPv6 - [RFC8200] public static let ipv6Nonxt = Self(rawValue: 59) /// Destination Options for IPv6 - [RFC8200] public static let ipv6Opts = Self(rawValue: 60) /// EIGRP - [RFC7868] public static let eigrp = Self(rawValue: 88) /// OSPFIGP - [RFC1583][RFC2328][RFC5340][John_Moy] public static let ospfigp = Self(rawValue: 89) /// Ethernet-within-IP Encapsulation - [RFC3378] public static let etherip = Self(rawValue: 97) /// Encapsulation Header - [RFC1241][Robert_Woodburn] public static let encap = Self(rawValue: 98) /// Protocol Independent Multicast - [RFC7761][Dino_Farinacci] public static let pim = Self(rawValue: 103) /// IP Payload Compression Protocol - [RFC2393] public static let ipcomp = Self(rawValue: 108) /// Virtual Router Redundancy Protocol - [RFC5798] public static let vrrp = Self(rawValue: 112) /// Layer Two Tunneling Protocol - [RFC3931][Bernard_Aboba] public static let l2tp = Self(rawValue: 115) /// Fibre Channel - [Murali_Rajagopal][RFC6172] public static let fc = Self(rawValue: 133) /// MANET Protocols - [RFC5498] public static let manet = Self(rawValue: 138) /// Host Identity Protocol - [RFC7401] public static let hip = Self(rawValue: 139) /// Shim6 Protocol - [RFC5533] public static let shim6 = Self(rawValue: 140) /// Wrapped Encapsulating Security Payload - [RFC5840] public static let wesp = Self(rawValue: 141) /// Robust Header Compression - [RFC5858] public static let rohc = Self(rawValue: 142) /// Ethernet - [RFC8986] public static let ethernet = Self(rawValue: 143) /// AGGFRAG encapsulation payload for ESP - [RFC-ietf-ipsecme-iptfs-19] public static let aggfrag = Self(rawValue: 144) } extension NIOIPProtocol: CustomStringConvertible { private var name: String? { switch self { case .hopopt: return "IPv6 Hop-by-Hop Option" case .icmp: return "Internet Control Message" case .igmp: return "Internet Group Management" case .ggp: return "Gateway-to-Gateway" case .ipv4: return "IPv4 encapsulation" case .st: return "Stream" case .tcp: return "Transmission Control" case .egp: return "Exterior Gateway Protocol" case .nvpIi: return "Network Voice Protocol" case .udp: return "User Datagram" case .hmp: return "Host Monitoring" case .rdp: return "Reliable Data Protocol" case .irtp: return "Internet Reliable Transaction" case .isoTp4: return "ISO Transport Protocol Class 4" case .netblt: return "Bulk Data Transfer Protocol" case .dccp: return "Datagram Congestion Control Protocol" case .ipv6: return "IPv6 encapsulation" case .rsvp: return "Reservation Protocol" case .gre: return "Generic Routing Encapsulation" case .dsr: return "Dynamic Source Routing Protocol" case .esp: return "Encap Security Payload" case .ah: return "Authentication Header" case .narp: return "NBMA Address Resolution Protocol" case .ipv6Icmp: return "ICMP for IPv6" case .ipv6Nonxt: return "No Next Header for IPv6" case .ipv6Opts: return "Destination Options for IPv6" case .eigrp: return "EIGRP" case .ospfigp: return "OSPFIGP" case .etherip: return "Ethernet-within-IP Encapsulation" case .encap: return "Encapsulation Header" case .pim: return "Protocol Independent Multicast" case .ipcomp: return "IP Payload Compression Protocol" case .vrrp: return "Virtual Router Redundancy Protocol" case .l2tp: return "Layer Two Tunneling Protocol" case .fc: return "Fibre Channel" case .manet: return "MANET Protocols" case .hip: return "Host Identity Protocol" case .shim6: return "Shim6 Protocol" case .wesp: return "Wrapped Encapsulating Security Payload" case .rohc: return "Robust Header Compression" case .ethernet: return "Ethernet" case .aggfrag: return "AGGFRAG encapsulation payload for ESP" default: return nil } } public var description: String { let name = self.name ?? "Unknown Protocol" return "\(name) - \(rawValue)" } }
apache-2.0
8b31644b4ffef748ee3ca8bc65826909
43.779661
97
0.655816
3.875795
false
false
false
false
maranathApp/GojiiFramework
GojiiFrameWork/UIWebViewExtensions.swift
1
2989
// // CGFloatExtensions.swift // GojiiFrameWork // // Created by Stency Mboumba on 01/06/2017. // Copyright © 2017 Stency Mboumba. All rights reserved. // import Foundation // MARK: - Extension UIWebView BSFramework public extension UIWebView { /* --------------------------------------------------------------------------- */ // MARK: - Stucture HTML /* --------------------------------------------------------------------------- */ /** Get structure HTML With pass Content <br><br> In marked your have div with id *"sizecontentid"* for get size of content, with set param *sizecontentid* in func <br> **getHeightByContent /<br>getWidthByContent**<br> - parameter inBodyHtml: String - parameter cssStyle: String / *Default = ""* - parameter meta: String / *Default = "<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">"* - returns: String */ public class func getHTMLstructure(inBodyHtml:String, cssStyle:String = "", meta:String = "<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">") -> String { var html = "<html>" html += "<head>" html += "\(meta)" html += "<style> body {" html += "\(cssStyle) } </style>" html += "</head>" html += "<body><div id='sizecontentid'>" html += inBodyHtml html += "</div>" html += "</body>" html += "</html>" return html } /* --------------------------------------------------------------------------- */ // MARK: - Size by Content /* --------------------------------------------------------------------------- */ /** Get size WebView with the marked - parameter nameMarkedId: String / Marked id - parameter jsHW: String / (scrollHeight, scrollWidth) - returns: CGFloat */ private func getSizeMarkedWebView(nameMarkedId:String?, jsHW:String) -> CGFloat? { var scriptJs:String = "" if let hasNameMarked = nameMarkedId { scriptJs = "document.getElementById('\(hasNameMarked)').\(jsHW);" } else { scriptJs = "document.body.\(jsHW);" } guard let sizeString = self.stringByEvaluatingJavaScript(from: scriptJs), let sizeCGFloat = sizeString.toCGFloat else { return nil } return sizeCGFloat } /** Get size Height WebView with the content marked - returns: CGFloat */ public func getHeightByContent(nameMarkedId:String?) -> CGFloat? { return self.getSizeMarkedWebView(nameMarkedId: nameMarkedId, jsHW: "scrollHeight") } /** Get size Width WebView with the content marked - returns: CGFloat */ public func getWidthByContent(nameMarkedId:String?) -> CGFloat? { return self.getSizeMarkedWebView(nameMarkedId: nameMarkedId, jsHW: "scrollWidth") } }
mit
1c40aefaab85a91c7d31f9584f2620de
32.954545
169
0.52075
4.727848
false
false
false
false
mrdepth/EVEOnlineAPI
EVEAPI/EVEAPI/EVEBlueprints.swift
1
1924
// // EVEBlueprints.swift // EVEAPI // // Created by Artem Shimanski on 29.11.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit public class EVEBlueprintsItem: EVEObject { public var itemID: Int64 = 0 public var locationID: Int64 = 0 public var typeID: Int = 0 public var typeName: String = "" public var flag: EVEInventoryFlag = .none public var quantity: Int = 0 public var timeEfficiency: Int = 0 public var materialEfficiency: Int = 0 public var runs: Int = 0 public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "itemID":EVESchemeElementType.Int64(elementName:nil, transformer:nil), "locationID":EVESchemeElementType.Int64(elementName:nil, transformer:nil), "typeID":EVESchemeElementType.Int(elementName:nil, transformer:nil), "typeName":EVESchemeElementType.String(elementName:nil, transformer:nil), "flag":EVESchemeElementType.Int(elementName:"flagID", transformer:nil), "quantity":EVESchemeElementType.Int(elementName:nil, transformer:nil), "timeEfficiency":EVESchemeElementType.Int(elementName:nil, transformer:nil), "materialEfficiency":EVESchemeElementType.Int(elementName:nil, transformer:nil), "runs":EVESchemeElementType.Int(elementName:nil, transformer:nil), ] } } public class EVEBlueprints: EVEResult { public var blueprints: [EVEBlueprintsItem] = [] public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "blueprints":EVESchemeElementType.Rowset(elementName: nil, type: EVEBlueprintsItem.self, transformer: nil) ] } }
mit
92bbbc6cc691a2e9e77b0f2b47625939
29.52381
109
0.74519
3.726744
false
false
false
false
garthmac/ChemicalVisualizer
UIColorCrayons.swift
1
6237
// // UIColorCrayons.swift // ChemicalVisualizer // // Created by iMac 27 on 2015-12-01. // // import UIKit extension UIColor { convenience init(hex: Int, alpha: CGFloat = 1.0) { let r = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let g = CGFloat((hex & 0x00FF00) >> 08) / 255.0 let b = CGFloat((hex & 0x0000FF) >> 00) / 255.0 self.init(red:r, green:g, blue:b, alpha:alpha) } class func crayons_cantaloupeColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xFFCC66, alpha: alpha) } class func crayons_honeydewColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xCCFF66, alpha: alpha) } class func crayons_spindriftColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x66FFCC, alpha: alpha) } class func crayons_skyColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x66CCFF, alpha: alpha) } class func crayons_lavenderColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xCC66FF, alpha: alpha) } class func crayons_carnationColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xFF6FCF, alpha: alpha) } class func crayons_licoriceColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x000000, alpha: alpha) } class func crayons_snowColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xFFFFFF, alpha: alpha) } class func crayons_salmonColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xFF6666, alpha: alpha) } class func crayons_bananaColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xFFFF66, alpha: alpha) } class func crayons_floraColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x66FF66, alpha: alpha) } class func crayons_iceColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x66FFFF, alpha: alpha) } class func crayons_orchidColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x6666FF, alpha: alpha) } class func crayons_bubblegumColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xff66ff, alpha: alpha) } class func crayons_leadColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x191919, alpha: alpha) } class func crayons_mercuryColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xe6e6e6, alpha: alpha) } class func crayons_tangerineColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xff8000, alpha: alpha) } class func crayons_limeColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x80ff00, alpha: alpha) } class func crayons_seaFoamColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x00ff80, alpha: alpha) } class func crayons_aquaColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x0080ff, alpha: alpha) } class func crayons_grapeColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x8000ff, alpha: alpha) } class func crayons_strawberryColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xff0080, alpha: alpha) } class func crayons_tungstenColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x333333, alpha: alpha) } class func crayons_silverColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xcccccc, alpha: alpha) } class func crayons_maraschinoColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xff0000, alpha: alpha) } class func crayons_lemonColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xffff00, alpha: alpha) } class func crayons_springColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x00ff00, alpha: alpha) } class func crayons_turquoiseColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x00ffff, alpha: alpha) } class func crayons_blueberryColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x0000ff, alpha: alpha) } class func crayons_magentaColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xff00ff, alpha: alpha) } class func crayons_ironColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x4c4c4c, alpha: alpha) } class func crayons_magnesiumColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xb3b3b3, alpha: alpha) } class func crayons_mochaColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x804000, alpha: alpha) } class func crayons_fernColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x408000, alpha: alpha) } class func crayons_mossColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x008040, alpha: alpha) } class func crayons_oceanColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x004080, alpha: alpha) } class func crayons_eggplantColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x400080, alpha: alpha) } class func crayons_maroonColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x800040, alpha: alpha) } class func crayons_steelColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x666666, alpha: alpha) } class func crayons_aluminumColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x999999, alpha: alpha) } class func crayons_cayenneColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x800000, alpha: alpha) } class func crayons_asparagusColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x808000, alpha: alpha) } class func crayons_cloverColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x008000, alpha: alpha) } class func crayons_tealColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x008080, alpha: alpha) } class func crayons_midnightColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x000080, alpha: alpha) } class func crayons_plumColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x800080, alpha: alpha) } class func crayons_tinColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x7f7f7f, alpha: alpha) } class func crayons_nickelColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x808080, alpha: alpha) } }
mit
b64e2ec4f20d780309a5fa77b3a436f6
90.720588
120
0.67308
3.156377
false
false
false
false
ZekeSnider/Jared
JaredFramework/Message.swift
1
3912
// // main.swift // Jared 3.0 - Swiftified // // Created by Zeke Snider on 4/3/16. // Copyright © 2016 Zeke Snider. All rights reserved. // import Foundation public struct Message: Encodable { public var body: MessageBody? public var date: Date? public var sender: SenderEntity public var recipient: RecipientEntity public var attachments: [Attachment]? public var sendStyle: SendStyle public var action: Action? public var guid: String? enum CodingKeys : String, CodingKey{ case date case body case sender case recipient case attachments case sendStyle case action case guid } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) var recipientCopy = recipient if let textBody = body as? TextBody { try container.encode(textBody, forKey: .body) } if let person = sender as? Person { try container.encode(person, forKey: .sender) } if let abstractRecipient = recipient as? AbstractRecipient { recipientCopy = abstractRecipient.getSpecificEntity() } if let person = recipientCopy as? Person { try container.encode(person, forKey: .recipient) } else if let group = recipientCopy as? Group { try container.encode(group, forKey: .recipient) } if let notOptionalDate = date { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.locale = Locale(identifier: "en_US_POSIX") try container.encode(formatter.string(from: notOptionalDate), forKey: .date) } try container.encode(sendStyle.rawValue, forKey: .sendStyle) try container.encode(attachments, forKey: .attachments) try container.encode(guid, forKey: .guid) if (action != nil) { try container.encode(action, forKey: .action) } } public init (body: MessageBody?, date: Date, sender: SenderEntity, recipient: RecipientEntity, guid: String? = nil, attachments: [Attachment] = [], sendStyle: String? = nil, associatedMessageType: Int? = nil, associatedMessageGUID: String? = nil) { self.body = body self.recipient = recipient self.sender = sender self.date = date self.attachments = attachments self.sendStyle = SendStyle(fromIdentifier: sendStyle) self.guid = guid if (associatedMessageType != 0 && associatedMessageGUID != nil) { self.action = Action(actionTypeInt: associatedMessageType!, targetGUID: associatedMessageGUID!.replacingOccurrences(of: "p:0/", with: "")) } } public func RespondTo() -> RecipientEntity? { if let senderPerson = sender as? Person { if (senderPerson.isMe) { if let person = recipient as? Person { return person } else if let group = recipient as? Group { return group } } else { if let group = recipient as? Group { return group } else { return senderPerson } } } NSLog("Couldn't coerce respond to entity properly.") return nil } public func getTextBody() -> String? { guard let body = self.body as? TextBody else { return nil } return body.message } public func getTextParameters() -> [String]? { return self.getTextBody()?.components(separatedBy: ",") } }
apache-2.0
30035c68a1e6e773cffa74714a57083e
32.144068
252
0.576835
4.804668
false
false
false
false
caicai0/ios_demo
load/thirdpart/SwiftKuery/Table.swift
1
8696
/** Copyright IBM Corporation 2016, 2017 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. */ // MARK: Table /// Subclasses of the Table class are metadata describing a table in a relational database that you want to work with. open class Table: Buildable { var _name = "" public private (set) var columns: [Column] private var columnsWithPrimaryKeyProperty = 0 /// The alias of the table. public private (set) var alias: String? private var primaryKey: [Column]? private var foreignKeyColumns: [Column]? private var foreignKeyReferences: [Column]? private var syntaxError = "" /// The name of the table to be used inside a query, i.e., either its alias (if exists) /// or its name. public var nameInQuery: String { return alias ?? _name } /// Initialize an instance of Table. public required init() { columns = [Column]() let mirror = Mirror(reflecting: self) for child in mirror.children { if let column = child.value as? Column { column._table = self columns.append(column) if column.isPrimaryKey { columnsWithPrimaryKeyProperty += 1 } } else if let label = child.label, label == "tableName" { _name = child.value as! String } } if columns.count == 0 { syntaxError += "No columns in the table. " } if columnsWithPrimaryKeyProperty > 1 { syntaxError += "Conflicting definitions of primary key. " } if _name == "" { syntaxError += "Table name not set. " } } /// Build the table using `QueryBuilder`. /// /// - Parameter queryBuilder: The QueryBuilder to use. /// - Returns: A String representation of the table. /// - Throws: QueryError.syntaxError if query build fails. public func build(queryBuilder: QueryBuilder) throws -> String { if columns.count == 0 { throw QueryError.syntaxError("No columns in the table. ") } if _name == "" { throw QueryError.syntaxError("Table name not set. ") } var result = Utils.packName(_name, queryBuilder: queryBuilder) if let alias = alias { result += " AS " + Utils.packName(alias, queryBuilder: queryBuilder) } return result } /// Add alias to the table, i.e., implement the SQL AS operator. /// /// - Parameter newName: A String containing the alias for the table. /// - Returns: A new Table instance with the alias. public func `as`(_ newName: String) -> Self { let new = type(of: self).init() new.alias = newName return new } /// Apply TRUNCATE TABLE query on the table. /// /// - Returns: An instance of `Raw`. public func truncate() -> Raw { return Raw(query: "TRUNCATE TABLE", table: self) } /// Apply DROP TABLE query on the table. /// /// - Returns: An instance of `Raw`. public func drop() -> Raw { return Raw(query: "DROP TABLE", table: self) } /// Create the table in the database. /// /// - Parameter connection: The connection to the database. /// - Parameter onCompletion: The function to be called when the execution of the query has completed. public func create(connection: Connection, onCompletion: @escaping ((QueryResult) -> ())) { do { let query = try description(connection: connection) connection.execute(query, onCompletion: onCompletion) } catch { onCompletion(.error(QueryError.syntaxError("\(error)"))) } } /// Add a primary key to the table. /// /// - Parameter columns: An Array of columns that constitute the primary key. /// - Returns: A new instance of `Table`. public func primaryKey(_ columns: [Column]) -> Self { if primaryKey != nil || columnsWithPrimaryKeyProperty > 0 { syntaxError += "Conflicting definitions of primary key. " } else if columns.count == 0 { syntaxError += "Empty primary key. " } else if !Table.columnsBelongTo(table: self, columns: columns) { syntaxError += "Primary key contains columns from another table. " } else { primaryKey = columns } return self } /// Add a primary key to the table. /// /// - Parameter columns: Columns that constitute the primary key. /// - Returns: A new instance of `Table`. public func primaryKey(_ columns: Column...) -> Self { return primaryKey(columns) } /// Add a foreign key to the table. /// /// - Parameter columns: An Array of columns that constitute the foreign key. /// - Parameter references: An Array of columns of the foreign table the foreign key references. /// - Returns: A new instance of `Table`. public func foreignKey(_ columns: [Column], references: [Column]) -> Self { if foreignKeyColumns != nil || foreignKeyReferences != nil { syntaxError += "Conflicting definitions of foreign key. " } else if columns.count == 0 || references.count == 0 || columns.count != references.count { syntaxError += "Invalid definition of foreign key. " } else if !Table.columnsBelongTo(table: self, columns: columns) { syntaxError += "Foreign key contains columns from another table. " } else if !Table.columnsBelongTo(table: references[0].table, columns: references) { syntaxError += "Foreign key references columns from more than one table. " } else { foreignKeyColumns = columns foreignKeyReferences = references } return self } private static func columnsBelongTo(table: Table, columns: [Column]) -> Bool { for column in columns { if column.table._name != table._name { return false } } return true } /// Add a foreign key to the table. /// /// - Parameter columns: A column that is the foreign key. /// - Parameter references: A column in the foreign table the foreign key references. /// - Returns: A new instance of `Table`. public func foreignKey(_ column: Column, references: Column) -> Self { return foreignKey([column], references: [references]) } /// Return a String representation of the table create statement. /// /// - Returns: A String representation of the table create statement. /// - Throws: QueryError.syntaxError if statement build fails. public func description(connection: Connection) throws -> String { if syntaxError != "" { throw QueryError.syntaxError(syntaxError) } let queryBuilder = connection.queryBuilder var query = "CREATE TABLE " + Utils.packName(_name, queryBuilder: queryBuilder) query += " (" query += try columns.map { try $0.create(queryBuilder: queryBuilder) }.joined(separator: ", ") if let primaryKey = primaryKey { query += ", PRIMARY KEY (" query += primaryKey.map { Utils.packName($0.name, queryBuilder: queryBuilder) }.joined(separator: ", ") query += ")" } if let foreignKeyColumns = foreignKeyColumns, let foreignKeyReferences = foreignKeyReferences { query += ", FOREIGN KEY (" query += foreignKeyColumns.map { Utils.packName($0.name, queryBuilder: queryBuilder) }.joined(separator: ", ") query += ") REFERENCES " let referencedTableName = foreignKeyReferences[0].table._name query += Utils.packName(referencedTableName, queryBuilder: queryBuilder) + "(" query += foreignKeyReferences.map { Utils.packName($0.name, queryBuilder: queryBuilder) }.joined(separator: ", ") query += ")" } query += ")" return query } }
mit
d74e01adf0e54ecea3b6a0c6ed1fc35e
36.973799
125
0.598551
4.87991
false
false
false
false
brunchmade/mojito
Mojito/ConfigViewController.swift
1
3224
// // ConfigViewController.swift // Mojito // // Created by Fang-Pen Lin on 2/6/16. // Copyright © 2016 VictorLin. All rights reserved. // import Foundation import Cocoa import ReactiveCocoa class ConfigViewController: NSViewController { static let websiteURL = "https://mojito.cool" static let authors = [ ("Wells Riley", "https://twitter.com/wr"), ("Victor Lin", "https://twitter.com/victorlin"), ("Ian Hirschfeld", "https://twitter.com/ianhirschfeld") ] var viewModel:ConfigViewModel! @IBOutlet weak var installButton: NSButton! @IBOutlet weak var mojitoTitle: NSTextField! @IBOutlet weak var websiteLink: NSTextField! @IBOutlet weak var authorLinks: NSTextField! private var installButtonHidden:DynamicProperty! func bindViewModel(viewModel:ConfigViewModel) { self.viewModel = viewModel let installButtonHidden = DynamicProperty(object: installButton, keyPath: "state") installButtonHidden.value = viewModel.installed.value installButtonHidden <~ viewModel.installed.signal.map { installed -> NSNumber in return installed ? NSOnState : NSOffState } installButton.rac_command = toRACCommand(viewModel.installOrUninstallAction) } override func viewDidLoad() { let bundleInfo = NSBundle.mainBundle().infoDictionary! let build = bundleInfo["CFBundleVersion"]! let version = bundleInfo["CFBundleShortVersionString"]! mojitoTitle.stringValue = "Mojito v\(version) (build \(build))" websiteLink.allowsEditingTextAttributes = true websiteLink.selectable = true websiteLink.editable = false websiteLink.toolTip = "Official website" let webAttrStr = NSMutableAttributedString(string: "🌎: ") webAttrStr.appendAttributedString(NSAttributedString.hyperlink(ConfigViewController.websiteURL, url: NSURL(string: ConfigViewController.websiteURL)!)) websiteLink.attributedStringValue = webAttrStr authorLinks.allowsEditingTextAttributes = true authorLinks.selectable = true authorLinks.editable = false authorLinks.toolTip = "Authors" let authorAttrStr = NSMutableAttributedString(string: "👥: ") let authorsExceptLastOne = ConfigViewController.authors[0..<ConfigViewController.authors.count - 1] for (index, (name, link)) in zip(authorsExceptLastOne.indices, authorsExceptLastOne) { authorAttrStr.appendAttributedString(NSAttributedString.hyperlink(name, url: NSURL(string: link)!)) if (index != ConfigViewController.authors.count - 2) { authorAttrStr.appendAttributedString(NSAttributedString(string: ", ")) } } if (ConfigViewController.authors.count > 1) { let (lastName, lastLink) = ConfigViewController.authors.last! authorAttrStr.appendAttributedString(NSAttributedString(string: " and ")) authorAttrStr.appendAttributedString(NSAttributedString.hyperlink(lastName, url: NSURL(string: lastLink)!)) } authorLinks.attributedStringValue = authorAttrStr } }
mit
c30039e782170b322e1929b807d0efde
41.328947
158
0.688219
4.91145
false
true
false
false
Johnykutty/SwiftLint
Source/SwiftLintFramework/Rules/FirstWhereRule.swift
4
3800
// // FirstWhereRule.swift // SwiftLint // // Created by Marcelo Fabri on 12/20/16. // Copyright © 2016 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct FirstWhereRule: OptInRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "first_where", name: "First Where", description: "Prefer using `.first(where:)` over `.filter { }.first` in collections.", nonTriggeringExamples: [ "kinds.filter(excludingKinds.contains).isEmpty && kinds.first == .identifier\n", "myList.first(where: { $0 % 2 == 0 })\n", "match(pattern: pattern).filter { $0.first == .identifier }\n" ], triggeringExamples: [ "↓myList.filter { $0 % 2 == 0 }.first\n", "↓myList.filter({ $0 % 2 == 0 }).first\n", "↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).first\n", "↓myList.map { $0 + 1 }.filter({ $0 % 2 == 0 }).first?.something()\n", "↓myList.filter(someFunction).first\n", "↓myList.filter({ $0 % 2 == 0 })\n.first\n" ] ) public func validate(file: File) -> [StyleViolation] { let pattern = "[\\}\\)]\\s*\\.first" let firstRanges = file.match(pattern: pattern, with: [.identifier]) let contents = file.contents.bridge() let structure = file.structure let violatingLocations: [Int] = firstRanges.flatMap { guard let bodyByteRange = contents.NSRangeToByteRange(start: $0.location, length: $0.length), case let firstLocation = $0.location + $0.length - 1, let firstByteRange = contents.NSRangeToByteRange(start: firstLocation, length: 1) else { return nil } return methodCall(forByteOffset: bodyByteRange.location - 1, excludingOffset: firstByteRange.location, dictionary: structure.dictionary, predicate: { dictionary in guard let name = dictionary.name else { return false } return name.hasSuffix(".filter") }) } return violatingLocations.map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, byteOffset: $0)) } } private func methodCall(forByteOffset byteOffset: Int, excludingOffset: Int, dictionary: [String: SourceKitRepresentable], predicate: ([String: SourceKitRepresentable]) -> Bool) -> Int? { if let kindString = (dictionary.kind), SwiftExpressionKind(rawValue: kindString) == .call, let bodyOffset = dictionary.bodyOffset, let bodyLength = dictionary.bodyLength, let offset = dictionary.offset { let byteRange = NSRange(location: bodyOffset, length: bodyLength) if NSLocationInRange(byteOffset, byteRange) && !NSLocationInRange(excludingOffset, byteRange) && predicate(dictionary) { return offset } } for dictionary in dictionary.substructure { if let offset = methodCall(forByteOffset: byteOffset, excludingOffset: excludingOffset, dictionary: dictionary, predicate: predicate) { return offset } } return nil } }
mit
ced2e4c14d098b6eee28c57a583ffec8
39.287234
114
0.55136
5.056075
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Scenes/API Key Input Scene/Table View Cells/Settings Text Entry Cell /SettingsTextEntryCell.swift
1
3677
// // SettingsTextEntryCell.swift // NearbyWeather // // Created by Erik Maximilian Martens on 11.03.22. // Copyright © 2022 Erik Maximilian Martens. All rights reserved. // import UIKit import RxSwift // MARK: - Definitions private extension SettingsTextEntryCell { struct Definitions {} } // MARK: - Class Definition final class SettingsTextEntryCell: UITableViewCell, BaseCell { typealias CellViewModel = SettingsTextEntryCellViewModel private typealias CellContentInsets = Constants.Dimensions.Spacing.ContentInsets private typealias CellInterelementSpacing = Constants.Dimensions.Spacing.InterElementSpacing // MARK: - UIComponents private(set) lazy var textEntryTextField = Factory.TextField.make(fromType: .standard(cornerRadiusWeight: .medium)) // MARK: - Assets private var disposeBag = DisposeBag() // MARK: - Properties var cellViewModel: CellViewModel? // MARK: - Initialization override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) layoutUserInterface() setupAppearance() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { printDebugMessage( domain: String(describing: self), message: "was deinitialized", type: .info ) } // MARK: - Cell Life Cycle func configure(with cellViewModel: BaseCellViewModelProtocol?) { guard let cellViewModel = cellViewModel as? SettingsTextEntryCellViewModel else { return } self.cellViewModel = cellViewModel cellViewModel.observeEvents() bindContentFromViewModel(cellViewModel) bindUserInputToViewModel(cellViewModel) } override func prepareForReuse() { super.prepareForReuse() disposeBag = DisposeBag() } } // MARK: - ViewModel Bindings extension SettingsTextEntryCell { func bindContentFromViewModel(_ cellViewModel: CellViewModel) { cellViewModel.cellModelDriver .drive(onNext: { [setContent] in setContent($0) }) .disposed(by: disposeBag) } func bindUserInputToViewModel(_ cellViewModel: SettingsTextEntryCellViewModel) { textEntryTextField.rx .value .bind(to: cellViewModel.textFieldTextSubject) .disposed(by: disposeBag) } } // MARK: - Cell Composition private extension SettingsTextEntryCell { func setContent(for cellModel: SettingsTextEntryCellModel) { textEntryTextField.placeholder = cellModel.textFieldPlaceholderText textEntryTextField.text = cellModel.textFieldText } func layoutUserInterface() { contentView.addSubview(textEntryTextField, constraints: [ textEntryTextField.heightAnchor.constraint(greaterThanOrEqualToConstant: Constants.Dimensions.ContentElement.height), textEntryTextField.topAnchor.constraint(equalTo: contentView.topAnchor, constant: CellContentInsets.top(from: .medium)), textEntryTextField.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -CellContentInsets.bottom(from: .medium)), textEntryTextField.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: CellContentInsets.leading(from: .large)), textEntryTextField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -CellContentInsets.trailing(from: .large)), textEntryTextField.centerYAnchor.constraint(equalTo: contentView.centerYAnchor) ]) } func setupAppearance() { backgroundColor = Constants.Theme.Color.ViewElement.primaryBackground contentView.backgroundColor = .clear selectionStyle = .none accessoryType = .none } }
mit
a710304c6cb95c7df60e369748544cae
29.131148
141
0.746736
5.19209
false
false
false
false
akane/Gaikan
Gaikan/Style/Style.swift
1
2437
// // This file is part of Gaikan // // Created by JC on 11/10/15. // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code // import Foundation /** * Defines a `StyleRule` on which you can apply supplemntary `StylePseudoState` states. */ public struct Style : ExpressibleByDictionaryLiteral { internal fileprivate(set) var style: StyleRule internal fileprivate(set) var states: [StyleState:StyleRule] = [:] public init(dictionaryLiteral elements: (StyleRule.Key, StyleRule.Value)...) { var attributes = Dictionary<StyleRule.Key, StyleRule.Value>() for (attributeName, attributeValue) in elements { attributes[attributeName] = attributeValue } self.init(style: StyleRule(attributes: attributes)) } public init(_ styleBlock: (_ style: inout StyleRule) -> ()) { self.init(style: StyleRule(styleBlock)) } fileprivate init(style: StyleRule) { self.style = style } public func state(_ state: StylePseudoState, styleRule styleBlock: (_ style: inout StyleRule) -> ()) -> Style { return self.state(.pseudoState(state), styleRule: styleBlock) } internal func state(_ state: StyleState, styleRule styleBlock: (_ style: inout StyleRule) -> ()) -> Style { var style = self style.states[state] = StyleRule(styleBlock) return style } public func state(_ state: String, styleRule styleBlock: (_ style: inout StyleRule) -> ()) -> Style { return self.state(.custom(state), styleRule: styleBlock) } public func state(_ state: StylePseudoState, _ attributes: [StyleRule.Key:StyleRule.Value]) -> Style { return self.state(.pseudoState(state), attributes: attributes) } public func state(_ state: String, _ attributes: [StyleRule.Key:StyleRule.Value]) -> Style { return self.state(.custom(state), attributes: attributes) } internal func state(_ state: StyleState, attributes: [StyleRule.Key:StyleRule.Value]) -> Style { var style = self style.states[state] = StyleRule(attributes: attributes) return style } internal subscript(state: StylePseudoState) -> StyleRule? { get { return self.states[.pseudoState(state)] } } internal subscript(state: String) -> StyleRule? { get { return self.states[.custom(state)] } } }
mit
bd8cc9cab4766bbc947e6c2278ef6187
31.493333
115
0.661469
4.194492
false
false
false
false
LuckyChen73/CW_WEIBO_SWIFT
WeiBo/WeiBo/Classes/View(视图)/Main(主控制器)/WBRootController.swift
1
4137
// // WBRootController.swift // WeiBo // // Created by chenWei on 2017/4/2. // Copyright © 2017年 陈伟. All rights reserved. // import UIKit import MJRefresh fileprivate let identifier = "identifer" class WBRootController: UIViewController { /// 上下拉刷新控件 lazy var refreshHeader: MJRefreshNormalHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadData)) lazy var refreshFooter: MJRefreshAutoNormalFooter = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadData)) lazy var tableView: UITableView = { let tableView = UITableView() tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier) return tableView }() //访客视图 var visitorView: WBVisitorView? //访客视图的文本,图标信息 var visitorDic: [String: Any]? override func viewDidLoad() { super.viewDidLoad() setupUI() //接收通知 NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: loginSuccessNotification, object: nil) } deinit { //移除通知 NotificationCenter.default.removeObserver(self) } } // MARK: - 加载数据 extension WBRootController { func loadData() { // print("刷新了") } } // MARK: - 创建 UI extension WBRootController { func setupUI() { self.automaticallyAdjustsScrollViewInsets = false //tablewView一定要创建在visitorView的下面 setupTableView() setupVisitorView() //添加上下拉刷新 tableView.mj_header = refreshHeader tableView.mj_footer = refreshFooter } /// 设置tableView func setupTableView() { self.view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.left.right.equalTo(self.view) make.top.equalTo(self.view).offset(64) make.bottom.equalTo(self.view) } } func setupVisitorView() { //只有在登录失败才加载访客视图 if WBUserAccount.shared.isLogIn == false { //创建访客视图并设置大小 visitorView = WBVisitorView(frame: self.view.bounds) //设置代理 visitorView?.delegate = self //给访客视图的文本,图标信息赋值 //visitorInfo 可空链式调用,如果前面有值,调用后面属性就有效果,反之 visitorView?.visitorInfo = self.visitorDic self.view.addSubview(visitorView!) } } } // MARK: - 代理方法 extension WBRootController: WBVisitorViewDelegate { //实现代理方法 func logIn() { //点击登录按钮后,跳转到登录控制器 let wbLoginVC = WBLogInController() let navLoginVC = UINavigationController(rootViewController: wbLoginVC) present(navLoginVC, animated: true, completion: nil) } } // MARK: - 接收通知 extension WBRootController { //接收通知后的事件 func loginSuccess() { visitorView?.removeFromSuperview() visitorView = nil //加载数据 loadData() } } // MARK: - tableView 的数据源 extension WBRootController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } } // MARK: - UITableViewDelegate extension WBRootController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
mit
444953b8467bcfd50f1c21c30a99c79d
20.976744
144
0.612434
4.967148
false
false
false
false
riteshhgupta/RGListKit
Source/ListKit/Core/DiffableListViewHolder+Extension.swift
1
1327
// // DiffableListViewHolder+Extension.swift // RGListKit // // Created by Ritesh Gupta on 04/10/17. // Copyright © 2017 Ritesh. All rights reserved. // import Foundation import UIKit import ProtoKit extension DiffableListViewHolder { func itemData<Item: ReusableView>(at indexPath: IndexPath) -> (Item, ListViewItemModel) { let model = sections[indexPath.section].cells[indexPath.row] let item: Item = listView.reusableItem(withIdentifier: model.reuseIdentifier, for: indexPath) return (item, model) } func headerFooterItemData<Item: ReusableView>(at indexPath: IndexPath, of kind: String) -> (Item, ListViewItemModel)? { let section = sections[indexPath.section] let identifier: String let headerFooterModel: ListViewItemModel switch kind { case UICollectionElementKindSectionHeader: guard let model = section.header else { return nil } identifier = model.reuseIdentifier headerFooterModel = model case UICollectionElementKindSectionFooter: guard let model = section.footer else { return nil } identifier = model.reuseIdentifier headerFooterModel = model default: return nil } let item: Item? = listView.reusableHeaderFooterItem(withIdentifier: identifier, for: indexPath, of: kind) guard let view = item else { return nil } return (view, headerFooterModel) } }
mit
8ddc2cac2b604835c6f115161f485438
30.571429
120
0.75641
4.018182
false
false
false
false
jf-rce/SwiftEasingFunctionsSample
EasingExample/ViewController.swift
1
3644
// // ViewController.swift // EasingExample // // Created by Justin Forsyth on 10/27/15. // Copyright © 2015 jforce. All rights reserved. // import UIKit import Easing class ViewController: UIViewController, EasingFunctionPainterDelegate, UITableViewDataSource, UITableViewDelegate { @IBOutlet var imageView: UIImageView! @IBOutlet var tableView: UITableView! @IBOutlet var orbView: OrbView! var painter: EasingFunctionPainter!; var currentFunction: EasingFunction!; var items: [String] = Array(EasingFunction.lut.keys).sort(); override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") painter = EasingFunctionPainter(imageView: self.imageView); painter.delegates.append(self); } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let margin: CGFloat = 20.0; imageView.frame = CGRectMake(margin, margin, self.view.frame.size.width - (2 * margin), (self.view.frame.size.height / 2) - (2 * margin)); tableView.frame = CGRectMake(margin, (self.view.frame.size.height / 2), self.view.frame.size.width - (2 * margin), (self.view.frame.size.height / 2) - (margin)); painter.orbView = orbView; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //begin EasingFunctionPainterDelegate implementation func paintStart(){ //called when painting has started } func paintProgress(progress: Int){ //called at each percentage of paint progress (0-100) } func paintComplete(){ //called when painting has completed painter.clear(); painter.paint(currentFunction) } func prepareStart() { //called when frame preparation has started } func prepareComplete() { //called when frame preparation has completed } func canceled() { painter.clear(); painter.paint(currentFunction) } //end EasingFunctionPainterDelegate implementation //begin UITableViewDataSource implementation func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell : UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell cell.textLabel?.text = self.items[indexPath.row] return cell } //end UITableViewDataSource implementation //begin UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ //Use EasingFunction's look up table to find the appropriate EasingFunction to paint currentFunction = EasingFunction.lut[(tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text)!]! if(painter.state == EasingFunctionPainterState.Idle){ painter.paint(currentFunction); } else{ painter.cancel(); } } //end UITableViewDelegate }
bsd-3-clause
f4fb96da47812301105c13f57b31fd5b
24.298611
169
0.608564
5.461769
false
false
false
false
k-o-d-e-n/CGLayout
Example/CGLayoutPlayground.playground/Pages/RectAnchors.xcplaygroundpage/Contents.swift
1
596
//: [Previous](@previous) import UIKit import CGLayout import PlaygroundSupport let sourceView = UIView(frame: UIScreen.main.bounds.insetBy(dx: 200, dy: 200)) sourceView.backgroundColor = .red let targetView = UIView() targetView.backgroundColor = .black sourceView.addSubview(targetView) PlaygroundPage.current.liveView = sourceView let layout = targetView.block { (anchors) in anchors.width.equal(to: 200) anchors.height.equal(to: 40) anchors.centerX.align(by: sourceView.layoutAnchors.centerX) anchors.centerY.align(by: sourceView.layoutAnchors.centerY) } layout.layout()
mit
bb060aaa1bab291998cf95706f4d6e9e
26.090909
78
0.771812
3.895425
false
false
false
false