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
YaQiongLu/LYQdyzb
LYQdyzb/LYQdyzb/Classes/Home/Controller/RecommendVC.swift
1
4611
// // RecommendVC.swift // LYQdyzb // // Created by 芦亚琼 on 2017/8/3. // Copyright © 2017年 芦亚琼. All rights reserved. // import UIKit fileprivate let kItemMargin : CGFloat = 10 fileprivate let kItemW = (kScreenW - 3 * kItemMargin) / 2 fileprivate let kItemNormalH = kItemW * 3 / 4 fileprivate let kItemPrettyH = kItemW * 4 / 3 fileprivate let kHeaderViewH : CGFloat = 50 fileprivate let kNormalCellId = "kNormalCellId" fileprivate let kPrettyCellId = "kPrettyCellId" fileprivate let kHeaderViewId = "kHeaderViewId" class RecommendVC: UIViewController { //MARK: - 懒加载属性 lazy var recommendVM : RecommendViewModel = RecommendViewModel() lazy var collectionView : UICollectionView = { //1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kItemNormalH) layout.minimumLineSpacing = 0 //最小线间距 layout.minimumInteritemSpacing = kItemMargin //最小项目间距 layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)//设置组头 layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)//设置内边距 让两边的margin平均 //2.创建collectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self as UICollectionViewDataSource collectionView.delegate = self collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth]//随着父控件的高度/宽度拉伸而拉伸 collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellId)//注册cell collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellId)//注册cell collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewId)//注册组头 return collectionView }() //MARK: - 系统回调函数 override func viewDidLoad() { super.viewDidLoad() //1.设置UI setupUI() //2.发送网络请求 loadData() } } //MARK: - 设置UI界面内容 extension RecommendVC{ fileprivate func setupUI() { //1.将collectionView添加到控制器view中 view.addSubview(collectionView) } } //MARK: -请求网络数据 extension RecommendVC{ fileprivate func loadData() { recommendVM.requestData() } } //MARK: - UICollectionViewDataSource数据源协议 extension RecommendVC : UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ //1.返回组 func numberOfSections(in collectionView: UICollectionView) -> Int { return 12 } //2.返回行 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return 8 } return 4 } //3.返回怎样的cell func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var cell : UICollectionViewCell! //1.获取cell if indexPath.section == 1 { cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellId, for: indexPath) }else{ cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellId, for: indexPath) } return cell } //4.返回怎样的组头 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { //1.取出每组的headerView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewId, for: indexPath) return headerView } //5.每组item返回怎样的高度 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kItemW, height: kItemPrettyH) }else{ return CGSize(width: kItemW, height: kItemNormalH) } } }
mit
c2e411822cf9040b3a59c9e78124f843
30.591241
192
0.678835
5.195678
false
false
false
false
VirgilSecurity/virgil-sdk-keys-ios
Source/JsonWebToken/AccessProviders/CachingJwtProvider.swift
1
5220
// // Copyright (C) 2015-2020 Virgil Security Inc. // // 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 AUTHOR ''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 AUTHOR 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. // // Lead Maintainer: Virgil Security Inc. <[email protected]> // import Foundation // swiftlint:disable trailing_closure /// Implementation of AccessTokenProvider which provides AccessToken using cache+renew callback @objc(VSSCachingJwtProvider) open class CachingJwtProvider: NSObject, AccessTokenProvider { /// Cached Jwt public private(set) var jwt: Jwt? /// Callback, which takes a TokenContext and completion handler /// Completion handler should be called with either JWT, or Error @objc public let renewJwtCallback: (TokenContext, @escaping (Jwt?, Error?) -> Void) -> Void private let semaphore = DispatchSemaphore(value: 1) /// Initializer /// /// - Parameters: /// - initialJwt: Initial jwt value /// - renewJwtCallback: Callback, which takes a TokenContext and completion handler /// Completion handler should be called with either JWT, or Error @objc public init(initialJwt: Jwt? = nil, renewJwtCallback: @escaping (TokenContext, @escaping (Jwt?, Error?) -> Void) -> Void) { self.jwt = initialJwt self.renewJwtCallback = renewJwtCallback super.init() } /// Typealias for callback used below public typealias JwtStringCallback = (String?, Error?) -> Void /// Typealias for callback used below public typealias RenewJwtCallback = (TokenContext, @escaping JwtStringCallback) -> Void /// Initializer /// /// - Parameters: /// - initialJwt: Initial jwt value /// - renewTokenCallback: Callback, which takes a TokenContext and completion handler /// Completion handler should be called with either JWT String, or Error @objc public convenience init(initialJwt: Jwt? = nil, renewTokenCallback: @escaping RenewJwtCallback) { self.init(initialJwt: initialJwt, renewJwtCallback: { ctx, completion in renewTokenCallback(ctx) { string, error in do { guard let string = string, error == nil else { completion(nil, error) return } completion(try Jwt(stringRepresentation: string), nil) } catch { completion(nil, error) } } }) } /// Typealias for callback used below public typealias AccessTokenCallback = (AccessToken?, Error?) -> Void /// Provides access token using callback /// /// - Parameters: /// - tokenContext: `TokenContext` provides context explaining why token is needed /// - completion: completion closure @objc public func getToken(with tokenContext: TokenContext, completion: @escaping AccessTokenCallback) { let expirationTime = Date().addingTimeInterval(5) if let jwt = self.jwt, !jwt.isExpired(date: expirationTime), !tokenContext.forceReload { completion(jwt, nil) return } self.semaphore.wait() if let jwt = self.jwt, !jwt.isExpired(date: expirationTime), !tokenContext.forceReload { self.semaphore.signal() completion(jwt, nil) return } self.renewJwtCallback(tokenContext) { token, err in guard let token = token, err == nil else { self.semaphore.signal() completion(nil, err) return } self.jwt = token self.semaphore.signal() completion(token, nil) } } } // swiftlint:enable trailing_closure
bsd-3-clause
4622d8adf829a99409b6089dfe6c6d76
38.545455
109
0.650766
4.980916
false
false
false
false
paulsumit1993/DailyFeed
DailyFeed/Supporting Files/PullToReach/PullToReachTarget.swift
1
4076
// // PullToReachTarget.swift // PullToReach // // Created by Stefan Kofler on 17.02.19. // Copyright © 2019 QuickBird Studios GmbH. All rights reserved. // import UIKit // MARK: - PullToReachTarget public protocol PullToReachTarget { func callSelector() func applyStyle(isHighlighted: Bool, highlightColor: UIColor) func removeHighlight() } // MARK: - UIBarButtonItem: PullToReachTarget extension UIBarButtonItem: PullToReachTarget { public func callSelector() { if let actionSelector = self.action { _ = self.target?.perform(actionSelector) } } public func removeHighlight() { removeSelectionIndicatorView() } @objc open func applyStyle(isHighlighted: Bool, highlightColor: UIColor) { guard let view = self.value(forKey: "view") as? UIView else { return } guard let selectionIndicator = addSelectionIndicatorView() else { return } guard let navigationBar = view.firstSuperview(ofType: UINavigationBar.self) else { return } let scale: CGFloat = isHighlighted ? 1.25 : 1.0 let selectionIndicatorSize: CGFloat = view.bounds.height * 1.2 selectionIndicator.layer.cornerRadius = selectionIndicatorSize / 2.0 selectionIndicator.bounds.size = CGSize(width: selectionIndicatorSize, height: selectionIndicatorSize) guard let nestedView = view.subviews.first else { return } let targetPosition1 = view.convert(nestedView.center, to: navigationBar) let targetPosition2 = view.superview?.convert(view.center, to: navigationBar) ?? .zero let targetPosition = CGPoint(x: (targetPosition1.x + targetPosition2.x) / 2.0, y: (targetPosition1.y + targetPosition2.y) / 2.0) if selectionIndicator.center == .zero { selectionIndicator.center = targetPosition } UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: [], animations: { view.transform = CGAffineTransform(scaleX: scale, y: scale) if isHighlighted { selectionIndicator.backgroundColor = highlightColor selectionIndicator.center = targetPosition selectionIndicator.transform = .identity } }, completion: nil) } private func removeSelectionIndicatorView() { guard let view = self.value(forKey: "view") as? UIView else { return } guard let navigationBar = view.firstSuperview(ofType: UINavigationBar.self) else { return } navigationBar.firstSubview(ofType: SelectionIndicatorView.self)?.removeFromSuperview() } private func addSelectionIndicatorView() -> UIView? { guard let view = self.value(forKey: "view") as? UIView else { return nil } guard let navigationBar = view.firstSuperview(ofType: UINavigationBar.self) else { return nil } if let selectionIndicator = navigationBar.firstSubview(ofType: SelectionIndicatorView.self) { return selectionIndicator } else { let selectionIndicator = SelectionIndicatorView() selectionIndicator.clipsToBounds = true navigationBar.insertSubview(selectionIndicator, at: 1) return selectionIndicator } } } // MARK: - UIControl: PullToReachTarget extension UIControl: PullToReachTarget { public func callSelector() { let callees = allTargets.flatMap { target -> [(NSObject, String)] in actions(forTarget: target as NSObject, forControlEvent: .touchUpInside)? .map { (target as NSObject, $0) } ?? [] } for (target, selector) in callees { target.perform(NSSelectorFromString(selector)) } } public func removeHighlight() {} @objc open func applyStyle(isHighlighted: Bool, highlightColor: UIColor) { let scale: CGFloat = isHighlighted ? 2.25 : 1.0 self.transform = CGAffineTransform(scaleX: scale, y: scale) } }
gpl-3.0
edb6772b54c23be155b05d8e1f006f50
35.383929
110
0.659877
4.874402
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/TableRecordTests.swift
1
12248
import XCTest import GRDB private struct RecordStruct: TableRecord { } private struct CustomizedRecordStruct: TableRecord { static let databaseTableName = "CustomizedRecordStruct" } private class RecordClass: TableRecord { } private class RecordSubClass: RecordClass { } private class CustomizedRecordClass: TableRecord { class var databaseTableName: String { "CustomizedRecordClass" } } private class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { "CustomizedRecordSubClass" } } private class CustomizedPlainRecord: Record { override class var databaseTableName: String { "CustomizedPlainRecord" } } private enum Namespace { struct RecordStruct: TableRecord { } struct CustomizedRecordStruct: TableRecord { static let databaseTableName = "CustomizedRecordStruct" } class RecordClass: TableRecord { } class RecordSubClass: RecordClass { } class CustomizedRecordClass: TableRecord { class var databaseTableName: String { "CustomizedRecordClass" } } class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { "CustomizedRecordSubClass" } } class CustomizedPlainRecord: Record { override class var databaseTableName: String { "CustomizedPlainRecord" } } } private struct HTTPRequest: TableRecord { } private struct TOEFL: TableRecord { } class TableRecordTests: GRDBTestCase { func testDefaultDatabaseTableName() { struct InnerRecordStruct: TableRecord { } struct InnerCustomizedRecordStruct: TableRecord { static let databaseTableName = "InnerCustomizedRecordStruct" } class InnerRecordClass: TableRecord { } class InnerRecordSubClass: InnerRecordClass { } class InnerCustomizedRecordClass: TableRecord { class var databaseTableName: String { "InnerCustomizedRecordClass" } } class InnerCustomizedRecordSubClass: InnerCustomizedRecordClass { override class var databaseTableName: String { "InnerCustomizedRecordSubClass" } } class InnerCustomizedPlainRecord: Record { override class var databaseTableName: String { "InnerCustomizedPlainRecord" } } XCTAssertEqual(RecordStruct.databaseTableName, "recordStruct") XCTAssertEqual(CustomizedRecordStruct.databaseTableName, "CustomizedRecordStruct") XCTAssertEqual(RecordClass.databaseTableName, "recordClass") XCTAssertEqual(RecordSubClass.databaseTableName, "recordSubClass") XCTAssertEqual(CustomizedRecordClass.databaseTableName, "CustomizedRecordClass") XCTAssertEqual(CustomizedRecordSubClass.databaseTableName, "CustomizedRecordSubClass") XCTAssertEqual(CustomizedPlainRecord.databaseTableName, "CustomizedPlainRecord") XCTAssertEqual(Namespace.RecordStruct.databaseTableName, "recordStruct") XCTAssertEqual(Namespace.CustomizedRecordStruct.databaseTableName, "CustomizedRecordStruct") XCTAssertEqual(Namespace.RecordClass.databaseTableName, "recordClass") XCTAssertEqual(Namespace.RecordSubClass.databaseTableName, "recordSubClass") XCTAssertEqual(Namespace.CustomizedRecordClass.databaseTableName, "CustomizedRecordClass") XCTAssertEqual(Namespace.CustomizedRecordSubClass.databaseTableName, "CustomizedRecordSubClass") XCTAssertEqual(Namespace.CustomizedPlainRecord.databaseTableName, "CustomizedPlainRecord") XCTAssertEqual(InnerRecordStruct.databaseTableName, "innerRecordStruct") XCTAssertEqual(InnerCustomizedRecordStruct.databaseTableName, "InnerCustomizedRecordStruct") XCTAssertEqual(InnerRecordClass.databaseTableName, "innerRecordClass") XCTAssertEqual(InnerRecordSubClass.databaseTableName, "innerRecordSubClass") XCTAssertEqual(InnerCustomizedRecordClass.databaseTableName, "InnerCustomizedRecordClass") XCTAssertEqual(InnerCustomizedRecordSubClass.databaseTableName, "InnerCustomizedRecordSubClass") XCTAssertEqual(InnerCustomizedPlainRecord.databaseTableName, "InnerCustomizedPlainRecord") XCTAssertEqual(HTTPRequest.databaseTableName, "httpRequest") XCTAssertEqual(TOEFL.databaseTableName, "toefl") func tableName<T: TableRecord>(_ type: T.Type) -> String { T.databaseTableName } XCTAssertEqual(tableName(RecordStruct.self), "recordStruct") XCTAssertEqual(tableName(CustomizedRecordStruct.self), "CustomizedRecordStruct") XCTAssertEqual(tableName(RecordClass.self), "recordClass") XCTAssertEqual(tableName(RecordSubClass.self), "recordSubClass") XCTAssertEqual(tableName(CustomizedRecordClass.self), "CustomizedRecordClass") XCTAssertEqual(tableName(CustomizedRecordSubClass.self), "CustomizedRecordSubClass") XCTAssertEqual(tableName(CustomizedPlainRecord.self), "CustomizedPlainRecord") XCTAssertEqual(tableName(Namespace.RecordStruct.self), "recordStruct") XCTAssertEqual(tableName(Namespace.CustomizedRecordStruct.self), "CustomizedRecordStruct") XCTAssertEqual(tableName(Namespace.RecordClass.self), "recordClass") XCTAssertEqual(tableName(Namespace.RecordSubClass.self), "recordSubClass") XCTAssertEqual(tableName(Namespace.CustomizedRecordClass.self), "CustomizedRecordClass") XCTAssertEqual(tableName(Namespace.CustomizedRecordSubClass.self), "CustomizedRecordSubClass") XCTAssertEqual(tableName(Namespace.CustomizedPlainRecord.self), "CustomizedPlainRecord") XCTAssertEqual(tableName(InnerRecordStruct.self), "innerRecordStruct") XCTAssertEqual(tableName(InnerCustomizedRecordStruct.self), "InnerCustomizedRecordStruct") XCTAssertEqual(tableName(InnerRecordClass.self), "innerRecordClass") XCTAssertEqual(tableName(InnerRecordSubClass.self), "innerRecordSubClass") XCTAssertEqual(tableName(InnerCustomizedRecordClass.self), "InnerCustomizedRecordClass") XCTAssertEqual(tableName(InnerCustomizedRecordSubClass.self), "InnerCustomizedRecordSubClass") XCTAssertEqual(tableName(InnerCustomizedPlainRecord.self), "InnerCustomizedPlainRecord") XCTAssertEqual(tableName(HTTPRequest.self), "httpRequest") XCTAssertEqual(tableName(TOEFL.self), "toefl") } func testDefaultDatabaseSelection() throws { struct Record: TableRecord { static let databaseTableName = "t1" } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE t1(a,b,c)") _ = try Row.fetchAll(db, Record.all()) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"t1\"") } } func testExtendedDatabaseSelection() throws { struct Record: TableRecord { static let databaseTableName = "t1" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE t1(a,b,c)") _ = try Row.fetchAll(db, Record.all()) XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"t1\"") } } func testRestrictedDatabaseSelection() throws { struct Record: TableRecord { static let databaseTableName = "t1" static let databaseSelection: [SQLSelectable] = [Column("a"), Column("b")] } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE t1(a,b,c)") _ = try Row.fetchAll(db, Record.all()) XCTAssertEqual(lastSQLQuery, "SELECT \"a\", \"b\" FROM \"t1\"") } } func testRecordInAttachedDatabase() throws { #if SQLITE_HAS_CODEC // Avoid error due to key not being provided: // file is not a database - while executing `ATTACH DATABASE...` throw XCTSkip("This test does not support encrypted databases") #endif struct Team: Codable, PersistableRecord, FetchableRecord, Equatable { var id: Int64 var name: String } struct Player: Codable, PersistableRecord, FetchableRecord, Equatable { var id: Int64 var teamID: Int64 var name: String var email: String } struct PlayerInfo: Decodable, FetchableRecord, Equatable { var player: Player var team: Team } let db1 = try makeDatabaseQueue(filename: "db1.sqlite") try db1.write { db in try db.create(table: "team") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() } try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("teamID", .integer).notNull().references("team") t.column("name", .text).notNull() t.column("email", .text).notNull().unique() } } let db2 = try makeDatabaseQueue(filename: "db2.sqlite") try db2.writeWithoutTransaction { db in try db.execute(literal: "ATTACH DATABASE \(db1.path) AS db1") try XCTAssertEqual(Player.fetchCount(db), 0) let team = Team(id: 1, name: "Arthur") let player = Player(id: 1, teamID: 1, name: "Arthur", email: "[email protected]") try team.insert(db) try player.insert(db) try XCTAssertEqual(Player.orderByPrimaryKey().fetchOne(db)?.name, "Arthur") try XCTAssertEqual( Player .including(required: Player.belongsTo(Team.self)) .asRequest(of: PlayerInfo.self) .fetchOne(db), PlayerInfo(player: player, team: team)) } } func testCrossAttachedDatabaseAssociation() throws { #if SQLITE_HAS_CODEC // Avoid error due to key not being provided: // file is not a database - while executing `ATTACH DATABASE...` throw XCTSkip("This test does not support encrypted databases") #endif struct Team: Codable, PersistableRecord, FetchableRecord, Equatable { var id: Int64 var name: String } struct Player: Codable, PersistableRecord, FetchableRecord, Equatable { var id: Int64 var teamID: Int64 var name: String var email: String } struct PlayerInfo: Decodable, FetchableRecord, Equatable { var player: Player var team: Team } let db1 = try makeDatabaseQueue(filename: "db1.sqlite") try db1.write { db in try db.create(table: "team") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() } } let db2 = try makeDatabaseQueue(filename: "db2.sqlite") try db2.writeWithoutTransaction { db in try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("teamID", .integer).notNull() t.column("name", .text).notNull() t.column("email", .text).notNull().unique() } try db.execute(literal: "ATTACH DATABASE \(db1.path) AS db1") try XCTAssertEqual(Player.fetchCount(db), 0) let team = Team(id: 1, name: "Arthur") let player = Player(id: 1, teamID: 1, name: "Arthur", email: "[email protected]") try team.insert(db) try player.insert(db) try XCTAssertEqual(Player.orderByPrimaryKey().fetchOne(db)?.name, "Arthur") try XCTAssertEqual( Player .including(required: Player.belongsTo(Team.self, using: ForeignKey(["teamID"]))) .asRequest(of: PlayerInfo.self) .fetchOne(db), PlayerInfo(player: player, team: team)) } } }
mit
aca1d16ab677e507077be97c376c33a0
48.991837
156
0.664598
5.128978
false
false
false
false
SwiftGen/SwiftGen
Tests/SwiftGenKitTests/StringPlaceholderTypeTests.swift
1
7891
// // SwiftGenKit UnitTests // Copyright © 2022 SwiftGen // MIT Licence // @testable import SwiftGenKit import XCTest final class StringPlaceholderTypeTests: XCTestCase { func testParseStringPlaceholder() throws { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: "%@") XCTAssertEqual(placeholders, [.object]) } func testParseFloatPlaceholder() throws { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: "%f") XCTAssertEqual(placeholders, [.float]) } func testParseDoublePlaceholders() throws { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: "%g-%e") XCTAssertEqual(placeholders, [.float, .float]) } func testParseFloatWithPrecisionPlaceholders() throws { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: "%1.2f : %.3f : %+3f : %-6.2f") XCTAssertEqual(placeholders, [.float, .float, .float, .float]) } func testParseIntPlaceholders() throws { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: "%d-%i-%o-%u-%x") XCTAssertEqual(placeholders, [.int, .int, .int, .int, .int]) } func testParseCCharAndStringPlaceholders() throws { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: "%c-%s") XCTAssertEqual(placeholders, [.char, .cString]) } func testParsePositionalPlaceholders() throws { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: "%2$d-%4$f-%3$@-%c") XCTAssertEqual(placeholders, [.char, .int, .object, .float]) } func testParseComplexFormatPlaceholders() throws { let format = "%2$1.3d - %4$-.7f - %3$@ - %% - %5$+3c - %%" let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: format) // positions 2, 4, 3, 5 set to .int, .float, .object, .char ; position 1 not matched XCTAssertEqual(placeholders, [.int, .object, .float, .char]) } func testParseManyPlaceholders() throws { let format = "%@ - %d - %f - %5$d - %04$f - %6$d - %007$@ - %8$3.2f - %11$1.2f - %9$@ - %10$d" let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: format) XCTAssertEqual( placeholders, [.object, .int, .float, .float, .int, .int, .object, .float, .object, .int, .float] ) } func testParseManyPlaceholdersWithZeroPos() throws { // %0$@ is interpreted by Foundation not as a placeholder (because invalid 0 position) // but instead rendered as a "0@" literal. let format = "%@ - %d - %0$@ - %f - %5$d - %04$f - %6$d - %007$@ - %8$3.2f - %11$1.2f - %9$@ - %10$d" let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: format) XCTAssertEqual( placeholders, [.object, .int, .float, .float, .int, .int, .object, .float, .object, .int, .float] ) } func testParseInterleavedPositionalAndNonPositionalPlaceholders() throws { let format = "%@ %7$d %@ %@ %8$d %@ %@" let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: format) XCTAssertEqual(placeholders, [.object, .object, .object, .object, .object, /* ?, */ .int, .int]) } func testParseFlags() throws { let formats = ["%-9d", "%+9d", "% 9d", "%#9d", "%09d"] for format in formats { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: format) XCTAssertEqual(placeholders, [.int], "Failed to parse format \"\(format)\"") } let invalidFormat = "%_9d %_9f %_9@ %!9@" let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: invalidFormat) XCTAssertEqual(placeholders, []) } func testParseDuplicateFormatPlaceholders() throws { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: "Text: %1$@; %1$@.") XCTAssertEqual(placeholders, [.object]) } private func pluralVariable( _ name: String, type: String, one: String, other: String ) -> StringsDict.PluralEntry.Variable { .init( name: name, rule: .init( specTypeKey: "NSStringPluralRuleType", valueTypeKey: type, zero: nil, one: one, two: nil, few: nil, many: nil, other: other ) ) } func testStringsDictPlaceholdersConversion() throws { let entry = StringsDict.PluralEntry( formatKey: """ %@ - %#@d2@ - %0$#@zero@ - %#@f3@ - %5$#@d5@ - %04$#@f4@ - %6$#@d6@ - %007$@ - %8$#@f8@ - %11$#@f11@ - %9$@ - %10$#@d10@ """, variables: [ pluralVariable("zero", type: "d", one: "unused", other: "unused"), pluralVariable("d2", type: "d", one: "%d two", other: "%d twos"), pluralVariable("f3", type: "f", one: "%f three", other: "%f threes"), pluralVariable("f4", type: "f", one: "%f four", other: "%f fours"), pluralVariable("d5", type: "d", one: "%d five", other: "%d fives"), pluralVariable("d6", type: "d", one: "%d six", other: "%d sixes"), pluralVariable("f8", type: "f", one: "%f eight", other: "%f eights"), pluralVariable("d10", type: "d", one: "%d ten", other: "%d tens"), pluralVariable("f11", type: "f", one: "%f eleven", other: "%f elevens") ] ) let converted = entry.formatKeyWithVariableValueTypes XCTAssertEqual( converted, "%@ - %d - %0$d - %f - %5$d - %4$f - %6$d - %007$@\n- %8$f - %11$f - %9$@ - %10$d" ) let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: converted) XCTAssertEqual( placeholders, [.object, .int, .float, .float, .int, .int, .object, .float, .object, .int, .float] ) } // MARK: - Testing Errors func testParseErrorOnTypeMismatch() throws { XCTAssertThrowsError( try Strings.PlaceholderType.placeholderTypes(fromFormat: "Text: %1$@; %1$ld."), "Code did parse string successfully while it was expected to fail for bad syntax" ) { error in guard let parserError = error as? Strings.ParserError, case .invalidPlaceholder = parserError // That's the expected exception we want to happen else { XCTFail("Unexpected error occured while parsing: \(error)") return } } } func testParseErrorOnPositionalValueBeingOverwritten() throws { let formatStrings: [String: (Strings.PlaceholderType, Strings.PlaceholderType)] = [ "%@ %1$d": (.object, .int), // `.int` would overwrite existing `.object` "%1$d %@": (.int, .object), // `.object` would overwrite existing `.int` "%@ %2$d %@": (.int, .object), // `.object` would overwrite existing `.int` "%@ %2$d %@ %@ %5$d %@ %@": (.int, .object), // `.object` would overwrite existing `.int` "%@ %@ %2$d %@ %5$d %@ %@": (.object, .int) // `.int` would overwrite existing `.object` ] for (formatString, expectedFormats) in formatStrings { XCTAssertThrowsError( try Strings.PlaceholderType.placeholderTypes(fromFormat: formatString), "Code did parse string successfully while it was expected to fail for bad syntax" ) { error in guard let parserError = error as? Strings.ParserError, case .invalidPlaceholder(previous: expectedFormats.0, new: expectedFormats.1) = parserError else { XCTFail("Unexpected error occured while parsing: \(error)") return } } } } // MARK: - Testing Percent Escapes func testParseEvenEscapePercentSign() throws { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: "%%foo") // Must NOT map to [.float] XCTAssertEqual(placeholders, []) } func testParseOddEscapePercentSign() throws { let placeholders = try Strings.PlaceholderType.placeholderTypes(fromFormat: "%%%foo") // Should map to [.float] XCTAssertEqual(placeholders, [.float]) } }
mit
da9094d2b4a3696efe4809e4f1003137
37.676471
111
0.63346
3.782359
false
true
false
false
AlexZd/SwiftUtils
Pod/Utils/UIView+Helpers/Init/UITextField+Init.swift
1
472
// // UITextField+Init.swift // Alamofire // // Created by Alex on 18.04.2018. // import Foundation import UIKit extension UITextField { public convenience init(background: UIColor? = nil, textColor: UIColor, font: UIFont?) { self.init() self.translatesAutoresizingMaskIntoConstraints = false self.clipsToBounds = true self.backgroundColor = background self.textColor = textColor self.font = font } }
mit
c2803d11ac2575836475fab239ab99f9
20.454545
92
0.652542
4.538462
false
false
false
false
xPutnikx/ProvisioningFlow
ProvisioningFlow/poc/ProvisioningFlow.swift
1
1783
// // ProvisioningFlow.swift // ProvisioningFlow // // Created by Vladimir Hudnitsky on 9/18/17. // Copyright © 2017 Vladimir Hudnitsky. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class ProvisioningFlow: FlowOrchestrator { typealias FlowDataModel = ProvisioningDataModel let initialData: ProvisioningDataModel let viewController: UINavigationController init(initialData: ProvisioningDataModel = ProvisioningDataModel(vin: nil, user: nil, terminalId: nil), viewController: UINavigationController) { self.initialData = initialData self.viewController = viewController } func createFlowObservable() -> Observable<ProvisioningDataModel>{ return Observable<ProvisioningDataModel>.deferred { return Observable<ProvisioningDataModel>.create { subscriber in subscriber.onNext(self.initialData) return Disposables.create() } .flatMap { data in return CheckVinTask() .buildObservable(viewController: self.viewController, param: ()) .flatMap { innerData -> Observable<ProvisioningDataModel> in let updatedData = ProvisioningDataModel(vin: innerData, user: data.user, terminalId: data.terminalId) return Observable.just(updatedData) } } .flatMap { data in return RegisterUserTask() .buildObservable(viewController: self.viewController, param: ()) .flatMap { innerData -> Observable<ProvisioningDataModel> in let updatedData = ProvisioningDataModel(vin: data.vin, user: innerData, terminalId: data.terminalId) return Observable.just(updatedData) } } } } }
apache-2.0
d2c53737ad40492f7efe22f9da5031ed
32
115
0.685746
4.895604
false
false
false
false
Kagamine/LongjiangAgricultureCloud
iOSLongjiangAgricultureCloud/LongjiangAgricultureCloud/LongjiangAgricultureCloud/ViewController.swift
2
2383
// // ViewController.swift // LongjiangAgricultureCloud // // Created by Amamiya Yuuko on 15/6/21. // Copyright (c) 2015年 龙江县超越现代玉米种植农民专业合作社. All rights reserved. // import UIKit class ViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "http://221.208.208.32:7532/Mobile") let request = NSURLRequest(URL: url!) for subView in webView.subviews { if (subView.isKindOfClass(UIScrollView)) { (subView as! UIScrollView).bounces = false for shadowView in subView.subviews { if (shadowView.isKindOfClass(UIImageView)) { (shadowView as! UIImageView).hidden = true } } } if (subView.isKindOfClass(UIImageView)) { (subView as! UIImageView).hidden = true } } webView.layer.borderWidth = 0 webView.opaque = false; webView.backgroundColor = UIColor.clearColor() webView.scrollView.bounces = false webView.delegate = self webView.dataDetectorTypes = UIDataDetectorTypes.All webView.loadRequest(request) // Do any additional setup after loading the view, typically from a nib. } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if (request.URL?.scheme == "tel") { let urlstr = (request.URL?.absoluteString)!.stringByReplacingOccurrencesOfString("tel:", withString:"tel://") let url = NSURL(string: urlstr); let result = UIApplication.sharedApplication().openURL(url!) return false; } else if (request.URL?.scheme == "wxpay" || request.URL?.scheme == "alipay") { let url = request.URL let result = UIApplication.sharedApplication().openURL(url!) return false; } return true; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
fd1f9f64b9eb9740ca93ca02572daa35
33.485294
137
0.58678
4.96822
false
false
false
false
ScottRobbins/RxCocoaTouch
Pod/Classes/CALayer+Rx.swift
1
9934
import RxSwift extension CALayer { // MARK: - Accessing the Delegate public var rx_delegate: ObserverOf<AnyObject?> { return observerOfWithPropertySetter { [weak self] (delegate: AnyObject?) in self?.delegate = delegate } } // MARK: - Providing the Layer's Content public var rx_contents: ObserverOf<AnyObject?> { return observerOfWithPropertySetter { [weak self] (contents: AnyObject?) in self?.contents = contents } } public var rx_contentsRect: ObserverOf<CGRect> { return observerOfWithPropertySetter { [weak self] (contentsRect: CGRect) in self?.contentsRect = contentsRect } } public var rx_contentsCenter: ObserverOf<CGRect> { return observerOfWithPropertySetter { [weak self] (contentsCenter: CGRect) in self?.contentsCenter = contentsCenter } } // MARK: - Modifying the Layer's Appearance public var rx_contentsGravity: ObserverOf<String> { return observerOfWithPropertySetter { [weak self] (contentsGravity: String) in self?.contentsGravity = contentsGravity } } public var rx_opacity: ObserverOf<Float> { return observerOfWithPropertySetter { [weak self] (opacity: Float) in self?.opacity = opacity } } public var rx_hidden: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (hidden: Bool) in self?.hidden = hidden } } public var rx_masksToBounds: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (masksToBounds: Bool) in self?.masksToBounds = masksToBounds } } public var rx_mask: ObserverOf<CALayer?> { return observerOfWithPropertySetter { [weak self] (mask: CALayer?) in self?.mask = mask } } public var rx_doubleSided: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (doubleSided: Bool) in self?.doubleSided = doubleSided } } public var rx_cornerRadius: ObserverOf<CGFloat> { return observerOfWithPropertySetter { [weak self] (cornerRadius: CGFloat) in self?.cornerRadius = cornerRadius } } public var rx_borderWidth: ObserverOf<CGFloat> { return observerOfWithPropertySetter { [weak self] (borderWidth: CGFloat) in self?.borderWidth = borderWidth } } public var rx_borderColor: ObserverOf<CGColor?> { return observerOfWithPropertySetter { [weak self] (borderColor: CGColor?) in self?.borderColor = borderColor } } public var rx_backgroundColor: ObserverOf<CGColor?> { return observerOfWithPropertySetter { [weak self] (backgroundColor: CGColor?) in self?.backgroundColor = backgroundColor } } public var rx_shadowOpacity: ObserverOf<Float> { return observerOfWithPropertySetter { [weak self] (shadowOpacity: Float) in self?.shadowOpacity = shadowOpacity } } public var rx_shadowRadius: ObserverOf<CGFloat> { return observerOfWithPropertySetter { [weak self] (shadowRadius: CGFloat) in self?.shadowRadius = shadowRadius } } public var rx_shadowOffset: ObserverOf<CGSize> { return observerOfWithPropertySetter { [weak self] (shadowOffset: CGSize) in self?.shadowOffset = shadowOffset } } public var rx_shadowColor: ObserverOf<CGColor?> { return observerOfWithPropertySetter { [weak self] (shadowColor: CGColor?) in self?.shadowColor = shadowColor } } public var rx_shadowPath: ObserverOf<CGPath?> { return observerOfWithPropertySetter { [weak self] (shadowPath: CGPath?) in self?.shadowPath = shadowPath } } public var rx_style: ObserverOf<[NSObject : AnyObject]?> { return observerOfWithPropertySetter { [weak self] (style: [NSObject : AnyObject]?) in self?.style = style } } // MARK: - Accessing the Layer's Filters public var rx_filters: ObserverOf<[AnyObject]?> { return observerOfWithPropertySetter { [weak self] (filters: [AnyObject]?) in self?.filters = filters } } public var rx_compositingFilter: ObserverOf<AnyObject?> { return observerOfWithPropertySetter { [weak self] (compositingFilter: AnyObject?) in self?.compositingFilter = compositingFilter } } public var rx_backgroundFilters: ObserverOf<[AnyObject]?> { return observerOfWithPropertySetter { [weak self] (backgroundFilters: [AnyObject]?) in self?.backgroundFilters = backgroundFilters } } public var rx_minificationFilter: ObserverOf<String> { return observerOfWithPropertySetter { [weak self] (minificationFilter: String) in self?.minificationFilter = minificationFilter } } public var rx_minificationFilterBias: ObserverOf<Float> { return observerOfWithPropertySetter { [weak self] (minificationFilterBias: Float) in self?.minificationFilterBias = minificationFilterBias } } public var rx_magnificationFilter: ObserverOf<String> { return observerOfWithPropertySetter { [weak self] (magnificationFilter: String) in self?.magnificationFilter = magnificationFilter } } // MARK: - Configuring the Layer's Rendering Behavior public var rx_opaque: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (opaque: Bool) in self?.opaque = opaque } } public var rx_edgeAntialiasingMask: ObserverOf<CAEdgeAntialiasingMask> { return observerOfWithPropertySetter { [weak self] (edgeAntialiasingMask: CAEdgeAntialiasingMask) in self?.edgeAntialiasingMask = edgeAntialiasingMask } } public var rx_geometryFlipped: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (geometryFlipped: Bool) in self?.geometryFlipped = geometryFlipped } } public var rx_drawsAsynchronously: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (drawsAsynchronously: Bool) in self?.drawsAsynchronously = drawsAsynchronously } } public var rx_shouldRasterize: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (shouldRasterize: Bool) in self?.shouldRasterize = shouldRasterize } } public var rx_rasterizationScale: ObserverOf<CGFloat> { return observerOfWithPropertySetter { [weak self] (rasterizationScale: CGFloat) in self?.rasterizationScale = rasterizationScale } } // MARK: - Modifying the Layer Geometry public var rx_frame: ObserverOf<CGRect> { return observerOfWithPropertySetter { [weak self] (frame: CGRect) in self?.frame = frame } } public var rx_bounds: ObserverOf<CGRect> { return observerOfWithPropertySetter { [weak self] (bounds: CGRect) in self?.bounds = bounds } } public var rx_position: ObserverOf<CGPoint> { return observerOfWithPropertySetter { [weak self] (position: CGPoint) in self?.position = position } } public var rx_zPosition: ObserverOf<CGFloat> { return observerOfWithPropertySetter { [weak self] (zPosition: CGFloat) in self?.zPosition = zPosition } } public var rx_anchorPointZ: ObserverOf<CGFloat> { return observerOfWithPropertySetter { [weak self] (anchorPointZ: CGFloat) in self?.anchorPointZ = anchorPointZ } } public var rx_anchorPoint: ObserverOf<CGPoint> { return observerOfWithPropertySetter { [weak self] (anchorPoint: CGPoint) in self?.anchorPoint = anchorPoint } } public var rx_contentsScale: ObserverOf<CGFloat> { return observerOfWithPropertySetter { [weak self] (contentsScale: CGFloat) in self?.contentsScale = contentsScale } } // MARK: - Managing the Layer's Transform public var rx_transform: ObserverOf<CATransform3D> { return observerOfWithPropertySetter { [weak self] (transform: CATransform3D) in self?.transform = transform } } public var rx_sublayerTransform: ObserverOf<CATransform3D> { return observerOfWithPropertySetter { [weak self] (sublayerTransform: CATransform3D) in self?.sublayerTransform = sublayerTransform } } // MARK: - Managing the Layer Hierarchy public var rx_sublayers: ObserverOf<[CALayer]?> { return observerOfWithPropertySetter { [weak self] (sublayers: [CALayer]?) in self?.sublayers = sublayers } } // MARK: - Updating Layer Display public var rx_needsDisplayOnBoundsChange: ObserverOf<Bool> { return observerOfWithPropertySetter { [weak self] (needsDisplayOnBoundsChange: Bool) in self?.needsDisplayOnBoundsChange = needsDisplayOnBoundsChange } } // MARK: - Getting the Layer's Actions public var rx_actions: ObserverOf<[String : CAAction]?> { return observerOfWithPropertySetter { [weak self] (actions: [String : CAAction]?) in self?.actions = actions } } // MARK: - Identifying the Layer public var rx_name: ObserverOf<String?> { return observerOfWithPropertySetter { [weak self] (name: String?) in self?.name = name } } }
mit
4e1575f9a2aac50cf66eb8414b97c388
32.447811
107
0.630662
5.091748
false
false
false
false
AbelSu131/SimpleMemo
Memo/印象便签 WatchKit Extension/MemoInterFaceController+WCSession.swift
1
1839
// // MemoInterFaceController+WCSession.swift // Memo // // Created by  李俊 on 15/9/27. // Copyright © 2015年  李俊. All rights reserved. // import WatchConnectivity import UIKit extension MemoInterfaceController: WCSessionDelegate { func sharedSession() -> WCSession? { let session: WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil session?.delegate = self session?.activateSession() return session } func shareMessage(message: [String : AnyObject]){ if let session = sharedSession() where session.reachable { session.sendMessage(message, replyHandler: { (replyData) -> Void in }, errorHandler: { (error) -> Void in }) }else{ do { try sharedSession()?.updateApplicationContext(message) }catch { } } } func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) { dispatch_async(dispatch_get_main_queue()) { () -> Void in self.readSharedMemos(message) } } func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) { readSharedMemos(applicationContext) } func readSharedMemos(sharedMemos: [String : AnyObject]){ let sharedMemo = sharedMemos["sharedMemos"] as? [[String : AnyObject]] if sharedMemo == nil { self.memos.insert(sharedMemos, atIndex: 0) }else{ self.memos = sharedMemo! sharedDefaults?.setObject(memos, forKey: "WatchMemo") sharedDefaults?.synchronize() } self.setTable() } }
mit
2e8cd33659db160a81a967435c115d45
22.410256
131
0.585433
4.805263
false
false
false
false
sdkshredder/SocialMe
SocialMe/SocialMe/FriendRequectTVCell.swift
1
5520
// // FriendRequectTVCell.swift // SocialMe // // Created by Kelsey Young on 5/24/15. // Copyright (c) 2015 new. All rights reserved. // import UIKit import Parse import Foundation class FriendRequectTVCell: UITableViewCell { @IBOutlet weak var profilePicture: UIImageView! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var acceptButton: UIButton! @IBOutlet weak var rejectButton: UIButton! @IBOutlet weak var blockButton: UIButton! var toUsername : NSString! var fromUsername : NSString! func addFriendShip(username :NSString, friendData :PFObject) { let query = PFQuery(className: "Friendships") query.whereKey("username", equalTo: username) var objectArr = query.findObjects() as! [PFObject] if objectArr.count > 0 { let friendshipObj = objectArr[0] if let friendsArr = friendshipObj["friends"] as? NSMutableArray { friendsArr.addObject(friendData) friendshipObj["friends"] = friendsArr friendshipObj.save() } } else { let newFriendship = PFObject(className: "Friendships") newFriendship["username"] = username let friendsArr = NSMutableArray() friendsArr.addObject(friendData) newFriendship["friends"] = friendsArr newFriendship.save() } } func reactToRequest(response :NSString) { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { var info = [String:Int]() info["index"] = self.acceptButton.tag let toUserQuery = PFUser.query() toUserQuery?.whereKey("username", equalTo: self.toUsername) var toUserArr = toUserQuery?.findObjects() as! [PFUser] let toUser = toUserArr[0] let fromUserQuery = PFUser.query() fromUserQuery?.whereKey("username", equalTo: self.fromUsername) var fromUserArr = fromUserQuery?.findObjects() as! [PFUser] let fromUser = fromUserArr[0] let requestQuery = PFQuery(className: "FriendRequests") requestQuery.whereKey("toUser", equalTo: toUser.username!) requestQuery.whereKey("fromUser", equalTo: fromUser.username!) var requestObjectArr = requestQuery.findObjects() as! [PFObject] let requestObject = requestObjectArr[0] if (response == "approved") { requestObject["status"] = "approved" requestObject.save() self.addFriendShip(toUser.username!, friendData: fromUser) self.addFriendShip(fromUser.username!, friendData: toUser) /* if let var fromUserFriends = fromUser["friends"] as? NSMutableArray { fromUserFriends.addObject(toUser) fromUser["friends"] = fromUserFriends } else { var friendArr = NSMutableArray() friendArr.addObject(toUser) fromUser["friends"] = friendArr } fromUser.save() if let var toUserFriends = toUser["friends"] as? NSMutableArray { toUserFriends.addObject(fromUser) toUser["friends"] = toUserFriends } else { var friendArr = NSMutableArray() friendArr.addObject(fromUser) toUser["friends"] = friendArr } toUser.save() */ } else if (response == "rejected") { requestObject["status"] = "rejected" requestObject.save() } else { requestObject["status"] = "blocked" requestObject.save() } print("toUser is \(toUser.username!)") print("fromUser is \(fromUser.username!)") dispatch_async(dispatch_get_main_queue()) { if (response == "approved") { let alert = UIAlertView(title: "Accept", message: "You have accepted this request", delegate: nil, cancelButtonTitle: "OK") alert.show() } else if (response == "rejected") { let alert = UIAlertView(title: "Reject", message: "You have rejected this request", delegate: nil, cancelButtonTitle: "OK") alert.show() } else { let alert = UIAlertView(title: "Blocked", message: "You have blocked this user", delegate: nil, cancelButtonTitle: "OK") alert.show() } NSNotificationCenter.defaultCenter().postNotificationName("updateRequestTable", object: nil, userInfo: info) } } } func showImg(username: NSString) { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { var storedError : NSError! let downloadGroup = dispatch_group_create() dispatch_group_enter(downloadGroup) let userQuery = PFUser.query() userQuery?.whereKey("username", equalTo: username) var userArr = userQuery?.findObjects() as! [PFUser] let user = userArr[0] var profImg : UIImage if let userImageFile = user.objectForKey("photo") as? PFFile { let imageData = userImageFile.getData() as NSData! profImg = UIImage(data:imageData!)! } else { profImg = UIImage(named: "[email protected]")! } self.profilePicture.image = profImg self.profilePicture.contentMode = .ScaleAspectFill dispatch_group_leave(downloadGroup) dispatch_group_wait(downloadGroup, 5000) } } @IBAction func acceptButtonTouched(sender: UIButton) { reactToRequest("approved") } @IBAction func RejectButtonTouched(sender: UIButton) { reactToRequest("rejected") } @IBAction func BlockButtonTouched(sender: UIButton) { reactToRequest("blocked") } @IBAction func profilePictureTouched(sender: UIButton) { print(profilePicture.tag) var info = [String : Int]() info["index"] = profilePicture.tag NSNotificationCenter.defaultCenter().postNotificationName("showUserProfile", object: nil, userInfo: info) } }
mit
7e4dac43e2a6a8949d5422dd5a8007b4
29
128
0.686775
3.838665
false
false
false
false
everald/JetPack
Sources/Core/Functional.swift
2
7362
import ObjectiveC @inline(__always) public func asObject(_ value: Any) -> AnyObject? { return isObject(value) ? value as AnyObject : nil } private func class_getInstanceMethodIgnoringSupertypes(_ clazz: AnyClass, _ name: Selector) -> Method? { let method = class_getInstanceMethod(clazz, name) if let superclass = class_getSuperclass(clazz) { let superclassMethod = class_getInstanceMethod(superclass, name) guard superclassMethod != method else { return nil } } return method! } internal func copyMethod(selector: Selector, from fromType: AnyClass, to toType: AnyClass) { precondition(fromType != toType) guard let fromMethod = class_getInstanceMethodIgnoringSupertypes(fromType, selector) else { log("Selector '\(selector)' was not moved from '\(fromType)' to '\(toType)' since it's not present in the former.") return } let toMethod = class_getInstanceMethodIgnoringSupertypes(toType, selector) guard toMethod == nil else { log("Selector '\(selector)' was not moved from '\(fromType)' to '\(toType)' since it's already present in the latter.") return } guard let typePointer = method_getTypeEncoding(fromMethod) else { log("Selector '\(selector)' was not moved from '\(fromType)' to '\(toType)' since it's type encoding could not be accessed.") return } let implementation = method_getImplementation(fromMethod) guard class_addMethod(toType, selector, implementation, typePointer) else { log("Selector '\(selector)' was not moved from '\(fromType)' to '\(toType)' since `class_addMethod` vetoed.") return } } internal func copyMethod(in type: AnyClass, includingSupertypes: Bool = false, from fromSelector: Selector, to toSelector: Selector) { precondition(fromSelector != toSelector) guard let fromMethod = (includingSupertypes ? class_getInstanceMethod : class_getInstanceMethodIgnoringSupertypes)(type, fromSelector) else { log("Selector '\(fromSelector)' was not copied to '\(toSelector)' since the former not present in '\(type)'.") return } let toMethod = class_getInstanceMethodIgnoringSupertypes(type, toSelector) guard toMethod == nil else { log("Selector '\(fromSelector)' was not copied to '\(toSelector)' since the latter is already present in '\(type)'.") return } guard let typePointer = method_getTypeEncoding(fromMethod) else { log("Selector '\(fromSelector)' was not copied to '\(toSelector)' in '\(type)' since it's type encoding could not be accessed.") return } let implementation = method_getImplementation(fromMethod) guard class_addMethod(type, toSelector, implementation, typePointer) else { log("Selector '\(fromMethod)' was not copied to '\(toSelector)' in '\(type)' since `class_addMethod` vetoed.") return } } public func identity<Value>(_ value: Value) -> Value { return value } @inline(__always) public func isObject(_ value: Any) -> Bool { return type(of: value) is AnyClass } public func lazyPlaceholder<Value>(file: StaticString = #file, line: UInt = #line) -> Value { fatalError("Lazy variable accessed before being initialized.", file: file, line: line) } public func not<Parameter>(_ closure: @escaping (Parameter) -> Bool) -> (Parameter) -> Bool { return { !closure($0) } } public func not<Parameter>(_ closure: @escaping (Parameter) throws -> Bool) -> (Parameter) throws -> Bool { return { try !closure($0) } } public func obfuscatedSelector(_ parts: String...) -> Selector { return Selector(parts.joined(separator: "")) } public func optionalMax<Element: Comparable>(_ elements: Element? ...) -> Element? { var maximumElement: Element? for element in elements { if let element = element { if let existingMaximumElement = maximumElement { if element > existingMaximumElement { maximumElement = element } } else { maximumElement = element } } } return maximumElement } public func optionalMin<Element: Comparable>(_ elements: Element? ...) -> Element? { var minimumElement: Element? for element in elements { if let element = element { if let existingMinimumElement = minimumElement { if element < existingMinimumElement { minimumElement = element } } else { minimumElement = element } } } return minimumElement } public func pointer(of object: AnyObject) -> UnsafeMutableRawPointer { return Unmanaged<AnyObject>.passUnretained(object).toOpaque() } public func redirectMethod(in type: AnyClass, from fromSelector: Selector, to toSelector: Selector, in toType: AnyClass? = nil) { let actualToType: AnyClass = toType ?? type precondition(fromSelector != toSelector || type != actualToType) guard let fromMethod = class_getInstanceMethodIgnoringSupertypes(type, fromSelector) else { log("Selector '\(fromSelector)' was not redirected to selector '\(toSelector)' since the former is not present in '\(type)'.") return } guard let toMethod = class_getInstanceMethod(actualToType, toSelector) else { log("Selector '\(fromSelector)' was not redirected to selector '\(toSelector)' since the latter is not present in '\(actualToType)'.") return } let fromMethodTypePointer = method_getTypeEncoding(fromMethod) let toMethodTypePointer = method_getTypeEncoding(toMethod) guard fromMethodTypePointer != nil && toMethodTypePointer != nil, let fromMethodType = String(validatingUTF8: fromMethodTypePointer!), let toMethodType = String(validatingUTF8: toMethodTypePointer!) else { log("Selector '\(fromSelector)' was not redirected to selector '\(toSelector)' since their type encodings could not be accessed.") return } guard fromMethodType == toMethodType else { log("Selector '\(fromSelector)' was not redirected to selector '\(toSelector)' since their type encodings don't match: '\(fromMethodType)' -> '\(toMethodType)'.") return } method_setImplementation(fromMethod, method_getImplementation(toMethod)) } public func swizzleMethod(in type: AnyClass, from fromSelector: Selector, to toSelector: Selector) { precondition(fromSelector != toSelector) guard let fromMethod = class_getInstanceMethodIgnoringSupertypes(type, fromSelector) else { log("Selector '\(fromSelector)' was not swizzled with selector '\(toSelector)' since the former is not present in '\(type)'.") return } guard let toMethod = class_getInstanceMethodIgnoringSupertypes(type, toSelector) else { log("Selector '\(fromSelector)' was not swizzled with selector '\(toSelector)' since the latter is not present in '\(type)'.") return } let fromTypePointer = method_getTypeEncoding(fromMethod) let toTypePointer = method_getTypeEncoding(toMethod) guard fromTypePointer != nil && toTypePointer != nil, let fromType = String(validatingUTF8: fromTypePointer!), let toType = String(validatingUTF8: toTypePointer!) else { log("Selector '\(fromSelector)' was not swizzled with selector '\(toSelector)' since their type encodings could not be accessed.") return } guard fromType == toType else { log("Selector '\(fromSelector)' was not swizzled with selector '\(toSelector)' since their type encodings don't match: '\(fromType)' -> '\(toType)'.") return } method_exchangeImplementations(fromMethod, toMethod) } public func synchronized<ReturnType>(_ object: AnyObject, closure: () throws -> ReturnType) rethrows -> ReturnType { objc_sync_enter(object) defer { objc_sync_exit(object) } return try closure() }
mit
67d5cef482dd095ad5df99d73cc9d818
32.616438
206
0.732274
4.02515
false
false
false
false
XeresRazor/SwiftRaytracer
src/pathtracer/Sphere.swift
1
1935
// // Sphere.swift // Raytracer // // Created by David Green on 4/6/16. // Copyright © 2016 David Green. All rights reserved. // import simd func sphereUV(point: double4) -> (u: Double, v: Double) { let phi = atan2(point.z, point.x) let theta = asin(point.y) let u = 1.0 - (phi + M_PI) / (2 * M_PI) let v = (theta + M_PI / 2.0) / M_PI return (u, v) } public class Sphere: Traceable { public var center: double4 public var radius: Double private var material: Material public override init() { center = double4() radius = 0 material = LambertianMaterial(albedo: ConstantTexture(color: double4(0.5, 0.5, 0.5, 0))) } public init(center c: double4, radius r: Double, material m: Material) { center = c radius = r material = m } public override func trace(r: Ray, minimumT tMin: Double, maximumT tMax: Double) -> HitRecord? { var rec = HitRecord() rec.material = material let oc = r.origin - center let a = dot(r.direction, r.direction) let b = dot(oc, r.direction) let c = dot(oc, oc) - radius * radius let discriminant = b * b - a * c if discriminant > 0 { var temp = (-b - sqrt(b * b - a * c)) / a if temp < tMax && temp > tMin { rec.time = temp rec.point = r.pointAtDistance(t: rec.time) rec.normal = normalize(rec.point - center) let uv = sphereUV(point: normalize(rec.point - center)) rec.u = uv.u rec.v = uv.v return rec } temp = (-b + sqrt(b * b - a * c)) / a if temp < tMax && temp > tMin { rec.time = temp rec.point = r.pointAtDistance(t: rec.time) rec.normal = normalize(rec.point - center) let uv = sphereUV(point: normalize(rec.point - center)) rec.u = uv.u rec.v = uv.v return rec } } return nil } public override func boundingBox(t0: Double, t1: Double) -> AABB? { return AABB(min: center - double4(radius, radius, radius, 0), max: center + double4(radius, radius, radius, 0)) } }
mit
6a859c73a402a8e1ede1ea7bc8860d2e
25.493151
113
0.620993
2.782734
false
false
false
false
wenluma/swift
test/SILGen/objc_blocks_bridging.swift
8
11431
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -verify -emit-silgen -I %S/Inputs -disable-objc-attr-requires-foundation-module %s | %FileCheck %s // REQUIRES: objc_interop import Foundation @objc class Foo { // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3fooS3ic_Si1xtFTo : // CHECK: bb0([[ARG1:%.*]] : $@convention(block) (Int) -> Int, {{.*}}, [[SELF:%.*]] : $Foo): // CHECK: [[ARG1_COPY:%.*]] = copy_block [[ARG1]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @_T0S2iIyByd_S2iIxyd_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[ARG1_COPY]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @callee_owned (Int) -> Int, Int, @guaranteed Foo) -> Int // CHECK: apply [[NATIVE]]([[BRIDGED]], {{.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: } // end sil function '_T020objc_blocks_bridging3FooC3fooS3ic_Si1xtFTo' dynamic func foo(_ f: (Int) -> Int, x: Int) -> Int { return f(x) } // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3barS3Sc_SS1xtFTo : $@convention(objc_method) (@convention(block) (NSString) -> @autoreleased NSString, NSString, Foo) -> @autoreleased NSString { // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (NSString) -> @autoreleased NSString, [[NSSTRING:%.*]] : $NSString, [[SELF:%.*]] : $Foo): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[NSSTRING]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @_T0So8NSStringCABIyBya_S2SIxxo_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[BLOCK_COPY]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @callee_owned (@owned String) -> @owned String, @owned String, @guaranteed Foo) -> @owned String // CHECK: apply [[NATIVE]]([[BRIDGED]], {{%.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: } // end sil function '_T020objc_blocks_bridging3FooC3barS3Sc_SS1xtFTo' dynamic func bar(_ f: (String) -> String, x: String) -> String { return f(x) } // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC3basSSSgA2Ec_AE1xtFTo : $@convention(objc_method) (@convention(block) (Optional<NSString>) -> @autoreleased Optional<NSString>, Optional<NSString>, Foo) -> @autoreleased Optional<NSString> { // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (Optional<NSString>) -> @autoreleased Optional<NSString>, [[OPT_STRING:%.*]] : $Optional<NSString>, [[SELF:%.*]] : $Foo): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[OPT_STRING]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK:%.*]] = function_ref @_T0So8NSStringCSgACIyBya_SSSgADIxxo_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [[THUNK]]([[BLOCK_COPY]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned @callee_owned (@owned Optional<String>) -> @owned Optional<String>, @owned Optional<String>, @guaranteed Foo) -> @owned Optional<String> // CHECK: apply [[NATIVE]]([[BRIDGED]], {{%.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] dynamic func bas(_ f: (String?) -> String?, x: String?) -> String? { return f(x) } // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC16cFunctionPointer{{[_0-9a-zA-Z]*}}FTo // CHECK: bb0([[F:%.*]] : $@convention(c) (Int) -> Int, [[X:%.*]] : $Int, [[SELF:%.*]] : $Foo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC16cFunctionPointer{{[_0-9a-zA-Z]*}}F // CHECK: apply [[NATIVE]]([[F]], [[X]], [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] dynamic func cFunctionPointer(_ fp: @convention(c) (Int) -> Int, x: Int) -> Int { _ = fp(x) } // Blocks and C function pointers must not be reabstracted when placed in optionals. // CHECK-LABEL: sil hidden [thunk] @_T020objc_blocks_bridging3FooC7optFunc{{[_0-9a-zA-Z]*}}FTo // CHECK: bb0([[ARG0:%.*]] : $Optional<@convention(block) (NSString) -> @autoreleased NSString>, // CHECK: [[COPY:%.*]] = copy_block [[ARG0]] // CHECK: switch_enum [[COPY]] : $Optional<@convention(block) (NSString) -> @autoreleased NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]([[BLOCK:%.*]] : $@convention(block) (NSString) -> @autoreleased NSString): // TODO: redundant reabstractions here // CHECK: [[BLOCK_THUNK:%.*]] = function_ref @_T0So8NSStringCABIyBya_S2SIxxo_TR // CHECK: [[BRIDGED:%.*]] = partial_apply [[BLOCK_THUNK]]([[BLOCK]]) // CHECK: enum $Optional<@callee_owned (@owned String) -> @owned String>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = function_ref @_T020objc_blocks_bridging3FooC7optFunc{{[_0-9a-zA-Z]*}}F : $@convention(method) (@owned Optional<@callee_owned (@owned String) -> @owned String>, @owned String, @guaranteed Foo) -> @owned Optional<String> // CHECK: apply [[NATIVE]] dynamic func optFunc(_ f: ((String) -> String)?, x: String) -> String? { return f?(x) } // CHECK-LABEL: sil hidden @_T020objc_blocks_bridging3FooC19optCFunctionPointer{{[_0-9a-zA-Z]*}}F // CHECK: [[FP_BUF:%.*]] = unchecked_enum_data %0 dynamic func optCFunctionPointer(_ fp: (@convention(c) (String) -> String)?, x: String) -> String? { return fp?(x) } } // => SEMANTIC SIL TODO: This test needs to be filled out more for ownership // // CHECK-LABEL: sil hidden @_T020objc_blocks_bridging10callBlocks{{[_0-9a-zA-Z]*}}F func callBlocks(_ x: Foo, f: @escaping (Int) -> Int, g: @escaping (String) -> String, h: @escaping (String?) -> String? ) -> (Int, String, String?, String?) { // CHECK: bb0([[ARG0:%.*]] : $Foo, [[ARG1:%.*]] : $@callee_owned (Int) -> Int, [[ARG2:%.*]] : $@callee_owned (@owned String) -> @owned String, [[ARG3:%.*]] : $@callee_owned (@owned Optional<String>) -> @owned Optional<String>): // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[FOO:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.foo!1.foreign // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[F_BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[F_BLOCK_CAPTURE:%.*]] = project_block_storage [[F_BLOCK_STORAGE]] // CHECK: store [[CLOSURE_COPY]] to [init] [[F_BLOCK_CAPTURE]] // CHECK: [[F_BLOCK_INVOKE:%.*]] = function_ref @_T0S2iIxyd_S2iIyByd_TR // CHECK: [[F_STACK_BLOCK:%.*]] = init_block_storage_header [[F_BLOCK_STORAGE]] : {{.*}}, invoke [[F_BLOCK_INVOKE]] // CHECK: [[F_BLOCK:%.*]] = copy_block [[F_STACK_BLOCK]] // CHECK: apply [[FOO]]([[F_BLOCK]] // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[BAR:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.bar!1.foreign // CHECK: [[G_BLOCK_INVOKE:%.*]] = function_ref @_T0S2SIxxo_So8NSStringCABIyBya_TR // CHECK: [[G_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[G_BLOCK_INVOKE]] // CHECK: [[G_BLOCK:%.*]] = copy_block [[G_STACK_BLOCK]] // CHECK: apply [[BAR]]([[G_BLOCK]] // CHECK: [[BORROWED_ARG0:%.*]] = begin_borrow [[ARG0]] // CHECK: [[BAS:%.*]] = class_method [volatile] [[BORROWED_ARG0]] : $Foo, #Foo.bas!1.foreign // CHECK: [[H_BLOCK_INVOKE:%.*]] = function_ref @_T0SSSgAAIxxo_So8NSStringCSgADIyBya_TR // CHECK: [[H_STACK_BLOCK:%.*]] = init_block_storage_header {{.*}}, invoke [[H_BLOCK_INVOKE]] // CHECK: [[H_BLOCK:%.*]] = copy_block [[H_STACK_BLOCK]] // CHECK: apply [[BAS]]([[H_BLOCK]] // CHECK: [[G_BLOCK:%.*]] = copy_block {{%.*}} : $@convention(block) (NSString) -> @autoreleased NSString // CHECK: enum $Optional<@convention(block) (NSString) -> @autoreleased NSString>, #Optional.some!enumelt.1, [[G_BLOCK]] return (x.foo(f, x: 0), x.bar(g, x: "one"), x.bas(h, x: "two"), x.optFunc(g, x: "three")) } class Test: NSObject { func blockTakesBlock() -> ((Int) -> Int) -> Int {} } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0S2iIxyd_SiIxxd_S2iIyByd_SiIyByd_TR // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[ORIG_BLOCK:%.*]] : // CHECK: [[CLOSURE:%.*]] = partial_apply {{%.*}}([[BLOCK_COPY]]) // CHECK: [[RESULT:%.*]] = apply {{%.*}}([[CLOSURE]]) // CHECK: return [[RESULT]] func clearDraggingItemImageComponentsProvider(_ x: NSDraggingItem) { x.imageComponentsProvider = {} } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0SayypGIxo_So7NSArrayCSgIyBa_TR // CHECK: [[CONVERT:%.*]] = function_ref @_T0Sa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF // CHECK: [[CONVERTED:%.*]] = apply [[CONVERT]] // CHECK: [[OPTIONAL:%.*]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[CONVERTED]] // CHECK: return [[OPTIONAL]] // CHECK-LABEL: sil hidden @{{.*}}bridgeNonnullBlockResult{{.*}} // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0SSIxo_So8NSStringCSgIyBa_TR // CHECK: [[CONVERT:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BRIDGED:%.*]] = apply [[CONVERT]] // CHECK: [[OPTIONAL_BRIDGED:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: return [[OPTIONAL_BRIDGED]] func bridgeNonnullBlockResult() { nonnullStringBlockResult { return "test" } } // CHECK-LABEL: sil hidden @{{.*}}bridgeNoescapeBlock{{.*}} func bridgeNoescapeBlock() { // CHECK: function_ref @_T0Ix_IyB_TR noescapeBlockAlias { } // CHECK: function_ref @_T0Ix_IyB_TR noescapeNonnullBlockAlias { } } class ObjCClass : NSObject {} extension ObjCClass { func someDynamicMethod(closure: (() -> ()) -> ()) {} } struct GenericStruct<T> { let closure: (() -> ()) -> () func doStuff(o: ObjCClass) { o.someDynamicMethod(closure: closure) } } // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0Ix_Ixx_IyB_IyBy_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@owned @callee_owned () -> ()) -> (), @convention(block) () -> ()) -> () // CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0IyB_Ix_TR : $@convention(thin) (@owned @convention(block) () -> ()) -> ()
mit
08d40ba5140b541b27369b1380bf08c9
60.789189
271
0.603097
3.363048
false
false
false
false
Maaimusic/BTree
Sources/BTreeMerger.swift
1
34100
// // BTreeMerger.swift // BTree // // Created by Károly Lőrentey on 2016-02-27. // Copyright © 2016–2017 Károly Lőrentey. // /// The matching strategy to use when comparing elements from two trees with duplicate keys. public enum BTreeMatchingStrategy { /// Use a matching strategy appropriate for a set. I.e., match partition classes over key equality rather than individual keys. /// /// This strategy ignores the multiplicity of keys, and only consider whether a key is included in the two trees at all. /// E.g., a single element from one tree will be considered a match for any positive number of elements with the same key in /// the other tree. case groupingMatches /// Use a matching strategy appropriate for a multiset. I.e., try to establish a one-to-one correspondence between /// elements from the two trees with equal keys. /// /// This strategy keeps track of the multiplicity of each key, and matches every element from one tree with /// at most a single element with an equal key from the other tree. If a key has different multiplicities in /// the two trees, duplicate elements above the lesser multiplicity will not be considered matching. case countingMatches } extension BTree { //MARK: Merging and set operations /// Merge elements from two trees into a new tree, and return it. /// /// - Parameter other: Any tree with the same order as `self`. /// /// - Parameter strategy: /// When `.groupingMatches`, elements in `self` whose keys also appear in `other` are not included in the result. /// If neither input tree had duplicate keys on its own, the result won't have any duplicates, either. /// /// When `.countingMatches`, all elements in both trees are kept in the result, including ones with duplicate keys. /// The result may have duplicate keys, even if the input trees only had unique-keyed elements. /// /// - Returns: A tree with elements from `self` with matching keys in `other` removed. /// /// - Note: /// The elements of the two input trees may interleave and overlap in any combination. /// However, if there are long runs of non-interleaved elements, parts of the input trees will be entirely /// skipped instead of elementwise processing. This may drastically improve performance. /// /// When `strategy == .groupingMatches`, this function also detects shared subtrees between the two trees, /// and links them directly into the result when possible. (Otherwise matching keys are individually processed.) /// /// - Requires: `self.order == other.order` /// /// - Complexity: /// - O(min(`self.count`, `other.count`)) in general. /// - O(log(`self.count` + `other.count`)) if there are only a constant amount of interleaving element runs. @inlinable public func union(_ other: BTree, by strategy: BTreeMatchingStrategy) -> BTree { var m = BTreeMerger(first: self, second: other) switch strategy { case .groupingMatches: while !m.done { m.copyFromFirst(.excludingOtherKey) m.copyFromSecond(.excludingOtherKey) m.copyCommonElementsFromSecond() } case .countingMatches: while !m.done { m.copyFromFirst(.includingOtherKey) m.copyFromSecond(.excludingOtherKey) } } m.appendFirst() m.appendSecond() return m.finish() } /// Return a tree with the same elements as `self` except those with matching keys in `other`. /// /// - Parameter other: Any tree with the same order as `self`. /// /// - Parameter strategy: /// When `.groupingMatches`, all elements in `self` that have a matching key in `other` are removed. /// /// When `.countingMatches`, for each key in `self`, only as many matching elements are removed as the key's multiplicity in `other`. /// /// - Returns: A tree with elements from `self` with matching keys in `other` removed. /// /// - Note: /// The elements of the two input trees may interleave and overlap in any combination. /// However, if there are long runs of non-interleaved elements, parts of the input trees will be entirely /// skipped or linked into the result instead of elementwise processing. This may drastically improve performance. /// /// This function also detects and skips over shared subtrees between the two trees. /// (Keys that appear in both trees otherwise require individual processing.) /// /// - Requires: `self.order == other.order` /// /// - Complexity: /// - O(min(`self.count`, `tree.count`)) in general. /// - O(log(`self.count` + `tree.count`)) if there are only a constant amount of interleaving element runs. @inlinable public func subtracting(_ other: BTree, by strategy: BTreeMatchingStrategy) -> BTree { var m = BTreeMerger(first: self, second: other) while !m.done { m.copyFromFirst(.excludingOtherKey) m.skipFromSecond(.excludingOtherKey) switch strategy { case .groupingMatches: m.skipCommonElements() case .countingMatches: m.skipMatchingNumberOfCommonElements() } } m.appendFirst() return m.finish() } /// Return a tree combining the elements of `self` and `other` except those whose keys can be matched in both trees. /// /// - Parameter other: Any tree with the same order as `self`. /// /// - Parameter strategy: /// When `.groupingMatches`, all elements in both trees are removed whose key appears in both /// trees, regardless of their multiplicities. /// /// When `.countingMatches`, for each key, only as many matching elements are removed as the minimum of the /// key's multiplicities in the two trees, leaving "extra" occurences from the "longer" tree in the result. /// /// - Returns: A tree combining elements of `self` and `other` except those whose keys can be matched in both trees. /// /// - Note: /// The elements of the two input trees may interleave and overlap in any combination. /// However, if there are long runs of non-interleaved elements, parts of the input trees will be entirely /// linked into the result instead of elementwise processing. This may drastically improve performance. /// /// This function also detects and skips over shared subtrees between the two trees. /// (Keys that appear in both trees otherwise require individual processing.) /// /// - Requires: `self.order == other.order` /// /// - Complexity: /// - O(min(`self.count`, `other.count`)) in general. /// - O(log(`self.count` + `other.count`)) if there are only a constant amount of interleaving element runs. @inlinable public func symmetricDifference(_ other: BTree, by strategy: BTreeMatchingStrategy) -> BTree { var m = BTreeMerger(first: self, second: other) while !m.done { m.copyFromFirst(.excludingOtherKey) m.copyFromSecond(.excludingOtherKey) switch strategy { case .groupingMatches: m.skipCommonElements() case .countingMatches: m.skipMatchingNumberOfCommonElements() } } m.appendFirst() m.appendSecond() return m.finish() } /// Return a tree with those elements of `other` whose keys are also included in `self`. /// /// - Parameter other: Any tree with the same order as `self`. /// /// - Parameter strategy: /// When `.groupingMatches`, all elements in `other` are included that have matching keys /// in `self`, regardless of multiplicities. /// /// When `.countingMatches`, for each key, only as many matching elements from `other` are kept as /// the minimum of the key's multiplicities in the two trees. /// /// - Returns: A tree combining elements of `self` and `other` except those whose keys can be matched in both trees. /// /// - Note: /// The elements of the two input trees may interleave and overlap in any combination. /// However, if there are long runs of non-interleaved elements, parts of the input trees will be entirely /// skipped instead of elementwise processing. This may drastically improve performance. /// /// This function also detects shared subtrees between the two trees, /// and links them directly into the result when possible. /// (Keys that appear in both trees otherwise require individual processing.) /// /// - Requires: `self.order == other.order` /// /// - Complexity: /// - O(min(`self.count`, `other.count`)) in general. /// - O(log(`self.count` + `other.count`)) if there are only a constant amount of interleaving element runs. @inlinable public func intersection(_ other: BTree, by strategy: BTreeMatchingStrategy) -> BTree { var m = BTreeMerger(first: self, second: other) while !m.done { m.skipFromFirst(.excludingOtherKey) m.skipFromSecond(.excludingOtherKey) switch strategy { case .groupingMatches: m.copyCommonElementsFromSecond() case .countingMatches: m.copyMatchingNumberOfCommonElementsFromSecond() } } return m.finish() } /// Return a tree that contains all elements in `self` whose key is not in the supplied sorted sequence. /// /// - Note: /// The keys of `self` may interleave and overlap with `sortedKeys` in any combination. /// However, if there are long runs of non-interleaved keys, parts of `self` will be entirely /// skipped instead of elementwise processing. This may drastically improve performance. /// /// - Requires: `sortedKeys` is sorted in ascending order. /// - Complexity: O(*n* + `self.count`), where *n* is the number of keys in `sortedKeys`. @inlinable public func subtracting<S: Sequence>(sortedKeys: S, by strategy: BTreeMatchingStrategy) -> BTree where S.Element == Key { if self.isEmpty { return self } var b = BTreeBuilder<Key, Value>(order: self.order) var lastKey: Key? = nil var path = BTreeStrongPath(startOf: self.root) outer: for key in sortedKeys { precondition(lastKey == nil || lastKey! <= key) lastKey = key while path.key < key { b.append(path.nextPart(until: .excluding(key))) if path.isAtEnd { break outer } } switch strategy { case .groupingMatches: while path.key == key { path.nextPart(until: .including(key)) if path.isAtEnd { break outer } } case .countingMatches: if path.key == key { path.moveForward() if path.isAtEnd { break outer } } } } if !path.isAtEnd { b.append(path.element) b.appendWithoutCloning(path.suffix().root) } return BTree(b.finish()) } /// Return a tree that contains all elements in `self` whose key is in the supplied sorted sequence. /// /// - Note: /// The keys of `self` may interleave and overlap with `sortedKeys` in any combination. /// However, if there are long runs of non-interleaved keys, parts of `self` will be entirely /// skipped instead of elementwise processing. This may drastically improve performance. /// /// - Requires: `sortedKeys` is sorted in ascending order. /// - Complexity: O(*n* + `self.count`), where *n* is the number of keys in `sortedKeys`. @inlinable public func intersection<S: Sequence>(sortedKeys: S, by strategy: BTreeMatchingStrategy) -> BTree where S.Element == Key { if self.isEmpty { return self } var b = BTreeBuilder<Key, Value>(order: self.order) var lastKey: Key? = nil var path = BTreeStrongPath(startOf: self.root) outer: for key in sortedKeys { precondition(lastKey == nil || lastKey! <= key) lastKey = key while path.key < key { path.nextPart(until: .excluding(key)) if path.isAtEnd { break outer } } switch strategy { case .groupingMatches: while path.key == key { b.append(path.nextPart(until: .including(key))) if path.isAtEnd { break outer } } case .countingMatches: if path.key == key { b.append(path.element) path.moveForward() if path.isAtEnd { break outer } } } } return BTree(b.finish()) } } enum BTreeLimit<Key: Comparable> { case including(Key) case excluding(Key) func match(_ key: Key) -> Bool { switch self { case .including(let limit): return key <= limit case .excluding(let limit): return key < limit } } } enum BTreeRelativeLimit { case includingOtherKey case excludingOtherKey func with<Key: Comparable>(_ key: Key) -> BTreeLimit<Key> { switch self { case .includingOtherKey: return .including(key) case .excludingOtherKey: return .excluding(key) } } } /// An abstraction for elementwise/subtreewise merging some of the elements from two trees into a new third tree. /// /// Merging starts at the beginning of each tree, then proceeds in order from smaller to larger keys. /// At each step you can decide which tree to merge elements/subtrees from next, until we reach the end of /// one of the trees. @usableFromInline internal struct BTreeMerger<Key: Comparable, Value> { @usableFromInline typealias Limit = BTreeLimit<Key> @usableFromInline typealias Node = BTreeNode<Key, Value> private var a: BTreeStrongPath<Key, Value> private var b: BTreeStrongPath<Key, Value> private var builder: BTreeBuilder<Key, Value> /// This flag is set to `true` when we've reached the end of one of the trees. /// When this flag is set, you may further skips and copies will do nothing. /// You may call `appendFirst` and/or `appendSecond` to append the remaining parts /// of whichever tree has elements left, or you may call `finish` to stop merging. @usableFromInline internal var done: Bool /// Construct a new merger starting at the starts of the specified two trees. @usableFromInline init(first: BTree<Key, Value>, second: BTree<Key, Value>) { precondition(first.order == second.order) self.a = BTreeStrongPath(startOf: first.root) self.b = BTreeStrongPath(startOf: second.root) self.builder = BTreeBuilder(order: first.order, keysPerNode: first.root.maxKeys) self.done = first.isEmpty || second.isEmpty } /// Stop merging and return the merged result. @usableFromInline mutating func finish() -> BTree<Key, Value> { return BTree(builder.finish()) } /// Append the rest of the first tree to the end of the result tree, jump to the end of the first tree, and /// set `done` to true. /// /// You may call this method even when `done` has been set to true by an earlier operation. It does nothing /// if the merger has already reached the end of the first tree. /// /// - Complexity: O(log(first.count)) @usableFromInline mutating func appendFirst() { if !a.isAtEnd { builder.append(a.element) builder.append(a.suffix().root) a.moveToEnd() done = true } } /// Append the rest of the second tree to the end of the result tree, jump to the end of the second tree, and /// set `done` to true. /// /// You may call this method even when `done` has been set to true by an earlier operation. It does nothing /// if the merger has already reached the end of the second tree. /// /// - Complexity: O(log(first.count)) @usableFromInline mutating func appendSecond() { if !b.isAtEnd { builder.append(b.element) builder.append(b.suffix().root) b.moveToEnd() done = true } } /// Copy elements from the first tree (starting at the current position) that are less than (or, when `limit` /// is `.includingOtherKey`, less than or equal to) the key in the second tree at its the current position. /// /// This method will link entire subtrees to the result whenever possible, which can considerably speed up the operation. /// /// This method does nothing if `done` has been set to `true` by an earlier operation. It sets `done` to true /// if it reaches the end of the first tree. /// /// - Complexity: O(*n*) where *n* is the number of elements copied. @usableFromInline mutating func copyFromFirst(_ limit: BTreeRelativeLimit) { if !b.isAtEnd { copyFromFirst(limit.with(b.key)) } } @usableFromInline mutating func copyFromFirst(_ limit: Limit) { while !a.isAtEnd && limit.match(a.key) { builder.append(a.nextPart(until: limit)) } if a.isAtEnd { done = true } } /// Copy elements from the second tree (starting at the current position) that are less than (or, when `limit` /// is `.includingOtherKey`, less than or equal to) the key in the first tree at its the current position. /// /// This method will link entire subtrees to the result whenever possible, which can considerably speed up the operation. /// /// This method does nothing if `done` has been set to `true` by an earlier operation. It sets `done` to true /// if it reaches the end of the second tree. /// /// - Complexity: O(*n*) where *n* is the number of elements copied. @usableFromInline mutating func copyFromSecond(_ limit: BTreeRelativeLimit) { if !a.isAtEnd { copyFromSecond(limit.with(a.key)) } } @usableFromInline mutating func copyFromSecond(_ limit: Limit) { while !b.isAtEnd && limit.match(b.key) { builder.append(b.nextPart(until: limit)) } if b.isAtEnd { done = true } } /// Skip elements from the first tree (starting at the current position) that are less than (or, when `limit` /// is `.includingOtherKey`, less than or equal to) the key in the second tree at its the current position. /// /// This method will jump over entire subtrees to the result whenever possible, which can considerably speed up the operation. /// /// This method does nothing if `done` has been set to `true` by an earlier operation. It sets `done` to true /// if it reaches the end of the first tree. /// /// - Complexity: O(*n*) where *n* is the number of elements skipped. @usableFromInline mutating func skipFromFirst(_ limit: BTreeRelativeLimit) { if !b.isAtEnd { skipFromFirst(limit.with(b.key)) } } @usableFromInline mutating func skipFromFirst(_ limit: Limit) { while !a.isAtEnd && limit.match(a.key) { a.nextPart(until: limit) } if a.isAtEnd { done = true } } /// Skip elements from the second tree (starting at the current position) that are less than (or, when `limit` /// is `.includingOtherKey`, less than or equal to) the key in the first tree at its the current position. /// /// This method will jump over entire subtrees to the result whenever possible, which can considerably speed up the operation. /// /// This method does nothing if `done` has been set to `true` by an earlier operation. It sets `done` to true /// if it reaches the end of the second tree. /// /// - Complexity: O(*n*) where *n* is the number of elements skipped. @usableFromInline mutating func skipFromSecond(_ limit: BTreeRelativeLimit) { if !a.isAtEnd { skipFromSecond(limit.with(a.key)) } } @usableFromInline mutating func skipFromSecond(_ limit: Limit) { while !b.isAtEnd && limit.match(b.key) { b.nextPart(until: limit) } if b.isAtEnd { done = true } } /// Take the longest possible sequence of elements that share the same key in both trees; ignore elements from /// the first tree, but append elements from the second tree to the end of the result tree. /// /// This method does not care how many duplicate keys it finds for each key. For example, with /// `first = [0, 0, 1, 2, 2, 5, 6, 7]`, `second = [0, 1, 1, 1, 2, 2, 6, 8]`, it appends `[0, 1, 1, 1, 2, 2]` /// to the result, and leaves the first tree at `[5, 6, 7]` and the second at `[6, 8]`. /// /// This method recognizes nodes that are shared between the two trees, and links them to the result in one step. /// This can considerably speed up the operation. /// /// - Complexity: O(*n*) where *n* is the number of elements processed. @usableFromInline mutating func copyCommonElementsFromSecond() { while !done && a.key == b.key { if a.node === b.node && a.node.isLeaf && a.slot == 0 && b.slot == 0 { /// We're at the first element of a shared subtree. Find the ancestor at which the shared subtree /// starts, and append it in a single step. /// /// It might happen that a shared node begins with a key that we've already fully processed in one of the trees. /// In this case, we cannot skip elementwise processing, since the trees are at different offsets in /// the shared subtree. The slot & leaf checks above & below ensure that this isn't the case. var key: Key var common: Node repeat { key = a.node.last!.0 common = a.node a.ascendOneLevel() b.ascendOneLevel() } while !a.isAtEnd && !b.isAtEnd && a.node === b.node && a.slot == 0 && b.slot == 0 builder.append(common) if !a.isAtEnd { a.ascendToKey() skipFromFirst(.including(key)) } if !b.isAtEnd { b.ascendToKey() copyFromSecond(.including(key)) } if a.isAtEnd || b.isAtEnd { done = true } } else { // Process the next run of equal keys in both trees, skipping them in `first`, but copying them from `second`. // Note that we cannot leave matching elements in either tree, even if we reach the end of the other. let key = a.key skipFromFirst(.including(key)) copyFromSecond(.including(key)) } } } @usableFromInline mutating func copyMatchingNumberOfCommonElementsFromSecond() { while !done && a.key == b.key { if a.node === b.node && a.node.isLeaf && a.slot == 0 && b.slot == 0 { /// We're at the first element of a shared subtree. Find the ancestor at which the shared subtree /// starts, and append it in a single step. /// /// It might happen that a shared node begins with a key that we've already fully processed in one of the trees. /// In this case, we cannot skip elementwise processing, since the trees are at different offsets in /// the shared subtree. The slot & leaf checks above & below ensure that this isn't the case. var common: Node repeat { common = a.node a.ascendOneLevel() b.ascendOneLevel() } while !a.isAtEnd && !b.isAtEnd && a.node === b.node && a.slot == 0 && b.slot == 0 builder.append(common) if !a.isAtEnd { a.ascendToKey() } if !b.isAtEnd { b.ascendToKey() } if a.isAtEnd || b.isAtEnd { done = true } } else { // Copy one matching element from the second tree, then step forward. // TODO: Count the number of matching elements in a and link entire subtrees from b into the result when possible. builder.append(b.element) a.moveForward() b.moveForward() done = a.isAtEnd || b.isAtEnd } } } /// Ignore and jump over the longest possible sequence of elements that share the same key in both trees, /// starting at the current positions. /// /// This method does not care how many duplicate keys it finds for each key. For example, with /// `first = [0, 0, 1, 2, 2, 5, 6, 7]`, `second = [0, 1, 1, 1, 2, 2, 6, 8]`, it skips to /// `[5, 6, 7]` in the first tree, and `[6, 8]` in the second. /// /// This method recognizes nodes that are shared between the two trees, and jumps over them in one step. /// This can considerably speed up the operation. /// /// - Complexity: O(*n*) where *n* is the number of elements processed. @usableFromInline mutating func skipCommonElements() { while !done && a.key == b.key { if a.node === b.node { /// We're inside a shared subtree. Find the ancestor at which the shared subtree /// starts, and append it in a single step. /// /// This variant doesn't care about where we're in the shared subtree. /// It assumes that if we ignore one set of common keys, we're ignoring all. var key: Key repeat { key = a.node.last!.0 assert(a.slot == b.slot) a.ascendOneLevel() b.ascendOneLevel() if a.isAtEnd || b.isAtEnd { done = true } } while !done && a.node === b.node if !a.isAtEnd { a.ascendToKey() skipFromFirst(.including(key)) } if !b.isAtEnd { b.ascendToKey() skipFromSecond(.including(key)) } } else { // Process the next run of equal keys in both trees, skipping them in both trees. // Note that we cannot leave matching elements in either tree, even if we reach the end of the other. let key = a.key skipFromFirst(.including(key)) skipFromSecond(.including(key)) } } } @usableFromInline mutating func skipMatchingNumberOfCommonElements() { while !done && a.key == b.key { if a.node === b.node && a.node.isLeaf && a.slot == b.slot { /// We're at the first element of a shared subtree. Find the ancestor at which the shared subtree /// starts, and append it in a single step. /// /// It might happen that a shared node begins with a key that we've already fully processed in one of the trees. /// In this case, we cannot skip elementwise processing, since the trees are at different offsets in /// the shared subtree. The slot & leaf checks above & below ensure that this isn't the case. repeat { a.ascendOneLevel() b.ascendOneLevel() if a.isAtEnd || b.isAtEnd { done = true } } while !done && a.node === b.node && a.slot == b.slot if !a.isAtEnd { a.ascendToKey() } if !b.isAtEnd { b.ascendToKey() } } else { // Skip one matching element from both trees. a.moveForward() b.moveForward() done = a.isAtEnd || b.isAtEnd } } } } @usableFromInline internal enum BTreePart<Key: Comparable, Value> { case element((Key, Value)) case node(BTreeNode<Key, Value>) case nodeRange(BTreeNode<Key, Value>, CountableRange<Int>) } extension BTreePart { @usableFromInline var count: Int { switch self { case .element(_, _): return 1 case .node(let node): return node.count case .nodeRange(let parent, let range): var count = range.count if !parent.isLeaf { for i in range.lowerBound ... range.upperBound { count += parent.children[i].count } } return count } } } extension BTreeBuilder { @usableFromInline mutating func append(_ part: BTreePart<Key, Value>) { switch part { case .element(let element): self.append(element) case .node(let node): self.append(node) case .nodeRange(let node, let range): self.appendWithoutCloning(Node(node: node, slotRange: range)) } } } internal extension BTreeStrongPath { @usableFromInline typealias Limit = BTreeLimit<Key> /// The parent of `node` and the slot of `node` in its parent, or `nil` if `node` is the root node. private var parent: (Node, Int)? { guard !_path.isEmpty else { return nil } return (_path.last!, _slots.last!) } /// The key following the `node` at the same slot in its parent, or `nil` if there is no such key. private var parentKey: Key? { guard let parent = self.parent else { return nil } guard parent.1 < parent.0.elements.count else { return nil } return parent.0.elements[parent.1].0 } /// Move sideways `n` slots to the right, skipping over subtrees along the way. @usableFromInline internal mutating func skipForward(_ n: Int) { if !node.isLeaf { for i in 0 ..< n { let s = slot! + i offset += node.children[s + 1].count } } offset += n slot! += n if offset != count { ascendToKey() } } /// Remove the deepest path component, leaving the path at the element following the node that was previously focused, /// or the spot after all elements if the node was the rightmost child. @usableFromInline mutating func ascendOneLevel() { if length == 1 { offset = count slot = node.elements.count return } popFromSlots() popFromPath() } /// If this path got to a slot at the end of a node but it hasn't reached the end of the tree yet, /// ascend to the ancestor that holds the key corresponding to the current offset. @usableFromInline mutating func ascendToKey() { assert(!isAtEnd) while slot == node.elements.count { slot = nil popFromPath() } } /// Return the next part in this tree that consists of elements less than `key`. If `inclusive` is true, also /// include elements matching `key`. /// The part returned is either a single element, or a range of elements in a node, including their associated subtrees. /// /// - Requires: The current position is not at the end of the tree, and the current key is matching the condition above. /// - Complexity: O(log(*n*)) where *n* is the number of elements in the returned part. @discardableResult @usableFromInline mutating func nextPart(until limit: Limit) -> BTreePart<Key, Value> { assert(!isAtEnd && limit.match(self.key)) // Find furthest ancestor whose entire leftmost subtree is guaranteed to consist of matching elements. assert(!isAtEnd) var includeLeftmostSubtree = false if slot == 0 && node.isLeaf { while slot == 0, let pk = parentKey, limit.match(pk) { popFromSlots() popFromPath() includeLeftmostSubtree = true } } if !includeLeftmostSubtree && !node.isLeaf { defer { moveForward() } return .element(self.element) } // Find range of matching elements in `node`. assert(limit.match(self.key)) let startSlot = slot! var endSlot = startSlot + 1 while endSlot < node.elements.count && limit.match(node.elements[endSlot].0) { endSlot += 1 } // See if we can include the subtree following the last matching element. // This is a log(n) check but it's worth it. let includeRightmostSubtree = node.isLeaf || limit.match(node.children[endSlot].last!.0) if includeRightmostSubtree { defer { skipForward(endSlot - startSlot) } return .nodeRange(node, startSlot ..< endSlot) } // If the last subtree has non-matching elements, leave off `endSlot - 1` from the returned range. if endSlot == startSlot + 1 { let n = node.children[slot!] return .node(n) } defer { skipForward(endSlot - startSlot - 1) } return .nodeRange(node, startSlot ..< endSlot - 1) } }
mit
f1297f548febd75532d35573ccc16031
42.877735
142
0.591764
4.497757
false
false
false
false
debugsquad/nubecero
nubecero/Model/Session/MSession.swift
1
779
import Foundation class MSession { enum Status:Int { case unknown case active case banned } typealias UserId = String static let sharedInstance:MSession = MSession() let user:MSessionUser let settings:MSessionSettings let server:MSessionServer let version:String private let kVersionKey:String = "CFBundleVersion" private let kEmpty:String = "" private init() { user = MSessionUser() settings = MSessionSettings() server = MSessionServer() if let version:String = Bundle.main.infoDictionary?[kVersionKey] as? String { self.version = version } else { self.version = kEmpty } } }
mit
d40387366eba792a4084286c6b11ff92
20.054054
83
0.581515
5.058442
false
false
false
false
0x0c/RDImageViewerController
RDImageViewerController/Classes/Extension/UIImageView+SizeFitting.swift
1
3495
// // UIImageView+SizeFitting.swift // RDImageViewerController // // Created by Akira Matsuda on 2020/11/02. // extension UIImageView { open var rd_contentClippingRect: CGRect { guard let image = image else { return bounds } guard contentMode == .scaleAspectFit else { return bounds } guard image.size.width > 0, image.size.height > 0 else { return bounds } let scale: CGFloat if image.size.width > image.size.height { scale = bounds.width / image.size.width } else { scale = bounds.height / image.size.height } let size = CGSize(width: image.size.width * scale, height: image.size.height * scale) let x = (bounds.width - size.width) / 2.0 let y = (bounds.height - size.height) / 2.0 return CGRect(x: x, y: y, width: size.width, height: size.height) } open func rd_fitToAspect(containerSize: CGSize) { sizeToFit() let height = containerSize.height let width = containerSize.width let imageHeight = max(1, frame.height) let imageWidth = max(1, frame.width) var scale: CGFloat = 1.0 if width < height { // device portrait if image?.rd_isLandspace() ?? false { // landscape image // fit imageWidth to viewWidth scale = width / imageWidth } else { // portrait image if imageWidth / imageHeight > width / height { // fit imageWidth to viewWidth scale = width / imageWidth } else { // fit imageHeight to viewHeight scale = height / imageHeight } } } else { // device landscape if image?.rd_isLandspace() ?? false { // image landscape if imageWidth / imageHeight > width / height { // fit imageWidth to viewWidth scale = width / imageWidth } else { // fit imageHeight to viewHeight scale = height / imageHeight } } else { // image portrait // fit imageHeight to viewHeight scale = height / imageHeight } } frame = CGRect( x: 0, y: 0, width: imageWidth * scale, height: imageHeight * scale ) } open func rd_fitToDisplay(containerSize: CGSize) -> Bool { sizeToFit() let height = containerSize.height let width = containerSize.width if width < height { // portrait rd_fitToAspect(containerSize: containerSize) return false } else { var scale: CGFloat { if width > height { return width / max(1, frame.width) } return height / max(1, frame.height) } frame = CGRect( x: 0, y: 0, width: frame.width * scale, height: frame.height * scale ) if height > frame.height { center = CGPoint(x: frame.width / 2.0, y: frame.height / 2.0) } return true } } }
mit
6728ffa6f2b108083563881d8dffd7f4
29.929204
93
0.47897
5.094752
false
false
false
false
boztalay/TaskScheduler
TaskScheduler/GenericTaskTableViewCell.swift
1
3667
// // GenericTaskTableViewCell.swift // TaskScheduler // // Created by Ben Oztalay on 1/3/16. // Copyright © 2016 Ben Oztalay. All rights reserved. // import UIKit class GenericTaskTableViewCell: UITableViewCell { static let ReuseIdentifier = "GenericTaskTableViewCell" private static let NibName = GenericTaskTableViewCell.ReuseIdentifier static let Nib = UINib(nibName: GenericTaskTableViewCell.NibName, bundle: nil) @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var workLabel: UILabel! @IBOutlet weak var statusDot: UIView! @IBOutlet weak var dueByLabel: UILabel! @IBOutlet weak var priorityLabel: UILabel! private static var dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.formattingContext = .MiddleOfSentence formatter.dateStyle = .MediumStyle formatter.timeStyle = .NoStyle formatter.doesRelativeDateFormatting = true return formatter }() override func awakeFromNib() { // Make the dot into a circle self.statusDot.layer.cornerRadius = self.statusDot.frame.width / 2.0 } func setFromTask(task: Task) { self.setCommonTextLabelsFromTask(task) self.workLabel.text = "\(task.workEstimate) hour" self.pluralizeWorkLabelForWork(task.workEstimate) if task.isComplete { self.statusDot.backgroundColor = TaskSchedulerColors.TaskComplete } else if task.isDueInPast && !task.isComplete { self.statusDot.backgroundColor = TaskSchedulerColors.TaskIncomplete } else if task.isDropped { self.statusDot.backgroundColor = TaskSchedulerColors.TaskDropped } else { self.statusDot.backgroundColor = TaskSchedulerColors.TaskInProgess } } func setFromWorkSession(workSession: TaskWorkSession) { let task = workSession.parentTask self.setCommonTextLabelsFromTask(task) self.workLabel.text = "For \(workSession.amountOfWork) hour" self.pluralizeWorkLabelForWork(workSession.amountOfWork) if workSession.hasBeenCompleted { self.statusDot.backgroundColor = TaskSchedulerColors.TaskComplete } else if task.isDropped { self.statusDot.backgroundColor = TaskSchedulerColors.TaskDropped } else { self.statusDot.backgroundColor = TaskSchedulerColors.TaskInProgess } } private func setCommonTextLabelsFromTask(task: Task) { self.titleLabel.text = task.title self.dueByLabel.text = "Due " + GenericTaskTableViewCell.dateFormatter.stringFromDate(task.dueDate) self.priorityLabel.text = "\(try! PriorityPrettifier.priorityNameFromLevel(task.priority)) Priortiy" } private func pluralizeWorkLabelForWork(work: Float) { if work != 1.0 { self.workLabel.text! += "s" } } // These are here as a silly workaround for the dot's background // color being reset when the cell is selected/highlighted override func setSelected(selected: Bool, animated: Bool) { let dotColor = self.statusDot.backgroundColor super.setSelected(selected, animated: animated) if selected { self.statusDot.backgroundColor = dotColor } } override func setHighlighted(highlighted: Bool, animated: Bool) { let dotColor = self.statusDot.backgroundColor super.setHighlighted(selected, animated: animated) if selected { self.statusDot.backgroundColor = dotColor } } }
mit
3662ca4a96eb0bca55a9acc295fdff9a
34.941176
108
0.673213
4.7
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/find-smallest-letter-greater-than-target.swift
2
858
/** * https://leetcode.com/problems/find-smallest-letter-greater-than-target/ * * */ class Solution { /// /// The key part of this binary search is: /// 1. left will be the first possible valid choice. /// 2. right - left >= 1, then stop when left == right /// 3. In the case left move to all the way to the end, but right never changed, we didn't find the valid choice. /// func nextGreatestLetter(_ letters: [Character], _ target: Character) -> Character { var left = 0 var right = letters.count while left < right { let mid = left + (right - left) / 2 if letters[mid] <= target { left = mid + 1 } else { right = mid } } // print("Index: \(left)") return letters[left % letters.count] } }
mit
b85e5fc67762bfdc315d7b7876fdc5a1
30.777778
117
0.534965
4.085714
false
false
false
false
gbuela/kanjiryokucha
KanjiRyokucha/StartRequest.swift
1
2313
// // StartRequest.swift // KanjiRyokucha // // Created by German Buela on 12/9/16. // Copyright © 2016 German Buela. All rights reserved. // import Foundation extension ReviewType { var querystringParam: String { switch self { case .expired: return "due" case .new: return "new" case .failed: return "failed" } } } fileprivate let itemsKey = "items" fileprivate let syncLimitKey = "limit_sync" struct CardIdsModel: Decodable { let ids: [Int] let syncLimit: Int init(ids: [Int]) { self.ids = ids self.syncLimit = defaultSyncLimit } static func nullObject() -> CardIdsModel { return CardIdsModel(ids: []) } enum CodingKeys: String, CodingKey { case ids = "items" case syncLimit = "limit_sync" } } protocol StartRequest : KoohiiRequest {} extension StartRequest { var apiMethod: String { return "review/start" } var useEndpoint: Bool { return true } var sendApiKey: Bool { return true } var method: RequestMethod { return .get } var contentType: ContentType { return .form } } struct SRSStartRequest: StartRequest { let reviewType: ReviewType let qsParams: ParamSet typealias ModelType = CardIdsModel typealias InputType = NoInput var querystringParams: ParamSet { return qsParams } init(reviewType: ReviewType, learnedOnly: Bool = false) { self.reviewType = reviewType var type = reviewType.querystringParam if case .failed = reviewType, learnedOnly { type = "learned" } qsParams = [ "mode": "srs", "type": type ] } } struct FreeReviewStartRequest: StartRequest { let qsParams: ParamSet typealias ModelType = CardIdsModel typealias InputType = NoInput var querystringParams: ParamSet { return qsParams } init(fromIndex:Int, toIndex:Int, shuffle:Bool) { qsParams = [ "mode": "free", "from": String(fromIndex), "to": String(toIndex), "shuffle": (shuffle ? "1" : "0") ] } }
mit
f21128d3e1bb581979443c48adda6859
20.018182
61
0.567907
4.273567
false
false
false
false
lorentey/swift
test/IRGen/type_layout_dumper_resilient.swift
30
2237
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/type_layout_dumper_other.swiftmodule -module-name=type_layout_dumper_other %S/Inputs/type_layout_dumper_other.swift // RUN: %target-swift-frontend -dump-type-info -type-info-dump-filter=resilient -I %t %s | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: OS=macosx import type_layout_dumper_other // CHECK: --- // CHECK-NEXT: Name: type_layout_dumper_other // CHECK-NEXT: Decls: // CHECK-NEXT: - Name: 24type_layout_dumper_other21ConcreteFragileStructV015NestedResilientG0V // CHECK-NEXT: Size: 0 // CHECK-NEXT: Alignment: 1 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: - Name: 24type_layout_dumper_other21ConcreteResilientEnumO // CHECK-NEXT: Size: 9 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 254 // CHECK-NEXT: - Name: 24type_layout_dumper_other22DependentResilientEnumO09NestedNonefG0O // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: - Name: 24type_layout_dumper_other23ConcreteResilientStructV // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: - Name: 24type_layout_dumper_other24DependentResilientStructV09NestedNonefG0V // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 1 // CHECK-NEXT: - Name: 24type_layout_dumper_other25NonDependentResilientEnumO // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: - Name: 24type_layout_dumper_other27NonDependentResilientStructV // CHECK-NEXT: Size: 8 // CHECK-NEXT: Alignment: 8 // CHECK-NEXT: ExtraInhabitants: 2147483647 // CHECK-NEXT: - Name: Si24type_layout_dumper_otherE17NestedInExtensionV // CHECK-NEXT: Size: 4 // CHECK-NEXT: Alignment: 4 // CHECK-NEXT: ExtraInhabitants: 0 // CHECK-NEXT: ...
apache-2.0
06692b102453f2657812d5c24ffd20e2
46.595745
206
0.629861
3.48986
false
false
false
false
AreejEssa/swift
Sources/Controller/Controller.swift
1
3642
/** * 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. **/ import Kitura import SwiftyJSON import LoggerAPI import CloudEnvironment import Health public class Controller { public let router: Router let cloudEnv: CloudEnv let health: Health public var port: Int { get { return cloudEnv.port } } public var url: String { get { return cloudEnv.url } } public init() { // Create CloudEnv instance cloudEnv = CloudEnv() // All web apps need a Router instance to define routes router = Router() // Instance of health for reporting heath check values health = Health() // Serve static content from "public" router.all("/", middleware: StaticFileServer()) // Basic GET request router.get("/hello", handler: getHello) // Basic POST request router.post("/hello", handler: postHello) // JSON Get request router.get("/json", handler: getJSON) // Basic application health check router.get("/health", handler: getHealthCheck) } /** * Handler for getting a text/plain response. */ public func getHello(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws { Log.debug("GET - /hello route handler...") response.headers["Content-Type"] = "text/plain; charset=utf-8" try response.status(.OK).send("Hello from Kitura-Starter!").end() } /** * Handler for posting the name of the entity to say hello to (a text/plain response). */ public func postHello(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws { Log.debug("POST - /hello route handler...") response.headers["Content-Type"] = "text/plain; charset=utf-8" if let name = try request.readString() { try response.status(.OK).send("Hello \(name), from Kitura-Starter!").end() } else { try response.status(.OK).send("Kitura-Starter received a POST request!").end() } } /** * Handler for getting an application/json response. */ public func getJSON(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws { Log.debug("GET - /json route handler...") response.headers["Content-Type"] = "application/json; charset=utf-8" var jsonResponse = JSON([:]) jsonResponse["framework"].stringValue = "Kitura" jsonResponse["applicationName"].stringValue = "Kitura-Starter" jsonResponse["company"].stringValue = "IBM" jsonResponse["organization"].stringValue = "Swift @ IBM" jsonResponse["location"].stringValue = "Austin, Texas" try response.status(.OK).send(json: jsonResponse).end() } /** * Handler for getting a text/plain response of application health status. */ public func getHealthCheck(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws { Log.debug("GET - /health route handler...") let result = health.status.toSimpleDictionary() if health.status.state == .UP { try response.send(json: result).end() } else { try response.status(.serviceUnavailable).send(json: result).end() } } }
apache-2.0
909d422276667c1d6110b8ea6f744b8b
31.230088
115
0.683416
4.171821
false
false
false
false
gregomni/swift
test/IDE/complete_in_accessors.swift
1
14061
// RUN: %empty-directory(%t) // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t //===--- Helper types that are used in this test struct FooStruct { var instanceVar: Int = 0 func instanceFunc0() {} static var staticVar: Int static func staticFunc0() {} } func returnsInt() -> Int {} // FOO_OBJECT_DOT: Begin completions // FOO_OBJECT_DOT-NEXT: Keyword[self]/CurrNominal: self[#FooStruct#]; name=self // FOO_OBJECT_DOT-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}} // FOO_OBJECT_DOT-NEXT: End completions // WITH_GLOBAL_DECLS: Begin completions // WITH_GLOBAL_DECLS-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // WITH_GLOBAL_DECLS-DAG: Decl[FreeFunction]/CurrModule{{(/TypeRelation\[Convertible\])?}}: returnsInt()[#Int#]{{; name=.+$}} // WITH_GLOBAL_DECLS: End completions // WITH_GLOBAL_DECLS1: Begin completions // WITH_GLOBAL_DECLS1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // WITH_GLOBAL_DECLS1-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Convertible]: returnsInt()[#Int#]{{; name=.+$}} // WITH_GLOBAL_DECLS1: End completions // WITH_MEMBER_DECLS: Begin completions // WITH_MEMBER_DECLS-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // WITH_MEMBER_DECLS-DAG: Decl[FreeFunction]/CurrModule{{(/TypeRelation\[Convertible\])?}}: returnsInt()[#Int#]{{; name=.+$}} // WITH_MEMBER_DECLS-DAG: Decl[LocalVar]/Local: self[#MemberAccessors#]{{; name=.+$}} // WITH_MEMBER_DECLS-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Double#]{{; name=.+$}} // WITH_MEMBER_DECLS-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Float#]{{; name=.+$}} // WITH_MEMBER_DECLS: End completions // WITH_MEMBER_DECLS_INIT: Begin completions // WITH_MEMBER_DECLS_INIT-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // WITH_MEMBER_DECLS_INIT-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Convertible]: returnsInt()[#Int#]{{; name=.+$}} // WITH_MEMBER_DECLS_INIT-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(self): MemberAccessors#})[#(Int) -> Float#]{{; name=.+$}} // WITH_MEMBER_DECLS_INIT: End completions // WITH_MEMBER_DECLS_INIT_WRONG-NOT: self[ // WITH_MEMBER_DECLS_INIT_WRONG-NOT: instanceVar // WITH_LOCAL_DECLS: Begin completions // WITH_LOCAL_DECLS-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // WITH_LOCAL_DECLS-DAG: Decl[FreeFunction]/CurrModule{{(/TypeRelation\[Convertible\])?}}: returnsInt()[#Int#]{{; name=.+$}} // WITH_LOCAL_DECLS-DAG: Decl[LocalVar]/Local{{(/TypeRelation\[Convertible\])?}}: functionParam[#Int#]{{; name=.+$}} // WITH_LOCAL_DECLS-DAG: Decl[FreeFunction]/Local: localFunc({#(a): Int#})[#Float#]{{; name=.+$}} // WITH_LOCAL_DECLS: End completions // WITH_LOCAL_DECLS1: Begin completions // WITH_LOCAL_DECLS1-DAG: Decl[Struct]/CurrModule: FooStruct[#FooStruct#]{{; name=.+$}} // WITH_LOCAL_DECLS1-DAG: Decl[FreeFunction]/CurrModule/TypeRelation[Convertible]: returnsInt()[#Int#]{{; name=.+$}} // WITH_LOCAL_DECLS1-DAG: Decl[LocalVar]/Local/TypeRelation[Convertible]: functionParam[#Int#]{{; name=.+$}} // WITH_LOCAL_DECLS1-DAG: Decl[FreeFunction]/Local: localFunc({#(a): Int#})[#Float#]{{; name=.+$}} // WITH_LOCAL_DECLS1: End completions // WITH_OLDVALUE: Begin completions // WITH_OLDVALUE-DAG: Decl[LocalVar]/Local: oldValue[#Int#]{{; name=.+$}} // WITH_OLDVALUE: End completions // WITH_NEWVALUE: Begin completions // WITH_NEWVALUE-DAG: Decl[LocalVar]/Local: newValue[#Int#]{{; name=.+$}} // WITH_NEWVALUE: End completions //===--- Check that we can complete inside accessors. // Each test comes in two variants: a basic one, with global completions, and // another one with a local variable to make sure that we type check accessor // bodies. var globalAccessorImplicitGet1: Int { #^GLOBAL_ACCESSOR_IMPLICIT_GET_1?check=WITH_GLOBAL_DECLS^# } var globalAccessorImplicitGet2: Int { var fs = FooStruct() fs.#^GLOBAL_ACCESSOR_IMPLICIT_GET_2?check=FOO_OBJECT_DOT^# } var globalAccessorGet1: Int { get { #^GLOBAL_ACCESSOR_GET_1?check=WITH_GLOBAL_DECLS^# } } var globalAccessorGet2: Int { get { var fs = FooStruct() fs.#^GLOBAL_ACCESSOR_GET_2?check=FOO_OBJECT_DOT^# } } var globalAccessorSet1: Int { set { #^GLOBAL_ACCESSOR_SET_1?check=WITH_GLOBAL_DECLS;check=WITH_NEWVALUE^# } } var globalAccessorSet2: Int { set { var fs = FooStruct() fs.#^GLOBAL_ACCESSOR_SET_2?check=FOO_OBJECT_DOT^# } } var globalAccessorSet3: Int { set(newValue) { #^GLOBAL_ACCESSOR_SET_3?check=WITH_GLOBAL_DECLS;check=WITH_NEWVALUE^# } } var globalAccessorSet4: Int { set(newValue) { var fs = FooStruct() fs.#^GLOBAL_ACCESSOR_SET_4?check=FOO_OBJECT_DOT^# } } var globalAccessorWillSet1: Int { willSet { #^GLOBAL_ACCESSOR_WILLSET_1?check=WITH_GLOBAL_DECLS;check=WITH_NEWVALUE^# } } var globalAccessorWillSet2: Int { willSet { var fs = FooStruct() fs.#^GLOBAL_ACCESSOR_WILLSET_2?check=FOO_OBJECT_DOT^# } } var globalAccessorWillSet3 = 42 { willSet { #^GLOBAL_ACCESSOR_WILLSET_3?check=WITH_GLOBAL_DECLS;check=WITH_NEWVALUE^# } } var globalAccessorDidSet1: Int { didSet { #^GLOBAL_ACCESSOR_DIDSET_1?check=WITH_GLOBAL_DECLS;check=WITH_OLDVALUE^# } } var globalAccessorDidSet2: Int { didSet { var fs = FooStruct() fs.#^GLOBAL_ACCESSOR_DIDSET_2?check=FOO_OBJECT_DOT^# } } var globalAccessorDidSet3 = 42 { didSet { #^GLOBAL_ACCESSOR_DIDSET_3?check=WITH_GLOBAL_DECLS;check=WITH_OLDVALUE^# } } var globalAccessorInit1: Int = #^GLOBAL_ACCESSOR_INIT_1?check=WITH_GLOBAL_DECLS1^# { } var globalAccessorInit2: Int = #^GLOBAL_ACCESSOR_INIT_2?check=WITH_GLOBAL_DECLS1^# { get {} } struct MemberAccessors { var instanceVar: Double func instanceFunc(_ a: Int) -> Float { return 0.0 } static var staticVar: Int static func staticFunc0(_ a: Float) -> Int { return 0 } var memberAccessorImplicitGet1: Int { #^MEMBER_ACCESSOR_IMPLICIT_GET_1?check=WITH_MEMBER_DECLS^# } var memberAccessorImplicitGet2: Int { var fs = FooStruct() fs.#^MEMBER_ACCESSOR_IMPLICIT_GET_2?check=FOO_OBJECT_DOT^# } var memberAccessorGet1: Int { get { #^MEMBER_ACCESSOR_GET_1?check=WITH_MEMBER_DECLS^# } } var memberAccessorGet2: Int { get { var fs = FooStruct() fs.#^MEMBER_ACCESSOR_GET_2?check=FOO_OBJECT_DOT^# } } var memberAccessorSet1: Int { set { #^MEMBER_ACCESSOR_SET_1?check=WITH_MEMBER_DECLS;check=WITH_NEWVALUE^# } } var memberAccessorSet2: Int { set { var fs = FooStruct() fs.#^MEMBER_ACCESSOR_SET_2?check=FOO_OBJECT_DOT^# } } var memberAccessorSet3: Int { set(newValue) { #^MEMBER_ACCESSOR_SET_3?check=WITH_MEMBER_DECLS;check=WITH_NEWVALUE^# } } var memberAccessorSet4: Int { set(newValue) { var fs = FooStruct() fs.#^MEMBER_ACCESSOR_SET_4?check=FOO_OBJECT_DOT^# } } var memberAccessorWillSet1: Int { willSet { #^MEMBER_ACCESSOR_WILLSET_1?check=WITH_MEMBER_DECLS;check=WITH_NEWVALUE^# } } var memberAccessorWillSet2: Int { willSet { var fs = FooStruct() fs.#^MEMBER_ACCESSOR_WILLSET_2?check=FOO_OBJECT_DOT^# } } var memberAccessorWillSet3 = 42 { willSet { #^MEMBER_ACCESSOR_WILLSET_3?check=WITH_MEMBER_DECLS;check=WITH_NEWVALUE^# } } var memberAccessorDidSet1: Int { didSet { #^MEMBER_ACCESSOR_DIDSET_1?check=WITH_MEMBER_DECLS;check=WITH_OLDVALUE^# } } var memberAccessorDidSet2: Int { didSet { var fs = FooStruct() fs.#^MEMBER_ACCESSOR_DIDSET_2?check=FOO_OBJECT_DOT^# } } var memberAccessorDidSet3 = 42 { didSet { #^MEMBER_ACCESSOR_DIDSET_3?check=WITH_MEMBER_DECLS;check=WITH_OLDVALUE^# } } var memberAccessorInit1: Int = #^MEMBER_ACCESSOR_INIT_1?check=WITH_MEMBER_DECLS_INIT;check=WITH_MEMBER_DECLS_INIT_WRONG^# { } var memberAccessorInit2: Int = #^MEMBER_ACCESSOR_INIT_2?check=WITH_MEMBER_DECLS_INIT;check=WITH_MEMBER_DECLS_INIT_WRONG^# { get {} } } func accessorsInFunction(_ functionParam: Int) { func localFunc(_ a: Int) -> Float { return 0.0 } var memberAccessorImplicitGet1: Int { #^LOCAL_ACCESSOR_IMPLICIT_GET_1?check=WITH_LOCAL_DECLS^# } var memberAccessorImplicitGet2: Int { var fs = FooStruct() fs.#^LOCAL_ACCESSOR_IMPLICIT_GET_2?check=FOO_OBJECT_DOT^# } var memberAccessorGet1: Int { get { #^LOCAL_ACCESSOR_GET_1?check=WITH_LOCAL_DECLS^# } } var memberAccessorGet2: Int { get { var fs = FooStruct() fs.#^LOCAL_ACCESSOR_GET_2?check=FOO_OBJECT_DOT^# } } var memberAccessorSet1: Int { set { #^LOCAL_ACCESSOR_SET_1?check=WITH_LOCAL_DECLS;check=WITH_NEWVALUE^# } } var memberAccessorSet2: Int { set { var fs = FooStruct() fs.#^LOCAL_ACCESSOR_SET_2?check=FOO_OBJECT_DOT^# } } var memberAccessorSet3: Int { set(newValue) { #^LOCAL_ACCESSOR_SET_3?check=WITH_LOCAL_DECLS;check=WITH_NEWVALUE^# } } var memberAccessorSet4: Int { set(newValue) { var fs = FooStruct() fs.#^LOCAL_ACCESSOR_SET_4?check=FOO_OBJECT_DOT^# } } var memberAccessorWillSet1: Int { willSet { #^LOCAL_ACCESSOR_WILLSET_1?check=WITH_LOCAL_DECLS;check=WITH_NEWVALUE^# } } var memberAccessorWillSet2: Int { willSet { var fs = FooStruct() fs.#^LOCAL_ACCESSOR_WILLSET_2?check=FOO_OBJECT_DOT^# } } var memberAccessorWillSet3 = 42 { willSet { #^LOCAL_ACCESSOR_WILLSET_3?check=WITH_LOCAL_DECLS;check=WITH_NEWVALUE^# } } var memberAccessorDidSet1: Int { didSet { #^LOCAL_ACCESSOR_DIDSET_1?check=WITH_LOCAL_DECLS;check=WITH_OLDVALUE^# } } var memberAccessorDidSet2: Int { didSet { var fs = FooStruct() fs.#^LOCAL_ACCESSOR_DIDSET_2?check=FOO_OBJECT_DOT^# } } var memberAccessorDidSet3: Int { didSet { #^LOCAL_ACCESSOR_DIDSET_3?check=WITH_LOCAL_DECLS;check=WITH_OLDVALUE^# } } var globalAccessorInit1: Int = #^LOCAL_ACCESSOR_INIT_1?check=WITH_LOCAL_DECLS1^# { } var globalAccessorInit2: Int = #^LOCAL_ACCESSOR_INIT_2?check=WITH_LOCAL_DECLS1^# { get {} } } // ACCESSORS_IN_MEMBER_FUNC_1: Begin completions // ACCESSORS_IN_MEMBER_FUNC_1-DAG: Decl[LocalVar]/Local: self[#AccessorsInMemberFunction#] // ACCESSORS_IN_MEMBER_FUNC_1-DAG: Decl[LocalVar]/Local/TypeRelation[Convertible]: functionParam[#Int#] // ACCESSORS_IN_MEMBER_FUNC_1-DAG: Decl[InstanceVar]/CurrNominal: instanceVar[#Double#] // ACCESSORS_IN_MEMBER_FUNC_1-DAG: Decl[InstanceMethod]/CurrNominal: instanceFunc({#(a): Int#})[#Float#] // ACCESSORS_IN_MEMBER_FUNC_1: End completions // ACCESSORS_IN_MEMBER_FUNC_2: Begin completions // ACCESSORS_IN_MEMBER_FUNC_2-DAG: Decl[LocalVar]/Local: self[#AccessorsInMemberFunction#] // ACCESSORS_IN_MEMBER_FUNC_2-DAG: Decl[LocalVar]/Local{{(/TypeRelation\[Convertible\])?}}: functionParam[#Int#] // ACCESSORS_IN_MEMBER_FUNC_2-DAG: Decl[InstanceVar]/OutNominal: instanceVar[#Double#] // ACCESSORS_IN_MEMBER_FUNC_2-DAG: Decl[InstanceMethod]/OutNominal: instanceFunc({#(a): Int#})[#Float#] // ACCESSORS_IN_MEMBER_FUNC_2: End completions struct AccessorsInMemberFunction { var instanceVar: Double func instanceFunc(_ a: Int) -> Float { return 0.0 } static var staticVar: Int static func staticFunc0(_ a: Float) -> Int { return 0 } func accessorsInInstanceFunction1(_ functionParam: Int) { var x: Int = #^ACCESSOR_IN_MEMBER_FUNC_1?check=WITH_GLOBAL_DECLS1;check=ACCESSORS_IN_MEMBER_FUNC_1^# { get {} } } func accessorsInInstanceFunction2(_ functionParam: Int) { var x: Int { get { #^ACCESSOR_IN_MEMBER_FUNC_2?check=WITH_GLOBAL_DECLS;check=ACCESSORS_IN_MEMBER_FUNC_2^# } } } } var testImplicitOldValue1: Int = 0 { didSet { var oldV = oldValue #^IMPLICIT_OLDVALUE_COPIED^# // IMPLICIT_OLDVALUE_COPIED: Begin completions // IMPLICIT_OLDVALUE_COPIED-DAG: Decl[LocalVar]/Local: oldV[#Int#]; // IMPLICIT_OLDVALUE_COPIED-DAG: Decl[LocalVar]/Local: oldValue[#Int#]; // IMPLICIT_OLDVALUE_COPIED: End completions } } var testImplicitOldValue2: Int = 0 { didSet { oldValue.#^IMPLICIT_OLDVALUE_MEMBER^# // IMPLICIT_OLDVALUE_MEMBER: Begin completions // IMPLICIT_OLDVALUE_MEMBER-DAG: Keyword[self]/CurrNominal: self[#Int#]; // IMPLICIT_OLDVALUE_MEMBER: End completions } } var testImplicitOldValue3: Int = 0 { didSet { var oldV = oldValue oldV.#^IMPLICIT_OLDVALUE_COPIEDMEMBER^# // IMPLICIT_OLDVALUE_COPIEDMEMBER: Begin completions // IMPLICIT_OLDVALUE_COPIEDMEMBER-DAG: Keyword[self]/CurrNominal: self[#Int#]; // IMPLICIT_OLDVALUE_COPIEDMEMBER: End completions } } var testExplicitOldValue1: Int = 0 { didSet(oldVal) { var oldV = oldVal #^EXPLICIT_OLDVALUE_COPIED^# // EXPLICIT_OLDVALUE_COPIED: Begin completions // EXPLICIT_OLDVALUE_COPIED-NOT: oldValue // EXPLICIT_OLDVALUE_COPIED-DAG: Decl[LocalVar]/Local: oldV[#Int#]; // EXPLICIT_OLDVALUE_COPIED-DAG: Decl[LocalVar]/Local: oldVal[#Int#]; // EXPLICIT_OLDVALUE_COPIED-NOT: oldValue // EXPLICIT_OLDVALUE_COPIED: End completions } } var testExplicitOldValue2: Int = 0 { didSet(oldVal) { oldVal.#^EXPLICIT_OLDVALUE_MEMBER^# // EXPLICIT_OLDVALUE_MEMBER: Begin completions // EXPLICIT_OLDVALUE_MEMBER-DAG: Keyword[self]/CurrNominal: self[#Int#]; // EXPLICIT_OLDVALUE_MEMBER: End completions } } var testExplicitOldValue3: Int = 0 { didSet(oldVal) { var oldV = oldVal oldV.#^EXPLICIT_OLDVALUE_COPIEDMEMBER^# // EXPLICIT_OLDVALUE_COPIEDMEMBER: Begin completions // EXPLICIT_OLDVALUE_COPIEDMEMBER-DAG: Keyword[self]/CurrNominal: self[#Int#]; // EXPLICIT_OLDVALUE_COPIEDMEMBER: End completions } }
apache-2.0
46ff2d205cf367afc720607e42e64239
31.776224
138
0.675201
3.477003
false
false
false
false
joostholslag/BNRiOS
iOSProgramming6ed/5 - ViewControllers/Solutions/WorldTrotter/WorldTrotter/ConversionViewController.swift
1
2155
// // Copyright © 2015 Big Nerd Ranch // import UIKit class ConversionViewController: UIViewController, UITextFieldDelegate { @IBOutlet var celsiusLabel: UILabel! @IBOutlet var textField: UITextField! var fahrenheitValue: Measurement<UnitTemperature>? { didSet { updateCelsiusLabel() } } var celsiusValue: Measurement<UnitTemperature>? { if let fahrenheitValue = fahrenheitValue { return fahrenheitValue.converted(to: .celsius) } else { return nil } } let numberFormatter: NumberFormatter = { let nf = NumberFormatter() nf.numberStyle = .decimal nf.minimumFractionDigits = 0 nf.maximumFractionDigits = 1 return nf }() override func viewDidLoad() { super.viewDidLoad() print("ConversionViewController loaded its view") updateCelsiusLabel() } @IBAction func dismissKeyboard(_ sender: UITapGestureRecognizer) { textField.resignFirstResponder() } func updateCelsiusLabel() { if let celsiusValue = celsiusValue { celsiusLabel.text = numberFormatter.string(from: NSNumber(value: celsiusValue.value)) } else { celsiusLabel.text = "???" } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let existingTextHasDecimalSeparator = textField.text?.range(of: ".") let replacementTextHasDecimalSeparator = string.range(of: ".") if existingTextHasDecimalSeparator != nil, replacementTextHasDecimalSeparator != nil { return false } else { return true } } @IBAction func fahrenheitFieldEditingChanges(_ textField: UITextField) { if let text = textField.text, let value = Double(text) { fahrenheitValue = Measurement(value: value, unit: .fahrenheit) } else { fahrenheitValue = nil } } }
gpl-3.0
9254490344396da778055b35654b3a84
27.342105
97
0.597957
5.594805
false
false
false
false
ljubinkovicd/Lingo-Chat
Lingo Chat/UserPasswordController.swift
1
5569
// // UserPasswordController.swift // Lingo Chat // // Created by Dorde Ljubinkovic on 8/30/17. // Copyright © 2017 Dorde Ljubinkovic. All rights reserved. // import UIKit import SkyFloatingLabelTextField import CryptoSwift class UserPasswordController: UIViewController { @IBOutlet weak var testLabe: UILabel! var newUser: TheUser? lazy var userPasswordTextField: SkyFloatingLabelTextField = { let textField = SkyFloatingLabelTextField(frame: CGRect(x: 0, y: 0, width: 132, height: 44)) textField.translatesAutoresizingMaskIntoConstraints = false // use to disable conflicts with auto layout textField.placeholder = "Password" textField.title = "Your Password" textField.isSecureTextEntry = true textField.errorColor = UIColor.red return textField }() lazy var continueButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(NSLocalizedString("Continue", comment: "Move from the email controller screen to name controller screen."), for: .normal) button.setTitleColor(UIColor.white, for: .normal) button.layer.cornerRadius = 4.0 button.layer.masksToBounds = true button.layer.borderWidth = 1.0 button.layer.borderColor = UIColor.cyan.cgColor button.backgroundColor = UIColor.blue button.contentEdgeInsets = UIEdgeInsetsMake(15, 0, 15, 0) button.addTarget(self, action: #selector(continueButtonTapped(sender:)), for: .touchUpInside) return button }() lazy var alreadyHaveAnAccountButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(NSLocalizedString("I already have an account", comment: "The user already has an account and doesn't need to sign up."), for: .normal) button.setTitleColor(UIColor.white, for: .normal) button.layer.cornerRadius = 4.0 button.layer.masksToBounds = true button.layer.borderWidth = 1.0 button.layer.borderColor = UIColor.black.cgColor button.backgroundColor = UIColor.gray button.contentEdgeInsets = UIEdgeInsetsMake(5, 15, 5, 15) button.addTarget(self, action: #selector(alreadyHaveAnAccountButtonTapped(sender:)), for: .touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil) view.addSubview(userPasswordTextField) view.addSubview(continueButton) view.addSubview(alreadyHaveAnAccountButton) userPasswordTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true userPasswordTextField.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true continueButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true continueButton.topAnchor.constraint(equalTo: userPasswordTextField.bottomAnchor, constant: 16.0).isActive = true continueButton.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0, constant: -32).isActive = true alreadyHaveAnAccountButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true alreadyHaveAnAccountButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16.0).isActive = true } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Globals.passwordToProfileSegue { let profileController = segue.destination as! UserGenderDateOfBirthPhotoController profileController.newUser = newUser } } } extension UserPasswordController: UITextFieldDelegate { func keyboardWillShow(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y == 0 { self.view.frame.origin.y -= keyboardSize.height } } } func keyboardWillHide(notification: Notification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y != 0 { self.view.frame.origin.y += keyboardSize.height } } } } extension UserPasswordController: RegistrationFormProtocol { func continueButtonTapped(sender: UIButton) { validateForm() } // Unwind Segue func alreadyHaveAnAccountButtonTapped(sender: UIButton) { newUser = nil performSegue(withIdentifier: "unwindSegueToLoginController", sender: self) } func validateForm() { let password = userPasswordTextField.text! if (password == "") { print("Invalid Form!") return } else { // newUser = User() newUser?.password = password.md5() performSegue(withIdentifier: Globals.passwordToProfileSegue, sender: nil) } } }
mit
7f7fe10645833f23ec0fc38e9160edca
37.136986
158
0.667924
5.25283
false
false
false
false
marc-medley/004.45macOS_CotEditorSwiftScripting
scripts/02)Tidy/23)Tidy XML (xmllint, 2-space).swift
1
2043
#!/usr/bin/swift // %%%{CotEditorXInput=AllText}%%% // %%%{CotEditorXOutput=ReplaceAllText}%%% import Foundation func setEnvironmentVar(key: String, value: String, overwrite: Bool = false) { setenv(key, value, overwrite ? 1 : 0) } var xmlString: String = "" var i = 0 while true { let line = readLine(strippingNewline: true) if line == nil { break } if line == "" { continue } // `break` or `continue` if let s = line { xmlString.append(s) // uncomment to view input // print("line[\(i)] \(s)") i = i + 1 } } let xmlData = xmlString.data(using: String.Encoding.utf8)! // XMLLINT_INDENT=$' ' xmllint --format --encode utf-8 - // Use `which -a xmllint` to find install location // e.g. /usr/bin/xmllint or /opt/local/bin/xmllint /// full command path required let commandPath = "/usr/bin/xmllint" /// comment/uncomment arguments as needed var args = [String]() args.append("--format") args.append(contentsOf: ["--encode", "utf-8"]) args.append("-") // two spaces setEnvironmentVar(key: "XMLLINT_INDENT", value: " ") let process = Process() process.launchPath = commandPath process.arguments = args let stdinPipe = Pipe() process.standardInput = stdinPipe let stdoutPipe = Pipe() process.standardOutput = stdoutPipe let stderrPipe = Pipe() process.standardError = stderrPipe process.launch() let stdin = stdinPipe.fileHandleForWriting stdin.write(xmlData) stdin.closeFile() let data = stdoutPipe.fileHandleForReading.readDataToEndOfFile() if let output = String(data: data, encoding: String.Encoding.utf8) { // print("STANDARD OUTPUT\n" + output) print(output) } /** Uncomment to include errors in stdout output */ // let dataError = stderrPipe.fileHandleForReading.readDataToEndOfFile() // if let outputError = String(data: dataError, encoding: String.Encoding.utf8) { // print("STANDARD ERROR \n" + outputError) // } process.waitUntilExit() /** Uncomment to include status in stdout output */ // let status = process.terminationStatus // print("STATUS: \(status)")
mit
71ea98109e53f2984f05304393e004c9
26.608108
81
0.692119
3.559233
false
false
false
false
davefoxy/SwiftBomb
Example/SwiftBomb/DetailViewControllers/FranchiseViewController.swift
1
4595
// // FranchiseViewController.swift // SwiftBomb // // Created by David Fox on 07/05/2016. // Copyright © 2016 David Fox. All rights reserved. // import UIKit import SwiftBomb class FranchiseViewController: BaseResourceDetailViewController { var franchise: FranchiseResource? override func viewDidLoad() { super.viewDidLoad() franchise?.fetchExtendedInfo() { [weak self] error in self?.tableView.reloadData() } } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? 1 : 3 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell var title = "" if (indexPath as NSIndexPath).section == 0 { cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byWordWrapping var infos = [ResourceInfoTuple(value: franchise?.name, "Name:"), ResourceInfoTuple(value: franchise?.deck, "Deck:"), ResourceInfoTuple(value: franchise?.aliases?.joined(separator: ", "), "Aliases:")] if (franchise?.description != nil) { infos.append(ResourceInfoTuple(value: "Tap to view", label: "Description:")) } cell.textLabel?.attributedText = createResourceInfoString(infos) return cell } else { switch (indexPath as NSIndexPath).row { case 0: if let games = franchise?.extendedInfo?.games { title = "Games (\(games.count))" } case 1: if let characters = franchise?.extendedInfo?.characters { title = "Characters (\(characters.count))" } case 2: if let people = franchise?.extendedInfo?.people { title = "People (\(people.count))" } default: break } } cell.textLabel?.text = title return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath as NSIndexPath).section == 0 { guard let description = franchise?.description else { tableView.deselectRow(at: indexPath, animated: true) return } showWebViewController(description) } else { let resourcesList = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ResourcesListViewController") as! ResourcesListViewController resourcesList.shouldLoadFromServer = false switch (indexPath as NSIndexPath).row { case 0: // games let gamesPaginator = GameResourcePaginator() gamesPaginator.games = (franchise?.extendedInfo?.games)! resourcesList.resourcePaginator = gamesPaginator resourcesList.cellPresenters = gamesPaginator.cellPresentersForResources((franchise?.extendedInfo?.games)!) case 1: // characters let charactersPaginator = CharactersResourcePaginator() charactersPaginator.characters = (franchise?.extendedInfo?.characters)! resourcesList.resourcePaginator = charactersPaginator resourcesList.cellPresenters = charactersPaginator.cellPresentersForResources((franchise?.extendedInfo?.characters)!) case 2: // people let personPaginator = PersonResourcePaginator() personPaginator.people = (franchise?.extendedInfo?.people)! resourcesList.resourcePaginator = personPaginator resourcesList.cellPresenters = personPaginator.cellPresentersForResources((franchise?.extendedInfo?.people)!) default: break } navigationController?.pushViewController(resourcesList, animated: true) } } }
mit
9d76beef1db15895f61966ba2142ae7c
35.460317
211
0.563779
5.756892
false
false
false
false
reza-ryte-club/firefox-ios
StorageTests/TestSQLiteHistory.swift
2
23415
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCTest extension Site { func asPlace() -> Place { return Place(guid: self.guid!, url: self.url, title: self.title) } } class TestSQLiteHistory: XCTestCase { // Test that our visit partitioning for frecency is correct. func testHistoryLocalAndRemoteVisits() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs)! let siteL = Site(url: "http://url1/", title: "title local only") let siteR = Site(url: "http://url2/", title: "title remote only") let siteB = Site(url: "http://url3/", title: "title local and remote") siteL.guid = "locallocal12" siteR.guid = "remoteremote" siteB.guid = "bothbothboth" let siteVisitL1 = SiteVisit(site: siteL, date: 1437088398461000, type: VisitType.Link) let siteVisitL2 = SiteVisit(site: siteL, date: 1437088398462000, type: VisitType.Link) let siteVisitR1 = SiteVisit(site: siteR, date: 1437088398461000, type: VisitType.Link) let siteVisitR2 = SiteVisit(site: siteR, date: 1437088398462000, type: VisitType.Link) let siteVisitR3 = SiteVisit(site: siteR, date: 1437088398463000, type: VisitType.Link) let siteVisitBL1 = SiteVisit(site: siteB, date: 1437088398464000, type: VisitType.Link) let siteVisitBR1 = SiteVisit(site: siteB, date: 1437088398465000, type: VisitType.Link) let deferred = history.clearHistory() >>> { history.addLocalVisit(siteVisitL1) } >>> { history.addLocalVisit(siteVisitL2) } >>> { history.addLocalVisit(siteVisitBL1) } >>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: 1437088398462) } >>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: 1437088398463) } >>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: 1437088398465) } // Do this step twice, so we exercise the dupe-visit handling. >>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) } >>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) } >>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) } >>> { history.getSitesByFrecencyWithLimit(3) >>== { (sites: Cursor) -> Success in XCTAssertEqual(3, sites.count) // Two local visits beat a single later remote visit and one later local visit. // Two local visits beat three remote visits. XCTAssertEqual(siteL.guid!, sites[0]!.guid!) XCTAssertEqual(siteB.guid!, sites[1]!.guid!) XCTAssertEqual(siteR.guid!, sites[2]!.guid!) return succeed() } // This marks everything as modified so we can fetch it. >>> history.onRemovedAccount // Now check that we have no duplicate visits. >>> { history.getModifiedHistoryToUpload() >>== { (places) -> Success in if let (_, visits) = find(places, f: {$0.0.guid == siteR.guid!}) { XCTAssertEqual(3, visits.count) } else { XCTFail("Couldn't find site R.") } return succeed() } } } XCTAssertTrue(deferred.value.isSuccess) } func testUpgrades() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) // This calls createOrUpdate. i.e. it may fail, but should not crash and should always return a valid SQLiteHistory object. let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs)! XCTAssertNotNil(history) // Insert some basic data that we'll have to upgrade let expectation = self.expectationWithDescription("First.") db.run([("INSERT INTO history (guid, url, title, server_modified, local_modified, is_deleted, should_upload) VALUES (guid, http://www.example.com, title, 5, 10, 0, 1)", nil), ("INSERT INTO visits (siteID, date, type, is_local) VALUES (1, 15, 1, 1)", nil), ("INSERT INTO favicons (url, width, height, type, date) VALUES (http://www.example.com/favicon.ico, 10, 10, 1, 20)", nil), ("INSERT INTO faviconSites (siteID, faviconID) VALUES (1, 1)", nil), ("INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES (guid, 1, http://www.example.com, 0, 1, title)", nil) ]).upon { result in for i in 1...BrowserTable.DefaultVersion { let history = SQLiteHistory(db: db, prefs: prefs, version: i) XCTAssertNotNil(history) } // This checks to make sure updates actually work (or at least that they don't crash :)) var err: NSError? = nil db.transaction(&err, callback: { (connection, err) -> Bool in for i in 0...BrowserTable.DefaultVersion { let table = BrowserTable(version: i) switch db.updateTable(connection, table: table) { case .Updated: XCTAssertTrue(true, "Update to \(i) succeeded") default: XCTFail("Update to version \(i) failed") return false } } return true }) if err != nil { XCTFail("Error creating a transaction \(err)") } expectation.fulfill() } waitForExpectationsWithTimeout(10, handler: nil) } func testDomainUpgrade() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs)! let site = Site(url: "http://www.example.com/test1.1", title: "title one") var err: NSError? = nil // Insert something with an invalid domainId. We have to manually do this since domains are usually hidden. db.withWritableConnection(&err, callback: { (connection, err) -> Int in let insert = "INSERT INTO \(TableHistory) (guid, url, title, local_modified, is_deleted, should_upload, domain_id) " + "?, ?, ?, ?, ?, ?, ?" let args: Args = [Bytes.generateGUID(), site.url, site.title, NSDate.nowNumber(), 0, 0, -1] err = connection.executeChange(insert, withArgs: args) return 0 }) // Now insert it again. This should update the domain history.addLocalVisit(SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: VisitType.Link)) // DomainID isn't normally exposed, so we manually query to get it let results = db.withReadableConnection(&err, callback: { (connection, err) -> Cursor<Int> in let sql = "SELECT domain_id FROM \(TableHistory) WHERE url = ?" let args: Args = [site.url] return connection.executeQuery(sql, factory: IntFactory, withArgs: args) }) XCTAssertNotEqual(results[0]!, -1, "Domain id was updated") } func testDomains() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs)! let initialGuid = Bytes.generateGUID() let site11 = Site(url: "http://www.example.com/test1.1", title: "title one") let site12 = Site(url: "http://www.example.com/test1.2", title: "title two") let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three") let site3 = Site(url: "http://www.example2.com/test1", title: "title three") let expectation = self.expectationWithDescription("First.") history.clearHistory().bind({ success in return all([history.addLocalVisit(SiteVisit(site: site11, date: NSDate.nowMicroseconds(), type: VisitType.Link)), history.addLocalVisit(SiteVisit(site: site12, date: NSDate.nowMicroseconds(), type: VisitType.Link)), history.addLocalVisit(SiteVisit(site: site3, date: NSDate.nowMicroseconds(), type: VisitType.Link))]) }).bind({ (results: [Maybe<()>]) in return history.insertOrUpdatePlace(site13, modified: NSDate.nowMicroseconds()) }).bind({ guid in XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct") return history.getSitesByFrecencyWithLimit(10) }).bind({ (sites: Maybe<Cursor<Site>>) -> Success in XCTAssert(sites.successValue!.count == 2, "2 sites returned") return history.removeSiteFromTopSites(site11) }).bind({ success in XCTAssertTrue(success.isSuccess, "Remove was successful") return history.getSitesByFrecencyWithLimit(10) }).upon({ (sites: Maybe<Cursor<Site>>) in XCTAssert(sites.successValue!.count == 1, "1 site returned") expectation.fulfill() }) waitForExpectationsWithTimeout(10.0) { error in return } } // This is a very basic test. Adds an entry, retrieves it, updates it, // and then clears the database. func testHistoryTable() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs)! let bookmarks = SQLiteBookmarks(db: db) let site1 = Site(url: "http://url1/", title: "title one") let site1Changed = Site(url: "http://url1/", title: "title one alt") let siteVisit1 = SiteVisit(site: site1, date: NSDate.nowMicroseconds(), type: VisitType.Link) let siteVisit2 = SiteVisit(site: site1Changed, date: NSDate.nowMicroseconds() + 1000, type: VisitType.Bookmark) let site2 = Site(url: "http://url2/", title: "title two") let siteVisit3 = SiteVisit(site: site2, date: NSDate.nowMicroseconds() + 2000, type: VisitType.Link) let expectation = self.expectationWithDescription("First.") func done() -> Success { expectation.fulfill() return succeed() } func checkSitesByFrecency(f: Cursor<Site> -> Success) -> () -> Success { return { history.getSitesByFrecencyWithLimit(10) >>== f } } func checkSitesByDate(f: Cursor<Site> -> Success) -> () -> Success { return { history.getSitesByLastVisit(10) >>== f } } func checkSitesWithFilter(filter: String, f: Cursor<Site> -> Success) -> () -> Success { return { history.getSitesByFrecencyWithLimit(10, whereURLContains: filter) >>== f } } func checkDeletedCount(expected: Int) -> () -> Success { return { history.getDeletedHistoryToUpload() >>== { guids in XCTAssertEqual(expected, guids.count) return succeed() } } } history.clearHistory() >>> { history.addLocalVisit(siteVisit1) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) XCTAssertEqual(site1.title, sites[0]!.title) XCTAssertEqual(site1.url, sites[0]!.url) sites.close() return succeed() } >>> { history.addLocalVisit(siteVisit2) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) XCTAssertEqual(site1Changed.title, sites[0]!.title) XCTAssertEqual(site1Changed.url, sites[0]!.url) sites.close() return succeed() } >>> { history.addLocalVisit(siteVisit3) } >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(2, sites.count) // They're in order of frecency. XCTAssertEqual(site1Changed.title, sites[0]!.title) XCTAssertEqual(site2.title, sites[1]!.title) return succeed() } >>> checkSitesByDate { (sites: Cursor<Site>) -> Success in XCTAssertEqual(2, sites.count) // They're in order of date last visited. let first = sites[0]! let second = sites[1]! XCTAssertEqual(site2.title, first.title) XCTAssertEqual(site1Changed.title, second.title) XCTAssertTrue(siteVisit3.date == first.latestVisit!.date) return succeed() } >>> checkSitesWithFilter("two") { (sites: Cursor<Site>) -> Success in XCTAssertEqual(1, sites.count) let first = sites[0]! XCTAssertEqual(site2.title, first.title) return succeed() } >>> checkDeletedCount(0) >>> { history.removeHistoryForURL("http://url2/") } >>> checkDeletedCount(1) >>> checkSitesByFrecency { (sites: Cursor) -> Success in XCTAssertEqual(1, sites.count) // They're in order of frecency. XCTAssertEqual(site1Changed.title, sites[0]!.title) return succeed() } >>> { history.clearHistory() } >>> checkDeletedCount(0) >>> checkSitesByDate { (sites: Cursor<Site>) -> Success in XCTAssertEqual(0, sites.count) return succeed() } >>> checkSitesByFrecency { (sites: Cursor<Site>) -> Success in XCTAssertEqual(0, sites.count) return succeed() } >>> done waitForExpectationsWithTimeout(10.0) { error in return } } func testFaviconTable() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs)! let bookmarks = SQLiteBookmarks(db: db) let expectation = self.expectationWithDescription("First.") func done() -> Success { expectation.fulfill() return succeed() } func updateFavicon() -> Success { let fav = Favicon(url: "http://url2/", date: NSDate(), type: .Icon) fav.id = 1 let site = Site(url: "http://bookmarkedurl/", title: "My Bookmark") return history.addFavicon(fav, forSite: site) >>> succeed } func checkFaviconForBookmarkIsNil() -> Success { return bookmarks.bookmarksByURL("http://bookmarkedurl/".asURL!) >>== { results in XCTAssertEqual(1, results.count) XCTAssertNil(results[0]?.favicon) return succeed() } } func checkFaviconWasSetForBookmark() -> Success { return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in XCTAssertEqual(1, results.count) if let actualFaviconURL = results[0]??.url { XCTAssertEqual("http://url2/", actualFaviconURL) } return succeed() } } func removeBookmark() -> Success { return bookmarks.removeByURL("http://bookmarkedurl/") } func checkFaviconWasRemovedForBookmark() -> Success { return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in XCTAssertEqual(0, results.count) return succeed() } } history.clearAllFavicons() >>> bookmarks.clearBookmarks >>> { bookmarks.addToMobileBookmarks("http://bookmarkedurl/".asURL!, title: "Title", favicon: nil) } >>> checkFaviconForBookmarkIsNil >>> updateFavicon >>> checkFaviconWasSetForBookmark >>> removeBookmark >>> checkFaviconWasRemovedForBookmark >>> done waitForExpectationsWithTimeout(10.0) { error in return } } func testTopSitesCache() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs)! history.setTopSitesCacheSize(20) history.clearTopSitesCache().value history.clearHistory().value // Make sure that we get back the top sites populateHistoryForFrecencyCalcuations(history, siteCount: 100) // Add extra visits to the 5th site to bubble it to the top of the top sites cache let site = Site(url: "http://s\(5)ite\(5)/foo", title: "A \(5)") site.guid = "abc\(5)def" for i in 0...20 { addVisitForSite(site, intoHistory: history, from: .Local, atTime: Timestamp(1438088398461 + (1000 * i))) } let expectation = self.expectationWithDescription("First.") func done() -> Success { expectation.fulfill() return succeed() } func loadCache() -> Success { return history.invalidateTopSitesIfNeeded() >>> succeed } func checkTopSitesReturnsResults() -> Success { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") return succeed() } } func invalidateIfNeededDoesntChangeResults() -> Success { return history.invalidateTopSitesIfNeeded() >>> { return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(5)def") return succeed() } } } func addVisitsToZerothSite() -> Success { let site = Site(url: "http://s\(0)ite\(0)/foo", title: "A \(0)") site.guid = "abc\(0)def" for i in 0...20 { addVisitForSite(site, intoHistory: history, from: .Local, atTime: Timestamp(1439088398461 + (1000 * i))) } return succeed() } func markInvalidation() -> Success { history.setTopSitesNeedsInvalidation() return succeed() } func checkSitesInvalidate() -> Success { history.invalidateTopSitesIfNeeded().value return history.getTopSitesWithLimit(20) >>== { topSites in XCTAssertEqual(topSites.count, 20) XCTAssertEqual(topSites[0]!.guid, "abc\(0)def") return succeed() } } loadCache() >>> checkTopSitesReturnsResults >>> invalidateIfNeededDoesntChangeResults >>> markInvalidation >>> addVisitsToZerothSite >>> checkSitesInvalidate >>> done waitForExpectationsWithTimeout(10.0) { error in return } } } class TestSQLiteHistoryTransactionUpdate: XCTestCase { func testUpdateInTransaction() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs)! history.clearHistory().value let site = Site(url: "http://site/foo", title: "AA") site.guid = "abcdefghiabc" history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).value let local = SiteVisit(site: site, date: Timestamp(1000 * 1437088398461), type: VisitType.Link) XCTAssertTrue(history.addLocalVisit(local).value.isSuccess) } } class TestSQLiteHistoryFrecencyPerf: XCTestCase { func testFrecencyPerf() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs)! let count = 500 history.clearHistory().value populateHistoryForFrecencyCalcuations(history, siteCount: count) self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) { for _ in 0...5 { history.getSitesByFrecencyWithLimit(10, includeIcon: false).value } self.stopMeasuring() } } } class TestSQLiteHistoryTopSitesCachePref: XCTestCase { func testCachePerf() { let files = MockFiles() let db = BrowserDB(filename: "browser.db", files: files) let prefs = MockProfilePrefs() let history = SQLiteHistory(db: db, prefs: prefs)! let count = 500 history.clearHistory().value populateHistoryForFrecencyCalcuations(history, siteCount: count) history.setTopSitesNeedsInvalidation() self.measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true) { history.invalidateTopSitesIfNeeded().value self.stopMeasuring() } } } // MARK - Private Test Helper Methods private enum VisitOrigin { case Local case Remote } private func populateHistoryForFrecencyCalcuations(history: SQLiteHistory, siteCount count: Int) { for i in 0...count { let site = Site(url: "http://s\(i)ite\(i)/foo", title: "A \(i)") site.guid = "abc\(i)def" history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).value for j in 0...20 { let visitTime = Timestamp(1000 * (1437088398461 + (1000 * i) + j)) addVisitForSite(site, intoHistory: history, from: .Local, atTime: visitTime) addVisitForSite(site, intoHistory: history, from: .Remote, atTime: visitTime) } } } private func addVisitForSite(site: Site, intoHistory history: SQLiteHistory, from: VisitOrigin, atTime: Timestamp) { let visit = SiteVisit(site: site, date: atTime, type: VisitType.Link) switch from { case .Local: history.addLocalVisit(visit).value case .Remote: history.storeRemoteVisits([visit], forGUID: site.guid!).value } }
mpl-2.0
2321272596d707c3ffa8f51cc39f30e9
39.372414
182
0.572582
4.808996
false
false
false
false
YMXian/Deliria
Deliria/Deliria/Crypto/Updatable.swift
1
2826
// // Updatable.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 06/05/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // // TODO: Consider if Updatable shoud use Collection rather than Sequence // /// A type that supports incremental updates. For example Digest or Cipher may be updatable /// and calculate result incerementally. public protocol Updatable { /// Update given bytes in chunks. /// /// - parameter bytes: Bytes to process /// - parameter isLast: (Optional) Given chunk is the last one. No more updates after this call. /// - returns: Processed data or empty array. mutating func update<T: Sequence>(withBytes bytes:T, isLast: Bool) throws -> Array<UInt8> where T.Iterator.Element == UInt8 /// Update given bytes in chunks. /// /// - parameter bytes: Bytes to process /// - parameter isLast: (Optional) Given chunk is the last one. No more updates after this call. /// - parameter output: Resulting data /// - returns: Processed data or empty array. mutating func update<T: Sequence>(withBytes bytes:T, isLast: Bool, output: (Array<UInt8>) -> Void) throws where T.Iterator.Element == UInt8 /// Finish updates. This may apply padding. /// - parameter bytes: Bytes to process /// - returns: Processed data. mutating func finish<T: Sequence>(withBytes bytes:T) throws -> Array<UInt8> where T.Iterator.Element == UInt8 /// Finish updates. This may apply padding. /// - parameter bytes: Bytes to process /// - parameter output: Resulting data /// - returns: Processed data. mutating func finish<T: Sequence>(withBytes bytes:T, output: (Array<UInt8>) -> Void) throws where T.Iterator.Element == UInt8 } extension Updatable { mutating public func update<T: Sequence>(withBytes bytes:T, isLast: Bool = false, output: (Array<UInt8>) -> Void) throws where T.Iterator.Element == UInt8 { let processed = try self.update(withBytes: bytes, isLast: isLast) if (!processed.isEmpty) { output(processed) } } mutating public func finish<T: Sequence>(withBytes bytes:T) throws -> Array<UInt8> where T.Iterator.Element == UInt8 { return try self.update(withBytes: bytes, isLast: true) } mutating public func finish() throws -> Array<UInt8> { return try self.update(withBytes: [], isLast: true) } mutating public func finish<T: Sequence>(withBytes bytes:T, output: (Array<UInt8>) -> Void) throws where T.Iterator.Element == UInt8 { let processed = try self.update(withBytes: bytes, isLast: true) if (!processed.isEmpty) { output(processed) } } mutating public func finish(output: (Array<UInt8>) -> Void) throws { try self.finish(withBytes: [], output: output) } }
mit
b739ca07b35e61fe52110b606df13255
41.164179
160
0.669381
4.16053
false
false
false
false
aschwaighofer/swift
test/Driver/Dependencies/fail-added-fine.swift
2
1956
/// bad ==> main | bad --> other // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-simple-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s // CHECK-INITIAL-NOT: warning // CHECK-INITIAL: Handled main.swift // CHECK-INITIAL: Handled other.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s // RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps // CHECK-ADDED-NOT: Handled // CHECK-ADDED: Handled bad.swift // CHECK-ADDED-NOT: Handled // CHECK-RECORD-ADDED-DAG: "./bad.swift": !private [ // CHECK-RECORD-ADDED-DAG: "./main.swift": [ // CHECK-RECORD-ADDED-DAG: "./other.swift": [ // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-simple-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./bad.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s // RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps
apache-2.0
eb8d9a2d0ed234dfa34937a1ac782de1
60.125
303
0.701431
3.051482
false
false
false
false
Johennes/firefox-ios
Sync/BatchingClient.swift
1
8244
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Alamofire import Shared import XCGLogger import Deferred public class SerializeRecordFailure<T: CleartextPayloadJSON>: MaybeErrorType { public let record: Record<T> public var description: String { return "Failed to serialize record: \(record)" } public init(record: Record<T>) { self.record = record } } private let log = Logger.syncLogger private typealias UploadRecord = (guid: GUID, payload: String, sizeBytes: Int) private typealias DeferredResponse = Deferred<Maybe<StorageResponse<POSTResult>>> typealias BatchUploadFunction = (lines: [String], ifUnmodifiedSince: Timestamp?, queryParams: [NSURLQueryItem]?) -> Deferred<Maybe<StorageResponse<POSTResult>>> private let commitParam = NSURLQueryItem(name: "commit", value: "true") private enum AccumulateRecordError: MaybeErrorType { var description: String { switch self { case .Full: return "Batch or payload is full." case .Unknown: return "Unknown errored while trying to accumulate records in batch" } } case Full(uploadOp: DeferredResponse) case Unknown } public class Sync15BatchClient<T: CleartextPayloadJSON> { private(set) var ifUnmodifiedSince: Timestamp? private let config: InfoConfiguration private let uploader: BatchUploadFunction private let serializeRecord: (Record<T>) -> String? private var batchToken: BatchToken? // Keep track of the limits of a single batch private var totalBytes: ByteCount = 0 private var totalRecords: Int = 0 // Keep track of the limits of a single POST private var postBytes: ByteCount = 0 private var postRecords: Int = 0 private var records = [UploadRecord]() private var onCollectionUploaded: (POSTResult, Timestamp?) -> DeferredTimestamp private func batchQueryParamWithValue(value: String) -> NSURLQueryItem { return NSURLQueryItem(name: "batch", value: value) } init(config: InfoConfiguration, ifUnmodifiedSince: Timestamp? = nil, serializeRecord: (Record<T>) -> String?, uploader: BatchUploadFunction, onCollectionUploaded: (POSTResult, Timestamp?) -> DeferredTimestamp) { self.config = config self.ifUnmodifiedSince = ifUnmodifiedSince self.uploader = uploader self.serializeRecord = serializeRecord self.onCollectionUploaded = onCollectionUploaded } public func endBatch() -> Success { guard !records.isEmpty else { return succeed() } if let token = self.batchToken { return commitBatch(token) >>> succeed } let lines = self.freezePost() return self.uploader(lines: lines, ifUnmodifiedSince: self.ifUnmodifiedSince, queryParams: nil) >>== effect(moveForward) >>> succeed } public func addRecords(records: [Record<T>]) -> Success { guard !records.isEmpty else { return succeed() } do { // Eagerly serializer the record prior to processing them so we can catch any issues // with record sizes before we start uploading to the server. let serialized = try records.map { try serialize($0) } return addRecords(serialized.generate()) } catch let e { return deferMaybe(e as! MaybeErrorType) } } private func addRecords(generator: IndexingGenerator<[UploadRecord]>) -> Success { var mutGenerator = generator while let record = mutGenerator.next() { return accumulateOrUpload(record) >>> { self.addRecords(mutGenerator) } } return succeed() } private func accumulateOrUpload(record: UploadRecord) -> Success { do { // Try to add the record to our buffer try accumulateRecord(record) } catch AccumulateRecordError.Full(let uploadOp) { // When we're full, run the upload and try to add the record // after uploading since we've made room for it. return uploadOp >>> { self.accumulateOrUpload(record) } } catch let e { // Should never happen. return deferMaybe(e as! MaybeErrorType) } return succeed() } private func accumulateRecord(record: UploadRecord) throws { guard let token = self.batchToken else { guard addToPost(record) else { throw AccumulateRecordError.Full(uploadOp: self.start()) } return } guard fitsInBatch(record) else { throw AccumulateRecordError.Full(uploadOp: self.commitBatch(token)) } guard addToPost(record) else { throw AccumulateRecordError.Full(uploadOp: self.postInBatch(token)) } addToBatch(record) } private func serialize(record: Record<T>) throws -> UploadRecord { guard let line = self.serializeRecord(record) else { throw SerializeRecordFailure(record: record) } let lineSize = line.utf8.count guard lineSize < Sync15StorageClient.maxRecordSizeBytes else { throw RecordTooLargeError(size: lineSize, guid: record.id) } return (record.id, line, lineSize) } private func addToPost(record: UploadRecord) -> Bool { guard postRecords + 1 <= config.maxPostRecords && postBytes + record.sizeBytes <= config.maxPostBytes else { return false } postRecords += 1 postBytes += record.sizeBytes records.append(record) return true } private func fitsInBatch(record: UploadRecord) -> Bool { return totalRecords + 1 <= config.maxTotalRecords && totalBytes + record.sizeBytes <= config.maxTotalBytes } private func addToBatch(record: UploadRecord) { totalRecords += 1 totalBytes += record.sizeBytes } private func postInBatch(token: BatchToken) -> DeferredResponse { // Push up the current payload to the server and reset let lines = self.freezePost() return uploader(lines: lines, ifUnmodifiedSince: self.ifUnmodifiedSince, queryParams: [batchQueryParamWithValue(token)]) } private func commitBatch(token: BatchToken) -> DeferredResponse { resetBatch() let lines = self.freezePost() let queryParams = [batchQueryParamWithValue(token), commitParam] return uploader(lines: lines, ifUnmodifiedSince: self.ifUnmodifiedSince, queryParams: queryParams) >>== effect(moveForward) } private func start() -> DeferredResponse { let postRecordCount = self.postRecords let postBytesCount = self.postBytes let lines = freezePost() return self.uploader(lines: lines, ifUnmodifiedSince: self.ifUnmodifiedSince, queryParams: [batchQueryParamWithValue("true")]) >>== effect(moveForward) >>== { response in if let token = response.value.batchToken { self.batchToken = token // Now that we've started a batch, make sure to set the counters for the batch to include // the records we just sent as part of the start call. self.totalRecords = postRecordCount self.totalBytes = postBytesCount } return deferMaybe(response) } } private func moveForward(response: StorageResponse<POSTResult>) { let lastModified = response.metadata.lastModifiedMilliseconds self.ifUnmodifiedSince = lastModified self.onCollectionUploaded(response.value, lastModified) } private func resetBatch() { totalBytes = 0 totalRecords = 0 self.batchToken = nil } private func freezePost() -> [String] { let lines = records.map { $0.payload } self.records = [] self.postBytes = 0 self.postRecords = 0 return lines } }
mpl-2.0
9eae7ead2d4429e7b0a094447c6e7e69
33.638655
160
0.643498
4.898396
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SpreadsheetView-master/Framework/Sources/ReuseQueue.swift
3
1501
// // ReuseQueue.swift // SpreadsheetView // // Created by Kishikawa Katsumi on 4/16/17. // Copyright © 2017 Kishikawa Katsumi. All rights reserved. // import Foundation final class ReuseQueue<Reusable> where Reusable: NSObject { var reusableObjects = Set<Reusable>() func enqueue(_ reusableObject: Reusable) { reusableObjects.insert(reusableObject) } func dequeue() -> Reusable? { if let _ = reusableObjects.first { return reusableObjects.removeFirst() } return nil } func dequeueOrCreate() -> Reusable { if let _ = reusableObjects.first { return reusableObjects.removeFirst() } return Reusable() } } final class ReusableCollection<Reusable>: Sequence where Reusable: NSObject { var pairs = [Address: Reusable]() var addresses = Set<Address>() func contains(_ member: Address) -> Bool { return addresses.contains(member) } @discardableResult func insert(_ newMember: Address) -> (inserted: Bool, memberAfterInsert: Address) { return addresses.insert(newMember) } func subtract(_ other: Set<Address>) { addresses.subtract(other) } subscript(key: Address) -> Reusable? { get { return pairs[key] } set(newValue) { pairs[key] = newValue } } func makeIterator() -> AnyIterator<Reusable> { return AnyIterator(pairs.values.makeIterator()) } }
mit
dbe43920c4ba2d5c70d0abecc0238779
23.193548
87
0.616667
4.573171
false
false
false
false
AdilVirani/WWDC-2015
Adil Virani/AdilVirani/Adil Virani/ContactViewController.swift
2
3759
// // ContactViewController.swift // Adil Virani // // Created by Adil Virani on 4/24/15. // Copyright (c) 2015 Adil Virani. All rights reserved. // import UIKit class ContactViewController: UIViewController { var contacts = [] override func viewDidLoad() { super.viewDidLoad() insertData() } override func viewWillAppear(animated: Bool) { self.navigationController?.navigationBarHidden = false; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return contacts.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Contact Me" } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: ContactTableViewCell let contactClass = ContactManager(dictionary: contacts[indexPath.row] as! NSDictionary) if(indexPath.row == 0) { cell = tableView.dequeueReusableCellWithIdentifier("cellTop") as! ContactTableViewCell cell.contactName.text = contactClass.nameContact cell.contactImage.image = UIImage(named:contactClass.imageIcon!) cell.contactImage.layer.cornerRadius = cell.contactImage.frame.size.width / 2; cell.contactImage.clipsToBounds = true; } else { cell = tableView.dequeueReusableCellWithIdentifier("cellContacts") as! ContactTableViewCell cell.contactUrl.text = contactClass.nameContact cell.contactIcon.image = UIImage(named:contactClass.imageIcon!) } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if(indexPath.row == 0) { return 120 } else { return 55 } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let contactClass = ContactManager(dictionary: contacts[indexPath.row] as! NSDictionary) if(indexPath.row == 1) { UIApplication.sharedApplication().openURL(NSURL(string: "mailto:" + contactClass.urlContact!)!) } else if(indexPath.row == 2) { UIApplication.sharedApplication().openURL(NSURL(string: "tel://" + contactClass.urlContact!)!) } else { UIApplication.sharedApplication().openURL(NSURL(string: contactClass.urlContact!)!) } } func insertData() { var one = ["Icon":"profile-image","Name":"Adil Sikander Virani", "Url":""] var fb = ["Icon":"fb-icon","Name":"/adisv9997", "Url":"http://fb.com/adisv9997"] var twitter = ["Icon":"twitter-icon","Name":"/adisv9997", "Url":"https://twitter.com/adisv9997"] var linkedin = ["Icon":"linkedin-icon","Name":"/adisv9997", "Url":"https://br.linkedin.com/in/adisv9997"] var instagram = ["Icon":"instagram-icon","Name":"/adil_virani", "Url":"http://instagram.com/adil_virani"] var mail = ["Icon":"mail-icon","Name":"[email protected]", "Url":"[email protected]"] var phone = ["Icon":"phone-icon","Name":"214-436-1433", "Url":"2144361433"] var github = ["Icon":"github-icon","Name":"/AdilVirani", "Url":"https://github.com/AdilVirani"] var bitbucket = ["Icon":"bitbucket-icon","Name":"/AdilVirani", "Url":"https://bitbucket.org/AdilVirani/"] contacts = [one, mail, phone, linkedin, github, bitbucket, instagram, fb, twitter] } }
apache-2.0
b9e745a293242b6255dafa2f597093c7
38.166667
113
0.639266
4.469679
false
false
false
false
hsusmita/MultiStepSlider
MultiStepSlider/ViewController.swift
1
2304
// // ViewController.swift // MultiStepSlider // // Created by Susmita Horrow on 11/01/16. // Copyright © 2016 hsusmita. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var minimumLabel: UILabel! @IBOutlet weak var maximimLabel: UILabel! @IBOutlet weak var slider: MultiStepRangeSlider! let numberFomatter = NumberFormatter() override func viewDidLoad() { super.viewDidLoad() let intervals = [Interval(min: 50000, max: 100000, stepValue: 10000), Interval(min: 100000, max: 1000000, stepValue: 100000), Interval(min: 1000000, max: 3000000, stepValue: 500000)] let preSelectedRange = RangeValue(lower: 80000, upper: 500000) slider.configureSlider(intervals: intervals, preSelectedRange: preSelectedRange) minimumLabel.text = abbreviateNumber(NSNumber(value: slider.discreteCurrentValue.lower as Float)) as String maximimLabel.text = abbreviateNumber(NSNumber(value: slider.discreteCurrentValue.upper as Float)) as String } @IBAction func handleSliderChange(_ sender: AnyObject) { minimumLabel.text = abbreviateNumber(NSNumber(value: slider.discreteCurrentValue.lower as Float)) as String maximimLabel.text = abbreviateNumber(NSNumber(value: slider.discreteCurrentValue.upper as Float)) as String print("lower = \(slider.continuousCurrentValue.lower) higher = \(slider.continuousCurrentValue.upper)") } } //http://stackoverflow.com/questions/18267211/ios-convert-large-numbers-to-smaller-format func abbreviateNumber(_ num: NSNumber) -> NSString { var ret: NSString = "" let abbrve: [String] = ["K", "M", "B"] let floatNum = num.floatValue if floatNum > 1000 { for i in 0..<abbrve.count { let size = pow(10.0, (Float(i) + 1.0) * 3.0) if (size <= floatNum) { let num = floatNum / size let str = floatToString(num) ret = NSString(format: "%@%@", str, abbrve[i]) } } } else { ret = NSString(format: "%d", Int(floatNum)) } return ret } func floatToString(_ val: Float) -> NSString { var ret = NSString(format: "%.1f", val) var c = ret.character(at: ret.length - 1) while c == 48 { ret = ret.substring(to: ret.length - 1) as NSString c = ret.character(at: ret.length - 1) if (c == 46) { ret = ret.substring(to: ret.length - 1) as NSString } } return ret }
mit
98d1803e800cbadbdeabeb2ca396a67b
28.525641
109
0.707772
3.342525
false
false
false
false
gaurav1981/Nuke
Sources/Loader.swift
1
5241
// The MIT License (MIT) // // Copyright (c) 2017 Alexander Grebenyuk (github.com/kean). import Foundation /// Loads images. public protocol Loading { /// Loads an image with the given request. /// /// Loader doesn't make guarantees on which thread the completion /// closure is called and whether it gets called or not after /// the operation gets cancelled. func loadImage(with request: Request, token: CancellationToken?, completion: @escaping (Result<Image>) -> Void) } public extension Loading { /// Loads an image with the given request. public func loadImage(with request: Request, completion: @escaping (Result<Image>) -> Void) { loadImage(with: request, token: nil, completion: completion) } /// Loads an image with the given url. public func loadImage(with url: URL, token: CancellationToken? = nil, completion: @escaping (Result<Image>) -> Void) { loadImage(with: Request(url: url), token: token, completion: completion) } } /// `Loader` implements an image loading pipeline: /// /// 1. Load data using an object conforming to `DataLoading` protocol. /// 2. Create an image with the data using `DataDecoding` object. /// 3. Transform the image using processor (`Processing`) provided in the request. /// /// `Loader` is thread-safe. public final class Loader: Loading { private let loader: DataLoading private let decoder: DataDecoding private let schedulers: Schedulers private let queue = DispatchQueue(label: "com.github.kean.Nuke.Loader") /// Returns a processor for the given image and request. Default /// implementation simply returns `request.processor`. public var makeProcessor: (Image, Request) -> AnyProcessor? = { return $1.processor } /// Shared `Loading` object. /// /// Shared loader is created with `DataLoader()` wrapped in `Deduplicator`. public static let shared: Loading = Deduplicator(loader: Loader(loader: DataLoader())) /// Initializes `Loader` instance with the given loader, decoder. /// - parameter decoder: `DataDecoder()` by default. /// - parameter schedulers: `Schedulers()` by default. public init(loader: DataLoading, decoder: DataDecoding = DataDecoder(), schedulers: Schedulers = Schedulers()) { self.loader = loader self.decoder = decoder self.schedulers = schedulers } /// Loads an image for the given request using image loading pipeline. public func loadImage(with request: Request, token: CancellationToken?, completion: @escaping (Result<Image>) -> Void) { queue.async { if token?.isCancelling == true { return } // Fast preflight check self.loadImage(with: Context(request: request, token: token, completion: completion)) } } private func loadImage(with ctx: Context) { self.loader.loadData(with: ctx.request, token: ctx.token) { [weak self] in switch $0 { case let .success(val): self?.decode(response: val, context: ctx) case let .failure(err): ctx.completion(.failure(err)) } } } private func decode(response: (Data, URLResponse), context ctx: Context) { queue.async { self.schedulers.decoding.execute(token: ctx.token) { [weak self] in if let image = self?.decoder.decode(data: response.0, response: response.1) { self?.process(image: image, context: ctx) } else { ctx.completion(.failure(Error.decodingFailed)) } } } } private func process(image: Image, context ctx: Context) { queue.async { guard let processor = self.makeProcessor(image, ctx.request) else { ctx.completion(.success(image)) // no need to process return } self.schedulers.processing.execute(token: ctx.token) { if let image = processor.process(image) { ctx.completion(.success(image)) } else { ctx.completion(.failure(Error.processingFailed)) } } } } private struct Context { let request: Request let token: CancellationToken? let completion: (Result<Image>) -> Void } /// Schedulers used to execute a corresponding steps of the pipeline. public struct Schedulers { /// `DispatchQueueScheduler` with a serial queue by default. public var decoding: Scheduler = DispatchQueueScheduler(queue: DispatchQueue(label: "com.github.kean.Nuke.Decoding")) // There is no reason to increase `maxConcurrentOperationCount` for // built-in `DataDecoder` that locks globally while decoding. /// `DispatchQueueScheduler` with a serial queue by default. public var processing: Scheduler = DispatchQueueScheduler(queue: DispatchQueue(label: "com.github.kean.Nuke.Processing")) } /// Error returns by `Loader` class itself. `Loader` might also return /// errors from underlying `DataLoading` object. public enum Error: Swift.Error { case decodingFailed case processingFailed } }
mit
c405fe9c04b7f014c658c50a496bf269
39.315385
129
0.642053
4.593339
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/MachineLearning/MachineLearning_Error.swift
1
3477
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for MachineLearning public struct MachineLearningErrorType: AWSErrorType { enum Code: String { case idempotentParameterMismatchException = "IdempotentParameterMismatchException" case internalServerException = "InternalServerException" case invalidInputException = "InvalidInputException" case invalidTagException = "InvalidTagException" case limitExceededException = "LimitExceededException" case predictorNotMountedException = "PredictorNotMountedException" case resourceNotFoundException = "ResourceNotFoundException" case tagLimitExceededException = "TagLimitExceededException" } private let error: Code public let context: AWSErrorContext? /// initialize MachineLearning public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// A second request to use or change an object was not allowed. This can result from retrying a request using a parameter that was not present in the original request. public static var idempotentParameterMismatchException: Self { .init(.idempotentParameterMismatchException) } /// An error on the server occurred when trying to process a request. public static var internalServerException: Self { .init(.internalServerException) } /// An error on the client occurred. Typically, the cause is an invalid input value. public static var invalidInputException: Self { .init(.invalidInputException) } public static var invalidTagException: Self { .init(.invalidTagException) } /// The subscriber exceeded the maximum number of operations. This exception can occur when listing objects such as DataSource. public static var limitExceededException: Self { .init(.limitExceededException) } /// The exception is thrown when a predict request is made to an unmounted MLModel. public static var predictorNotMountedException: Self { .init(.predictorNotMountedException) } /// A specified resource cannot be located. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } public static var tagLimitExceededException: Self { .init(.tagLimitExceededException) } } extension MachineLearningErrorType: Equatable { public static func == (lhs: MachineLearningErrorType, rhs: MachineLearningErrorType) -> Bool { lhs.error == rhs.error } } extension MachineLearningErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
e7e86980ea55d66e206981eb5e05251b
44.75
172
0.704918
5.341014
false
false
false
false
tjw/swift
test/expr/cast/nil_value_to_optional.swift
2
901
// RUN: %target-typecheck-verify-swift var t = true var f = false func markUsed<T>(_ t: T) {} markUsed(t != nil) // expected-warning {{comparing non-optional value of type 'Bool' to nil always returns true}} markUsed(f != nil) // expected-warning {{comparing non-optional value of type 'Bool' to nil always returns true}} class C : Equatable {} func == (lhs: C, rhs: C) -> Bool { return true } func test(_ c: C) { if c == nil {} // expected-warning {{comparing non-optional value of type 'C' to nil always returns false}} } class D {} var d = D() var dopt: D? = nil var diuopt: D! = nil _ = d! // expected-error {{cannot force unwrap value of non-optional type 'D'}} _ = dopt == nil _ = diuopt == nil _ = diuopt is ExpressibleByNilLiteral // expected-warning {{'is' test is always true}} // expected-warning@-1 {{conditional cast from 'D?' to 'ExpressibleByNilLiteral' always succeeds}}
apache-2.0
487870ba2aa6745c67ba5576c99caca4
28.064516
113
0.665927
3.324723
false
true
false
false
recoveryrecord/SurveyNative
SurveyNative/Classes/TableViewCells/DatePickerViewController.swift
1
2055
// // DatePickerViewController.swift // SurveyNative // // Created by Nora Mullaney on 1/31/17. // Copyright © 2017 Recovery Record. All rights reserved. // import UIKit class DatePickerViewController: UIViewController { @IBOutlet var datePickerView: UIDatePicker? var controllerDelegate: DatePickerViewControllerDelegate? var currentDate: Date? { didSet { datePickerView?.date = currentDate! } } var minDate: Date? { didSet { datePickerView?.minimumDate = minDate } } var maxDate: Date? { didSet { datePickerView?.maximumDate = maxDate } } override func viewDidLoad() { super.viewDidLoad() datePickerView?.date = currentDate ?? Date() datePickerView?.datePickerMode = UIDatePicker.Mode.date datePickerView?.minimumDate = minDate datePickerView?.maximumDate = maxDate if #available(iOS 13.4, *) { datePickerView?.preferredDatePickerStyle = .wheels } else { // Fallback on earlier versions } setColors() } func setColors() { if #available(iOS 12.0, *) { if traitCollection.userInterfaceStyle == .dark { datePickerView?.backgroundColor = UIColor.black } else { datePickerView?.backgroundColor = UIColor.white } } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) setColors() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func doneTapped(_ sender: UIButton) { controllerDelegate?.onDone(selectedDate: datePickerView?.date) } } public protocol DatePickerViewControllerDelegate : NSObjectProtocol { func onDone(selectedDate: Date?); }
mit
5f3b676203a1bbfc6b4b1c3a646c5885
26.756757
91
0.618793
5.581522
false
false
false
false
atrick/swift
benchmark/single-source/SIMDReduceInteger.swift
7
7085
//===--- SIMDReduceInteger.swift ------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let benchmarks = [ BenchmarkInfo( name: "SIMDReduce.Int32", runFunction: run_SIMDReduceInt32x1, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x4.Initializer", runFunction: run_SIMDReduceInt32x4_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x4.Cast", runFunction: run_SIMDReduceInt32x4_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x16.Initializer", runFunction: run_SIMDReduceInt32x16_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int32x16.Cast", runFunction: run_SIMDReduceInt32x16_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int32Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8", runFunction: run_SIMDReduceInt8x1, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x16.Initializer", runFunction: run_SIMDReduceInt8x16_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x16.Cast", runFunction: run_SIMDReduceInt8x16_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x64.Initializer", runFunction: run_SIMDReduceInt8x64_init, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ), BenchmarkInfo( name: "SIMDReduce.Int8x64.Cast", runFunction: run_SIMDReduceInt8x64_cast, tags: [.validation, .SIMD], setUpFunction: { blackHole(int8Data) } ) ] // TODO: use 100 for Onone? let scale = 1000 let int32Data: UnsafeBufferPointer<Int32> = { let count = 256 // Allocate memory for `count` Int32s with alignment suitable for all // SIMD vector types. let untyped = UnsafeMutableRawBufferPointer.allocate( byteCount: MemoryLayout<Int32>.size * count, alignment: 16 ) // Initialize the memory as Int32 and fill with random values. let typed = untyped.initializeMemory(as: Int32.self, repeating: 0) var g = SplitMix64(seed: 0) for i in 0 ..< typed.count { typed[i] = .random(in: .min ... .max, using: &g) } return UnsafeBufferPointer(typed) }() @inline(never) public func run_SIMDReduceInt32x1(_ n: Int) { for _ in 0 ..< scale*n { var accum: Int32 = 0 for v in int32Data { accum &+= v &* v } blackHole(accum) } } @inline(never) public func run_SIMDReduceInt32x4_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD4<Int32>() for i in stride(from: 0, to: int32Data.count, by: 4) { let v = SIMD4(int32Data[i ..< i+4]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt32x4_cast(_ n: Int) { // Morally it seems like we "should" be able to use withMemoryRebound // to SIMD4<Int32>, but that function requires that the sizes match in // debug builds, so this is pretty ugly. The following "works" for now, // but is probably in violation of the formal model (the exact rules // for "assumingMemoryBound" are not clearly documented). We need a // better solution. let vecs = UnsafeBufferPointer<SIMD4<Int32>>( start: UnsafeRawPointer(int32Data.baseAddress!).assumingMemoryBound(to: SIMD4<Int32>.self), count: int32Data.count / 4 ) for _ in 0 ..< scale*n { var accum = SIMD4<Int32>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt32x16_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD16<Int32>() for i in stride(from: 0, to: int32Data.count, by: 16) { let v = SIMD16(int32Data[i ..< i+16]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt32x16_cast(_ n: Int) { let vecs = UnsafeBufferPointer<SIMD16<Int32>>( start: UnsafeRawPointer(int32Data.baseAddress!).assumingMemoryBound(to: SIMD16<Int32>.self), count: int32Data.count / 16 ) for _ in 0 ..< scale*n { var accum = SIMD16<Int32>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } } let int8Data: UnsafeBufferPointer<Int8> = { let count = 1024 // Allocate memory for `count` Int8s with alignment suitable for all // SIMD vector types. let untyped = UnsafeMutableRawBufferPointer.allocate( byteCount: MemoryLayout<Int8>.size * count, alignment: 16 ) // Initialize the memory as Int8 and fill with random values. let typed = untyped.initializeMemory(as: Int8.self, repeating: 0) var g = SplitMix64(seed: 0) for i in 0 ..< typed.count { typed[i] = .random(in: .min ... .max, using: &g) } return UnsafeBufferPointer(typed) }() @inline(never) public func run_SIMDReduceInt8x1(_ n: Int) { for _ in 0 ..< scale*n { var accum: Int8 = 0 for v in int8Data { accum &+= v &* v } blackHole(accum) } } @inline(never) public func run_SIMDReduceInt8x16_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD16<Int8>() for i in stride(from: 0, to: int8Data.count, by: 16) { let v = SIMD16(int8Data[i ..< i+16]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt8x16_cast(_ n: Int) { let vecs = UnsafeBufferPointer<SIMD16<Int8>>( start: UnsafeRawPointer(int8Data.baseAddress!).assumingMemoryBound(to: SIMD16<Int8>.self), count: int8Data.count / 16 ) for _ in 0 ..< scale*n { var accum = SIMD16<Int8>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt8x64_init(_ n: Int) { for _ in 0 ..< scale*n { var accum = SIMD64<Int8>() for i in stride(from: 0, to: int8Data.count, by: 64) { let v = SIMD64(int8Data[i ..< i+64]) accum &+= v &* v } blackHole(accum.wrappedSum()) } } @inline(never) public func run_SIMDReduceInt8x64_cast(_ n: Int) { let vecs = UnsafeBufferPointer<SIMD64<Int8>>( start: UnsafeRawPointer(int8Data.baseAddress!).assumingMemoryBound(to: SIMD64<Int8>.self), count: int8Data.count / 64 ) for _ in 0 ..< scale*n { var accum = SIMD64<Int8>() for v in vecs { accum &+= v &* v } blackHole(accum.wrappedSum()) } }
apache-2.0
93839c83116e503e37472481700e2670
27.684211
96
0.642343
3.407888
false
false
false
false
LeonardoCardoso/SwiftLinkPreview
SwiftLinkPreviewTests/URLs.swift
1
3949
// // URLs.swift // SwiftLinkPreview // // Created by Leonardo Cardoso on 16/07/2016. // Copyright © 2016 leocardz.com. All rights reserved. // import Foundation struct URLs { // Please add the text in the format: // [text, expectation, canonical] // ["xxx https://your.url.com/etc#something?else=true xxx", "https://your.url.com/etc#something?else=true", "your.url.com"] static let bunch = [ [ "aaa www.google.com aaa", "http://www.google.com", "www.google.com" ], [ "bbb https://www.google.com.br/?gfe_rd=cr&ei=iVKKV7nXLcSm8wfE5InADg&gws_rd=ssl bbb", "https://www.google.com.br/?gfe_rd=cr&ei=iVKKV7nXLcSm8wfE5InADg&gws_rd=ssl", "www.google.com.br" ], [ "ccc123 http://google.com qwqwe", "http://google.com", "google.com" ], [ "ddd http://ios.leocardz.com/swift-link-preview/ ddd", "http://ios.leocardz.com/swift-link-preview/", "ios.leocardz.com" ], [ "ddd ios.leocardz.com/swift-link-preview/ ddd", "http://ios.leocardz.com/swift-link-preview/", "ios.leocardz.com" ], [ "ddd ios.leocardz.com ddd", "http://ios.leocardz.com", "ios.leocardz.com" ], [ "eee http://www.nasa.gov/ eee", "http://www.nasa.gov/", "www.nasa.gov" ], [ "fff theverge.com/2016/6/21/11996280/tesla-offer-solar-city-buy fff", "http://theverge.com/2016/6/21/11996280/tesla-offer-solar-city-buy", "theverge.com" ], [ "fff http://theverge.com/2016/6/21/11996280/tesla-offer-solar-city-buy fff", "http://theverge.com/2016/6/21/11996280/tesla-offer-solar-city-buy", "theverge.com" ], [ "ggg http://bit.ly/14SD1eR ggg", "http://bit.ly/14SD1eR", "bit.ly" ], [ "hhh https://twitter.com hhh", "https://twitter.com", "twitter.com" ], [ "hhh twitter.com hhh", "http://twitter.com", "twitter.com" ], [ "iii https://www.nationalgallery.org.uk#2123123?sadasd&asd iii", "https://www.nationalgallery.org.uk#2123123?sadasd&asd", "www.nationalgallery.org.uk" ], [ "jjj http://globo.com jjj", "http://globo.com", "globo.com" ], [ "kkk http://uol.com.br kkk", "http://uol.com.br", "uol.com.br" ], [ "lll http://vnexpress.net/ lll", "http://vnexpress.net/", "vnexpress.net" ], [ "mmm http://www3.nhk.or.jp/ mmm", "http://www3.nhk.or.jp/", "www3.nhk.or.jp" ], [ "nnn http://habrahabr.ru nnn", "http://habrahabr.ru", "habrahabr.ru" ], [ "ooo http://www.youtube.com/watch?v=cv2mjAgFTaI ooo", "http://www.youtube.com/watch?v=cv2mjAgFTaI", "www.youtube.com" ], [ "ppp http://vimeo.com/67992157 ppp", "http://vimeo.com/67992157", "vimeo.com" ], [ "qqq https://lh6.googleusercontent.com/-aDALitrkRFw/UfQEmWPMQnI/AAAAAAAFOlQ/mDh1l4ej15k/w337-h697-no/db1969caa4ecb88ef727dbad05d5b5b3.jpg qqq", "https://lh6.googleusercontent.com/-aDALitrkRFw/UfQEmWPMQnI/AAAAAAAFOlQ/mDh1l4ej15k/w337-h697-no/db1969caa4ecb88ef727dbad05d5b5b3.jpg", "lh6.googleusercontent.com" ], [ "rrr http://goo.gl/jKCPgp rrr", "http://goo.gl/jKCPgp", "goo.gl" ] ] }
mit
f919502a163ed0f68a640636d72d4966
29.604651
155
0.486829
3.079563
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/AppDelegate.swift
1
3713
// // AppDelegate.swift // breadwallet // // Created by Aaron Voisine on 10/5/16. // Copyright (c) 2016-2019 Breadwinner AG. All rights reserved. // import UIKit import LocalAuthentication class AppDelegate: UIResponder, UIApplicationDelegate { private var window: UIWindow? { return applicationController.window } let applicationController = ApplicationController() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { redirectStdOut() UIView.swizzleSetFrame() applicationController.launch(application: application, options: launchOptions) return true } func applicationDidBecomeActive(_ application: UIApplication) { UIApplication.shared.applicationIconBadgeNumber = 0 applicationController.didBecomeActive() } func applicationWillEnterForeground(_ application: UIApplication) { applicationController.willEnterForeground() } func applicationDidEnterBackground(_ application: UIApplication) { applicationController.didEnterBackground() } func applicationWillResignActive(_ application: UIApplication) { applicationController.willResignActive() } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { applicationController.performFetch(completionHandler) } func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplication.ExtensionPointIdentifier) -> Bool { return false // disable extensions such as custom keyboards for security purposes } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { applicationController.application(application, didFailToRegisterForRemoteNotificationsWithError: error) } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { applicationController.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { return applicationController.open(url: url) } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { return applicationController.application(application, continue: userActivity, restorationHandler: restorationHandler) } // stdout is redirected to C.logFilePath for testflight and debug builds private func redirectStdOut() { guard E.isTestFlight else { return } let logFilePath = C.logFilePath let previousLogFilePath = C.previousLogFilePath // If there is already content at C.logFilePath from the previous run of the app, // store that content in C.previousLogFilePath so that we can upload both the previous // and current log from Menu / Developer / Send Logs. if FileManager.default.fileExists(atPath: logFilePath.path) { // save the logging data from the previous run of the app if let logData = try? Data(contentsOf: C.logFilePath) { try? logData.write(to: previousLogFilePath, options: Data.WritingOptions.atomic) } } C.logFilePath.withUnsafeFileSystemRepresentation { _ = freopen($0, "w+", stdout) } } }
mit
d1d9b5e1f682643a285ba026b62e7713
41.193182
167
0.72502
5.93131
false
false
false
false
apple/swift
validation-test/compiler_crashers_2_fixed/0022-rdar21625478.swift
1
11446
// RUN: %target-swift-frontend %s -emit-silgen // rdar://80395274 tracks getting this to pass with the requirement machine. // XFAIL: * // The test hangs in a noassert build: // REQUIRES: asserts import StdlibUnittest public struct MyRange<Bound : ForwardIndex> { var startIndex: Bound var endIndex: Bound } public protocol ForwardIndex : Equatable { associatedtype Distance : SignedNumeric func successor() -> Self } public protocol MySequence { associatedtype Iterator : IteratorProtocol associatedtype SubSequence = Void func makeIterator() -> Iterator var underestimatedCount: Int { get } func map<T>( _ transform: (Iterator.Element) -> T ) -> [T] func filter( _ isIncluded: (Iterator.Element) -> Bool ) -> [Iterator.Element] func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> func _copyContents( initializing ptr: UnsafeMutablePointer<Iterator.Element> ) -> UnsafeMutablePointer<Iterator.Element> } extension MySequence { var underestimatedCount: Int { return 0 } public func map<T>( _ transform: (Iterator.Element) -> T ) -> [T] { return [] } public func filter( _ isIncluded: (Iterator.Element) -> Bool ) -> [Iterator.Element] { return [] } public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } public func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? { return nil } public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> { fatalError() } public func _copyContents( initializing ptr: UnsafeMutablePointer<Iterator.Element> ) -> UnsafeMutablePointer<Iterator.Element> { fatalError() } } public protocol MyIndexable : MySequence { associatedtype Index : ForwardIndex var startIndex: Index { get } var endIndex: Index { get } associatedtype _Element subscript(_: Index) -> _Element { get } } public protocol MyCollection : MyIndexable { associatedtype Iterator : IteratorProtocol = IndexingIterator<Self> associatedtype SubSequence : MySequence subscript(_: Index) -> Iterator.Element { get } subscript(_: MyRange<Index>) -> SubSequence { get } var first: Iterator.Element? { get } var isEmpty: Bool { get } var count: Index.Distance { get } func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? } extension MyCollection { public var isEmpty: Bool { return startIndex == endIndex } public func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? { return preprocess(self) } public var count: Index.Distance { return 0 } public func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? { return nil } } public struct IndexingIterator<I : MyIndexable> : IteratorProtocol { public func next() -> I._Element? { return nil } } protocol Resettable : AnyObject { func reset() } internal var _allResettables: [Resettable] = [] public class TypeIndexed<Value> : Resettable { public init(_ value: Value) { self.defaultValue = value _allResettables.append(self) } public subscript(t: Any.Type) -> Value { get { return byType[ObjectIdentifier(t)] ?? defaultValue } set { byType[ObjectIdentifier(t)] = newValue } } public func reset() { byType = [:] } internal var byType: [ObjectIdentifier:Value] = [:] internal var defaultValue: Value } //===--- LoggingWrappers.swift --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// public protocol Wrapper { associatedtype Base init(_: Base) var base: Base {get set} } public protocol LoggingType : Wrapper { associatedtype Log : AnyObject } extension LoggingType { public var log: Log.Type { return Log.self } public var selfType: Any.Type { return type(of: self) } } public class IteratorLog { public static func dispatchTester<G : IteratorProtocol>( _ g: G ) -> LoggingIterator<LoggingIterator<G>> { return LoggingIterator(LoggingIterator(g)) } public static var next = TypeIndexed(0) } public struct LoggingIterator<Base: IteratorProtocol> : IteratorProtocol, LoggingType { public typealias Log = IteratorLog public init(_ base: Base) { self.base = base } public mutating func next() -> Base.Element? { Log.next[selfType] += 1 return base.next() } public var base: Base } public class SequenceLog { public static func dispatchTester<S: MySequence>( _ s: S ) -> LoggingSequence<LoggingSequence<S>> { return LoggingSequence(LoggingSequence(s)) } public static var iterator = TypeIndexed(0) public static var underestimatedCount = TypeIndexed(0) public static var map = TypeIndexed(0) public static var filter = TypeIndexed(0) public static var _customContainsEquatableElement = TypeIndexed(0) public static var _preprocessingPass = TypeIndexed(0) public static var _copyToContiguousArray = TypeIndexed(0) public static var _copyContents = TypeIndexed(0) } public protocol LoggingSequenceType : MySequence, LoggingType { associatedtype Base : MySequence associatedtype Log : AnyObject = SequenceLog associatedtype Iterator : IteratorProtocol = LoggingIterator<Base.Iterator> } extension LoggingSequenceType { public var underestimatedCount: Int { SequenceLog.underestimatedCount[selfType] += 1 return base.underestimatedCount } } extension LoggingSequenceType where Log == SequenceLog, Iterator == LoggingIterator<Base.Iterator> { public func makeIterator() -> LoggingIterator<Base.Iterator> { Log.iterator[selfType] += 1 return LoggingIterator(base.makeIterator()) } public func map<T>( _ transform: (Base.Iterator.Element) -> T ) -> [T] { Log.map[selfType] += 1 return base.map(transform) } public func filter( _ isIncluded: (Base.Iterator.Element) -> Bool ) -> [Base.Iterator.Element] { Log.filter[selfType] += 1 return base.filter(isIncluded) } public func _customContainsEquatableElement( _ element: Base.Iterator.Element ) -> Bool? { Log._customContainsEquatableElement[selfType] += 1 return base._customContainsEquatableElement(element) } /// If `self` is multi-pass (i.e., a `Collection`), invoke /// `preprocess` on `self` and return its result. Otherwise, return /// `nil`. public func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? { Log._preprocessingPass[selfType] += 1 return base._preprocessingPass { _ in preprocess(self) } } /// Create a native array buffer containing the elements of `self`, /// in the same order. public func _copyToContiguousArray() -> ContiguousArray<Base.Iterator.Element> { Log._copyToContiguousArray[selfType] += 1 return base._copyToContiguousArray() } /// Copy a Sequence into an array. public func _copyContents( initializing ptr: UnsafeMutablePointer<Base.Iterator.Element> ) -> UnsafeMutablePointer<Base.Iterator.Element> { Log._copyContents[selfType] += 1 return base._copyContents(initializing: ptr) } } public struct LoggingSequence< Base_: MySequence > : LoggingSequenceType, MySequence { public typealias Log = SequenceLog public typealias Base = Base_ public init(_ base: Base_) { self.base = base } public var base: Base_ } public class CollectionLog : SequenceLog { public class func dispatchTester<C: MyCollection>( _ c: C ) -> LoggingCollection<LoggingCollection<C>> { return LoggingCollection(LoggingCollection(c)) } static var startIndex = TypeIndexed(0) static var endIndex = TypeIndexed(0) static var subscriptIndex = TypeIndexed(0) static var subscriptRange = TypeIndexed(0) static var isEmpty = TypeIndexed(0) static var count = TypeIndexed(0) static var _customIndexOfEquatableElement = TypeIndexed(0) static var first = TypeIndexed(0) } public protocol LoggingCollectionType : LoggingSequenceType, MyCollection { associatedtype Base : MyCollection associatedtype Index : ForwardIndex = Base.Index } extension LoggingCollectionType where Index == Base.Index { public var startIndex: Base.Index { CollectionLog.startIndex[selfType] += 1 return base.startIndex } public var endIndex: Base.Index { CollectionLog.endIndex[selfType] += 1 return base.endIndex } public subscript(position: Base.Index) -> Base.Iterator.Element { CollectionLog.subscriptIndex[selfType] += 1 return base[position] } public subscript(_prext_bounds: MyRange<Base.Index>) -> Base.SubSequence { CollectionLog.subscriptRange[selfType] += 1 return base[_prext_bounds] } public var isEmpty: Bool { CollectionLog.isEmpty[selfType] += 1 return base.isEmpty } public var count: Base.Index.Distance { CollectionLog.count[selfType] += 1 return base.count } public func _customIndexOfEquatableElement(_ element: Base.Iterator.Element) -> Base.Index?? { CollectionLog._customIndexOfEquatableElement[selfType] += 1 return base._customIndexOfEquatableElement(element) } public var first: Base.Iterator.Element? { CollectionLog.first[selfType] += 1 return base.first } } public struct LoggingCollection<Base_ : MyCollection> : LoggingCollectionType { public typealias Iterator = LoggingIterator<Base.Iterator> public typealias Log = CollectionLog public typealias Base = Base_ public typealias SubSequence = Base.SubSequence public func makeIterator() -> Iterator { return Iterator(base.makeIterator()) } public init(_ base: Base_) { self.base = base } public var base: Base_ } public func expectCustomizable< T : Wrapper >(_: T, _ counters: TypeIndexed<Int>, stackTrace: SourceLocStack? = nil, file: String = #file, line: UInt = #line, collectMoreInfo: (()->String)? = nil ) where T : LoggingType, T.Base : Wrapper, T.Base : LoggingType, T.Log == T.Base.Log { expectNotEqual( 0, counters[T.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) expectEqual( counters[T.self], counters[T.Base.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) } public func expectNotCustomizable< T : Wrapper >(_: T, _ counters: TypeIndexed<Int>, stackTrace: SourceLocStack? = nil, file: String = #file, line: UInt = #line, collectMoreInfo: (()->String)? = nil ) where T : LoggingType, T.Base : Wrapper, T.Base : LoggingType, T.Log == T.Base.Log { expectNotEqual( 0, counters[T.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) expectEqual( 0, counters[T.Base.self], collectMoreInfo?() ?? "", stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line) }
apache-2.0
8d856cdbe55e22c14f3e4e96985e8f82
25.312644
96
0.68714
4.362043
false
false
false
false
danielsaidi/iExtra
iExtraTests/Files/AppFileManagerDefaultTests.swift
1
6406
// // AppFileManagerDefaultTests.swift // iExtra // // Created by Daniel Saidi on 2016-12-19. // Copyright © 2018 Daniel Saidi. All rights reserved. // import Quick import Nimble import iExtra class AppFileManagerDefaultTests: QuickSpec { override func spec() { describe("default global file manager") { var manager = AppFileManagerDefault() let directory = FileManager.SearchPathDirectory.documentDirectory let directoryUrl = FileManager.default.urls(for: directory, in: .userDomainMask).last! let fileNames = ["file1", "file2"] func createFiles() { fileNames.forEach { _ = manager.createFile(at: url(for: $0), contents: nil) } } func createFile(named name: String, contents: Data?) -> Bool { return manager.createFile(at: url(for: name), contents: contents) } func url(for fileName: String) -> URL { return directoryUrl.appendingPathComponent(fileName) } afterEach { fileNames.forEach { _ = manager.removeFile(at: url(for: $0)) } } context("document folder url") { it("is resolved for test simulator") { let simulatorPattern = "Library/Developer/CoreSimulator/Devices" let simulatorMatch = directoryUrl.path.contains(simulatorPattern) let devicePattern = "/var/mobile/Containers" let deviceMatch = directoryUrl.path.contains(devicePattern) let match = simulatorMatch || deviceMatch expect(match).to(beTrue()) } } context("when creating files") { it("can create empty file") { let name = "file1" let didCreate = createFile(named: name, contents: nil) expect(didCreate).to(beTrue()) } it("can create non-empty file") { let name = "file1" let didCreate = createFile(named: name, contents: Data()) expect(didCreate).to(beTrue()) } } context("when checking if files exists") { it("finds existing file") { createFiles() let exists = manager.fileExists(at: url(for: "file1")) expect(exists).to(beTrue()) } it("does not find non-existing file") { let exists = manager.fileExists(at: url(for: "file1")) expect(exists).to(beFalse()) } } context("when getting attributes of file") { it("returns nil if file does not exist") { let url = URL(string: "file:///foo/bar")! let attributes = manager.getAttributesForFile(at: url) expect(attributes).to(beNil()) } it("returns attributes if file exists") { createFiles() let attributes = manager.getAttributesForFile(at: url(for: "file1")) expect(attributes).toNot(beNil()) } it("returns valid attributes if file exists") { createFiles() let attributes = manager.getAttributesForFile(at: url(for: "file1"))! let attribute = attributes[FileAttributeKey.size] as? NSNumber expect(attribute).to(equal(0)) } } context("when getting content of folder") { it("returns urls for existing files") { createFiles() let urls = manager.getContentsOfDirectory(at: directoryUrl) let fileNames = urls.map { $0.lastPathComponent } expect(fileNames).to(contain("file1")) expect(fileNames).to(contain("file2")) } it("returns no urls for no existing files") { let urls = manager.getContentsOfDirectory(at: directoryUrl) let fileNames = urls.map { $0.lastPathComponent } expect(fileNames).toNot(contain("file1")) expect(fileNames).toNot(contain("file2")) } } context("when getting size of file") { it("returns nil if file does not exist") { let url = URL(string: "file:///foo/bar")! let size = manager.getSizeOfFile(at: url) expect(size).to(beNil()) } it("returns zero size if empty file exists") { createFiles() let size = manager.getSizeOfFile(at: url(for: "file1")) expect(size).to(equal(0)) } it("returns non-zero size if empty file exists") { let content = "content".data(using: .utf8) _ = createFile(named: "file1", contents: content) let size = manager.getSizeOfFile(at: url(for: "file1")) expect(size).to(equal(7)) } } context("when removing file") { it("can remove existing file") { createFiles() let didRemove = manager.removeFile(at: url(for: "file1")) expect(didRemove).to(beTrue()) } it("can not remove non-existing file") { let didRemove = manager.removeFile(at: url(for: "file1")) expect(didRemove).to(beFalse()) } } } } }
mit
8d1ba6dc6ccc7bbd88e74df78ff442d0
37.353293
98
0.453084
5.66313
false
false
false
false
hooman/swift
test/Concurrency/Runtime/async_let_fibonacci.swift
2
1278
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime func fib(_ n: Int) -> Int { var first = 0 var second = 1 for _ in 0..<n { let temp = first first = second second = temp + first } return first } @available(SwiftStdlib 5.5, *) func asyncFib(_ n: Int) async -> Int { if n == 0 || n == 1 { return n } async let first = await asyncFib(n-2) async let second = await asyncFib(n-1) // Sleep a random amount of time waiting on the result producing a result. await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000) let result = await first + second // Sleep a random amount of time before producing a result. await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000) return result } @available(SwiftStdlib 5.5, *) func runFibonacci(_ n: Int) async { let result = await asyncFib(n) print() print("Async fib = \(result), sequential fib = \(fib(n))") assert(result == fib(n)) } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await runFibonacci(10) } }
apache-2.0
57cc35efe70625e8b713846172959a97
21.821429
114
0.658059
3.372032
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Inspector/Inspector_Paginator.swift
1
28065
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension Inspector { /// Retrieves the exclusions preview (a list of ExclusionPreview objects) specified by the preview token. You can obtain the preview token by running the CreateExclusionsPreview API. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func getExclusionsPreviewPaginator<Result>( _ input: GetExclusionsPreviewRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, GetExclusionsPreviewResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: getExclusionsPreview, tokenKey: \GetExclusionsPreviewResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func getExclusionsPreviewPaginator( _ input: GetExclusionsPreviewRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (GetExclusionsPreviewResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: getExclusionsPreview, tokenKey: \GetExclusionsPreviewResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the agents of the assessment runs that are specified by the ARNs of the assessment runs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAssessmentRunAgentsPaginator<Result>( _ input: ListAssessmentRunAgentsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAssessmentRunAgentsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAssessmentRunAgents, tokenKey: \ListAssessmentRunAgentsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAssessmentRunAgentsPaginator( _ input: ListAssessmentRunAgentsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAssessmentRunAgentsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAssessmentRunAgents, tokenKey: \ListAssessmentRunAgentsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the assessment runs that correspond to the assessment templates that are specified by the ARNs of the assessment templates. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAssessmentRunsPaginator<Result>( _ input: ListAssessmentRunsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAssessmentRunsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAssessmentRuns, tokenKey: \ListAssessmentRunsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAssessmentRunsPaginator( _ input: ListAssessmentRunsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAssessmentRunsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAssessmentRuns, tokenKey: \ListAssessmentRunsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the ARNs of the assessment targets within this AWS account. For more information about assessment targets, see Amazon Inspector Assessment Targets. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAssessmentTargetsPaginator<Result>( _ input: ListAssessmentTargetsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAssessmentTargetsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAssessmentTargets, tokenKey: \ListAssessmentTargetsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAssessmentTargetsPaginator( _ input: ListAssessmentTargetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAssessmentTargetsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAssessmentTargets, tokenKey: \ListAssessmentTargetsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the assessment templates that correspond to the assessment targets that are specified by the ARNs of the assessment targets. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAssessmentTemplatesPaginator<Result>( _ input: ListAssessmentTemplatesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAssessmentTemplatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAssessmentTemplates, tokenKey: \ListAssessmentTemplatesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAssessmentTemplatesPaginator( _ input: ListAssessmentTemplatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAssessmentTemplatesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAssessmentTemplates, tokenKey: \ListAssessmentTemplatesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists all the event subscriptions for the assessment template that is specified by the ARN of the assessment template. For more information, see SubscribeToEvent and UnsubscribeFromEvent. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listEventSubscriptionsPaginator<Result>( _ input: ListEventSubscriptionsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListEventSubscriptionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listEventSubscriptions, tokenKey: \ListEventSubscriptionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listEventSubscriptionsPaginator( _ input: ListEventSubscriptionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListEventSubscriptionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listEventSubscriptions, tokenKey: \ListEventSubscriptionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// List exclusions that are generated by the assessment run. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listExclusionsPaginator<Result>( _ input: ListExclusionsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListExclusionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listExclusions, tokenKey: \ListExclusionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listExclusionsPaginator( _ input: ListExclusionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListExclusionsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listExclusions, tokenKey: \ListExclusionsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists findings that are generated by the assessment runs that are specified by the ARNs of the assessment runs. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listFindingsPaginator<Result>( _ input: ListFindingsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListFindingsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listFindings, tokenKey: \ListFindingsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listFindingsPaginator( _ input: ListFindingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListFindingsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listFindings, tokenKey: \ListFindingsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists all available Amazon Inspector rules packages. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listRulesPackagesPaginator<Result>( _ input: ListRulesPackagesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListRulesPackagesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listRulesPackages, tokenKey: \ListRulesPackagesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listRulesPackagesPaginator( _ input: ListRulesPackagesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListRulesPackagesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listRulesPackages, tokenKey: \ListRulesPackagesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Previews the agents installed on the EC2 instances that are part of the specified assessment target. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func previewAgentsPaginator<Result>( _ input: PreviewAgentsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, PreviewAgentsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: previewAgents, tokenKey: \PreviewAgentsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func previewAgentsPaginator( _ input: PreviewAgentsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (PreviewAgentsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: previewAgents, tokenKey: \PreviewAgentsResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension Inspector.GetExclusionsPreviewRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Inspector.GetExclusionsPreviewRequest { return .init( assessmentTemplateArn: self.assessmentTemplateArn, locale: self.locale, maxResults: self.maxResults, nextToken: token, previewToken: self.previewToken ) } } extension Inspector.ListAssessmentRunAgentsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Inspector.ListAssessmentRunAgentsRequest { return .init( assessmentRunArn: self.assessmentRunArn, filter: self.filter, maxResults: self.maxResults, nextToken: token ) } } extension Inspector.ListAssessmentRunsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Inspector.ListAssessmentRunsRequest { return .init( assessmentTemplateArns: self.assessmentTemplateArns, filter: self.filter, maxResults: self.maxResults, nextToken: token ) } } extension Inspector.ListAssessmentTargetsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Inspector.ListAssessmentTargetsRequest { return .init( filter: self.filter, maxResults: self.maxResults, nextToken: token ) } } extension Inspector.ListAssessmentTemplatesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Inspector.ListAssessmentTemplatesRequest { return .init( assessmentTargetArns: self.assessmentTargetArns, filter: self.filter, maxResults: self.maxResults, nextToken: token ) } } extension Inspector.ListEventSubscriptionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Inspector.ListEventSubscriptionsRequest { return .init( maxResults: self.maxResults, nextToken: token, resourceArn: self.resourceArn ) } } extension Inspector.ListExclusionsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Inspector.ListExclusionsRequest { return .init( assessmentRunArn: self.assessmentRunArn, maxResults: self.maxResults, nextToken: token ) } } extension Inspector.ListFindingsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Inspector.ListFindingsRequest { return .init( assessmentRunArns: self.assessmentRunArns, filter: self.filter, maxResults: self.maxResults, nextToken: token ) } } extension Inspector.ListRulesPackagesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Inspector.ListRulesPackagesRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension Inspector.PreviewAgentsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> Inspector.PreviewAgentsRequest { return .init( maxResults: self.maxResults, nextToken: token, previewAgentsArn: self.previewAgentsArn ) } }
apache-2.0
85f32b500ed5dd11a2c4b14fa5cf13d4
43.127358
196
0.650383
5.055846
false
false
false
false
vbudhram/firefox-ios
Storage/SQL/BrowserSchema.swift
2
59541
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger let BookmarksFolderTitleMobile: String = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.") let BookmarksFolderTitleMenu: String = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.") let BookmarksFolderTitleToolbar: String = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.") let BookmarksFolderTitleUnsorted: String = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.") let _TableBookmarks = "bookmarks" // Removed in v12. Kept for migration. let TableBookmarksMirror = "bookmarksMirror" // Added in v9. let TableBookmarksMirrorStructure = "bookmarksMirrorStructure" // Added in v10. let TableBookmarksBuffer = "bookmarksBuffer" // Added in v12. bookmarksMirror is renamed to bookmarksBuffer. let TableBookmarksBufferStructure = "bookmarksBufferStructure" // Added in v12. let TableBookmarksLocal = "bookmarksLocal" // Added in v12. Supersedes 'bookmarks'. let TableBookmarksLocalStructure = "bookmarksLocalStructure" // Added in v12. let TablePendingBookmarksDeletions = "pending_deletions" // Added in v28. let TableFavicons = "favicons" let TableHistory = "history" let TableCachedTopSites = "cached_top_sites" let TablePinnedTopSites = "pinned_top_sites" let TableDomains = "domains" let TableVisits = "visits" let TableFaviconSites = "favicon_sites" let TableQueuedTabs = "queue" let TableSyncCommands = "commands" let TableClients = "clients" let TableTabs = "tabs" let TableActivityStreamBlocklist = "activity_stream_blocklist" let TablePageMetadata = "page_metadata" let TableHighlights = "highlights" let TableRemoteDevices = "remote_devices" // Added in v29. let ViewBookmarksBufferOnMirror = "view_bookmarksBuffer_on_mirror" let ViewBookmarksBufferWithDeletionsOnMirror = "view_bookmarksBuffer_with_deletions_on_mirror" let ViewBookmarksBufferStructureOnMirror = "view_bookmarksBufferStructure_on_mirror" let ViewBookmarksLocalOnMirror = "view_bookmarksLocal_on_mirror" let ViewBookmarksLocalStructureOnMirror = "view_bookmarksLocalStructure_on_mirror" let ViewAllBookmarks = "view_all_bookmarks" let ViewAwesomebarBookmarks = "view_awesomebar_bookmarks" let TempTableAwesomebarBookmarks = "awesomebar_bookmarks_temp_table" let ViewAwesomebarBookmarksWithIcons = "view_awesomebar_bookmarks_with_favicons" let ViewHistoryVisits = "view_history_visits" let ViewWidestFaviconsForSites = "view_favicons_widest" let ViewHistoryIDsWithWidestFavicons = "view_history_id_favicon" let ViewIconForURL = "view_icon_for_url" let IndexHistoryShouldUpload = "idx_history_should_upload" let IndexVisitsSiteIDDate = "idx_visits_siteID_date" // Removed in v6. let IndexVisitsSiteIDIsLocalDate = "idx_visits_siteID_is_local_date" // Added in v6. let IndexBookmarksMirrorStructureParentIdx = "idx_bookmarksMirrorStructure_parent_idx" // Added in v10. let IndexBookmarksLocalStructureParentIdx = "idx_bookmarksLocalStructure_parent_idx" // Added in v12. let IndexBookmarksBufferStructureParentIdx = "idx_bookmarksBufferStructure_parent_idx" // Added in v12. let IndexBookmarksMirrorStructureChild = "idx_bookmarksMirrorStructure_child" // Added in v14. let IndexPageMetadataCacheKey = "idx_page_metadata_cache_key_uniqueindex" // Added in v19 let IndexPageMetadataSiteURL = "idx_page_metadata_site_url_uniqueindex" // Added in v21 private let AllTables: [String] = [ TableDomains, TableFavicons, TableFaviconSites, TableHistory, TableVisits, TableCachedTopSites, TableBookmarksBuffer, TableBookmarksBufferStructure, TableBookmarksLocal, TableBookmarksLocalStructure, TableBookmarksMirror, TableBookmarksMirrorStructure, TablePendingBookmarksDeletions, TableQueuedTabs, TableActivityStreamBlocklist, TablePageMetadata, TableHighlights, TablePinnedTopSites, TableRemoteDevices, TableSyncCommands, TableClients, TableTabs, ] private let AllViews: [String] = [ ViewHistoryIDsWithWidestFavicons, ViewWidestFaviconsForSites, ViewIconForURL, ViewBookmarksBufferOnMirror, ViewBookmarksBufferWithDeletionsOnMirror, ViewBookmarksBufferStructureOnMirror, ViewBookmarksLocalOnMirror, ViewBookmarksLocalStructureOnMirror, ViewAllBookmarks, ViewAwesomebarBookmarks, ViewAwesomebarBookmarksWithIcons, ViewHistoryVisits, ] private let AllIndices: [String] = [ IndexHistoryShouldUpload, IndexVisitsSiteIDIsLocalDate, IndexBookmarksBufferStructureParentIdx, IndexBookmarksLocalStructureParentIdx, IndexBookmarksMirrorStructureParentIdx, IndexBookmarksMirrorStructureChild, IndexPageMetadataCacheKey, IndexPageMetadataSiteURL, ] private let AllTablesIndicesAndViews: [String] = AllViews + AllIndices + AllTables private let log = Logger.syncLogger /** * The monolithic class that manages the inter-related history etc. tables. * We rely on SQLiteHistory having initialized the favicon table first. */ open class BrowserSchema: Schema { static let DefaultVersion = 34 // Bug 1409777. public var name: String { return "BROWSER" } public var version: Int { return BrowserSchema.DefaultVersion } let sqliteVersion: Int32 let supportsPartialIndices: Bool public init() { let v = sqlite3_libversion_number() self.sqliteVersion = v self.supportsPartialIndices = v >= 3008000 // 3.8.0. let ver = String(cString: sqlite3_libversion()) log.info("SQLite version: \(ver) (\(v)).") } func run(_ db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool { do { try db.executeChange(sql, withArgs: args) } catch let err as NSError { log.error("Error running SQL in BrowserSchema: \(err.localizedDescription)") log.error("SQL was \(sql)") return false } return true } // TODO: transaction. func run(_ db: SQLiteDBConnection, queries: [(String, Args?)]) -> Bool { for (sql, args) in queries { if !run(db, sql: sql, args: args) { return false } } return true } func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool { for sql in queries { if !run(db, sql: sql) { return false } } return true } func runValidQueries(_ db: SQLiteDBConnection, queries: [(String?, Args?)]) -> Bool { for (sql, args) in queries { if let sql = sql { if !run(db, sql: sql, args: args) { return false } } } return true } func runValidQueries(_ db: SQLiteDBConnection, queries: [String?]) -> Bool { return self.run(db, queries: optFilter(queries)) } func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool { let type = BookmarkNodeType.folder.rawValue let now = Date.nowNumber() let status = SyncStatus.new.rawValue let localArgs: Args = [ BookmarkRoots.RootID, BookmarkRoots.RootGUID, type, now, BookmarkRoots.RootGUID, status, now, BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, now, BookmarkRoots.RootGUID, status, now, BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, now, BookmarkRoots.RootGUID, status, now, BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, now, BookmarkRoots.RootGUID, status, now, BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, now, BookmarkRoots.RootGUID, status, now, ] // Compute these args using the sequence in RootChildren, rather than hard-coding. var idx = 0 var structureArgs = Args() structureArgs.reserveCapacity(BookmarkRoots.RootChildren.count * 3) BookmarkRoots.RootChildren.forEach { guid in structureArgs.append(BookmarkRoots.RootGUID) structureArgs.append(guid) structureArgs.append(idx) idx += 1 } // Note that we specify an empty title and parentName for these records. We should // never need a parentName -- we don't use content-based reconciling or // reparent these -- and we'll use the current locale's string, retrieved // via titleForSpecialGUID, if necessary. let local = "INSERT INTO \(TableBookmarksLocal) " + "(id, guid, type, date_added, parentid, title, parentName, sync_status, local_modified) VALUES " + Array(repeating: "(?, ?, ?, ?, ?, '', '', ?, ?)", count: BookmarkRoots.RootChildren.count + 1).joined(separator: ", ") let structure = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES " + Array(repeating: "(?, ?, ?)", count: BookmarkRoots.RootChildren.count).joined(separator: ", ") return self.run(db, queries: [(local, localArgs), (structure, structureArgs)]) } let topSitesTableCreate = "CREATE TABLE IF NOT EXISTS \(TableCachedTopSites) (" + "historyID INTEGER, " + "url TEXT NOT NULL, " + "title TEXT NOT NULL, " + "guid TEXT NOT NULL UNIQUE, " + "domain_id INTEGER, " + "domain TEXT NO NULL, " + "localVisitDate REAL, " + "remoteVisitDate REAL, " + "localVisitCount INTEGER, " + "remoteVisitCount INTEGER, " + "iconID INTEGER, " + "iconURL TEXT, " + "iconDate REAL, " + "iconType INTEGER, " + "iconWidth INTEGER, " + "frecencies REAL" + ")" let pinnedTopSitesTableCreate = "CREATE TABLE IF NOT EXISTS \(TablePinnedTopSites) (" + "historyID INTEGER, " + "url TEXT NOT NULL UNIQUE, " + "title TEXT, " + "guid TEXT, " + "pinDate REAL, " + "domain TEXT NOT NULL " + ")" let domainsTableCreate = "CREATE TABLE IF NOT EXISTS \(TableDomains) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "domain TEXT NOT NULL UNIQUE, " + "showOnTopSites TINYINT NOT NULL DEFAULT 1" + ")" let queueTableCreate = "CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" + "url TEXT NOT NULL UNIQUE, " + "title TEXT" + ") " let syncCommandsTableCreate = "CREATE TABLE IF NOT EXISTS \(TableSyncCommands) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "client_guid TEXT NOT NULL, " + "value TEXT NOT NULL" + ")" let clientsTableCreate = "CREATE TABLE IF NOT EXISTS \(TableClients) (" + "guid TEXT PRIMARY KEY, " + "name TEXT NOT NULL, " + "modified INTEGER NOT NULL, " + "type TEXT, " + "formfactor TEXT, " + "os TEXT, " + "version TEXT, " + "fxaDeviceId TEXT" + ")" let tabsTableCreate = "CREATE TABLE IF NOT EXISTS \(TableTabs) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "client_guid TEXT REFERENCES clients(guid) ON DELETE CASCADE, " + "url TEXT NOT NULL, " + "title TEXT, " + "history TEXT, " + "last_used INTEGER" + ")" let activityStreamBlocklistCreate = "CREATE TABLE IF NOT EXISTS \(TableActivityStreamBlocklist) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP " + ") " let pageMetadataCreate = "CREATE TABLE IF NOT EXISTS \(TablePageMetadata) (" + "id INTEGER PRIMARY KEY, " + "cache_key LONGVARCHAR UNIQUE, " + "site_url TEXT, " + "media_url LONGVARCHAR, " + "title TEXT, " + "type VARCHAR(32), " + "description TEXT, " + "provider_name TEXT, " + "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, " + "expired_at LONG" + ") " let highlightsCreate = "CREATE TABLE IF NOT EXISTS \(TableHighlights) (" + "historyID INTEGER PRIMARY KEY," + "cache_key LONGVARCHAR," + "url TEXT," + "title TEXT," + "guid TEXT," + "visitCount INTEGER," + "visitDate DATETIME," + "is_bookmarked INTEGER" + ") " let indexPageMetadataCacheKeyCreate = "CREATE UNIQUE INDEX IF NOT EXISTS \(IndexPageMetadataCacheKey) ON page_metadata (cache_key)" let indexPageMetadataSiteURLCreate = "CREATE UNIQUE INDEX IF NOT EXISTS \(IndexPageMetadataSiteURL) ON page_metadata (site_url)" let iconColumns = ", faviconID INTEGER REFERENCES \(TableFavicons)(id) ON DELETE SET NULL" let mirrorColumns = ", is_overridden TINYINT NOT NULL DEFAULT 0" let serverColumns = ", server_modified INTEGER NOT NULL" + // Milliseconds. ", hasDupe TINYINT NOT NULL DEFAULT 0" // Boolean, 0 (false) if deleted. let localColumns = ", local_modified INTEGER" + // Can be null. Client clock. In extremis only. ", sync_status TINYINT NOT NULL" // SyncStatus enum. Set when changed or created. func getBookmarksTableCreationStringForTable(_ table: String, withAdditionalColumns: String="") -> String { // The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry. // For now we have the simplest possible schema: everything in one. let sql = "CREATE TABLE IF NOT EXISTS \(table) " + // Shared fields. "( id INTEGER PRIMARY KEY AUTOINCREMENT" + ", guid TEXT NOT NULL UNIQUE" + ", type TINYINT NOT NULL" + // Type enum. ", date_added INTEGER" + // Record/envelope metadata that'll allow us to do merges. ", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean ", parentid TEXT" + // GUID ", parentName TEXT" + // Type-specific fields. These should be NOT NULL in many cases, but we're going // for a sparse schema, so this'll do for now. Enforce these in the application code. ", feedUri TEXT, siteUri TEXT" + // LIVEMARKS ", pos INT" + // SEPARATORS ", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES ", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES ", folderName TEXT, queryId TEXT" + // QUERIES withAdditionalColumns + ", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" + ", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" + ")" return sql } /** * We need to explicitly store what's provided by the server, because we can't rely on * referenced child nodes to exist yet! */ func getBookmarksStructureTableCreationStringForTable(_ table: String, referencingMirror mirror: String) -> String { let sql = "CREATE TABLE IF NOT EXISTS \(table) " + "( parent TEXT NOT NULL REFERENCES \(mirror)(guid) ON DELETE CASCADE" + ", child TEXT NOT NULL" + // Should be the GUID of a child. ", idx INTEGER NOT NULL" + // Should advance from 0. ")" return sql } fileprivate let bufferBookmarksView = "CREATE VIEW \(ViewBookmarksBufferOnMirror) AS " + "SELECT" + " -1 AS id" + ", mirror.guid AS guid" + ", mirror.type AS type" + ", mirror.date_added AS date_added" + ", mirror.is_deleted AS is_deleted" + ", mirror.parentid AS parentid" + ", mirror.parentName AS parentName" + ", mirror.feedUri AS feedUri" + ", mirror.siteUri AS siteUri" + ", mirror.pos AS pos" + ", mirror.title AS title" + ", mirror.description AS description" + ", mirror.bmkUri AS bmkUri" + ", mirror.keyword AS keyword" + ", mirror.folderName AS folderName" + ", null AS faviconID" + ", 0 AS is_overridden" + // LEFT EXCLUDING JOIN to get mirror records that aren't in the buffer. // We don't have an is_overridden flag to help us here. " FROM \(TableBookmarksMirror) mirror LEFT JOIN" + " \(TableBookmarksBuffer) buffer ON mirror.guid = buffer.guid" + " WHERE buffer.guid IS NULL" + " UNION ALL " + "SELECT" + " -1 AS id" + ", guid" + ", type" + ", date_added" + ", is_deleted" + ", parentid" + ", parentName" + ", feedUri" + ", siteUri" + ", pos" + ", title" + ", description" + ", bmkUri" + ", keyword" + ", folderName" + ", null AS faviconID" + ", 1 AS is_overridden" + " FROM \(TableBookmarksBuffer) WHERE is_deleted IS 0" fileprivate let bufferBookmarksWithDeletionsView = "CREATE VIEW \(ViewBookmarksBufferWithDeletionsOnMirror) AS " + "SELECT" + " -1 AS id" + ", mirror.guid AS guid" + ", mirror.type AS type" + ", mirror.date_added AS date_added" + ", mirror.is_deleted AS is_deleted" + ", mirror.parentid AS parentid" + ", mirror.parentName AS parentName" + ", mirror.feedUri AS feedUri" + ", mirror.siteUri AS siteUri" + ", mirror.pos AS pos" + ", mirror.title AS title" + ", mirror.description AS description" + ", mirror.bmkUri AS bmkUri" + ", mirror.keyword AS keyword" + ", mirror.folderName AS folderName" + ", null AS faviconID" + ", 0 AS is_overridden" + // LEFT EXCLUDING JOIN to get mirror records that aren't in the buffer. // We don't have an is_overridden flag to help us here. " FROM \(TableBookmarksMirror) mirror LEFT JOIN" + " \(TableBookmarksBuffer) buffer ON mirror.guid = buffer.guid" + " WHERE buffer.guid IS NULL" + " UNION ALL " + "SELECT" + " -1 AS id" + ", guid" + ", type" + ", date_added" + ", is_deleted" + ", parentid" + ", parentName" + ", feedUri" + ", siteUri" + ", pos" + ", title" + ", description" + ", bmkUri" + ", keyword" + ", folderName" + ", null AS faviconID" + ", 1 AS is_overridden" + " FROM \(TableBookmarksBuffer) WHERE is_deleted IS 0" + " AND NOT EXISTS (SELECT 1 FROM \(TablePendingBookmarksDeletions) deletions WHERE deletions.id = guid)" // TODO: phrase this without the subselect… fileprivate let bufferBookmarksStructureView = // We don't need to exclude deleted parents, because we drop those from the structure // table when we see them. "CREATE VIEW \(ViewBookmarksBufferStructureOnMirror) AS " + "SELECT parent, child, idx, 1 AS is_overridden FROM \(TableBookmarksBufferStructure) " + "UNION ALL " + // Exclude anything from the mirror that's present in the buffer -- dynamic is_overridden. "SELECT parent, child, idx, 0 AS is_overridden FROM \(TableBookmarksMirrorStructure) " + "LEFT JOIN \(TableBookmarksBuffer) ON parent = guid WHERE guid IS NULL" fileprivate let localBookmarksView = "CREATE VIEW \(ViewBookmarksLocalOnMirror) AS " + "SELECT -1 AS id, guid, type, date_added, is_deleted, parentid, parentName, feedUri," + " siteUri, pos, title, description, bmkUri, folderName, faviconID, NULL AS local_modified, server_modified, 0 AS is_overridden " + "FROM \(TableBookmarksMirror) WHERE is_overridden IS NOT 1 " + "UNION ALL " + "SELECT -1 AS id, guid, type, date_added, is_deleted, parentid, parentName, feedUri, siteUri, pos, title, description, bmkUri, folderName, faviconID," + " local_modified, NULL AS server_modified, 1 AS is_overridden " + "FROM \(TableBookmarksLocal) WHERE is_deleted IS NOT 1" // TODO: phrase this without the subselect… fileprivate let localBookmarksStructureView = "CREATE VIEW \(ViewBookmarksLocalStructureOnMirror) AS " + "SELECT parent, child, idx, 1 AS is_overridden FROM \(TableBookmarksLocalStructure) " + "WHERE " + "((SELECT is_deleted FROM \(TableBookmarksLocal) WHERE guid = parent) IS NOT 1) " + "UNION ALL " + "SELECT parent, child, idx, 0 AS is_overridden FROM \(TableBookmarksMirrorStructure) " + "WHERE " + "((SELECT is_overridden FROM \(TableBookmarksMirror) WHERE guid = parent) IS NOT 1) " // This view exists only to allow for text searching of URLs and titles in the awesomebar. // As such, we cheat a little: we include buffer, non-overridden mirror, and local. // Usually this will be indistinguishable from a more sophisticated approach, and it's way // easier. fileprivate let allBookmarksView = "CREATE VIEW \(ViewAllBookmarks) AS " + "SELECT guid, bmkUri AS url, title, description, faviconID FROM " + "\(TableBookmarksMirror) WHERE " + "type = \(BookmarkNodeType.bookmark.rawValue) AND is_overridden IS 0 AND is_deleted IS 0 " + "UNION ALL " + "SELECT guid, bmkUri AS url, title, description, faviconID FROM " + "\(TableBookmarksLocal) WHERE " + "type = \(BookmarkNodeType.bookmark.rawValue) AND is_deleted IS 0 " + "UNION ALL " + "SELECT guid, bmkUri AS url, title, description, -1 AS faviconID FROM " + "\(TableBookmarksBuffer) bb WHERE " + "bb.type = \(BookmarkNodeType.bookmark.rawValue) AND bb.is_deleted IS 0 " + // Exclude pending bookmark deletions. "AND NOT EXISTS (SELECT 1 FROM \(TablePendingBookmarksDeletions) AS pd WHERE pd.id = bb.guid)" // This exists only to allow upgrade from old versions. We have view dependencies, so // we can't simply skip creating ViewAllBookmarks. Here's a stub. fileprivate let oldAllBookmarksView = "CREATE VIEW \(ViewAllBookmarks) AS " + "SELECT guid, bmkUri AS url, title, description, faviconID FROM " + "\(TableBookmarksMirror) WHERE " + "type = \(BookmarkNodeType.bookmark.rawValue) AND is_overridden IS 0 AND is_deleted IS 0" // This smushes together remote and local visits. So it goes. fileprivate let historyVisitsView = "CREATE VIEW \(ViewHistoryVisits) AS " + "SELECT h.url AS url, MAX(v.date) AS visitDate, h.domain_id AS domain_id FROM " + "\(TableHistory) h JOIN \(TableVisits) v ON v.siteID = h.id " + "GROUP BY h.id" // Join all bookmarks against history to find the most recent visit. // visits. fileprivate let awesomebarBookmarksView = "CREATE VIEW \(ViewAwesomebarBookmarks) AS " + "SELECT b.guid AS guid, b.url AS url, b.title AS title, " + "b.description AS description, b.faviconID AS faviconID, " + "h.visitDate AS visitDate " + "FROM \(ViewAllBookmarks) b " + "LEFT JOIN " + "\(ViewHistoryVisits) h ON b.url = h.url" fileprivate let awesomebarBookmarksWithIconsView = "CREATE VIEW \(ViewAwesomebarBookmarksWithIcons) AS " + "SELECT b.guid AS guid, b.url AS url, b.title AS title, " + "b.description AS description, b.visitDate AS visitDate, " + "f.id AS iconID, f.url AS iconURL, f.date AS iconDate, " + "f.type AS iconType, f.width AS iconWidth " + "FROM \(ViewAwesomebarBookmarks) b " + "LEFT JOIN " + "\(TableFavicons) f ON f.id = b.faviconID" fileprivate let pendingBookmarksDeletions = "CREATE TABLE IF NOT EXISTS \(TablePendingBookmarksDeletions) (" + "id TEXT PRIMARY KEY REFERENCES \(TableBookmarksBuffer)(guid) ON DELETE CASCADE" + ")" fileprivate let remoteDevices = "CREATE TABLE IF NOT EXISTS \(TableRemoteDevices) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT UNIQUE NOT NULL, " + "name TEXT NOT NULL, " + "type TEXT NOT NULL, " + "is_current_device INTEGER NOT NULL, " + "date_created INTEGER NOT NULL, " + // Timestamps in ms. "date_modified INTEGER NOT NULL, " + "last_access_time INTEGER" + ")" public func create(_ db: SQLiteDBConnection) -> Bool { let favicons = "CREATE TABLE IF NOT EXISTS \(TableFavicons) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "url TEXT NOT NULL UNIQUE, " + "width INTEGER, " + "height INTEGER, " + "type INTEGER NOT NULL, " + "date REAL NOT NULL" + ") " let history = "CREATE TABLE IF NOT EXISTS \(TableHistory) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's. "url TEXT UNIQUE, " + // May only be null for deleted records. "title TEXT NOT NULL, " + "server_modified INTEGER, " + // Can be null. Integer milliseconds. "local_modified INTEGER, " + // Can be null. Client clock. In extremis only. "is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted. "should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added. "domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " + "CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" + ")" // Right now we don't need to track per-visit deletions: Sync can't // represent them! See Bug 1157553 Comment 6. // We flip the should_upload flag on the history item when we add a visit. // If we ever want to support logic like not bothering to sync if we added // and then rapidly removed a visit, then we need an 'is_new' flag on each visit. let visits = "CREATE TABLE IF NOT EXISTS \(TableVisits) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "date REAL NOT NULL, " + // Microseconds since epoch. "type INTEGER NOT NULL, " + "is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split. "UNIQUE (siteID, date, type) " + ") " let indexShouldUpload: String if self.supportsPartialIndices { // There's no point tracking rows that are not flagged for upload. indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload) WHERE should_upload = 1" } else { indexShouldUpload = "CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " + "ON \(TableHistory) (should_upload)" } let indexSiteIDDate = "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " + "ON \(TableVisits) (siteID, is_local, date)" let faviconSites = "CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " + "faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " + "UNIQUE (siteID, faviconID) " + ") " let widestFavicons = "CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " + "SELECT " + "\(TableFaviconSites).siteID AS siteID, " + "\(TableFavicons).id AS iconID, " + "\(TableFavicons).url AS iconURL, " + "\(TableFavicons).date AS iconDate, " + "\(TableFavicons).type AS iconType, " + "MAX(\(TableFavicons).width) AS iconWidth " + "FROM \(TableFaviconSites), \(TableFavicons) WHERE " + "\(TableFaviconSites).faviconID = \(TableFavicons).id " + "GROUP BY siteID " let historyIDsWithIcon = "CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " + "SELECT \(TableHistory).id AS id, " + "iconID, iconURL, iconDate, iconType, iconWidth " + "FROM \(TableHistory) " + "LEFT OUTER JOIN " + "\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID " let iconForURL = "CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " + "SELECT history.url AS url, icons.iconID AS iconID FROM " + "\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " + "\(TableHistory).id = icons.siteID " // Locally we track faviconID. // Local changes end up in the mirror, so we track it there too. // The buffer and the mirror additionally track some server metadata. let bookmarksLocal = getBookmarksTableCreationStringForTable(TableBookmarksLocal, withAdditionalColumns: self.localColumns + self.iconColumns) let bookmarksLocalStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksLocalStructure, referencingMirror: TableBookmarksLocal) let bookmarksBuffer = getBookmarksTableCreationStringForTable(TableBookmarksBuffer, withAdditionalColumns: self.serverColumns) let bookmarksBufferStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksBufferStructure, referencingMirror: TableBookmarksBuffer) let bookmarksMirror = getBookmarksTableCreationStringForTable(TableBookmarksMirror, withAdditionalColumns: self.serverColumns + self.mirrorColumns + self.iconColumns) let bookmarksMirrorStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror) let indexLocalStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksLocalStructureParentIdx) " + "ON \(TableBookmarksLocalStructure) (parent, idx)" let indexBufferStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksBufferStructureParentIdx) " + "ON \(TableBookmarksBufferStructure) (parent, idx)" let indexMirrorStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" let indexMirrorStructureChild = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureChild) " + "ON \(TableBookmarksMirrorStructure) (child)" let queries: [String] = [ // Tables. self.domainsTableCreate, history, favicons, visits, bookmarksBuffer, bookmarksBufferStructure, bookmarksLocal, bookmarksLocalStructure, bookmarksMirror, bookmarksMirrorStructure, self.pendingBookmarksDeletions, faviconSites, widestFavicons, historyIDsWithIcon, iconForURL, pageMetadataCreate, pinnedTopSitesTableCreate, highlightsCreate, self.remoteDevices, activityStreamBlocklistCreate, indexPageMetadataSiteURLCreate, indexPageMetadataCacheKeyCreate, self.queueTableCreate, self.topSitesTableCreate, syncCommandsTableCreate, clientsTableCreate, tabsTableCreate, // Indices. indexBufferStructureParentIdx, indexLocalStructureParentIdx, indexMirrorStructureParentIdx, indexMirrorStructureChild, indexShouldUpload, indexSiteIDDate, // Views. self.localBookmarksView, self.localBookmarksStructureView, self.bufferBookmarksView, self.bufferBookmarksWithDeletionsView, self.bufferBookmarksStructureView, allBookmarksView, historyVisitsView, awesomebarBookmarksView, awesomebarBookmarksWithIconsView, ] assert(queries.count == AllTablesIndicesAndViews.count, "Did you forget to add your table, index, or view to the list?") log.debug("Creating \(queries.count) tables, views, and indices.") return self.run(db, queries: queries) && self.prepopulateRootFolders(db) } public func update(_ db: SQLiteDBConnection, from: Int) -> Bool { let to = self.version if from == to { log.debug("Skipping update from \(from) to \(to).") return true } if from == 0 { // If we're upgrading from `0`, it is likely that we have not yet switched // from tracking the schema version using `tableList` to `PRAGMA user_version`. // This will write the *previous* version number from `tableList` into // `PRAGMA user_version` if necessary in addition to upgrading the schema of // some of the old tables that were previously managed separately. if self.migrateFromSchemaTableIfNeeded(db) { let version = db.version // If the database is now properly reporting a `user_version`, it may // still need to be upgraded further to get to the current version of // the schema. So, let's simply call this `update()` function a second // time to handle any remaining post-v31 migrations. if version > 0 { return self.update(db, from: version) } } // Otherwise, this is likely an upgrade from before Bug 1160399, so // let's drop and re-create. log.debug("Updating schema \(self.name) from zero. Assuming drop and recreate.") return drop(db) && create(db) } if from > to { // This is likely an upgrade from before Bug 1160399. log.debug("Downgrading browser tables. Assuming drop and recreate.") return drop(db) && create(db) } log.debug("Updating schema \(self.name) from \(from) to \(to).") if from < 4 && to >= 4 { return drop(db) && create(db) } if from < 5 && to >= 5 { if !self.run(db, sql: self.queueTableCreate) { return false } } if from < 6 && to >= 6 { if !self.run(db, queries: [ "DROP INDEX IF EXISTS \(IndexVisitsSiteIDDate)", "CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) ON \(TableVisits) (siteID, is_local, date)", self.domainsTableCreate, "ALTER TABLE \(TableHistory) ADD COLUMN domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE", ]) { return false } let urls = db.executeQuery("SELECT DISTINCT url FROM \(TableHistory) WHERE url IS NOT NULL", factory: { $0["url"] as! String }) if !fillDomainNamesFromCursor(urls, db: db) { return false } } if from < 8 && to == 8 { // Nothing to do: we're just shifting the favicon table to be owned by this class. return true } if from < 9 && to >= 9 { if !self.run(db, sql: getBookmarksTableCreationStringForTable(TableBookmarksMirror)) { return false } } if from < 10 && to >= 10 { if !self.run(db, sql: getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror)) { return false } let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" if !self.run(db, sql: indexStructureParentIdx) { return false } } if from < 11 && to >= 11 { if !self.run(db, sql: self.topSitesTableCreate) { return false } } if from < 12 && to >= 12 { let bookmarksLocal = getBookmarksTableCreationStringForTable(TableBookmarksLocal, withAdditionalColumns: self.localColumns + self.iconColumns) let bookmarksLocalStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksLocalStructure, referencingMirror: TableBookmarksLocal) let bookmarksMirror = getBookmarksTableCreationStringForTable(TableBookmarksMirror, withAdditionalColumns: self.serverColumns + self.mirrorColumns + self.iconColumns) let bookmarksMirrorStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror) let indexLocalStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksLocalStructureParentIdx) " + "ON \(TableBookmarksLocalStructure) (parent, idx)" let indexBufferStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksBufferStructureParentIdx) " + "ON \(TableBookmarksBufferStructure) (parent, idx)" let indexMirrorStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " + "ON \(TableBookmarksMirrorStructure) (parent, idx)" let prep = [ // Drop indices. "DROP INDEX IF EXISTS idx_bookmarksMirrorStructure_parent_idx", // Rename the old mirror tables to buffer. // The v11 one is the same shape as the current buffer table. "ALTER TABLE \(TableBookmarksMirror) RENAME TO \(TableBookmarksBuffer)", "ALTER TABLE \(TableBookmarksMirrorStructure) RENAME TO \(TableBookmarksBufferStructure)", // Create the new mirror and local tables. bookmarksLocal, bookmarksMirror, bookmarksLocalStructure, bookmarksMirrorStructure, ] // Only migrate bookmarks. The only folders are our roots, and we'll create those later. // There should be nothing else in the table, and no structure. // Our old bookmarks table didn't have creation date, so we use the current timestamp. let modified = Date.now() let status = SyncStatus.new.rawValue // We don't specify a title, expecting it to be generated on the fly, because we're smarter than Android. // We also don't migrate the 'id' column; we'll generate new ones that won't conflict with our roots. let migrateArgs: Args = [BookmarkRoots.MobileFolderGUID] let migrateLocal = "INSERT INTO \(TableBookmarksLocal) " + "(guid, type, bmkUri, title, faviconID, local_modified, sync_status, parentid, parentName) " + "SELECT guid, type, url AS bmkUri, title, faviconID, " + "\(modified) AS local_modified, \(status) AS sync_status, ?, '' " + "FROM \(_TableBookmarks) WHERE type IS \(BookmarkNodeType.bookmark.rawValue)" // Create structure for our migrated bookmarks. // In order to get contiguous positions (idx), we first insert everything we just migrated under // Mobile Bookmarks into a temporary table, then use rowid as our idx. let temporaryTable = "CREATE TEMPORARY TABLE children AS " + "SELECT guid FROM \(_TableBookmarks) WHERE " + "type IS \(BookmarkNodeType.bookmark.rawValue) ORDER BY id ASC" let createStructure = "INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) " + "SELECT ? AS parent, guid AS child, (rowid - 1) AS idx FROM children" let migrate: [(String, Args?)] = [ (migrateLocal, migrateArgs), (temporaryTable, nil), (createStructure, migrateArgs), // Drop the temporary table. ("DROP TABLE children", nil), // Drop the old bookmarks table. ("DROP TABLE \(_TableBookmarks)", nil), // Create indices for each structure table. (indexBufferStructureParentIdx, nil), (indexLocalStructureParentIdx, nil), (indexMirrorStructureParentIdx, nil), ] if !self.run(db, queries: prep) || !self.prepopulateRootFolders(db) || !self.run(db, queries: migrate) { return false } // TODO: trigger a sync? } // Add views for the overlays. if from < 14 && to >= 14 { let indexMirrorStructureChild = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureChild) " + "ON \(TableBookmarksMirrorStructure) (child)" if !self.run(db, queries: [ self.bufferBookmarksStructureView, self.localBookmarksStructureView, indexMirrorStructureChild]) { return false } } if from == 14 && to >= 15 { // We screwed up some of the views. Recreate them. if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewBookmarksBufferStructureOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksLocalStructureOnMirror)", self.bufferBookmarksStructureView, self.localBookmarksStructureView]) { return false } } if from < 16 && to >= 16 { if !self.run(db, queries: [ oldAllBookmarksView, // Replaced in v30. The new one is not compatible here. historyVisitsView, awesomebarBookmarksView, // … but this depends on ViewAllBookmarks. awesomebarBookmarksWithIconsView]) { return false } } // That view is re-created later // if from < 17 && to >= 17 { // if !self.run(db, queries: [ // // Adds the local_modified, server_modified times to the local bookmarks view // "DROP VIEW IF EXISTS \(ViewBookmarksLocalOnMirror)", // self.localBookmarksView]) { // return false // } // } if from < 18 && to >= 18 { if !self.run(db, queries: [ // Adds the Activity Stream blocklist table activityStreamBlocklistCreate]) { return false } } if from < 19 && to >= 19 { if !self.run(db, queries: [ // Adds tables/indicies for metadata content pageMetadataCreate, indexPageMetadataCacheKeyCreate]) { return false } } // That view is re-created later // if from < 20 && to >= 20 { // if !self.run(db, queries: [ // "DROP VIEW IF EXISTS \(ViewBookmarksBufferOnMirror)", // self.bufferBookmarksView]) { // return false // } // } if from < 21 && to >= 21 { if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewHistoryVisits)", self.historyVisitsView, indexPageMetadataSiteURLCreate]) { return false } } // Someone upgrading from v21 will get these tables anyway. // So, there's no need to create them only to be dropped and // re-created at v27 anyway. // if from < 22 && to >= 22 { // if !self.run(db, queries: [ // "DROP TABLE IF EXISTS \(TablePageMetadata)", // pageMetadataCreate, // indexPageMetadataCacheKeyCreate, // indexPageMetadataSiteURLCreate]) { // return false // } // } // // if from < 23 && to >= 23 { // if !self.run(db, queries: [ // highlightsCreate]) { // return false // } // } // // if from < 24 && to >= 24 { // if !self.run(db, queries: [ // // We can safely drop the highlights cache table since it gets cleared on every invalidate anyways. // "DROP TABLE IF EXISTS \(TableHighlights)", // highlightsCreate // ]) { // return false // } // } // Someone upgrading from v21 will get this table anyway. // So, there's no need to create it only to be dropped and // re-created at v26 anyway. // if from < 25 && to >= 25 { // if !self.run(db, queries: [ // pinnedTopSitesTableCreate // ]) { // return false // } // } if from < 26 && to >= 26 { if !self.run(db, queries: [ // The old pin table was never released so we can safely drop "DROP TABLE IF EXISTS \(TablePinnedTopSites)", pinnedTopSitesTableCreate ]) { return false } } if from < 27 && to >= 27 { if !self.run(db, queries: [ "DROP TABLE IF EXISTS \(TablePageMetadata)", "DROP TABLE IF EXISTS \(TableHighlights)", pageMetadataCreate, indexPageMetadataCacheKeyCreate, indexPageMetadataSiteURLCreate, highlightsCreate ]) { return false } } if from < 28 && to >= 28 { if !self.run(db, queries: [ self.pendingBookmarksDeletions ]) { return false } } if from < 29 && to >= 29 { if !self.run(db, queries: [ self.remoteDevices ]) { return false } } if from < 30 && to >= 30 { // We changed this view as a follow-up to the above in order to exclude buffer // deletions from the bookmarked set. if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewAllBookmarks)", allBookmarksView ]) { return false } } // NOTE: These tables should have already existed in prior // versions, but were managed separately via the SchemaTable. // Here we create them if they don't already exist to handle // cases where we are creating a brand new DB. if from < 31 && to >= 31 { if !self.run(db, queries: [ syncCommandsTableCreate, clientsTableCreate, tabsTableCreate ]) { return false } } if from < 32 && to >= 32 { var queries: [String] = [] // If upgrading from < 12 these tables are created with that column already present. if from > 12 { queries.append(contentsOf: [ "ALTER TABLE \(TableBookmarksLocal) ADD date_added INTEGER", "ALTER TABLE \(TableBookmarksMirror) ADD date_added INTEGER", "ALTER TABLE \(TableBookmarksBuffer) ADD date_added INTEGER" ]) } queries.append(contentsOf: [ "UPDATE \(TableBookmarksLocal) SET date_added = local_modified", "UPDATE \(TableBookmarksMirror) SET date_added = server_modified" ]) if !self.run(db, queries: queries) { return false } } if from < 33 && to >= 33 { if !self.run(db, queries: [ "DROP VIEW IF EXISTS \(ViewBookmarksBufferOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksBufferWithDeletionsOnMirror)", "DROP VIEW IF EXISTS \(ViewBookmarksLocalOnMirror)", self.bufferBookmarksView, self.bufferBookmarksWithDeletionsView, self.localBookmarksView ]) { return false } } if from < 34 && to >= 34 { // Drop over-large items from the database, and truncate // over-long titles. // We do this once, and only for local bookmarks: if they // already escaped, then it's better to let them be. // Hard-code values here both for simplicity and to make // migrations predictable. // We don't need to worry about description: we never wrote it. if !self.run(db, queries: [ "DELETE FROM \(TableHistory) WHERE is_deleted = 0 AND length(url) > 65536", "DELETE FROM \(TablePageMetadata) WHERE length(site_url) > 65536", "DELETE FROM \(TableBookmarksLocal) WHERE is_deleted = 0 AND length(bmkUri) > 65536", "UPDATE \(TableBookmarksLocal) SET title = substr(title, 1, 4096)" + " WHERE is_deleted = 0 AND length(title) > 4096", ]) { return false } } return true } fileprivate func migrateFromSchemaTableIfNeeded(_ db: SQLiteDBConnection) -> Bool { log.info("Checking if schema table migration is needed.") // If `PRAGMA user_version` is v31 or later, we don't need to do anything here. guard db.version < 31 else { return true } // Query for the existence of the `tableList` table to determine if we are // migrating from an older DB version or if this is just a brand new DB. let sqliteMasterCursor = db.executeQueryUnsafe("SELECT COUNT(*) AS number FROM sqlite_master WHERE type = 'table' AND name = 'tableList'", factory: IntFactory, withArgs: [] as Args) let tableListTableExists = sqliteMasterCursor[0] == 1 sqliteMasterCursor.close() // If `tableList` still exists in this DB, then we need to continue to check if // any table-specific migrations are required before removing it. Otherwise, if // `tableList` does not exist, it is likely due to this being a brand new DB and // no additional steps need to be taken at this point. guard tableListTableExists else { return true } // If we are unable to migrate the `clients` table from the schema table, we // have failed and cannot continue. guard migrateClientsTableFromSchemaTableIfNeeded(db) != .failure else { return false } // Get the *previous* schema version (prior to v31) specified in `tableList` // before dropping it. let previousVersionCursor = db.executeQueryUnsafe("SELECT version FROM tableList WHERE name = 'BROWSER'", factory: IntFactory, withArgs: [] as Args) let previousVersion = previousVersionCursor[0] ?? 0 previousVersionCursor.close() // No other intermediate migrations are needed for the remaining tables and // we have already captured the *previous* schema version specified in // `tableList`, so we can now safely drop it. log.info("Schema table migrations complete; Dropping 'tableList' table.") let sql = "DROP TABLE IF EXISTS tableList" do { try db.executeChange(sql) } catch let err as NSError { Sentry.shared.sendWithStacktrace(message: "Error dropping tableList table", tag: SentryTag.browserDB, severity: .error, description: "\(err.localizedDescription)") return false } // Lastly, write the *previous* schema version (prior to v31) to the database // using `PRAGMA user_version = ?`. do { try db.setVersion(previousVersion) } catch let err as NSError { Sentry.shared.sendWithStacktrace(message: "Error setting database version", tag: SentryTag.browserDB, severity: .error, description: "\(err.localizedDescription)") return false } return true } // Performs the intermediate migrations for the `clients` table that were previously // being handled by the schema table. This should update older versions of the `clients` // table prior to v31. If the `clients` table is able to be successfully migrated, this // will return `.success`. If no migration is required because either the `clients` table // is already at v31 or it does not exist yet at all, this will return `.skipped`. // Otherwise, if the `clients` table migration is needed and an error was encountered, we // return `.failure`. fileprivate func migrateClientsTableFromSchemaTableIfNeeded(_ db: SQLiteDBConnection) -> SchemaUpgradeResult { // Query for the existence of the `clients` table to determine if we are // migrating from an older DB version or if this is just a brand new DB. let sqliteMasterCursor = db.executeQueryUnsafe("SELECT COUNT(*) AS number FROM sqlite_master WHERE type = 'table' AND name = '\(TableClients)'", factory: IntFactory, withArgs: [] as Args) let clientsTableExists = sqliteMasterCursor[0] == 1 sqliteMasterCursor.close() guard clientsTableExists else { return .skipped } // Check if intermediate migrations are necessary for the 'clients' table. let previousVersionCursor = db.executeQueryUnsafe("SELECT version FROM tableList WHERE name = '\(TableClients)'", factory: IntFactory, withArgs: [] as Args) let previousClientsTableVersion = previousVersionCursor[0] ?? 0 previousVersionCursor.close() guard previousClientsTableVersion > 0 && previousClientsTableVersion <= 3 else { return .skipped } log.info("Migrating '\(TableClients)' table from version \(previousClientsTableVersion).") if previousClientsTableVersion < 2 { let sql = "ALTER TABLE \(TableClients) ADD COLUMN version TEXT" do { try db.executeChange(sql) } catch let err as NSError { log.error("Error altering \(TableClients) table: \(err.localizedDescription); SQL was \(sql)") let extra = ["table": "\(TableClients)", "errorDescription": "\(err.localizedDescription)", "sql": "\(sql)"] Sentry.shared.sendWithStacktrace(message: "Error altering table", tag: SentryTag.browserDB, severity: .error, extra: extra) return .failure } } if previousClientsTableVersion < 3 { let sql = "ALTER TABLE \(TableClients) ADD COLUMN fxaDeviceId TEXT" do { try db.executeChange(sql) } catch let err as NSError { log.error("Error altering \(TableClients) table: \(err.localizedDescription); SQL was \(sql)") let extra = ["table": "\(TableClients)", "errorDescription": "\(err.localizedDescription)", "sql": "\(sql)"] Sentry.shared.sendWithStacktrace(message: "Error altering table", tag: SentryTag.browserDB, severity: .error, extra: extra) return .failure } } return .success } fileprivate func fillDomainNamesFromCursor(_ cursor: Cursor<String>, db: SQLiteDBConnection) -> Bool { if cursor.count == 0 { return true } // URL -> hostname, flattened to make args. var pairs = Args() pairs.reserveCapacity(cursor.count * 2) for url in cursor { if let url = url, let host = url.asURL?.normalizedHost { pairs.append(url) pairs.append(host) } } cursor.close() let tmpTable = "tmp_hostnames" let table = "CREATE TEMP TABLE \(tmpTable) (url TEXT NOT NULL UNIQUE, domain TEXT NOT NULL, domain_id INT)" if !self.run(db, sql: table, args: nil) { log.error("Can't create temporary table. Unable to migrate domain names. Top Sites is likely to be broken.") return false } // Now insert these into the temporary table. Chunk by an even number, for obvious reasons. let chunks = chunk(pairs, by: BrowserDB.MaxVariableNumber - (BrowserDB.MaxVariableNumber % 2)) for chunk in chunks { let ins = "INSERT INTO \(tmpTable) (url, domain) VALUES " + Array<String>(repeating: "(?, ?)", count: chunk.count / 2).joined(separator: ", ") if !self.run(db, sql: ins, args: Array(chunk)) { log.error("Couldn't insert domains into temporary table. Aborting migration.") return false } } // Now make those into domains. let domains = "INSERT OR IGNORE INTO \(TableDomains) (domain) SELECT DISTINCT domain FROM \(tmpTable)" // … and fill that temporary column. let domainIDs = "UPDATE \(tmpTable) SET domain_id = (SELECT id FROM \(TableDomains) WHERE \(TableDomains).domain = \(tmpTable).domain)" // Update the history table from the temporary table. let updateHistory = "UPDATE \(TableHistory) SET domain_id = (SELECT domain_id FROM \(tmpTable) WHERE \(tmpTable).url = \(TableHistory).url)" // Clean up. let dropTemp = "DROP TABLE \(tmpTable)" // Now run these. if !self.run(db, queries: [domains, domainIDs, updateHistory, dropTemp]) { log.error("Unable to migrate domains.") return false } return true } public func drop(_ db: SQLiteDBConnection) -> Bool { log.debug("Dropping all browser tables.") let additional = [ "DROP TABLE IF EXISTS faviconSites" // We renamed it to match naming convention. ] let views = AllViews.map { "DROP VIEW IF EXISTS \($0)" } let indices = AllIndices.map { "DROP INDEX IF EXISTS \($0)" } let tables = AllTables.map { "DROP TABLE IF EXISTS \($0)" } let queries = Array([views, indices, tables, additional].joined()) return self.run(db, queries: queries) } }
mpl-2.0
1f3c25a248908ac2edcbeb5c9bcddd02
42.171139
246
0.605597
4.784842
false
false
false
false
venticake/RetricaImglyKit-iOS
RetricaImglyKit/Classes/Frontend/Views/TextButton.swift
1
2347
// This file is part of the PhotoEditor Software Development Kit. // Copyright (C) 2016 9elements GmbH <[email protected]> // All rights reserved. // Redistribution and use in source and binary forms, without // modification, are permitted provided that the following license agreement // is approved and a legal/financial contract was signed by the user. // The license agreement can be found under the following link: // https://www.photoeditorsdk.com/LICENSE.txt import UIKit /** * A `TextButton` is used within a `FontSelectorView` to present different fonts and their names. */ @available(iOS 8, *) @objc(IMGLYTextButton) public class TextButton: UIButton { /// The color of the label. public var labelColor = UIColor.whiteColor() { didSet { updateFontLabel() } } /// The name of the font. public var fontName = "" { didSet { updateFontLabel() } } /// :nodoc: public override var frame: CGRect { didSet { super.frame = frame updateFontNameLabelFrame() } } /// The name that is shown to the user. public var displayName = "" { didSet { updateFontLabel() } } private let fontNameLabel = UILabel() /** :nodoc: */ public override init(frame: CGRect) { super.init(frame: frame) commonInit() } /** :nodoc: */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.contentMode = .Center commonInit() } private func commonInit() { configureFontLabel() updateFontLabel() } private func configureFontLabel() { fontNameLabel.textAlignment = .Center fontNameLabel.isAccessibilityElement = false addSubview(fontNameLabel) } private func updateFontLabel() { fontNameLabel.font = fontNameLabel.font.fontWithSize(10) fontNameLabel.textColor = labelColor if fontName.characters.count > 0 { fontNameLabel.text = displayName.characters.count > 0 ? displayName : fontName } } private func updateFontNameLabelFrame() { fontNameLabel.frame = CGRect(x: 0, y: self.bounds.height - 15, width: self.bounds.width, height: 15) } }
mit
23a4b598e8fe19235156e0e8d66f949a
25.670455
108
0.622071
4.487572
false
false
false
false
jvesala/teknappi
teknappi/Pods/RxSwift/RxSwift/Observables/Implementations/Concat.swift
29
1523
// // Concat.swift // Rx // // Created by Krunoslav Zaher on 3/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class ConcatSink<S: SequenceType, O: ObserverType where S.Generator.Element : ObservableType, S.Generator.Element.E == O.E> : TailRecursiveSink<S, O> { typealias Element = O.E override init(observer: O, cancel: Disposable) { super.init(observer: observer, cancel: cancel) } override func on(event: Event<Element>){ switch event { case .Next(_): observer?.on(event) case .Error: observer?.on(event) dispose() case .Completed: scheduleMoveNext() } } override func extract(observable: Observable<E>) -> S.Generator? { if let source = observable as? Concat<S> { return source.sources.generate() } else { return nil } } } class Concat<S: SequenceType where S.Generator.Element : ObservableType> : Producer<S.Generator.Element.E> { typealias Element = S.Generator.Element.E let sources: S init(sources: S) { self.sources = sources } override func run<O: ObserverType where O.E == Element> (observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = ConcatSink<S, O>(observer: observer, cancel: cancel) setSink(sink) return sink.run(sources.generate()) } }
gpl-3.0
1a55de5e184768a36aecdf52bf6a3c10
25.736842
151
0.592252
4.138587
false
false
false
false
respan/ChainableSwift
ChainableSwift/Classes/UIViewExtensions.swift
1
8910
// // UIViewExtensions.swift // Pods // // Created by Denis Sushko on 17.04.16. // // public extension UIView { /// ChainableSwift func userInteractionEnabled(_ userInteractionEnabled: Bool) -> Self { self.isUserInteractionEnabled = userInteractionEnabled return self } /// ChainableSwift func tag(_ tag: Int) -> Self { self.tag = tag return self } /// ChainableSwift func clipsToBounds(_ clipsToBounds: Bool) -> Self { self.clipsToBounds = clipsToBounds return self } /// ChainableSwift func frame(_ frame: CGRect) -> Self { self.frame = frame return self } /// ChainableSwift func center(_ center: CGPoint) -> Self { self.center = center return self } /// ChainableSwift func transform(_ transform: CGAffineTransform) -> Self { self.transform = transform return self } /// ChainableSwift func contentScaleFactor(_ contentScaleFactor: CGFloat) -> Self { self.contentScaleFactor = contentScaleFactor return self } /// ChainableSwift func multipleTouchEnabled(_ multipleTouchEnabled: Bool) -> Self { self.isMultipleTouchEnabled = multipleTouchEnabled return self } /// ChainableSwift func exclusiveTouch(_ exclusiveTouch: Bool) -> Self { self.isExclusiveTouch = exclusiveTouch return self } /// ChainableSwift func autoresizesSubviews(_ autoresizesSubviews: Bool) -> Self { self.autoresizesSubviews = autoresizesSubviews return self } /// ChainableSwift func autoresizingMask(_ autoresizingMask: UIView.AutoresizingMask) -> Self { self.autoresizingMask = autoresizingMask return self } /// ChainableSwift func backgroundColor(_ backgroundColor: UIColor?) -> Self { self.backgroundColor = backgroundColor return self } /// ChainableSwift func alpha(_ alpha: CGFloat) -> Self { self.alpha = alpha return self } /// ChainableSwift func opaque(_ opaque: Bool) -> Self { self.isOpaque = opaque return self } /// ChainableSwift func clearsContextBeforeDrawing(_ clearsContextBeforeDrawing: Bool) -> Self { self.clearsContextBeforeDrawing = clearsContextBeforeDrawing return self } /// ChainableSwift func hidden(_ hidden: Bool) -> Self { self.isHidden = hidden return self } /// ChainableSwift func contentMode(_ contentMode: UIView.ContentMode) -> Self { self.contentMode = contentMode return self } /// ChainableSwift func maskView(_ maskView: UIView?) -> Self { self.mask = maskView return self } /// ChainableSwift func tintColor(_ tintColor: UIColor) -> Self { self.tintColor = tintColor return self } /// ChainableSwift func tintAdjustmentMode(_ tintAdjustmentMode: UIView.TintAdjustmentMode) -> Self { self.tintAdjustmentMode = tintAdjustmentMode return self } /// ChainableSwift func gestureRecognizers(_ gestureRecognizers: [UIGestureRecognizer]?) -> Self { self.gestureRecognizers = gestureRecognizers return self } /// ChainableSwift func motionEffects(_ motionEffects: [UIMotionEffect]) -> Self { self.motionEffects = motionEffects return self } /// ChainableSwift func translatesAutoresizingMaskIntoConstraints(_ translatesAutoresizingMaskIntoConstraints: Bool) -> Self { self.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints return self } } public extension UIView { /// ChainableSwift @discardableResult final func layerBounds(_ bounds: CGRect) -> Self { self.layer.bounds = bounds return self } /// ChainableSwift @discardableResult final func layerPosition(_ position: CGPoint) -> Self { self.layer.position = position return self } /// ChainableSwift @discardableResult final func layerZPosition(_ zPosition: CGFloat) -> Self { self.layer.zPosition = zPosition return self } /// ChainableSwift @discardableResult final func layerAnchorPoint(_ anchorPoint: CGPoint) -> Self { self.layer.anchorPoint = anchorPoint return self } /// ChainableSwift @discardableResult final func layerAnchorPointZ(_ anchorPointZ: CGFloat) -> Self { self.layer.anchorPointZ = anchorPointZ return self } /// ChainableSwift @discardableResult final func layerTransform(_ transform: CATransform3D) -> Self { self.layer.transform = transform return self } /// ChainableSwift @discardableResult final func layerFrame(_ frame: CGRect) -> Self { self.layer.frame = frame return self } /// ChainableSwift @discardableResult final func layerHidden(_ hidden: Bool) -> Self { self.layer.isHidden = hidden return self } /// ChainableSwift @discardableResult final func layerDoubleSided(_ doubleSided: Bool) -> Self { self.layer.isDoubleSided = doubleSided return self } /// ChainableSwift @discardableResult final func layerGeometryFlipped(_ geometryFlipped: Bool) -> Self { self.layer.isGeometryFlipped = geometryFlipped return self } /// ChainableSwift @discardableResult final func layerMask(_ mask: CALayer?) -> Self { self.layer.mask = mask return self } /// ChainableSwift @discardableResult final func layerMasksToBounds(_ masksToBounds: Bool) -> Self { self.layer.masksToBounds = masksToBounds return self } /// ChainableSwift @discardableResult final func layerOpaque(_ opaque: Bool) -> Self { self.layer.isOpaque = opaque return self } /// ChainableSwift @discardableResult final func layerAllowsEdgeAntialiasing(_ allowsEdgeAntialiasing: Bool) -> Self { self.layer.allowsEdgeAntialiasing = allowsEdgeAntialiasing return self } /// ChainableSwift @discardableResult final func layerBackgroundColor(_ backgroundColor: CGColor?) -> Self { self.layer.backgroundColor = backgroundColor return self } /// ChainableSwift @discardableResult final func layerCornerRadius(_ cornerRadius: CGFloat) -> Self { self.layer.cornerRadius = cornerRadius return self } /// ChainableSwift @discardableResult final func layerBorderWidth(_ borderWidth: CGFloat) -> Self { self.layer.borderWidth = borderWidth return self } /// ChainableSwift @discardableResult final func layerBorderColor(_ borderColor: CGColor?) -> Self { self.layer.borderColor = borderColor return self } /// ChainableSwift @discardableResult final func layerOpacity(_ opacity: Float) -> Self { self.layer.opacity = opacity return self } /// ChainableSwift @discardableResult final func layerAllowsGroupOpacity(_ allowsGroupOpacity: Bool) -> Self { self.layer.allowsGroupOpacity = allowsGroupOpacity return self } /// ChainableSwift @discardableResult final func layerCompositingFilter(_ compositingFilter: Any?) -> Self { self.layer.compositingFilter = compositingFilter return self } /// ChainableSwift @discardableResult final func layerShouldRasterize(_ shouldRasterize: Bool) -> Self { self.layer.shouldRasterize = shouldRasterize return self } /// ChainableSwift @discardableResult final func layerRasterizationScale(_ rasterizationScale: CGFloat) -> Self { self.layer.rasterizationScale = rasterizationScale return self } /// ChainableSwift @discardableResult final func layerShadowColor(_ shadowColor: CGColor?) -> Self { self.layer.shadowColor = shadowColor return self } /// ChainableSwift @discardableResult final func layerShadowOpacity(_ shadowOpacity: Float) -> Self { self.layer.shadowOpacity = shadowOpacity return self } /// ChainableSwift @discardableResult final func layerShadowOffset(_ shadowOffset: CGSize) -> Self { self.layer.shadowOffset = shadowOffset return self } /// ChainableSwift @discardableResult final func layerShadowRadius(_ shadowRadius: CGFloat) -> Self { self.layer.shadowRadius = shadowRadius return self } /// ChainableSwift @discardableResult final func layerShadowPath(_ shadowPath: CGPath?) -> Self { self.layer.shadowPath = shadowPath return self } }
mit
35c9b705a1013145351358f075e42d08
23.211957
111
0.647138
5.348139
false
false
false
false
soapyigu/LeetCode_Swift
Stack/ValidParentheses.swift
1
1009
/** * Question Link: https://leetcode.com/problems/valid-parentheses/ * Primary idea: Use a stack to see whether the peek left brace is correspond to the current right one * Time Complexity: O(n), Space Complexity: O(n) */ class ValidParentheses { func isValid(_ s: String) -> Bool { var stack = [Character]() for char in s { if char == "(" || char == "[" || char == "{" { stack.append(char) } else if char == ")" { guard stack.count != 0 && stack.removeLast() == "(" else { return false } } else if char == "]" { guard stack.count != 0 && stack.removeLast() == "[" else { return false } } else if char == "}" { guard stack.count != 0 && stack.removeLast() == "{" else { return false } } } return stack.isEmpty } }
mit
67514e46f7c7e8a436908af7d9dfb743
31.580645
102
0.445986
4.827751
false
false
false
false
skunkmb/donut-mayhem
Donut Mayhem/Donut Mayhem/ShopViewController.swift
1
18226
/* ShopViewController.swift Donut Mayhem Created by skunkmb on 2/16/17. Copyright © 2017 skunkmb. All rights reserved. */ import UIKit import QuartzCore class ShopViewController: UIViewController { let selectedBorderColor = UIColor(red:0.89, green:0.00, blue:0.02, alpha:1.0).cgColor let selectedBorderWidth: CGFloat = 2 let selectedBorderRadius: CGFloat = 5 @IBOutlet var coinsLabel: UILabel! @IBOutlet var moreDetailLabel: UILabel! @IBOutlet var basicMuffinImageView: UIImageView! @IBOutlet var branMuffinImageView: UIImageView! @IBOutlet var cupcakeMuffinImageView: UIImageView! @IBOutlet var glutenFreeMuffinImageView: UIImageView! @IBOutlet var illuminatiMuffinImageView: UIImageView! @IBOutlet var swagMuffinImageView: UIImageView! @IBOutlet var basicMuffinButton: UIButton! @IBOutlet var branMuffinButton: UIButton! @IBOutlet var cupcakeMuffinButton: UIButton! @IBOutlet var glutenFreeMuffinButton: UIButton! @IBOutlet var illuminatiMuffinButton: UIButton! @IBOutlet var swagMuffinButton: UIButton! @IBOutlet var bagelDonutImageView: UIImageView! @IBOutlet var basicDonutImageView: UIImageView! @IBOutlet var evilDonutImageView: UIImageView! @IBOutlet var holeDonutImageView: UIImageView! @IBOutlet var jellyDonutImageView: UIImageView! @IBOutlet var nerdDonutImageView: UIImageView! @IBOutlet var bagelDonutButton: UIButton! @IBOutlet var basicDonutButton: UIButton! @IBOutlet var evilDonutButton: UIButton! @IBOutlet var holeDonutButton: UIButton! @IBOutlet var jellyDonutButton: UIButton! @IBOutlet var nerdDonutButton: UIButton! override func viewDidLoad() { super.viewDidLoad() refresh() } /** Updates the shop by refreshing the coin coint and the selected muffin and donut, and hiding unowned muffins and donuts. */ func refresh() { let currentCoins = UserDefaults.standard.integer(forKey: "coins") coinsLabel.text = "Coins: " + String(currentCoins) // If there are no ownedMuffins, add one. if UserDefaults.standard.array(forKey: "ownedMuffins") == nil { UserDefaults.standard.set([GameScene.MuffinType.basicMuffin.rawValue], forKey: "ownedMuffins") } // If there are no ownedDonuts, add one. if UserDefaults.standard.array(forKey: "ownedDonuts") == nil { UserDefaults.standard.set([GameScene.DonutType.basicDonut.rawValue], forKey: "ownedDonuts") } let muffinTypeString = UserDefaults.standard.string(forKey: "muffinType")! let muffinType = GameScene.MuffinType(rawValue: muffinTypeString) let donutTypeString = UserDefaults.standard.string(forKey: "donutType")! let donutType = GameScene.DonutType(rawValue: donutTypeString) let selectedMuffinImageView = findMuffinImageView(withType: muffinType!) let selectedDonutImageView = findDonutImageView(withType: donutType!) selectedMuffinImageView.layer.borderColor = selectedBorderColor selectedMuffinImageView.layer.borderWidth = selectedBorderWidth selectedMuffinImageView.layer.cornerRadius = selectedBorderRadius selectedDonutImageView.layer.borderColor = selectedBorderColor selectedDonutImageView.layer.borderWidth = selectedBorderWidth selectedDonutImageView.layer.cornerRadius = selectedBorderRadius // Go through the rest of the ownedMuffins. for ownedMuffinString in UserDefaults.standard.array(forKey: "ownedMuffins") as! [String] { guard ownedMuffinString != muffinTypeString else { continue } // Remove their borders in the event that a new muffin is bought and selected. let ownedMuffinImageView = findMuffinImageView(withType: GameScene.MuffinType(rawValue: ownedMuffinString)!) ownedMuffinImageView.layer.borderColor = nil ownedMuffinImageView.layer.borderWidth = 0 ownedMuffinImageView.layer.cornerRadius = 0 } // Go through the rest of the ownedDonuts. for ownedDonutString in UserDefaults.standard.array(forKey: "ownedDonuts") as! [String] { guard ownedDonutString != donutTypeString else { continue } // Remove their borders in the event that a new donut is bought and selected. let ownedDonutImageView = findDonutImageView(withType: GameScene.DonutType(rawValue: ownedDonutString)!) ownedDonutImageView.layer.borderColor = nil ownedDonutImageView.layer.borderWidth = 0 ownedDonutImageView.layer.cornerRadius = 0 } let unownedMuffinStrings = getUnownedMuffinStrings() let unownedDonutStrings = getUnownedDonutStrings() // Go through and change the unowned muffins. for unownedMuffinString in unownedMuffinStrings { let unownedMuffinType = GameScene.MuffinType.init(rawValue: unownedMuffinString) let unownedMuffinImageView = findMuffinImageView(withType: unownedMuffinType!) unownedMuffinImageView.image = UIImage.init(named: "mysteryMuffin") } // Also change the unowned donuts. for unownedDonutString in unownedDonutStrings { let unownedDonutType = GameScene.DonutType.init(rawValue: unownedDonutString) let unownedDonutImageView = findDonutImageView(withType: unownedDonutType!) unownedDonutImageView.image = UIImage.init(named: "mysteryDonut") } } /** Finds and returns the `UIImageView` of a `GameScene.MuffinType`. - Parameters: - type: The `GameScene.MuffinType` to find the `UIImageView` of. - Returns: The `UIImageView` that was found. */ func findMuffinImageView(withType type: GameScene.MuffinType) -> UIImageView { switch type { case GameScene.MuffinType.basicMuffin: return basicMuffinImageView case GameScene.MuffinType.branMuffin: return branMuffinImageView case GameScene.MuffinType.cupcakeMuffin: return cupcakeMuffinImageView case GameScene.MuffinType.glutenFreeMuffin: return glutenFreeMuffinImageView case GameScene.MuffinType.illuminatiMuffin: return illuminatiMuffinImageView case GameScene.MuffinType.swagMuffin: return swagMuffinImageView } } /** Finds and returns the `UIImageView` of a `GameScene.DonutType`. - Parameters: - type: The `GameScene.DonutType` to find the `UIImageView` of. - Returns: The `UIImageView` that was found. */ func findDonutImageView(withType type: GameScene.DonutType) -> UIImageView { switch type { case GameScene.DonutType.basicDonut: return basicDonutImageView case GameScene.DonutType.bagelDonut: return bagelDonutImageView case GameScene.DonutType.evilDonut: return evilDonutImageView case GameScene.DonutType.holeDonut: return holeDonutImageView case GameScene.DonutType.jellyDonut: return jellyDonutImageView case GameScene.DonutType.nerdDonut: return nerdDonutImageView } } /** Generates and returns an array of currently unowned muffins as `String`s. - Returns: The array of currently unowned muffins as `String`s. */ func getUnownedMuffinStrings() -> [String] { // Temporarily create a local list of unowned muffins, which can then be shortened by a loop. var unownedMuffins = [ GameScene.MuffinType.basicMuffin.rawValue, GameScene.MuffinType.branMuffin.rawValue, GameScene.MuffinType.cupcakeMuffin.rawValue, GameScene.MuffinType.glutenFreeMuffin.rawValue, GameScene.MuffinType.illuminatiMuffin.rawValue, GameScene.MuffinType.swagMuffin.rawValue, ] for ownedMuffinString in UserDefaults.standard.array(forKey: "ownedMuffins")! { unownedMuffins.remove(at: unownedMuffins.index(of: ownedMuffinString as! String)!) } return unownedMuffins } /** Generates and returns an array of currently unowned donuts as `String`s. - Returns: The array of currently unowned donuts as `String`s. */ func getUnownedDonutStrings() -> [String] { // Temporarily create a local list of unowned donuts, which can then be shortened by a loop. var unownedDonuts = [ GameScene.DonutType.bagelDonut.rawValue, GameScene.DonutType.basicDonut.rawValue, GameScene.DonutType.evilDonut.rawValue, GameScene.DonutType.holeDonut.rawValue, GameScene.DonutType.jellyDonut.rawValue, GameScene.DonutType.nerdDonut.rawValue, ] for ownedDonutString in UserDefaults.standard.array(forKey: "ownedDonuts")! { unownedDonuts.remove(at: unownedDonuts.index(of: ownedDonutString as! String)!) } return unownedDonuts } /** Tries to select a muffin with the specified `GameScene.MuffinType`. - Parameters: - type: The `GameScene.MuffinType` of the muffin to attempt to select. */ func attemptToSelectMuffin(withType type: GameScene.MuffinType) { let muffinString = type.rawValue let ownedMuffinsArray = UserDefaults.standard.array(forKey: "ownedMuffins") as! [String] guard ownedMuffinsArray.index(of: muffinString) != nil else { let alertController = UIAlertController(title: nil, message: "You haven’t unlocked that!", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Okay!", style: UIAlertActionStyle.cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) return } UserDefaults.standard.set(muffinString, forKey: "muffinType") /* Set the description here instead of in refresh because the description should say “Tap to see more detail” at the beginning before a muffin or donut is tapped. */ moreDetailLabel.text = getDescriptionForMuffin(withType: type) refresh() } /** Tries to select a donut with the specified `GameScene.DonutType`. - Parameters: - type: The `GameScene.DonutType` of the donut to attempt to select. */ func attemptToSelectDonut(withType type: GameScene.DonutType) { let donutString = type.rawValue let ownedDonutsArray = UserDefaults.standard.array(forKey: "ownedDonuts") as! [String] guard ownedDonutsArray.index(of: donutString) != nil else { let alertController = UIAlertController(title: nil, message: "You haven’t unlocked that!", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Okay!", style: UIAlertActionStyle.cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) return } UserDefaults.standard.set(donutString, forKey: "donutType") /* Set the description here instead of in refresh because the description should say “Tap to see more detail” at the beginning before a muffin or donut is tapped. */ moreDetailLabel.text = getDescriptionForDonut(withType: type) refresh() } /** Returns a description for a specified `GameScene.MuffinType`. - Parameters: - type: The `GameScene.MuffinType` of the muffin to find the description of. - Returns: The description of the muffin. */ func getDescriptionForMuffin(withType type: GameScene.MuffinType) -> String { switch type { case GameScene.MuffinType.basicMuffin: return "Basic Muffin" case GameScene.MuffinType.branMuffin: return "Bran Muffin" case GameScene.MuffinType.cupcakeMuffin: return "Cupcake" case GameScene.MuffinType.glutenFreeMuffin: return "Gluten-free Muffin" case GameScene.MuffinType.illuminatiMuffin: return "Illuminati Muffin" case GameScene.MuffinType.swagMuffin: return "Swag Muffin" } } /** Returns a description for a specified `GameScene.DonutType`. - Parameters: - type: The `GameScene.DonutType` of the donut to find the description of. - Returns: The description of the donut. */ func getDescriptionForDonut(withType type: GameScene.DonutType) -> String { switch type { case GameScene.DonutType.bagelDonut: return "Bagel" case GameScene.DonutType.basicDonut: return "Sprinkle Donut" case GameScene.DonutType.evilDonut: return "Evil Donut" case GameScene.DonutType.holeDonut: return "Donut Hole" case GameScene.DonutType.jellyDonut: return "Jelly Donut" case GameScene.DonutType.nerdDonut: return "Nerd Donut" } } /** Calls `attemptToSelectMuffin` on the `GameScene.MuffinType` of a muffin when it is pressed. - Parameters: - sender: The `UIButton` of the muffin which was pressed. */ @IBAction func anyMuffinButtonTouchUpInside(_ sender: UIButton) { switch sender { case basicMuffinButton: attemptToSelectMuffin(withType: GameScene.MuffinType.basicMuffin) case branMuffinButton: attemptToSelectMuffin(withType: GameScene.MuffinType.branMuffin) case cupcakeMuffinButton: attemptToSelectMuffin(withType: GameScene.MuffinType.cupcakeMuffin) case glutenFreeMuffinButton: attemptToSelectMuffin(withType: GameScene.MuffinType.glutenFreeMuffin) case illuminatiMuffinButton: attemptToSelectMuffin(withType: GameScene.MuffinType.illuminatiMuffin) case swagMuffinButton: attemptToSelectMuffin(withType: GameScene.MuffinType.swagMuffin) default: break } } /** Calls `attemptToSelectDonut` on the `GameScene.DonutType` of a donut when it is pressed. - Parameters: - sender: The `UIButton` of the donut which was pressed. */ @IBAction func anyDonutButtonTouchUpInside(_ sender: UIButton) { switch sender { case bagelDonutButton: attemptToSelectDonut(withType: GameScene.DonutType.bagelDonut) case basicDonutButton: attemptToSelectDonut(withType: GameScene.DonutType.basicDonut) case evilDonutButton: attemptToSelectDonut(withType: GameScene.DonutType.evilDonut) case holeDonutButton: attemptToSelectDonut(withType: GameScene.DonutType.holeDonut) case jellyDonutButton: attemptToSelectDonut(withType: GameScene.DonutType.jellyDonut) case nerdDonutButton: attemptToSelectDonut(withType: GameScene.DonutType.nerdDonut) default: break } } /** Buys and selects random muffin or donut for 100 coins (if the user has enough) when the “buy” button is pressed, or makes an alert if all unlockables have already been bought. */ @IBAction func buyButtonTouchUpInside() { var currentCoins = UserDefaults.standard.integer(forKey: "coins") guard currentCoins >= 100 else { let alertController = UIAlertController(title: nil, message: "You don’t have enough coins!", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Okay!", style: UIAlertActionStyle.cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) return } var unownedMuffinStrings = getUnownedMuffinStrings() var unownedDonutStrings = getUnownedDonutStrings() guard unownedMuffinStrings.count > 0 || unownedDonutStrings.count > 0 else { let alertController = UIAlertController(title: nil, message: "You’ve unlocked everything!", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Okay!", style: UIAlertActionStyle.cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) return } if unownedMuffinStrings.count > 0 && unownedDonutStrings.count > 0 { /* Decide whether to unlock a muffin or donut by seeing if a random integer from 0 to 1 is equal to 0. */ let unlockMuffin = arc4random_uniform(2) == 0 if unlockMuffin { let randomIndex = arc4random_uniform(UInt32(unownedMuffinStrings.count)) let unlockedMuffinString = unownedMuffinStrings[Int(randomIndex)] var currentOwnedMuffins = UserDefaults.standard.array(forKey: "ownedMuffins") currentOwnedMuffins?.append(unlockedMuffinString) UserDefaults.standard.set(currentOwnedMuffins, forKey: "ownedMuffins") attemptToSelectMuffin(withType: GameScene.MuffinType(rawValue: unlockedMuffinString)!) // Reset the unlocked muffin’s image view to use the actual muffin, not the mystery. let newMuffinImageView = findMuffinImageView(withType: GameScene.MuffinType(rawValue: unlockedMuffinString)!) newMuffinImageView.image = UIImage(named: unlockedMuffinString) } else { let randomIndex = arc4random_uniform(UInt32(unownedDonutStrings.count)) let unlockedDonutString = unownedDonutStrings[Int(randomIndex)] var currentOwnedDonuts = UserDefaults.standard.array(forKey: "ownedDonuts") currentOwnedDonuts?.append(unlockedDonutString) UserDefaults.standard.set(currentOwnedDonuts, forKey: "ownedDonuts") attemptToSelectDonut(withType: GameScene.DonutType(rawValue: unlockedDonutString)!) // Reset the unlocked donut’s image view to use the actual donut, not the mystery. let newDonutImageView = findDonutImageView(withType: GameScene.DonutType(rawValue: unlockedDonutString)!) newDonutImageView.image = UIImage(named: unlockedDonutString) } /* Check to see if the unownedMuffinStrings’s count is greater than 0 (therefore it is the only one with any unowned values left because the && operator failed). */ } else if unownedMuffinStrings.count > 0 { let randomIndex = arc4random_uniform(UInt32(unownedMuffinStrings.count - 1)) let unlockedMuffinString = unownedMuffinStrings[Int(randomIndex)] var currentOwnedMuffins = UserDefaults.standard.array(forKey: "ownedMuffins") currentOwnedMuffins?.append(unlockedMuffinString) UserDefaults.standard.set(currentOwnedMuffins, forKey: "ownedMuffins") attemptToSelectMuffin(withType: GameScene.MuffinType(rawValue: unlockedMuffinString)!) // Reset the unlocked muffin’s image view to use the actual muffin, not the mystery. let newMuffinImageView = findMuffinImageView(withType: GameScene.MuffinType(rawValue: unlockedMuffinString)!) newMuffinImageView.image = UIImage(named: unlockedMuffinString) // If all else fails, but hasn’t returned yet, unlock a new donut. } else { let randomIndex = arc4random_uniform(UInt32(unownedDonutStrings.count - 1)) let unlockedDonutString = unownedDonutStrings[Int(randomIndex)] var currentOwnedDonuts = UserDefaults.standard.array(forKey: "ownedDonuts") currentOwnedDonuts?.append(unlockedDonutString) UserDefaults.standard.set(currentOwnedDonuts, forKey: "ownedDonuts") attemptToSelectDonut(withType: GameScene.DonutType(rawValue: unlockedDonutString)!) // Reset the unlocked donut’s image view to use the actual donut, not the mystery. let newDonutImageView = findDonutImageView(withType: GameScene.DonutType(rawValue: unlockedDonutString)!) newDonutImageView.image = UIImage(named: unlockedDonutString) } // Do some general maitnence on coins. currentCoins -= 100 UserDefaults.standard.set(currentCoins, forKey: "coins") refresh() } }
mit
51a6f15bd1cb0f5b4a08e3b3250ecfe2
35.679435
105
0.77233
3.561668
false
false
false
false
miracl/amcl
version3/swift/fp4.swift
1
13229
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // fp4.swift // // Created by Michael Scott on 07/07/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // /* Finite Field arithmetic Fp^4 functions */ /* FP4 elements are of the form a+ib, where i is sqrt(-1+sqrt(-1)) */ public struct FP4 { private var a:FP2 private var b:FP2 /* constructors */ public init() { a=FP2() b=FP2() } public init(_ c:Int) { a=FP2(c) b=FP2() } public init(_ x:FP4) { a=FP2(x.a) b=FP2(x.b) } public init(_ c:FP2,_ d:FP2) { a=FP2(c) b=FP2(d) } public init(_ c:FP2) { a=FP2(c) b=FP2() } /* reduce all components of this mod Modulus */ mutating func reduce() { a.reduce() b.reduce() } /* normalise all components of this mod Modulus */ mutating func norm() { a.norm() b.norm() } /* test this==0 ? */ func iszilch() -> Bool { return a.iszilch() && b.iszilch() } mutating func cmove(_ g:FP4,_ d:Int) { a.cmove(g.a,d) b.cmove(g.b,d) } /* test this==1 ? */ func isunity() -> Bool { let one=FP2(1); return a.equals(one) && b.iszilch() } /* test is w real? That is in a+ib test b is zero */ func isreal() -> Bool { return b.iszilch(); } /* extract real part a */ func real() -> FP2 { return a; } func geta() -> FP2 { return a; } /* extract imaginary part b */ func getb() -> FP2 { return b; } /* test self=x? */ func equals(_ x:FP4) -> Bool { return a.equals(x.a) && b.equals(x.b) } mutating func set_fp2s(_ c: FP2,_ d: FP2) { a.copy(c) b.copy(d) } mutating func set_fp2(_ c: FP2) { a.copy(c) b.zero() } mutating func set_fp2h(_ c: FP2) { b.copy(c) a.zero() } /* copy self=x */ mutating func copy(_ x:FP4) { a.copy(x.a) b.copy(x.b) } /* set this=0 */ mutating func zero() { a.zero() b.zero() } /* set this=1 */ mutating func one() { a.one() b.zero() } /* set self=-self */ mutating func neg() { norm() var m=FP2(a) var t=FP2() m.add(b) m.neg() t.copy(m); t.add(b) b.copy(m) b.add(a) a.copy(t) norm() } /* self=conjugate(self) */ mutating func conj() { b.neg(); norm() } /* this=-conjugate(this) */ mutating func nconj() { a.neg(); norm() } mutating func adds(_ x: FP2) { a.add(x) } /* self+=x */ mutating func add(_ x:FP4) { a.add(x.a) b.add(x.b) } /* self-=x */ mutating func sub(_ x:FP4) { var m=FP4(x) m.neg() add(m) } /* self-=x */ mutating func rsub(_ x: FP4) { neg() add(x) } /* self*=s where s is FP2 */ mutating func pmul(_ s:FP2) { a.mul(s) b.mul(s) } /* self*=s where s is FP */ mutating func qmul(_ s:FP) { a.pmul(s) b.pmul(s) } /* self*=c where c is int */ mutating func imul(_ c:Int) { a.imul(c) b.imul(c) } /* self*=self */ mutating func sqr() { var t1=FP2(a) var t2=FP2(b) var t3=FP2(a) t3.mul(b) t1.add(b) t2.mul_ip() t2.add(a) t1.norm(); t2.norm() a.copy(t1) a.mul(t2) t2.copy(t3) t2.mul_ip() t2.add(t3); t2.norm() t2.neg() a.add(t2) b.copy(t3) b.add(t3) norm() } /* self*=y */ mutating func mul(_ y:FP4) { var t1=FP2(a) var t2=FP2(b) var t3=FP2() var t4=FP2(b) t1.mul(y.a) t2.mul(y.b) t3.copy(y.b) t3.add(y.a) t4.add(a) t3.norm(); t4.norm() t4.mul(t3) t3.copy(t1) t3.neg() t4.add(t3) t4.norm() t3.copy(t2) t3.neg() b.copy(t4) b.add(t3) t2.mul_ip() a.copy(t2) a.add(t1) norm(); } /* convert this to hex string */ public func toString() -> String { return ("["+a.toString()+","+b.toString()+"]") } public func toRawString() -> String { return ("["+a.toRawString()+","+b.toRawString()+"]") } /* self=1/self */ mutating func inverse() { //norm(); var t1=FP2(a) var t2=FP2(b) t1.sqr() t2.sqr() t2.mul_ip(); t2.norm() t1.sub(t2) t1.inverse() a.mul(t1) t1.neg(); t1.norm() b.mul(t1) } /* self*=i where i = sqrt(-1+sqrt(-1)) */ mutating func times_i() { var s=FP2(b) var t=FP2(b) s.times_i() t.add(s) b.copy(a) a.copy(t) norm() } /* self=self^p using Frobenius */ mutating func frob(_ f:FP2) { a.conj() b.conj() b.mul(f) } /* self=self^e */ func pow(_ e:BIG) -> FP4 { var w=FP4(self) w.norm() var z=BIG(e) var r=FP4(1) z.norm() while (true) { let bt=z.parity() z.fshr(1) if bt==1 {r.mul(w)} if z.iszilch() {break} w.sqr() } r.reduce() return r } /* XTR xtr_a function */ mutating func xtr_A(_ w:FP4,_ y:FP4,_ z:FP4) { var r=FP4(w) var t=FP4(w) r.sub(y); r.norm() r.pmul(a) t.add(y); t.norm() t.pmul(b) t.times_i() copy(r) add(t) add(z) norm() } /* XTR xtr_d function */ mutating func xtr_D() { var w=FP4(self) sqr(); w.conj() w.add(w); w.norm(); sub(w) reduce() } /* r=x^n using XTR method on traces of FP12s */ func xtr_pow(_ n:BIG) -> FP4 { var a=FP4(3) var b=FP4(self) var c=FP4(b) c.xtr_D() var t=FP4() var r=FP4() var sf=FP4(self) let par=n.parity() var v=BIG(n); v.norm(); v.fshr(1) if par==0 {v.dec(1); v.norm()} let nb=v.nbits() var i=nb-1 while i>=0 { if (v.bit(UInt(i)) != 1) { t.copy(b) sf.conj() c.conj() b.xtr_A(a,sf,c) sf.conj() c.copy(t) c.xtr_D() a.xtr_D() } else { t.copy(a); t.conj() a.copy(b) a.xtr_D() b.xtr_A(c,sf,t) c.xtr_D() } i-=1 } if par==0 {r.copy(c)} else {r.copy(b)} r.reduce() return r } /* r=ck^a.cl^n using XTR double exponentiation method on traces of FP12s. See Stam thesis. */ func xtr_pow2(_ ck:FP4,_ ckml:FP4,_ ckm2l:FP4,_ a:BIG,_ b:BIG) -> FP4 { var e=BIG(a) var d=BIG(b) var w=BIG(0) e.norm(); d.norm() var cu=FP4(ck) // can probably be passed in w/o copying var cv=FP4(self) var cumv=FP4(ckml) var cum2v=FP4(ckm2l) var r=FP4() var t=FP4() var f2:Int=0 while d.parity()==0 && e.parity()==0 { d.fshr(1); e.fshr(1); f2 += 1; } while (BIG.comp(d,e) != 0) { if BIG.comp(d,e)>0 { w.copy(e); w.imul(4); w.norm() if BIG.comp(d,w)<=0 { w.copy(d); d.copy(e) e.rsub(w); e.norm() t.copy(cv) t.xtr_A(cu,cumv,cum2v) cum2v.copy(cumv) cum2v.conj() cumv.copy(cv) cv.copy(cu) cu.copy(t) } else if d.parity()==0 { d.fshr(1) r.copy(cum2v); r.conj() t.copy(cumv) t.xtr_A(cu,cv,r) cum2v.copy(cumv) cum2v.xtr_D() cumv.copy(t) cu.xtr_D() } else if e.parity()==1 { d.sub(e); d.norm() d.fshr(1) t.copy(cv) t.xtr_A(cu,cumv,cum2v) cu.xtr_D() cum2v.copy(cv) cum2v.xtr_D() cum2v.conj() cv.copy(t) } else { w.copy(d) d.copy(e); d.fshr(1) e.copy(w) t.copy(cumv) t.xtr_D() cumv.copy(cum2v); cumv.conj() cum2v.copy(t); cum2v.conj() t.copy(cv) t.xtr_D() cv.copy(cu) cu.copy(t) } } if BIG.comp(d,e)<0 { w.copy(d); w.imul(4); w.norm() if BIG.comp(e,w)<=0 { e.sub(d); e.norm() t.copy(cv) t.xtr_A(cu,cumv,cum2v) cum2v.copy(cumv) cumv.copy(cu) cu.copy(t) } else if e.parity()==0 { w.copy(d) d.copy(e); d.fshr(1) e.copy(w) t.copy(cumv) t.xtr_D() cumv.copy(cum2v); cumv.conj() cum2v.copy(t); cum2v.conj() t.copy(cv) t.xtr_D() cv.copy(cu) cu.copy(t) } else if d.parity()==1 { w.copy(e) e.copy(d) w.sub(d); w.norm() d.copy(w); d.fshr(1) t.copy(cv) t.xtr_A(cu,cumv,cum2v) cumv.conj() cum2v.copy(cu) cum2v.xtr_D() cum2v.conj() cu.copy(cv) cu.xtr_D() cv.copy(t) } else { d.fshr(1) r.copy(cum2v); r.conj() t.copy(cumv) t.xtr_A(cu,cv,r) cum2v.copy(cumv) cum2v.xtr_D() cumv.copy(t) cu.xtr_D() } } } r.copy(cv) r.xtr_A(cu,cumv,cum2v) for _ in 0 ..< f2 {r.xtr_D()} r=r.xtr_pow(d) return r } /* self/=2 */ mutating func div2() { a.div2() b.div2() } mutating func div_i() { var u=FP2(a) let v=FP2(b) u.div_ip() a.copy(v) b.copy(u) } mutating func div_2i() { var u=FP2(a) var v=FP2(b) u.div_ip2() v.add(v); v.norm() a.copy(v) b.copy(u) } /* sqrt(a+ib) = sqrt(a+sqrt(a*a-n*b*b)/2)+ib/(2*sqrt(a+sqrt(a*a-n*b*b)/2)) */ /* returns true if this is QR */ mutating func sqrt() -> Bool { if iszilch() {return true} var aa=FP2(a) var s=FP2(b) var t=FP2(a) if s.iszilch() { if t.sqrt() { a.copy(t) b.zero() } else { t.div_ip() _=t.sqrt() b.copy(t) a.zero() } return true } s.sqr() a.sqr() s.mul_ip() s.norm() aa.sub(s) s.copy(aa) if !s.sqrt() { return false } aa.copy(t); aa.add(s); aa.norm(); aa.div2() if !aa.sqrt() { aa.copy(t); aa.sub(s); aa.norm(); aa.div2() if !a.sqrt() { return false } } t.copy(b) s.copy(aa); s.add(aa) s.inverse() t.mul(s) a.copy(aa) b.copy(t) return true } }
apache-2.0
7e798c988402de4fa886bf92f6b6454c
19.605919
97
0.390279
3.147514
false
false
false
false
mitchtreece/Bulletin
Example/Pods/Espresso/Espresso/Classes/Core/Foundation/DataSource.swift
1
2187
// // DataSource.swift // Espresso // // Created by Mitch Treece on 3/10/19. // // NOTE: Still working on this. // Will uncomment and release when ready. //import Foundation // //public protocol DataSourceDelegate: class { // // func dataSourceWillFetchData<T>(_ dataSource: DataSource<T>) // func dataSource<T>(_ dataSource: DataSource<T>, didFetchData newData: [T]) // func dataSourceWillReloadData<T>(_ dataSource: DataSource<T>) // func dataSourceDidReloadData<T>(_ dataSource: DataSource<T>) // //} // //public extension DataSourceDelegate /* Optional */ { // // func dataSourceWillFetchData<T>(_ dataSource: DataSource<T>) {} // func dataSource<T>(_ dataSource: DataSource<T>, didFetchData newData: [T]) {} // func dataSourceWillReloadData<T>(_ dataSource: DataSource<T>) {} // func dataSourceDidReloadData<T>(_ dataSource: DataSource<T>) {} // //} // //public class DataSource<T> { // // public typealias Completion = ([T])->() // public typealias Request = (Completion)->() // // private let request: Request // private var isLoading: Bool = false // private var isReloading: Bool = false // // public private(set) var data = [T]() // // public weak var delegate: DataSourceDelegate? // // public init(_ request: @escaping Request) { // self.request = request // } // // public func fetch() { // // guard !self.isLoading else { return } // self.isLoading = true // // self.delegate?.dataSourceWillFetchData(self) // // func finish(newData: [T]) { // // self.data.append(contentsOf: newData) // self.isLoading = false // // self.delegate?.dataSource(self, didFetchData: newData) // // if self.isReloading { // // self.isReloading = false // self.delegate?.dataSourceDidReloadData(self) // // } // // } // // self.request(finish) // // } // // public func reload() { // // guard !self.isLoading else { return } // // self.delegate?.dataSourceWillReloadData(self) // // self.isReloading = true // self.data.removeAll() // fetch() // // } // //}
mit
ebd627053d301261ed32828ffdb26205
24.137931
83
0.598994
3.713073
false
false
false
false
NorthernRealities/ColorSenseRainbow
ColorSenseRainbow/RainbowHexStringBuilder.swift
1
3529
// // RainbowHexStringBuilder.swift // ColorSenseRainbow // // Created by Reid Gravelle on 2015-05-28. // Copyright (c) 2015 Northern Realities Inc. All rights reserved. // import AppKit class RainbowHexStringBuilder: ColorBuilder { /** Generates a String containing the code required to create a color object for the specified color in the method detailed by the SearchResults. While a new string could be generated more easily by just entering the values into a template replacing the values in the existing string will keep the formatting the way the user prefers. This involves moving backwards through the values as the new values may be different lengths and would change the ranges for later values. - parameter color: The new color that will be described by the string. - parameter forSearchResults: A SearchResults object containing the ranges for text to replace. - returns: A String object containing code how to create the color. */ override func stringForColor( color : NSColor, forSearchResult : SearchResult ) -> String? { guard var returnString = forSearchResult.capturedStrings.first else { return nil } let numberFormatter = NSNumberFormatter() numberFormatter.locale = NSLocale(localeIdentifier: "us") numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle numberFormatter.maximumFractionDigits = ColorBuilder.maximumAlphaFractionDigits numberFormatter.minimumFractionDigits = 1 numberFormatter.decimalSeparator = "." guard let alphaComponent = convertNumberToString( Double ( color.alphaComponent ), numberDesc: "alpha component", numberFormatter: numberFormatter ) else { return nil } if ( forSearchResult.tcr.numberOfRanges == 3 ) { if let modifiedString = processCaptureGroupInSearchResult( forSearchResult, forRangeAtIndex: 2, inText: returnString, withReplacementText: alphaComponent ) { returnString = modifiedString } else { return nil } } else if ( color.alphaComponent < 1.0 ) { // User has changed the alpha so we need to add it to the code. We fake a search result to take account for // the " that the string has at the end before we append the alpha component. var replacementString = forSearchResult.capturedStrings[1] replacementString += "\", alpha: " + alphaComponent let fakeTCR : NSTextCheckingResult = forSearchResult.tcr.copy() as! NSTextCheckingResult var fakeRange = fakeTCR.rangeAtIndex( 1 ) fakeRange.length += 1 let rangeToChange = NSMakeRange( forSearchResult.tcr.rangeAtIndex( 1 ).location - forSearchResult.tcr.rangeAtIndex( 0 ).location, forSearchResult.tcr.rangeAtIndex( 1 ).length + 1 ) let stringRange = rangeToChange.calculateRangeInString( returnString ) returnString.replaceRange( stringRange, with: replacementString ) } if let modifiedString = processCaptureGroupInSearchResult( forSearchResult, forRangeAtIndex: 1, inText: returnString, withReplacementText: color.asHexString() ) { returnString = modifiedString } else { return nil } return returnString } }
mit
3823ed70b2373df71d787c668096cf2f
44.24359
475
0.665628
5.619427
false
false
false
false
iAugux/Zoom-Contacts
Phonetic/PolyphonicCharacters.swift
1
5941
// // PolyphonicCharacters.swift // Phonetic // // Created by Augus on 2/2/16. // Copyright © 2016 iAugus. All rights reserved. // import Foundation /// Add following code to Xcode Playground and replace "重" with your new polyphonic character /// to test whether the result is completely correct. /// Note: guarantee the Pinyin Tone is also correct. /* import Foundation let characterForTesting = "重" func phonetic(str: String) -> String? { var source = str.mutableCopy() CFStringTransform(source as! CFMutableStringRef, nil, kCFStringTransformMandarinLatin, false) if !(source as! NSString).isEqualToString(str) { if source.rangeOfString(" ").location != NSNotFound { let phoneticParts = source.componentsSeparatedByString(" ") source = NSMutableString() for part in phoneticParts { source.appendString(part) } } return source as? String } return nil } phonetic(characterForTesting) */ // REFERENCE: http://www.smartisan.com/special/#/duoyinzi // Some polyphonic characters don't need to be fixed: // 宓 郇 隗 乐 覃 藏 朝 便 校 行 // 艾 巴 暴 贲 邲 伯 柏 车 冲 褚...... struct PolyphonicChar { static let all = [ b1, b2, b3, c1, c2, c3, d1, g1, g2, g3, g4, h1, j1, j2, k1, m1, m2, n1, o1, p1, p2, q1, q2, q3, q4, r1, s1, s2, s3, s4, x1, x2, y1, y2, y3, y4, z1, z2, z3, z4, z5 ] static var b1 = Polyphonic(character: "秘", replacement: "必", pinyin: "bì") static var b2 = Polyphonic(character: "薄", replacement: "博", pinyin: "bó") static var b3 = Polyphonic(character: "卜", replacement: "补", pinyin: "bǔ") static var c1 = Polyphonic(character: "重", replacement: "虫", pinyin: "chóng") static var c2 = Polyphonic(character: "种", replacement: "虫", pinyin: "chóng") static var c3 = Polyphonic(character: "单于", replacement: "缠于", pinyin: "chán yú") static var d1 = Polyphonic(character: "都", replacement: "嘟", pinyin: "dū") static var g1 = Polyphonic(character: "盖", replacement: "哿", pinyin: "gě") static var g2 = Polyphonic(character: "句", replacement: "勾", pinyin: "gōu") static var g3 = Polyphonic(character: "炅", replacement: "贵", pinyin: "guì") static var g4 = Polyphonic(character: "过", replacement: "锅", pinyin: "guō") static var h1 = Polyphonic(character: "华", replacement: "话", pinyin: "huà") static var j1 = Polyphonic(character: "纪", replacement: "几", pinyin: "jǐ") static var j2 = Polyphonic(character: "圈", replacement: "眷", pinyin: "juàn") static var k1 = Polyphonic(character: "阚", replacement: "看", pinyin: "kàn") static var m1 = Polyphonic(character: "缪", replacement: "庙", pinyin: "miào") static var m2 = Polyphonic(character: "万俟", replacement: "莫奇", pinyin: "mò qí") static var n1 = Polyphonic(character: "粘", replacement: "年", pinyin: "nián") static var o1 = Polyphonic(character: "区", replacement: "欧", pinyin: "ōu") static var p1 = Polyphonic(character: "朴", replacement: "嫖", pinyin: "piáo") static var p2 = Polyphonic(character: "繁", replacement: "婆", pinyin: "pó") static var q1 = Polyphonic(character: "戚", replacement: "器", pinyin: "qì") static var q2 = Polyphonic(character: "卡", replacement: "酠", pinyin: "qiǎ") static var q3 = Polyphonic(character: "覃", replacement: "秦", pinyin: "qín") static var q4 = Polyphonic(character: "仇", replacement: "球", pinyin: "qiú") static var r1 = Polyphonic(character: "任", replacement: "人", pinyin: "rén") static var s1 = Polyphonic(character: "单", replacement: "善", pinyin: "shàn") static var s2 = Polyphonic(character: "召", replacement: "绍", pinyin: "shào") static var s3 = Polyphonic(character: "折", replacement: "蛇", pinyin: "shé") static var s4 = Polyphonic(character: "沈", replacement: "审", pinyin: "shěn") static var x1 = Polyphonic(character: "颉", replacement: "鞋", pinyin: "xié") static var x2 = Polyphonic(character: "解", replacement: "谢", pinyin: "xiè") static var y1 = Polyphonic(character: "燕", replacement: "烟", pinyin: "yān") static var y2 = Polyphonic(character: "闫", replacement: "颜", pinyin: "yán") static var y3 = Polyphonic(character: "员", replacement: "运", pinyin: "yùn") static var y4 = Polyphonic(character: "玉迟", replacement: "玉迟", pinyin: "yù chí") static var z1 = Polyphonic(character: "曾", replacement: "增", pinyin: "zēng") static var z2 = Polyphonic(character: "查", replacement: "渣", pinyin: "zhā") static var z3 = Polyphonic(character: "翟", replacement: "宅", pinyin: "zhái") static var z4 = Polyphonic(character: "祭", replacement: "债", pinyin: "zhài") static var z5 = Polyphonic(character: "中行", replacement: "中航", pinyin: "zhōng háng") } class Polyphonic { var character: String var replacement: String var pinyin: String var prefix: String var key: String var on: Bool { get { guard NSUserDefaults.standardUserDefaults().valueForKey(key) != nil else { return true } return NSUserDefaults.standardUserDefaults().boolForKey(key) } } init(character: String, replacement: String, pinyin: String) { self.character = character self.replacement = replacement self.pinyin = pinyin self.key = "kPolyphonicKey+" + character self.prefix = prefixLetter(pinyin) } } private func prefixLetter(str: String) -> String { let str = str as NSString return str.length > 0 ? str.substringToIndex(1).uppercaseString : "" }
mit
ded268eb3a811cd760151c50d6a2972b
33.369697
100
0.627403
3.222159
false
false
false
false
JasonPan/ADSSocialFeedScrollView
ADSSocialFeedScrollView/Providers/Youtube/Data/YoutubeVideo.swift
1
1543
// // YoutubeVideo.swift // ADSSocialFeedScrollView // // Created by Jason Pan on 14/02/2016. // Copyright © 2016 ANT Development Studios. All rights reserved. // import UIKit class YoutubeVideo: PostProtocol { private(set) var playlist: YoutubePlaylist! var id: String! var title: String! var description: String! var thumbnailImageURL: String! var publishedAt: String! var publishedAt_DATE: NSDate! //********************************************************************************************************* // MARK: - Constructors //********************************************************************************************************* init(playlist: YoutubePlaylist, videoId: String, title: String!, description: String!, thumbnailImageURL: String!, publishedAt: String!) { self.playlist = playlist self.id = videoId self.title = title self.description = description self.thumbnailImageURL = thumbnailImageURL self.publishedAt = publishedAt self.publishedAt_DATE = ADSSocialDateFormatter.dateFromString(self.publishedAt, provider: .Youtube) } //********************************************************************************************************* // MARK: - PostProtocol //********************************************************************************************************* var createdAtDate: NSDate! { return self.publishedAt_DATE } }
mit
461b4103a39c3966a404f29956cda7d6
32.521739
142
0.465629
6.39834
false
false
false
false
MA806P/SwiftDemo
SwiftTestDemo/SwiftTestDemo/main.swift
1
11758
// // main.swift // SwiftTestDemo // // Created by MA806P on 2018/7/11. // Copyright © 2018年 myz. All rights reserved. // import Foundation //var enumerationTest = EnumerationsTestObject() //enumerationTest.enmerationsDemo() //var structClassTest = StructClassTest() //structClassTest.structClassFuncTest() //var obj = OCObject() //obj.startTimerRunWithGCD() //class Person: NSObject { // var name: String // override init() { // self.name = "adsf"; // } //} //for i in 0..<3 { // print(i); //} // 0 1 2 //for i in 0...3 { // print(i) //} // 0 1 2 3 //let names = [1, 2, 3, 4] //for name in names[2...] { // print(name) //} // 3 4 //for name in names[...2] { // print(name) //}// 1 2 3 //for name in names[..<2] { // print(name) //}// 1 2 //let range = ...5 //range.contains(7) // false //range.contains(4) // true //print( range.contains(-9) ) // true //let http404Error = (404, "Not Found") //let (statusCode, statusMessage) = http404Error //print("Tuples code:\(statusCode), message:\(statusMessage). \(http404Error.0) + \(http404Error.1)") ////let (statusCode, _) = http404Error //let http200Status = (code: 200, description: "OK") //print("Status: \(http200Status.code), \(http200Status.description)") /* Swift’s nil isn’t the same as nil in Objective-C. In Objective-C, nil is a pointer to a nonexistent object. In Swift, nil isn’t a pointer—it’s the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types. */ //var optionalVar : Int? = 200 //print("optinal var \(optionalVar ?? 404)") //if optionalVar != nil { // print("i'm sure is contain a value \(optionalVar!)") //} //two tuples of type (String, Bool) //can’t be compared with the < operator //because the < operator can’t be applied to Bool values. //print(("blue", -1) < ("purple", 1)) // OK, evaluates to true //("blue", false) < ("purple", true) // Error because < can't compare Boolean values //let possibleString: String? = "An optional string." //let forcedString: String = possibleString! // requires an exclamation mark //let assumedString: String! = "An implicitly unwrapped optional string." //let implicitString: String = assumedString // no need for an exclamation mark //print("\(possibleString) = \(forcedString) \n\(assumedString) = \(implicitString)") //--------------- Strings and Characters ----------------- //let quotation = """ // //If you need a string that spans several lines, \ //use a multiline string literal—a sequence of characters // surrounded by three double quotation marks // //"test is test" // //""" //print(quotation) //var emptyString = "" //if emptyString.isEmpty { // print("Nothing to see here") //} // //for character in "Dog" { // print(character) //} // //let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"] //let catString = String(catCharacters) //print(catString)//Cat!🐱 //let greeting = "Guten Tag!" //greeting[greeting.startIndex] // G //greeting[greeting.index(before: greeting.endIndex)] // ! //greeting[greeting.index(after: greeting.startIndex)] // u //let index = greeting.index(greeting.startIndex, offsetBy: 7) //greeting[index] // a //var welcome = "hello" //welcome.insert("!", at: welcome.endIndex) //// welcome now equals "hello!" //welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex)) //// welcome now equals "hello there!" // //welcome.remove(at: welcome.index(before: welcome.endIndex)) //// welcome now equals "hello there" // //let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex //welcome.removeSubrange(range) //// welcome now equals "hello" // //let greeting = "Hello, world!" //let index = greeting.firstIndex(of: ",") ?? greeting.endIndex //let beginning = greeting[..<index] //// beginning is "Hello" // //// Convert the result to a String for long-term storage. //let newString = String(beginning) //--------------- Collection Types ----------------- //array set dictionary //var a = Array(repeating: 1, count: 3) //var b = Array(repeating: 2, count: 3) ////b += a; //print(a+b) //[1, 1, 1, 2, 2, 2] // //var c = ["1", "2", "3", "4", "5", "6", "7"] //c[4...6] = ["e", "f"] //print(c) //["1", "2", "3", "4", "e", "f"] // //for (index, value) in c.enumerated() { // print("item \(index + 1) = \(value)") //} //var d : Set = ["x", "z", "y"] //for i in d.sorted() { // print(i) //} // x y z //var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] //for (airportCode, airportName) in airports { // print("\(airportCode): \(airportName)") //} //let airportCodes = [String](airports.keys) //print(airportCodes) //let airportNames = [String](airports.values) //print(airportNames) //--------------- Control Flow ----------------- //let base = 3 //let power = 10 //var answer = 1 //for _ in 1...power { // answer *= base //} //let minuteInterval = 5 //for tickMark in stride(from: 0, to: 60, by: minuteInterval) { // // render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55) // print(tickMark) //} //let c: Character = "h" //switch c { //case "a": // print("a") //case "b": // print("b") //case "c": // print("c") //case "d","e","f": // print("def") //case "g"..<"l": // print("g..<l") //default: // print("NO") //} /* the entire switch statement finishes its execution as soon as the first matching switch case is completed, without requiring an explicit break statement. */ //let somePoint = (6, 1) //switch somePoint { //case (0,0): // print("origin") //case (_, 0): // print("x-axis") //case (0, _): // print("y-axis") //case (-2...2, -2...2): // print("inside the box") // //case (let x, 1): // print(" x value of \(x)") //case (1, let y): // print(" y value of \(y)") //case let (x, y): // print("somewhere else at (\(x), \(y))") ////default: //// print("outside") // //} //let a = (1, 1) //switch a { //case let(x,y) where x == y: // print("x==y") //case let(x,y) where x == -y: // print("x==-y") //case let(x,y): // print("x=\(x), y=\(y)") //} //gameLoop: while square != finalSquare { // diceRoll += 1 // if diceRoll == 7 { diceRoll = 1 } // switch square + diceRoll { // case finalSquare: // // diceRoll will move us to the final square, so the game is over // break gameLoop // case let newSquare where newSquare > finalSquare: // // diceRoll will move us beyond the final square, so roll again // continue gameLoop // default: // // this is a valid move, so find out its effect // square += diceRoll // square += board[square] // } //} //print("Game over!") /*A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause—the code inside the else clause is executed if the condition is not true.*/ //func greet(person: [String: String]) { // guard let name = person["name"] else { // return // } // print("Hello \(name)!") // guard let location = person["location"] else { // print("I hope the weather is nice near you.") // return // } // print("I hope the weather is nice in \(location).") //} //greet(person: ["name": "John"]) //// Prints "Hello John!" //// Prints "I hope the weather is nice near you." //greet(person: ["name": "Jane", "location": "Cupertino"]) //// Prints "Hello Jane!" //// Prints "I hope the weather is nice in Cupertino." //greet(person: ["a":"b"]) //Checking API Availability //if #available(iOS 10, macOS 10.12, *) {} //--------------- Objects and Classes ----------------- //class Person { // var name: String // var otherVar: Int = 0 // // init(name: String) { // self.name = name // } // // func greet() -> String { // return "a person name is \(name)" // } //} //class Child : Person { // var age: Int // // init(age: Int, name: String) { // self.age = age // super.init(name: name) // otherVar = 11 // } // // override func greet() -> String { // return "greet from child \(name), \(age), \(otherVar)" // } //} //var pereson1 = Person(name: "Tom") //print(pereson1.greet()) //var child = Child(age: 10, name: "coco") //print(child.greet()) ////One of the most important differences between structures and classes ////is that structures are always copied when they are passed around in your code, ////but classes are passed by reference. //struct Card { // var rank: Int // var suit: String // func simpleDescription() -> String { // return "The \(rank) of \(suit)" // } //} //let threeOfSpades = Card(rank: 1, suit: "aa") //let threeOfSpadesDescription = threeOfSpades.simpleDescription() //print(threeOfSpadesDescription) //The 1 of aa //--------------- Protocols and Extensions ----------------- //protocol ExampleProtocol { // var simpleDescription: String { get } // mutating func adjust() //} ////Classes, enumerations, and structs can all adopt protocols. // //struct SimpleStructure: ExampleProtocol { // var simpleDescription: String = "A simple structure" // mutating func adjust() { // simpleDescription += " (adjusted)" // } //} //var b = SimpleStructure() //b.adjust() //let bDescription = b.simpleDescription //print(bDescription) //A simple structure (adjusted) // ////the use of the mutating keyword in the declaration of SimpleStructure ////to mark a method that modifies the structure. ////The declaration of SimpleClass doesn’t need any of its methods marked as mutating ////because methods on a class can always modify the class. // //extension Int: ExampleProtocol { // var simpleDescription: String { // return "The number \(self)" // } // mutating func adjust() { // self += 42 // } //} //print(7.simpleDescription) //var a = 1; //a.adjust() //print(a) //43 //--------------- Error Handling ----------------- //enum PrinterError: Error { // case outOfPaper // case noToner // case onFire //} //func send(job: Int, toPrinter printerName: String) throws -> String { // if printerName == "Never Has Toner" { // throw PrinterError.noToner // } // return "Job sent" //} // // //do { // let printerResponse = try send(job: 1040, toPrinter: "Never Has Toner") // print(printerResponse) //} catch { // print(error) //} // //do { // let printerResponse = try send(job: 1440, toPrinter: "Gutenberg") // print(printerResponse) //} catch PrinterError.onFire { // print("I'll just put this over here, with the rest of the fire.") //} catch let printerError as PrinterError { // print("Printer error: \(printerError).") //} catch { // print(error) //} //let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner") //Assertions are checked only in debug builds, //but preconditions are checked in both debug and production builds. //In production builds, the condition inside an assertion isn’t evaluated. //This means you can use as many assertions as you want during your development process, without impacting performance in production. //let age = -3 //assert(age >= 0, "A person's age can't be less than zero.") //// This assertion fails because -3 is not >= 0. //print("age = \(age)") // //if age > 10 { // print("You can ride the roller-coaster or the ferris wheel.") //} else if age > 0 { // print("You can ride the ferris wheel.") //} else { // assertionFailure("A person's age can't be less than zero.") //}
apache-2.0
a8871c88c97d80b38a515660c170eeb9
23.845339
386
0.610301
3.390286
false
false
false
false
wikimedia/wikipedia-ios
WMF Framework/EventLoggingService.swift
1
17248
import Foundation import CocoaLumberjackSwift enum EventLoggingError { case generic case network } @objc(WMFEventLoggingService) public class EventLoggingService : NSObject, URLSessionDelegate { private struct Key { static let isEnabled = "SendUsageReports" static let appInstallID = "WMFAppInstallID" static let lastLoggedSnapshot = "WMFLastLoggedSnapshot" static let appInstallDate = "AppInstallDate" static let loggedDaysInstalled = "DailyLoggingStatsDaysInstalled" static let lastSuccessfulPost = "LastSuccessfulPost" } private var pruningAge: TimeInterval = 60*60*24*30 // 30 days private var sendOnWWANThreshold: TimeInterval = 24 * 60 * 60 private var postBatchSize = 32 private var postTimeout: TimeInterval = 60*2 // 2 minutes private var postInterval: TimeInterval = 60*10 // 10 minutes private var debugDisableImmediateSend = false private let session: Session private let persistentStoreCoordinator: NSPersistentStoreCoordinator private let managedObjectContext: NSManagedObjectContext private let operationQueue: OperationQueue @objc(sharedInstance) public static let shared: EventLoggingService? = { let fileManager = FileManager.default var permanentStorageDirectory = fileManager.wmf_containerURL().appendingPathComponent("Event Logging", isDirectory: true) var didGetDirectoryExistsError = false do { try fileManager.createDirectory(at: permanentStorageDirectory, withIntermediateDirectories: true, attributes: nil) } catch let error { DDLogError("EventLoggingService: Error creating permanent cache: \(error)") } do { var values = URLResourceValues() values.isExcludedFromBackup = true try permanentStorageDirectory.setResourceValues(values) } catch let error { DDLogError("EventLoggingService: Error excluding from backup: \(error)") } let permanentStorageURL = permanentStorageDirectory.appendingPathComponent("Events.sqlite") DDLogDebug("EventLoggingService: Events persistent store: \(permanentStorageURL)") // SINGLETONTODO let eventLoggingService = EventLoggingService(session: MWKDataStore.shared().session, permanentStorageURL: permanentStorageURL) if let eventLoggingService = eventLoggingService { MWKDataStore.shared().setupAbTestsController(withPersistenceService: eventLoggingService) } return eventLoggingService }() @objc public func log(event: [String: Any], schema: String, revision: Int, wiki: String) { let event: NSDictionary = ["event": event, "schema": schema, "revision": revision, "wiki": wiki] logEvent(event) } public init?(session: Session, permanentStorageURL: URL?) { let bundle = Bundle.wmf let modelURL = bundle.url(forResource: "EventLogging", withExtension: "momd")! let model = NSManagedObjectModel(contentsOf: modelURL)! let psc = NSPersistentStoreCoordinator(managedObjectModel: model) let options = [NSMigratePersistentStoresAutomaticallyOption: NSNumber(booleanLiteral: true), NSInferMappingModelAutomaticallyOption: NSNumber(booleanLiteral: true)] operationQueue = OperationQueue() operationQueue.maxConcurrentOperationCount = 1 self.session = session if let storeURL = permanentStorageURL { do { try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) } catch { do { try FileManager.default.removeItem(at: storeURL) } catch { } do { try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options) } catch { return nil } } } else { do { try psc.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: options) } catch { return nil } } self.persistentStoreCoordinator = psc self.managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) self.managedObjectContext.persistentStoreCoordinator = psc super.init() } @objc public func reset() { self.resetSession() self.resetInstall() } @objc func migrateShareUsageAndInstallIDToUserDefaults() { let enabledNumber = libraryValue(for: Key.isEnabled) as? NSNumber if enabledNumber != nil { UserDefaults.standard.wmf_sendUsageReports = enabledNumber!.boolValue } else { UserDefaults.standard.wmf_sendUsageReports = false } UserDefaults.standard.wmf_appInstallId = libraryValue(for: Key.appInstallID) as? String } @objc private func logEvent(_ event: NSDictionary) { let now = NSDate() perform { moc in let record = NSEntityDescription.insertNewObject(forEntityName: "WMFEventRecord", into: self.managedObjectContext) as! EventRecord record.event = event record.recorded = now record.userAgent = WikipediaAppUtils.versionedUserAgent() DDLogDebug("EventLoggingService: \(record.objectID) recorded!") self.save(moc) } } @objc private func tryPostEvents(_ completion: (() -> Void)? = nil) { let operation = AsyncBlockOperation { (operation) in self.perform { moc in let pruneFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "WMFEventRecord") pruneFetch.returnsObjectsAsFaults = false let pruneDate = Date().addingTimeInterval(-(self.pruningAge)) as NSDate pruneFetch.predicate = NSPredicate(format: "(recorded < %@) OR (posted != nil) OR (failed == TRUE)", pruneDate) let delete = NSBatchDeleteRequest(fetchRequest: pruneFetch) delete.resultType = .resultTypeCount do { let result = try self.managedObjectContext.execute(delete) guard let deleteResult = result as? NSBatchDeleteResult else { DDLogError("EventLoggingService: Could not read NSBatchDeleteResult") return } guard let count = deleteResult.result as? Int else { DDLogError("EventLoggingService: Could not read NSBatchDeleteResult count") return } if count > 0 { DDLogInfo("EventLoggingService: Pruned \(count) events") } } catch let error { DDLogError("EventLoggingService: Error pruning events: \(error.localizedDescription)") } let fetch: NSFetchRequest<EventRecord> = EventRecord.fetchRequest() fetch.sortDescriptors = [NSSortDescriptor(keyPath: \EventRecord.recorded, ascending: true)] fetch.predicate = NSPredicate(format: "(posted == nil) AND (failed != TRUE)") fetch.fetchLimit = self.postBatchSize var eventRecords: [EventRecord] = [] do { eventRecords = try moc.fetch(fetch) } catch let error { DDLogError(error.localizedDescription) } var wifiOnly = true if let lastSuccessNumber = moc.wmf_keyValue(forKey: Key.lastSuccessfulPost)?.value as? NSNumber { let now = CFAbsoluteTimeGetCurrent() let interval = now - CFAbsoluteTime(lastSuccessNumber.doubleValue) if interval > self.sendOnWWANThreshold { wifiOnly = false } } if !eventRecords.isEmpty { self.postEvents(eventRecords, onlyWiFi: wifiOnly, completion: { operation.finish() }) } else { operation.finish() } } } operationQueue.addOperation(operation) guard let completion = completion else { return } let completionBlockOp = BlockOperation(block: completion) completionBlockOp.addDependency(operation) operationQueue.addOperation(completion) } private func perform(_ block: @escaping (_ moc: NSManagedObjectContext) -> Void) { let moc = self.managedObjectContext moc.perform { block(moc) } } private func performAndWait(_ block: (_ moc: NSManagedObjectContext) -> Void) { let moc = self.managedObjectContext moc.performAndWait { block(moc) } } private func asyncSave() { perform { (moc) in self.save(moc) } } private func postEvents(_ eventRecords: [EventRecord], onlyWiFi: Bool, completion: @escaping () -> Void) { DDLogDebug("EventLoggingService: Posting \(eventRecords.count) events!") let taskGroup = WMFTaskGroup() var completedRecordIDs = Set<NSManagedObjectID>() var failedRecordIDs = Set<NSManagedObjectID>() for record in eventRecords { let moid = record.objectID guard let payload = record.event else { failedRecordIDs.insert(moid) continue } taskGroup.enter() let userAgent = record.userAgent ?? WikipediaAppUtils.versionedUserAgent() submit(payload: payload, userAgent: userAgent, onlyWiFi: onlyWiFi) { (error) in if let error = error { if error != .network { failedRecordIDs.insert(moid) } } else { completedRecordIDs.insert(moid) } taskGroup.leave() } } taskGroup.waitInBackground { self.perform { moc in let postDate = NSDate() for moid in completedRecordIDs { let mo = try? self.managedObjectContext.existingObject(with: moid) guard let record = mo as? EventRecord else { continue } record.posted = postDate } for moid in failedRecordIDs { let mo = try? self.managedObjectContext.existingObject(with: moid) guard let record = mo as? EventRecord else { continue } record.failed = true } if completedRecordIDs.count == eventRecords.count { self.managedObjectContext.wmf_setValue(NSNumber(value: CFAbsoluteTimeGetCurrent()), forKey: Key.lastSuccessfulPost) DDLogDebug("EventLoggingService: All records succeeded") } else { DDLogDebug("EventLoggingService: Some records failed") } self.save(moc) completion() } } } private func submit(payload: NSObject, userAgent: String, onlyWiFi: Bool, completion: @escaping (EventLoggingError?) -> Void) { guard let url = Configuration.current.eventLoggingAPIURL(with: payload) else { DDLogError("EventLoggingService: Could not create URL") completion(EventLoggingError.generic) return } var request = URLRequest(url: url) request.setValue(userAgent, forHTTPHeaderField: "User-Agent") let session = onlyWiFi ? self.session.wifiOnlyURLSession : self.session.defaultURLSession let task = session.dataTask(with: request, completionHandler: { (_, response, error) in guard error == nil, let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode / 100 == 2 else { if let error = error as NSError?, error.domain == NSURLErrorDomain { completion(EventLoggingError.network) } else { completion(EventLoggingError.generic) } return } completion(nil) // DDLogDebug("EventLoggingService: event \(eventRecord.objectID) posted!") }) task.resume() } // mark stored values private func save(_ moc: NSManagedObjectContext) { guard moc.hasChanges else { return } do { try moc.save() } catch let error { DDLogError("Error saving EventLoggingService managedObjectContext: \(error)") } } private var semaphore = DispatchSemaphore(value: 1) private var libraryValueCache: [String: NSCoding] = [:] public func libraryValue(for key: String) -> NSCoding? { semaphore.wait() defer { semaphore.signal() } var value = libraryValueCache[key] if value != nil { return value } performAndWait { moc in value = managedObjectContext.wmf_keyValue(forKey: key)?.value if value != nil { libraryValueCache[key] = value return } if let legacyValue = UserDefaults.standard.object(forKey: key) as? NSCoding { value = legacyValue libraryValueCache[key] = legacyValue managedObjectContext.wmf_setValue(legacyValue, forKey: key) UserDefaults.standard.removeObject(forKey: key) save(moc) } } return value } public func setLibraryValue(_ value: NSCoding?, for key: String) { semaphore.wait() defer { semaphore.signal() } libraryValueCache[key] = value perform { moc in self.managedObjectContext.wmf_setValue(value, forKey: key) self.save(moc) } } @objc public var isEnabled: Bool { return UserDefaults.standard.wmf_sendUsageReports } @objc public var lastLoggedSnapshot: NSCoding? { get { return libraryValue(for: Key.lastLoggedSnapshot) } set { setLibraryValue(newValue, for: Key.lastLoggedSnapshot) } } @objc public var appInstallDate: Date? { get { var value = libraryValue(for: Key.appInstallDate) as? Date if value == nil { value = Date() setLibraryValue(value as NSDate?, for: Key.appInstallDate) } return value } set { setLibraryValue(newValue as NSDate?, for: Key.appInstallDate) } } @objc public var loggedDaysInstalled: NSNumber? { get { return libraryValue(for: Key.loggedDaysInstalled) as? NSNumber } set { setLibraryValue(newValue, for: Key.loggedDaysInstalled) } } private var _sessionID: String? @objc public var sessionID: String? { semaphore.wait() defer { semaphore.signal() } if _sessionID == nil { _sessionID = UUID().uuidString } return _sessionID } private var _sessionStartDate: Date? @objc public var sessionStartDate: Date? { semaphore.wait() defer { semaphore.signal() } if _sessionStartDate == nil { _sessionStartDate = Date() } return _sessionStartDate } @objc public func resetSession() { semaphore.wait() defer { semaphore.signal() } _sessionID = nil _sessionStartDate = Date() } private func resetInstall() { UserDefaults.standard.wmf_appInstallId = nil lastLoggedSnapshot = nil loggedDaysInstalled = nil appInstallDate = nil } } extension EventLoggingService: PeriodicWorker { public func doPeriodicWork(_ completion: @escaping () -> Void) { tryPostEvents(completion) } } extension EventLoggingService: BackgroundFetcher { public func performBackgroundFetch(_ completion: @escaping (UIBackgroundFetchResult) -> Void) { doPeriodicWork { completion(.noData) } } } extension EventLoggingService: ABTestsPersisting { }
mit
6a48a3ac68b25b9077b87bb1af4aa364
35.854701
172
0.573458
5.821127
false
false
false
false
wilbert/Inflection
Source/Pluralize.swift
1
8859
// // Pluralize.swift // // usage: // "Tooth".pluralize // "Nutrtion".pluralize // "House".pluralize(count: 1) // "Person".pluralize(count: 2, with: "Persons") // // Copyright (c) 2014 Joshua Arvin Lat // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation public class Pluralize { var uncountables:[String] = [] var rules:[(rule: String, template: String)] = [] public init() { uncountables = [ "access", "accommodation", "adulthood", "advertising", "advice", "aggression", "aid", "air", "alcohol", "anger", "applause", "arithmetic", "art", "assistance", "athletics", "attention", "bacon", "baggage", "ballet", "beauty", "beef", "beer", "biology", "botany", "bread", "butter", "carbon", "cash", "chaos", "cheese", "chess", "childhood", "clothing", "coal", "coffee", "commerce", "compassion", "comprehension", "content", "corruption", "cotton", "courage", "currency", "dancing", "danger", "data", "delight", "dignity", "dirt", "distribution", "dust", "economics", "education", "electricity", "employment", "engineering", "envy", "equipment", "ethics", "evidence", "evolution", "faith", "fame", "fish", "flour", "flu", "food", "freedom", "fuel", "fun", "furniture", "garbage", "garlic", "genetics", "gold", "golf", "gossip", "grammar", "gratitude", "grief", "ground", "guilt", "gymnastics", "hair", "happiness", "hardware", "harm", "hate", "hatred", "health", "heat", "height", "help", "homework", "honesty", "honey", "hospitality", "housework", "humour", "hunger", "hydrogen", "ice", "ice", "cream", "importance", "inflation", "information", "injustice", "innocence", "iron", "irony", "jealousy", "jelly", "judo", "karate", "kindness", "knowledge", "labour", "lack", "laughter", "lava", "leather", "leisure", "lightning", "linguistics", "litter", "livestock", "logic", "loneliness", "luck", "luggage", "machinery", "magic", "management", "mankind", "marble", "mathematics", "mayonnaise", "measles", "meat", "methane", "milk", "money", "mud", "music", "nature", "news", "nitrogen", "nonsense", "nurture", "nutrition", "obedience", "obesity", "oil", "oxygen", "passion", "pasta", "patience", "permission", "physics", "poetry", "pollution", "poverty", "power", "pronunciation", "psychology", "publicity", "quartz", "racism", "rain", "relaxation", "reliability", "research", "respect", "revenge", "rice", "rubbish", "rum", "salad", "satire", "seaside", "shame", "shopping", "silence", "sleep", "smoke", "smoking", "snow", "soap", "software", "soil", "sorrow", "soup", "speed", "spelling", "steam", "stuff", "stupidity", "sunshine", "symmetry", "tennis", "thirst", "thunder", "toast", "tolerance", "toys", "traffic", "transporation", "travel", "trust", "understanding", "unemployment", "unity", "validity", "veal", "vengeance", "violence"] rule("$", with:"$1s") rule("s$", with:"$1ses") rule("(t|r|l|b)y$", with:"$1ies") rule("x$", with:"$1xes") rule("(sh|zz|ss)$", with:"$1es") rule("(ax)is", with: "$1es") rule("(cact|nucle|alumn|bacill|fung|radi|stimul|syllab)us$", with:"$1i") rule("(corp)us$", with:"$1ora") rule("sis$", with:"$1ses") rule("ch$", with:"$1ches") rule("o$", with:"$1os") rule("(buffal|carg|mosquit|torped|zer|vet|her|ech)o$", with:"$1oes") rule("fe$", with:"$1ves") rule("(thie)f$", with:"$1ves") rule("oaf$", with:"$1oaves") rule("um$", with:"$1a") rule("ium$", with:"$1ia") rule("oof$", with:"$1ooves") rule("(nebul)a", with:"$1ae") rule("(criteri|phenomen)on$", with:"$1a") rule("(potat|tomat|volcan)o$", with:"$1oes") rule("^(|wo|work|fire)man$", with: "$1men") rule("(f)oot$", with: "$1eet") rule("lf$", with: "$1lves") rule("(t)ooth$", with: "$1eeth") rule("(g)oose$", with: "$1eese") rule("^(c)hild$", with: "$1hildren") rule("^(o)x$", with: "$1xen") rule("^(p)erson$", with: "$1eople") rule("(m|l)ouse$", with: "$1ice") rule("^(d)ie$", with: "$1ice") rule("^(alg|vertebr|vit)a$", with: "$1ae") rule("^(a)lumna$", with: "$1lumnae") rule("^(a)pparatus$", with: "$1pparatuses") rule("^(ind)ex$", with: "$1ices") rule("^(append|matr)ix$", with: "$1ices") rule("^(b|tabl)eau$", with: "$1eaux") rule("arf$", with: "$1arves") rule("(embarg)o$", with: "$1oes") rule("(gen)us$", with: "$1era") rule("(r)oof$", with: "$1oofs") rule("(l)eaf$", with: "$1eaves") rule("(millen)ium$", with: "$1ia") rule("(th)at$", with: "$1ose") rule("(th)is$", with: "$1ese") unchanging("sheep") unchanging("deer") unchanging("moose") unchanging("swine") unchanging("bison") unchanging("corps") unchanging("means") unchanging("series") unchanging("scissors") unchanging("species") } public class func apply(var word: String) -> String { if contains(sharedInstance.uncountables, word.lowercaseString) || count(word) == 0 { return word } else { for pair in sharedInstance.rules { var newValue = regexReplace(word, pattern: pair.rule, template: pair.template) if newValue != word { return newValue } } } return word } public class func rule(rule: String, with template: String) { sharedInstance.rule(rule, with: template) } public class func uncountable(word: String) { sharedInstance.uncountable(word) } public class func unchanging(word: String) { sharedInstance.unchanging(word) } public class var sharedInstance : Pluralize { struct Static { static var onceToken : dispatch_once_t = 0 static var instance : Pluralize? = nil } dispatch_once(&Static.onceToken) { Static.instance = Pluralize() } return Static.instance! } private class func regexReplace(input: String, pattern: String, template: String) -> String { var regex = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: nil)! var range = NSMakeRange(0, count(input)) var output = regex.stringByReplacingMatchesInString(input, options: nil, range: range, withTemplate: template) return output } private func rule(rule: String, with template: String) { rules.insert((rule: rule, template: template), atIndex: 0) } private func uncountable(word: String) { uncountables.insert(word.lowercaseString, atIndex: 0) } private func unchanging(word: String) { uncountables.insert(word.lowercaseString, atIndex: 0) } } extension String { public func pluralize(count: Int = 2, with: String = "") -> String { if count == 1 { return self } else { if with.length != 0 { return with } else { return Pluralize.apply(self) } } } // Workaround to allow us to use `count` as an argument name in pluralize() above. private var length: Int { return count(self) } }
mit
879a190aa428179f0e3b43d669541aec
40.990521
118
0.558415
3.614443
false
false
false
false
sunlijian/sinaBlog_repository
sinaBlog_sunlijian/sinaBlog_sunlijian/AppDelegate.swift
1
3684
// // AppDelegate.swift // sinaBlog_sunlijian // // Created by sunlijian on 15/10/9. // Copyright © 2015年 myCompany. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func hasNewVersion() -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) //判断是不是第一次登陆或有新版本 //取出当前的版本号 let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String //取出偏好设置中的版本号 let appVersion = NSUserDefaults.standardUserDefaults().objectForKey("currentVersion") //进行比较 if appVersion?.compare(currentVersion) == NSComparisonResult.OrderedAscending || appVersion == nil { //保存新的版本号 NSUserDefaults.standardUserDefaults().setValue(currentVersion, forKey: "currentVersion") //同步一下 NSUserDefaults.standardUserDefaults().synchronize() return true } return false } //判断账号是否有 func defaultViewController() -> UIViewController{ let account = IWUserAccount.loadAccount() if (account != nil) { return IWWelcomViewController() }else{ return IWNavigationController(rootViewController: IWOAthViewController()) } } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { //初始化一个 WINDOWS //判断是不是第一次登陆或有新版本 let isTrue = hasNewVersion() if isTrue { window?.rootViewController = IWNewFeatureViewController() }else { window?.rootViewController = defaultViewController() } //让 windows 可见 window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
cd9fcae22414a445d774480074c57533
39.494253
285
0.693443
5.556782
false
false
false
false
sammyd/Concurrency-VideoSeries
projects/010_GCDDelights/010_ChallengeComplete/Pollster.playground/Contents.swift
2
1211
import Foundation import XCPlayground XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: # Pollster //: __Challenge:__ Complete the following class to simulate a polling mechanism using `dispatch_after()` class Pollster { let callback: (String) -> () private var active: Bool = false private let isolationQueue = dispatch_queue_create("com.raywenderlich.pollster.isolation", DISPATCH_QUEUE_SERIAL) init(callback: (String) -> ()) { self.callback = callback } func start() { print("Start polling") active = true dispatch_async(isolationQueue) { self.makeRequest() } } func stop() { active = false print("Stop polling") } private func makeRequest() { if active { callback("\(NSDate())") let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 1)) dispatch_after(dispatchTime, isolationQueue) { self.makeRequest() } } } } //: The following will test the completed class let pollster = Pollster(callback: { print($0) }) pollster.start() delay(5) { pollster.stop() delay(2) { print("Finished") XCPlaygroundPage.currentPage.finishExecution() } }
mit
7027864908f8b6b1c4f1d7d654611d9a
20.625
115
0.661437
4.063758
false
false
false
false
Arcovv/CleanArchitectureRxSwift
CleanArchitectureRxSwift/Application/Application.swift
1
2328
import Foundation import Domain import Network import CoreDataPlatform import RealmPlatform final class Application { static let shared = Application() private let coreDataUseCaseProvider: Domain.UseCaseProvider private let realmUseCaseProvider: Domain.UseCaseProvider private let networkUseCaseProvider: Network.UseCaseProvider private init() { self.coreDataUseCaseProvider = CoreDataPlatform.UseCaseProvider() self.realmUseCaseProvider = RealmPlatform.UseCaseProvider() self.networkUseCaseProvider = Network.UseCaseProvider() } func configureMainInterface(in window: UIWindow) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let cdNavigationController = UINavigationController() cdNavigationController.tabBarItem = UITabBarItem(title: "CoreData", image: UIImage(named: "Box"), selectedImage: nil) let cdNavigator = DefaultPostsNavigator(services: coreDataUseCaseProvider, navigationController: cdNavigationController, storyBoard: storyboard) let rmNavigationController = UINavigationController() rmNavigationController.tabBarItem = UITabBarItem(title: "Realm", image: UIImage(named: "Toolbox"), selectedImage: nil) let rmNavigator = DefaultPostsNavigator(services: realmUseCaseProvider, navigationController: rmNavigationController, storyBoard: storyboard) let networkNavigationController = UINavigationController() networkNavigationController.tabBarItem = UITabBarItem(title: "Network", image: UIImage(named: "Toolbox"), selectedImage: nil) let networkNavigator = DefaultPostsNavigator(services: networkUseCaseProvider, navigationController: networkNavigationController, storyBoard: storyboard) let tabBarController = UITabBarController() tabBarController.viewControllers = [ cdNavigationController, rmNavigationController, networkNavigationController ] window.rootViewController = tabBarController cdNavigator.toPosts() rmNavigator.toPosts() networkNavigator.toPosts() } }
mit
80900616f90452f69499cf35d7703ef8
39.137931
86
0.688574
6.224599
false
false
false
false
dtrauger/Charts
Source/Charts/Renderers/XAxisRendererRadarChart.swift
1
3190
// // XAxisRendererRadarChart.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 #if !os(OSX) import UIKit #endif open class XAxisRendererRadarChart: XAxisRenderer { open weak var chart: RadarChartView? public init(viewPortHandler: ViewPortHandler?, xAxis: XAxis?, chart: RadarChartView?) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: nil) self.chart = chart } open override func renderAxisLabels(context: CGContext) { guard let xAxis = axis as? XAxis, let chart = chart else { return } if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled { return } let labelFont = xAxis.labelFont let labelTextColor = xAxis.labelTextColor let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD let drawLabelAnchor = CGPoint(x: 0.5, y: 0.25) let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets for i in stride(from: 0, to: chart.data?.maxEntryCountSet?.entryCount ?? 0, by: 1) { let label = xAxis.valueFormatter?.stringForValue(Double(i), axis: xAxis) ?? "" let angle = (sliceangle * CGFloat(i) + chart.rotationAngle).truncatingRemainder(dividingBy: 360.0) let p = ChartUtils.getPosition(center: center, dist: CGFloat(chart.yRange) * factor + xAxis.labelRotatedWidth / 2.0, angle: angle) drawLabel(context: context, formattedLabel: label, x: p.x, y: p.y - xAxis.labelRotatedHeight / 2.0, attributes: [convertFromNSAttributedStringKey(NSAttributedString.Key.font): labelFont, convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): labelTextColor], anchor: drawLabelAnchor, angleRadians: labelRotationAngleRadians) } } open func drawLabel( context: CGContext, formattedLabel: String, x: CGFloat, y: CGFloat, attributes: [String: NSObject], anchor: CGPoint, angleRadians: CGFloat) { ChartUtils.drawText( context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, anchor: anchor, angleRadians: angleRadians) } open override func renderLimitLines(context: CGContext) { /// XAxis LimitLines on RadarChart not yet supported. } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue }
apache-2.0
9f7b5c4799be6f147ec7e75a0068906a
30.9
199
0.607524
5.238095
false
false
false
false
normand1/TDDWeatherApp
TDDWeatherApp/CacheAccess.swift
1
1454
// // CacheAccess.swift // TDDWeatherApp // // Created by David Norman on 6/25/15. // Copyright (c) 2015 David Norman. All rights reserved. // import Foundation let weatherAppKey = "com.monsoonco.weatherapp" class CacheAccess { class func cacheJsonDict(_ zip: String, dictionary : NSDictionary)->Bool { UserDefaults.standard.set(dictionary, forKey: zip) let result = UserDefaults.standard.object(forKey: zip) as? NSDictionary if result != nil { return true } else { return false } } class func tempFromCache(_ zip : String)->Double? { if let resultDictionary = UserDefaults.standard.object(forKey: zip) as? NSDictionary { if let temp = OpenWeatherAPIHandler.temperatureFromDictionary(resultDictionary) { return temp } } return nil } class func weatherDescriptionFromCache(_ zip: String)->String? { if let resultDictionary = UserDefaults.standard.object(forKey: zip) as? NSDictionary { if let temp = OpenWeatherAPIHandler.weatherDescriptionFromDictionary(resultDictionary) { return temp } } return nil } class func zipIsCached(_ zip : String)->Bool { let temp = CacheAccess.tempFromCache(zip) if temp != nil { return true } else { return false } } }
mit
1df0d0a47fa7e30e9777aa9926866499
26.961538
100
0.603164
4.675241
false
false
false
false
Eonil/EditorLegacy
Modules/EditorWorkspaceNavigationFeature/EditorWorkspaceNavigationFeature/Internals/ContextMenuController.swift
1
1456
// // ContextMenuController.swift // EditorWorkspaceNavigationFeature // // Created by Hoon H. on 2015/02/22. // Copyright (c) 2015 Eonil. All rights reserved. // import Foundation import AppKit import EditorCommon import EditorUIComponents final class ContextMenuController: MenuController { let showInFinder = NSMenuItem(title: "Show in Finder") let showInTerminal = NSMenuItem(title: "Show in Terminal") let newFile = NSMenuItem(title: "New File...") let newFolder = NSMenuItem(title: "New Folder") let newFolderWithSelection = NSMenuItem(title: "New Folder with Selection") let delete = NSMenuItem(title: "Delete") let deleteReferenceOnly = NSMenuItem(title: "Delete Reference Only") let addAllUnregistredFiles = NSMenuItem(title: "Add All Unregistered Files") let removeAllMissingFiles = NSMenuItem(title: "Remove All Missing Files") let note = NSMenuItem(title: "Note...") init() { let m = NSMenu() m.autoenablesItems = false [ showInFinder, // showInTerminal, NSMenuItem.separatorItem(), newFile, newFolder, // newFolderWithSelection, NSMenuItem.separatorItem(), delete, deleteReferenceOnly, // NSMenuItem.separatorItem(), // addAllUnregistredFiles, // removeAllMissingFiles, // NSMenuItem.separatorItem(), // note, ].map(m.addItem) super.init(m) } } private extension NSMenuItem { convenience init(title:String) { self.init() self.title = title } }
mit
04c4fde8ebd241b95d5ff189d46e467a
24.12069
77
0.71772
3.316629
false
false
false
false
bitjammer/swift
test/SILGen/call_chain_reabstraction.swift
14
846
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s struct A { func g<U>(_ recur: (A, U) -> U) -> (A, U) -> U { return { _, x in return x } } // CHECK-LABEL: sil hidden @_T024call_chain_reabstraction1AV1f{{[_0-9a-zA-Z]*}}F // CHECK: [[G:%.*]] = function_ref @_T024call_chain_reabstraction1AV1g{{[_0-9a-zA-Z]*}}F // CHECK: [[G2:%.*]] = apply [[G]]<A> // CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @_T024call_chain_reabstraction1AVA2CIxyir_A3CIxyyd_TR // CHECK: [[REABSTRACT:%.*]] = partial_apply [[REABSTRACT_THUNK]]([[G2]]) // CHECK: apply [[REABSTRACT]]([[SELF:%.*]], [[SELF]]) func f() { let recur: (A, A) -> A = { c, x in x } let b = g(recur)(self, self) } }
apache-2.0
96be978e80e6c941ccbd489a0141580e
48.764706
119
0.470449
3.317647
false
false
false
false
aliabbas90/DraggableDynamicModal
Example/DraggableDynamicModal/ViewController.swift
1
2948
// // ViewController.swift // DecathlonDraggableView // // Created by Ali ABBAS on 12/05/2017. // Copyright © 2017 Decathlon. All rights reserved. // import UIKit import DraggableDynamicModal enum ModalVCType: String { case labelModalVC = "Modal", scrollableModalVC = "ScrollableViewController", navigationController = "DraggableNavigationViewController" } class ViewController: UIViewController { let type: ModalVCType = .navigationController var draggableAnimator: ZFModalTransitionAnimator! = ZFModalTransitionAnimator() var modalManager: ModalViewControllerManager! override func viewDidLoad() { super.viewDidLoad() let image = UIImageView(image: UIImage(named: "bg")) self.modalManager = ModalViewControllerManager(parentViewController: self, shouldTransformBehindView: false, backgroundBlurredView: image) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func openModal(_ sender: Any) { switch type { case .labelModalVC: let modal = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Modal") as! LabelModalViewController self.modalManager.presentModal(viewController: modal) modal.delegate = self case .scrollableModalVC: let modal = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: type.rawValue) as! ScrollableViewController self.modalManager.presentModal(viewController: modal) case .navigationController: let modal = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: type.rawValue) as! DraggableNavigationViewController self.modalManager.presentModal(viewController: modal) } } } extension ViewController: LabelModalViewControllerProtocol { func labelModalViewControllerProtocolSwitchMe() { let validate = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ValidateViewController") as! ValidateViewController self.modalManager.presentModal(viewController: validate) } } protocol Bluring { func blur(_ alpha: CGFloat) -> UIVisualEffectView } extension Bluring where Self: UIView { func blur(_ alpha: CGFloat = 0.5) -> UIVisualEffectView { // create effect let effect = UIBlurEffect(style: .dark) let effectView = UIVisualEffectView(effect: effect) // set boundry and alpha effectView.frame = self.bounds effectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] effectView.alpha = alpha return effectView } } // Conformance extension UIImageView: Bluring {}
mit
e5ea52645a5109d48405145f5b57beec
35.382716
158
0.705124
5.234458
false
false
false
false
toggl/superday
teferi/UI/Modules/Goals/GoalList/GoalViewModel.swift
1
8423
import Foundation import RxSwift class GoalViewModel { //MARK: Public Properties var goalsObservable: Observable<[Goal]> { return self.goals.asObservable() } var todaysGoal: Observable<Goal?> { return self.goals.asObservable() .map(toTodaysGoal) } var lastGoal: Observable<Goal?> { return self.goals.asObservable() .map(removePlaceHolders) .map({ $0.first }) } var suggestionObservable: Observable<String?> { let movedToForeground = appLifecycleService .movedToForegroundObservable .mapTo(()) let timelineEdit = Observable.merge([ NotificationCenter.default.rx.typedNotification(OnTimeSlotCreated.self).map{ $0.startTime }, NotificationCenter.default.rx.typedNotification(OnTimeSlotDeleted.self).map{ $0.startTime }, NotificationCenter.default.rx.typedNotification(OnTimeSlotStartTimeEdited.self).map{ $0.oldStartTime }, NotificationCenter.default.rx.typedNotification(OnTimeSlotCategoriesEdited.self).map{ $0.startTimes.first }.filterNil() ]) let updatedTimeSlotsForYesterday = timelineEdit .filter(dateOnSameDayAs(timeService.now.yesterday)) .mapTo(()) return Observable.of(movedToForeground, updatedTimeSlotsForYesterday) .merge() .filter(suggestionForTodayNotShown) .map(yesterdaysGoal) .filterNil() .flatMap(toFailedGoalSuggestion) .do(onNext: { [unowned self] suggestion in guard let _ = suggestion else { return } self.settingsService.setLastShownGoalSuggestion(self.timeService.now) }) } //MARK: Private Properties private let disposeBag = DisposeBag() private var goals : Variable<[Goal]> = Variable([]) private let timeService : TimeService private let settingsService : SettingsService private let goalService : GoalService private let appLifecycleService : AppLifecycleService private let goalHeaderMessageProvider: GoalMessageProvider //MARK: Initializers init(timeService: TimeService, settingsService : SettingsService, goalService: GoalService, appLifecycleService: AppLifecycleService) { self.timeService = timeService self.settingsService = settingsService self.goalService = goalService self.appLifecycleService = appLifecycleService self.goalHeaderMessageProvider = GoalMessageProvider(timeService: self.timeService, settingsService: self.settingsService) let newGoalForThisDate = goalService.goalCreatedObservable .mapTo(()) let updatedGoalForThisDate = goalService.goalUpdatedObservable .mapTo(()) let updatedTimelineForThisDate = Observable.merge([ NotificationCenter.default.rx.typedNotification(OnTimeSlotCreated.self).map{ $0.startTime }, NotificationCenter.default.rx.typedNotification(OnTimeSlotCategoriesEdited.self).map{ $0.startTimes.first }.filterNil(), NotificationCenter.default.rx.typedNotification(OnTimeSlotStartTimeEdited.self).map{ $0.oldStartTime } ]) .filter(dateOnSameDayAs(timeService.now)) .mapTo(()) let movedToForeground = appLifecycleService .movedToForegroundObservable .mapTo(()) let refreshObservable = Observable.of(newGoalForThisDate, updatedGoalForThisDate, movedToForeground, updatedTimelineForThisDate) .merge() .startWith(()) refreshObservable .map(getGoals) .map(withMissingDateGoals) .bind(to: goals) .disposed(by: disposeBag) } func isCurrentGoal(_ goal: Goal?) -> Bool { guard let goal = goal else { return false } return goal.date.ignoreTimeComponents() == timeService.now.ignoreTimeComponents() } func messageAndCategoryVisibility(forGoal goal: Goal?) -> (message: String?, categoryVisible: Bool, newGoalButtonVisible: Bool) { return goalHeaderMessageProvider.message(forGoal: goal) } //MARK: Private Methods private func toTodaysGoal(goals: [Goal]) -> Goal? { guard let firstGoal = goals.first else { return nil } if firstGoal.date.ignoreTimeComponents() == self.timeService.now.ignoreTimeComponents() { return firstGoal } return nil } private func removePlaceHolders(goals: [Goal]) -> [Goal] { return goals.filter({ $0.category != .unknown }) } /// Adds placeholder goals to the given goals array to fill the dates that did not have any goal. /// The placeholder goals have the date of the days that do not have any goal and a category of .unknown /// /// - Parameter goals: Goals that were set by the user already /// - Returns: Goals that have extra placeholder goals for the date that the user did not set a goal private func withMissingDateGoals(_ goals: [Goal]) -> [Goal] { guard let firstGoalAdded = goals.last else { return [] } let firstDay = firstGoalAdded.date let today = timeService.now var sourceGoals = goals var goalsToReturn = [Goal]() var date = firstDay repeat { if let last = sourceGoals.last, date.isSameDay(asDate: last.date) { sourceGoals = Array(sourceGoals.dropLast()) goalsToReturn.append(last) } else { if !date.isSameDay(asDate: today) { goalsToReturn.append(Goal(date: date, category: .unknown, targetTime: 0)) } } date = date.add(days: 1) } while !date.isSameDay(asDate: today.tomorrow) return goalsToReturn.reversed() } private func getGoals() -> [Goal] { guard let installDate = settingsService.installDate else { return [] } return goalService.getGoals(sinceDaysAgo: installDate.differenceInDays(toDate: timeService.now)) } private func yesterdaysGoal() -> Goal? { return goalService.getGoals(sinceDaysAgo: 1) .filter{ [unowned self] in $0.date.ignoreTimeComponents() == self.timeService.now.yesterday.ignoreTimeComponents() } .first } private func dateOnSameDayAs(_ date: Date) -> (Date) -> Bool { return { otherDate in return date.ignoreTimeComponents() == otherDate.ignoreTimeComponents() } } private func suggestionForTodayNotShown() -> Bool { guard let lastSuggestionShownDate = settingsService.lastShownGoalSuggestion else { return true } return lastSuggestionShownDate.ignoreTimeComponents() != timeService.now.ignoreTimeComponents() } private func toFailedGoalSuggestion(goal: Goal) -> Observable<String?> { if goal.percentageCompleted > 1 { return Observable.just(nil) } if goal.targetTime >= 2 * 60 * 60 { let halfTime = formatedElapsedTimeLongText(for: goal.targetTime / 2) return arc4random_uniform(2) == 0 ? Observable.of(L10n.goalSuggestion1(halfTime)) : Observable.of(L10n.goalSuggestion2(halfTime)) } let yesterday = timeService.now.yesterday let getTimeSLotsInteractor = InteractorFactory.shared.createGetTimeSlotsForDateInteractor(date: yesterday) return getTimeSLotsInteractor.execute() .map { timeSlots -> String? in let filteredTimeSlots = timeSlots.filter { timeSlot in return timeSlot.startTime.ignoreDateComponents() < Date.createTime(hour: 9, minute: 30) } .filter { timeSlot in return timeSlot.category == Category.commute || timeSlot.category == Category.fitness || timeSlot.category == goal.category } if filteredTimeSlots.count > 0 { return nil } return arc4random_uniform(2) == 1 ? L10n.goalSuggestion3 : L10n.goalSuggestion4 } } }
bsd-3-clause
9500dd23dacaa2b20fcd46fbf2692016
38.544601
147
0.627924
4.905649
false
false
false
false
vimeo/VimeoUpload
VimeoUpload/Upload/Model/VideoSettings.swift
1
3875
// // VideoSettings.swift // VimeoUpload // // Created by Alfred Hanssen on 10/3/15. // Copyright © 2015 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation @objc open class VideoSettings: NSObject, NSCoding { @objc public var title: String? { didSet { self.title = self.trim(text: self.title) } } @objc public var desc: String? { didSet { self.desc = self.trim(text: self.desc) } } @objc public var privacy: String? @objc public var users: [String]? // List of uris of users who can view this video @objc public var password: String? @objc public init(title: String?, description: String?, privacy: String?, users: [String]?, password: String?) { super.init() self.privacy = privacy self.users = users self.password = password self.title = self.trim(text: title) self.desc = self.trim(text: description) } // MARK: Public API @objc open func parameterDictionary() -> [String: Any] { var parameters: [String: Any] = [:] if let title = self.title, title.isEmpty == false { parameters["name"] = title } if let description = self.desc, description.count > 0 { parameters["description"] = description } if let privacy = self.privacy, privacy.count > 0 { parameters["privacy"] = (["view": privacy]) } if let users = self.users { parameters["users"] = (users.map { ["uri": $0] }) } if let password = self.password { parameters["password"] = password } return parameters } // MARK: NSCoding @objc required public init(coder aDecoder: NSCoder) { self.title = aDecoder.decodeObject(forKey: "title") as? String self.desc = aDecoder.decodeObject(forKey: "desc") as? String self.privacy = aDecoder.decodeObject(forKey: "privacy") as? String self.users = aDecoder.decodeObject(forKey: "users") as? [String] self.password = aDecoder.decodeObject(forKey: "password") as? String } @objc public func encode(with aCoder: NSCoder) { aCoder.encode(self.title, forKey: "title") aCoder.encode(self.desc, forKey: "desc") aCoder.encode(self.privacy, forKey: "privacy") aCoder.encode(self.users, forKey: "users") aCoder.encode(self.password, forKey: "password") } // MARK : String Methods func trim(text: String?) -> String? { return text?.trimmingCharacters(in: CharacterSet.whitespaces) } }
mit
bfcdbd030dfb85810bbe8cae4c645fb7
30.754098
114
0.615901
4.367531
false
false
false
false
luosheng/Swocket
Pod/Extensions/Transmittable+Async.swift
1
2173
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation extension Transmittable where Self : Asyncable { public func sendDataAsync(data: NSData, onError errorClosure: SwocketErrorClosure? = nil) { dispatch { () -> Void in do { try self.sendData(data) } catch { if let error = error as? SwocketError { self.handleError(error, withClosure: errorClosure) } } } } public func receiveDataAsync(completion: SwocketDataClosure? = nil) { dispatch { () -> Void in do { let data = try self.receiveData() if let completion = completion { self.callback({ () -> Void in completion(data, nil) }) } } catch { if let error = error as? SwocketError { self.handleError(error, withClosure: completion) } } } } }
mit
9d0e7c46f9cda4edd664fa418c20d14b
38.509091
95
0.619705
4.891892
false
false
false
false
butterproject/butter-ios
Butter/Local Database/MovieFavorites.swift
1
1566
// // MovieFavorites.swift // Butter // // Created by Moorice on 28-09-15. // Copyright (c) 2015 Butter Project. All rights reserved. // import Foundation import SQLite public class MovieFavorites { private static let movieFavorites = Table("MovieFavorites") private static let imdb_id = Expression<String>("imdb_id") private class func prepareTable() throws { try DatabaseManager.sharedDb?.run(movieFavorites.create(temporary: false, ifNotExists: true, block: { t in t.column(imdb_id, primaryKey: true) })) } public class func addFavorite(imdbId : String) -> Int64? { do { try prepareTable() let insert = movieFavorites.insert(imdb_id <- imdbId) return try DatabaseManager.sharedDb?.run(insert) } catch { return nil } } public class func removeFavorite(imdbId : String) -> Int { do { try prepareTable() let media = movieFavorites.filter(imdb_id == imdbId) return try DatabaseManager.sharedDb!.run(media.delete()) } catch { return 0 } } public class func isFavorite(imdbId : String) -> Bool { do { try prepareTable() return (DatabaseManager.sharedDb?.scalar(movieFavorites.filter(imdb_id == imdbId).count) > 0) } catch { return false } } public class func getFavorites() -> [String]? { do { try prepareTable() return DatabaseManager.sharedDb?.prepare(movieFavorites).map({ $0[imdb_id] }) } catch { return nil } } public class func toggleFavorite(imdbId : String) { if isFavorite(imdbId) { removeFavorite(imdbId) } else { addFavorite(imdbId) } } }
gpl-3.0
7e766bdc93e8d10f4e9403543babd34b
22.029412
108
0.684547
3.289916
false
false
false
false
iscriptology/swamp
Swamp/SwampSession.swift
1
16105
// // SwampSession.swift // import Foundation import SwiftyJSON // MARK: Call callbacks public typealias CallCallback = (_ details: [String: Any], _ results: [Any]?, _ kwResults: [String: Any]?) -> Void public typealias ErrorCallCallback = (_ details: [String: Any], _ error: String, _ args: [Any]?, _ kwargs: [String: Any]?) -> Void // MARK: Callee callbacks // For now callee is irrelevant //public typealias RegisterCallback = (registration: Registration) -> Void //public typealias ErrorRegisterCallback = (details: [String: AnyObject], error: String) -> Void //public typealias SwampProc = (args: [AnyObject]?, kwargs: [String: AnyObject]?) -> AnyObject //public typealias UnregisterCallback = () -> Void //public typealias ErrorUnregsiterCallback = (details: [String: AnyObject], error: String) -> Void // MARK: Subscribe callbacks public typealias SubscribeCallback = (_ subscription: Subscription) -> Void public typealias ErrorSubscribeCallback = (_ details: [String: Any], _ error: String) -> Void public typealias EventCallback = (_ details: [String: Any], _ results: [Any]?, _ kwResults: [String: Any]?) -> Void public typealias UnsubscribeCallback = () -> Void public typealias ErrorUnsubscribeCallback = (_ details: [String: Any], _ error: String) -> Void // MARK: Publish callbacks public typealias PublishCallback = () -> Void public typealias ErrorPublishCallback = (_ details: [String: Any], _ error: String) -> Void // TODO: Expose only an interface (like Cancellable) to user open class Subscription { fileprivate let session: SwampSession internal let subscription: Int internal let eventCallback: EventCallback fileprivate var isActive: Bool = true internal init(session: SwampSession, subscription: Int, onEvent: @escaping EventCallback) { self.session = session self.subscription = subscription self.eventCallback = onEvent } internal func invalidate() { self.isActive = false } open func cancel(_ onSuccess: @escaping UnsubscribeCallback, onError: @escaping ErrorUnsubscribeCallback) { if !self.isActive { onError([:], "Subscription already inactive.") } self.session.unsubscribe(self.subscription, onSuccess: onSuccess, onError: onError) } } // For now callee is irrelevant //public class Registration { // private let session: SwampSession //} public protocol SwampSessionDelegate { func swampSessionHandleChallenge(_ authMethod: String, extra: [String: Any]) -> String func swampSessionConnected(_ session: SwampSession, sessionId: Int) func swampSessionEnded(_ reason: String) } open class SwampSession: SwampTransportDelegate { // MARK: Public typealiases // MARK: delegate open var delegate: SwampSessionDelegate? // MARK: Constants // No callee role for now fileprivate let supportedRoles: [SwampRole] = [SwampRole.Caller, SwampRole.Subscriber, SwampRole.Publisher] fileprivate let clientName = "Swamp-dev-0.1.0" // MARK: Members fileprivate let realm: String fileprivate let transport: SwampTransport fileprivate let authmethods: [String]? fileprivate let authid: String? fileprivate let authrole: String? fileprivate let authextra: [String: Any]? // MARK: State members fileprivate var currRequestId: Int = 1 // MARK: Session state fileprivate var serializer: SwampSerializer? fileprivate var sessionId: Int? fileprivate var routerSupportedRoles: [SwampRole]? // MARK: Call role // requestId fileprivate var callRequests: [Int: (callback: CallCallback, errorCallback: ErrorCallCallback)] = [:] // MARK: Subscriber role // requestId fileprivate var subscribeRequests: [Int: (callback: SubscribeCallback, errorCallback: ErrorSubscribeCallback, eventCallback: EventCallback)] = [:] // subscription fileprivate var subscriptions: [Int: Subscription] = [:] // requestId fileprivate var unsubscribeRequests: [Int: (subscription: Int, callback: UnsubscribeCallback, errorCallback: ErrorUnsubscribeCallback)] = [:] // MARK: Publisher role // requestId fileprivate var publishRequests: [Int: (callback: PublishCallback, errorCallback: ErrorPublishCallback)] = [:] // MARK: C'tor required public init(realm: String, transport: SwampTransport, authmethods: [String]?=nil, authid: String?=nil, authrole: String?=nil, authextra: [String: Any]?=nil){ self.realm = realm self.transport = transport self.authmethods = authmethods self.authid = authid self.authrole = authrole self.authextra = authextra self.transport.delegate = self } // MARK: Public API final public func isConnected() -> Bool { return self.sessionId != nil } final public func connect() { self.transport.connect() } final public func disconnect(_ reason: String="wamp.error.close_realm") { self.sendMessage(GoodbyeSwampMessage(details: [:], reason: reason)) } // MARK: Caller role open func call(_ proc: String, options: [String: Any]=[:], args: [Any]?=nil, kwargs: [String: Any]?=nil, onSuccess: @escaping CallCallback, onError: @escaping ErrorCallCallback) { let callRequestId = self.generateRequestId() // Tell router to dispatch call self.sendMessage(CallSwampMessage(requestId: callRequestId, options: options, proc: proc, args: args, kwargs: kwargs)) // Store request ID to handle result self.callRequests[callRequestId] = (callback: onSuccess, errorCallback: onError ) } // MARK: Callee role // For now callee is irrelevant // public func register(proc: String, options: [String: AnyObject]=[:], onSuccess: RegisterCallback, onError: ErrorRegisterCallback, onFire: SwampProc) { // } // MARK: Subscriber role open func subscribe(_ topic: String, options: [String: Any]=[:], onSuccess: @escaping SubscribeCallback, onError: @escaping ErrorSubscribeCallback, onEvent: @escaping EventCallback) { // TODO: assert topic is a valid WAMP uri let subscribeRequestId = self.generateRequestId() // Tell router to subscribe client on a topic self.sendMessage(SubscribeSwampMessage(requestId: subscribeRequestId, options: options, topic: topic)) // Store request ID to handle result self.subscribeRequests[subscribeRequestId] = (callback: onSuccess, errorCallback: onError, eventCallback: onEvent) } // Internal because only a Subscription object can call this internal func unsubscribe(_ subscription: Int, onSuccess: @escaping UnsubscribeCallback, onError: @escaping ErrorUnsubscribeCallback) { let unsubscribeRequestId = self.generateRequestId() // Tell router to unsubscribe me from some subscription self.sendMessage(UnsubscribeSwampMessage(requestId: unsubscribeRequestId, subscription: subscription)) // Store request ID to handle result self.unsubscribeRequests[unsubscribeRequestId] = (subscription, onSuccess, onError) } // MARK: Publisher role // without acknowledging open func publish(_ topic: String, options: [String: Any]=[:], args: [Any]?=nil, kwargs: [String: Any]?=nil) { // TODO: assert topic is a valid WAMP uri let publishRequestId = self.generateRequestId() // Tell router to publish the event self.sendMessage(PublishSwampMessage(requestId: publishRequestId, options: options, topic: topic, args: args, kwargs: kwargs)) // We don't need to store the request, because it's unacknowledged anyway } // with acknowledging open func publish(_ topic: String, options: [String: Any]=[:], args: [Any]?=nil, kwargs: [String: Any]?=nil, onSuccess: @escaping PublishCallback, onError: @escaping ErrorPublishCallback) { // add acknowledge to options, so we get callbacks var options = options options["acknowledge"] = true // TODO: assert topic is a valid WAMP uri let publishRequestId = self.generateRequestId() // Tell router to publish the event self.sendMessage(PublishSwampMessage(requestId: publishRequestId, options: options, topic: topic, args: args, kwargs: kwargs)) // Store request ID to handle result self.publishRequests[publishRequestId] = (callback: onSuccess, errorCallback: onError) } // MARK: SwampTransportDelegate open func swampTransportDidDisconnect(_ error: NSError?, reason: String?) { if reason != nil { self.delegate?.swampSessionEnded(reason!) } else if error != nil { self.delegate?.swampSessionEnded("Unexpected error: \(error!.description)") } else { self.delegate?.swampSessionEnded("Unknown error.") } } open func swampTransportDidConnectWithSerializer(_ serializer: SwampSerializer) { self.serializer = serializer // Start session by sending a Hello message! var roles = [String: Any]() for role in self.supportedRoles { // For now basic profile, (demands empty dicts) roles[role.rawValue] = [:] } var details: [String: Any] = [:] if let authmethods = self.authmethods { details["authmethods"] = authmethods } if let authid = self.authid { details["authid"] = authid } if let authrole = self.authrole { details["authrole"] = authrole } if let authextra = self.authextra { details["authextra"] = authextra } details["agent"] = self.clientName details["roles"] = roles self.sendMessage(HelloSwampMessage(realm: self.realm, details: details)) } open func swampTransportReceivedData(_ data: Data) { if let payload = self.serializer?.unpack(data), let message = SwampMessages.createMessage(payload) { self.handleMessage(message) } } fileprivate func handleMessage(_ message: SwampMessage) { switch message { // MARK: Auth responses case let message as ChallengeSwampMessage: if let authResponse = self.delegate?.swampSessionHandleChallenge(message.authMethod, extra: message.extra) { self.sendMessage(AuthenticateSwampMessage(signature: authResponse, extra: [:])) } else { print("There was no delegate, aborting.") self.abort() } // MARK: Session responses case let message as WelcomeSwampMessage: self.sessionId = message.sessionId let routerRoles = message.details["roles"]! as! [String : [String : Any]] self.routerSupportedRoles = routerRoles.keys.map { SwampRole(rawValue: $0)! } self.delegate?.swampSessionConnected(self, sessionId: message.sessionId) case let message as GoodbyeSwampMessage: if message.reason != "wamp.error.goodbye_and_out" { // Means it's not our initiated goodbye, and we should reply with goodbye self.sendMessage(GoodbyeSwampMessage(details: [:], reason: "wamp.error.goodbye_and_out")) } self.transport.disconnect(message.reason) case let message as AbortSwampMessage: self.transport.disconnect(message.reason) // MARK: Call role case let message as ResultSwampMessage: let requestId = message.requestId if let (callback, _) = self.callRequests.removeValue(forKey: requestId) { callback(message.details, message.results, message.kwResults) } else { // TODO: log this erroneous situation } // MARK: Subscribe role case let message as SubscribedSwampMessage: let requestId = message.requestId if let (callback, _, eventCallback) = self.subscribeRequests.removeValue(forKey: requestId) { // Notify user and delegate him to unsubscribe this subscription let subscription = Subscription(session: self, subscription: message.subscription, onEvent: eventCallback) callback(subscription) // Subscription succeeded, we should store event callback for when it's fired self.subscriptions[message.subscription] = subscription } else { // TODO: log this erroneous situation } case let message as EventSwampMessage: if let subscription = self.subscriptions[message.subscription] { subscription.eventCallback(message.details, message.args, message.kwargs) } else { // TODO: log this erroneous situation } case let message as UnsubscribedSwampMessage: let requestId = message.requestId if let (subscription, callback, _) = self.unsubscribeRequests.removeValue(forKey: requestId) { if let subscription = self.subscriptions.removeValue(forKey: subscription) { subscription.invalidate() callback() } else { // TODO: log this erroneous situation } } else { // TODO: log this erroneous situation } case let message as PublishedSwampMessage: let requestId = message.requestId if let (callback, _) = self.publishRequests.removeValue(forKey: requestId) { callback() } else { // TODO: log this erroneous situation } //////////////////////////////////////////// // MARK: Handle error responses //////////////////////////////////////////// case let message as ErrorSwampMessage: switch message.requestType { case SwampMessages.call: if let (_, errorCallback) = self.callRequests.removeValue(forKey: message.requestId) { errorCallback(message.details, message.error, message.args, message.kwargs) } else { // TODO: log this erroneous situation } case SwampMessages.subscribe: if let (_, errorCallback, _) = self.subscribeRequests.removeValue(forKey: message.requestId) { errorCallback(message.details, message.error) } else { // TODO: log this erroneous situation } case SwampMessages.unsubscribe: if let (_, _, errorCallback) = self.unsubscribeRequests.removeValue(forKey: message.requestId) { errorCallback(message.details, message.error) } else { // TODO: log this erroneous situation } case SwampMessages.publish: if let(_, errorCallback) = self.publishRequests.removeValue(forKey: message.requestId) { errorCallback(message.details, message.error) } else { // TODO: log this erroneous situation } default: return } default: return } } // MARK: Private methods fileprivate func abort() { if self.sessionId != nil { return } self.sendMessage(AbortSwampMessage(details: [:], reason: "wamp.error.system_shutdown")) self.transport.disconnect("No challenge delegate found.") } fileprivate func sendMessage(_ message: SwampMessage){ let marshalledMessage = message.marshal() let data = self.serializer!.pack(marshalledMessage as [Any])! self.transport.sendData(data) } fileprivate func generateRequestId() -> Int { self.currRequestId += 1 return self.currRequestId } }
mit
0e678a823f2c5b4dfa321947e758f456
43.123288
193
0.636262
4.90408
false
false
false
false
minsOne/DigitClockInSwift
MainFeature/MainFeature/Dependencies/Clock/Clock/Source/ViewController.swift
1
9649
// // ViewController.swift // DigitClockinSwift // // Created by minsOne on 2015. 4. 22.. // Copyright (c) 2015년 minsOne. All rights reserved. // import UIKit import Resources import Library import Settings import ClockTimer import RIBs private let spaceViewAlpha: CGFloat = 0.5 public enum PresentableListenerAction { case tappedSettingButton case viewDidLoad } public protocol PresentableListener: class { func action(action: PresentableListenerAction) } final public class ViewController: UIViewController, Instantiable, Presentable, ViewControllable { public static var storyboardName: String { "ClockViewController" } // MARK: Properties @IBOutlet private weak var weekView: UIView! @IBOutlet private weak var spaceView: UIView! @IBOutlet private weak var timeView: UIView! @IBOutlet private var weekLabels: [UILabel]! @IBOutlet private var timeImageViews: [UIImageView]! @IBOutlet private var colonImageViews: [UIImageView]! @IBOutlet private weak var rotationButton: UIButton! @IBOutlet private weak var settingButton: UIButton! public weak var listener: PresentableListener? private var clockTimer: ClockScheduledTimerable? private var spaceViewTimer: SpaceViewScheduledTimerable? private var lastTranslation: CGPoint? private var isRotate: Bool = true { didSet { self.updateRotateLockButtonImage() } } private var isTouch: Bool = false { didSet { self.updateSpaceView() } } private var weekday: Int = 0 { didSet { self.updateWeekLabel() } } var baseColor = UIColor(red:1, green:0.19, blue:0.12, alpha:1) public var colorStorageService: ColorStorageService? deinit { clockTimer?.stop() offSpaceViewTimer() } } // MARK: View Life Cycle extension ViewController { override public func viewDidLoad() { super.viewDidLoad() self.setup() } } // MARK: Initialize extension ViewController { func setup() { initBackgroundView() initWeekLabel() initTimeView() initColonView() initRotationBtn() initSpaceView() onTickTimer() addTapGesture() addPanGesuture() updateRotateLockButtonImage() addSettingButtonTapAction() } private func initBackgroundView() { view.backgroundColor = colorStorageService?.initBackgroundColor ?? baseColor } private func initTimeView() { let f = setDigitImageLayer timeImageViews.forEach { f(0, $0) } } private func initColonView() { let f = setDigitImageLayer colonImageViews.forEach { f(10, $0) } } private func initWeekLabel() { var count = 1 weekday = ClockDate.now.weekday weekLabels.forEach { label in label.tag = count label.alpha = (label.tag == self.weekday) ? 1.0 : 0.2 count += 1 } } func initRotationBtn() { guard responds(to: #selector(pressedRotationBtn)) else { return } rotationButton.addTarget(self, action: #selector(pressedRotationBtn), for: .touchUpInside) } func addTapGesture() { let singleTap = UITapGestureRecognizer( target: self, action: #selector(handleSingleTap)) view.addGestureRecognizer(singleTap) } func addPanGesuture() { let selector = #selector(displayGestureForPanGestureRecognizer) let pan = UIPanGestureRecognizer( target: self, action: selector) view.addGestureRecognizer(pan) } func addSettingButtonTapAction() { let selector = #selector(presentSettingViewController(sender:)) settingButton.addTarget(self, action: selector, for: .touchUpInside) } @objc func presentSettingViewController(sender: UIButton) { listener?.action(action: .tappedSettingButton) } public func present(viewController: RIBs.ViewControllable) { let nc = UINavigationController(rootViewController: viewController.uiviewController) if #available(iOS 13.0, *) { nc.isModalInPresentation = true } nc.modalPresentationStyle = .popover nc.popoverPresentationController?.permittedArrowDirections = .any nc.popoverPresentationController?.sourceView = self.view let sourceRect = view.convert(settingButton.frame, from: settingButton.superview) nc.popoverPresentationController?.sourceRect = sourceRect present(nc, animated: true, completion: nil) } public func dismiss(viewController: RIBs.ViewControllable) { viewController.uiviewController.dismiss(animated: true, completion: nil) } func initSpaceView() { spaceView.layer.cornerRadius = 4 } } // MARK: View Handling extension ViewController { override public var prefersStatusBarHidden: Bool { true } func updateSpaceView() { spaceView.layer.removeAllAnimations() UIView.animate(withDuration: 0.7) { [spaceView, isTouch] in spaceView?.alpha = isTouch ? spaceViewAlpha : 0 } } func updateRotateLockButtonImage() { let isRotate = self.isRotate asyncUI { let rotationImage = isRotate ? R.Image.rotationUnLock : R.Image.rotationLock self.rotationButton.setImage(rotationImage, for: .normal) } } func updateWeekLabel() { let weekLabels = self.weekLabels asyncUI { weekLabels?.forEach { $0.alpha = ($0.tag == self.weekday ? 1.0 : 0.2) } } } public func update(color: UIColor) { asyncUI { self.view.backgroundColor = color } colorStorageService?.store(color: color) } func setDigitImageLayer(xPosition: Int, forView view: UIImageView) { view.image = R.Image.digits view.layer.contentsGravity = CALayerContentsGravity.resizeAspect view.layer.magnificationFilter = .nearest setDigitContentRect(xPosition: xPosition, forView: view) } func setDigitContentRect(xPosition: Int, forView view: UIImageView) { view.layer.contentsRect = CGRect(x: Double(xPosition)/11.0, y: 0, width: 1.0/11.0, height: 1.0) } } // MARK: View Rotate extension ViewController { override public var shouldAutorotate: Bool { isRotate } } // MARK: Touch/Gesture Handling extension ViewController { @objc func handleSingleTap(recognizer: UITapGestureRecognizer) { isTouch.toggle() if UIDevice.isIPad { isTouch ? onSpaceViewTimer() : offSpaceViewTimer() } } @objc func pressedRotationBtn(sender: UIButton) { isRotate.toggle() offSpaceViewTimer() onSpaceViewTimer() } func changeViewAlpha(nowPoint: CGPoint) { defer { lastTranslation = nowPoint } guard let lastPoint = lastTranslation, case let alpha = view.alpha else { return } if lastPoint.y > nowPoint.y && alpha < 1.0 { view.alpha = alpha + 0.01 } else if lastPoint.y < nowPoint.y && alpha >= 0.02 { view.alpha = alpha - 0.01 } } @objc func displayGestureForPanGestureRecognizer(sender: UIPanGestureRecognizer) { let translation = sender.translation(in: view) switch sender.state { case .began: lastTranslation = translation case .changed: changeViewAlpha(nowPoint: translation) case .cancelled, .ended, .failed, .possible: fallthrough default: lastTranslation = nil } } } // MARK: Time Handling extension ViewController: ClockScheduledTimerReceivable, SpaceViewScheduledTimerReceivable { func onTickTimer() { clockTimer = ClockScheduledTimer() clockTimer?.receiver = self clockTimer?.start() } public func tick(clockDate date: ClockDate) { weekday = date.weekday let timeList = getTimeList(hour: date.hour, minute: date.minute, second: date.second) let fn = setDigitContentRect UIView.animate(withDuration: 1.0) { [weak self] in guard let self = self else { return } var count = 0 timeList.forEach { fn($0, self.timeImageViews[count]) count += 1 } self.colonImageViews .forEach { $0.alpha = (Int($0.alpha) == 1 ? 0.2 : 1.0) } } } func onSpaceViewTimer() { spaceViewTimer = SpaceViewScheduledTimer() spaceViewTimer?.receiver = self spaceViewTimer?.start() } func offSpaceViewTimer() { spaceViewTimer?.stop() } public func tickSpaceView() { offSpaceViewTimer() isTouch = false } } private func getTimeList(hour h: Int, minute m: Int, second s: Int) -> [Int] { var timeLists: [Int] = [] timeLists += [h / 10] timeLists += [h % 10] timeLists += [m / 10] timeLists += [m % 10] timeLists += [s / 10] timeLists += [s % 10] return timeLists } private func asyncUI(f: @escaping () -> Void) { DispatchQueue.main.async(execute: f) }
mit
bc6e995a14be8e38d791859d001f36b8
27.883234
103
0.611382
4.651398
false
false
false
false
rockgarden/swift_language
Playground/Design-Patterns.playground/Design-Patterns.playground/Pages/Behavioral.xcplaygroundpage/Contents.swift
1
16886
//: Behavioral | //: [Creational](Creational) | //: [Structural](Structural) /*: Behavioral ========== >In software engineering, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication. > >**Source:** [wikipedia.org](http://en.wikipedia.org/wiki/Behavioral_pattern) */ import Swift import Foundation /*: 🐝 Chain Of Responsibility -------------------------- The chain of responsibility pattern is used to process varied requests, each of which may be dealt with by a different handler. ### Example: */ final class MoneyPile { let value: Int var quantity: Int var nextPile: MoneyPile? init(value: Int, quantity: Int, nextPile: MoneyPile?) { self.value = value self.quantity = quantity self.nextPile = nextPile } func canWithdraw(amount: Int) -> Bool { var amount = amount func canTakeSomeBill(want: Int) -> Bool { return (want / self.value) > 0 } var quantity = self.quantity while canTakeSomeBill(want: amount) { if quantity == 0 { break } amount -= self.value quantity -= 1 } guard amount > 0 else { return true } if let next = self.nextPile { return next.canWithdraw(amount: amount) } return false } } final class ATM { private var hundred: MoneyPile private var fifty: MoneyPile private var twenty: MoneyPile private var ten: MoneyPile private var startPile: MoneyPile { return self.hundred } init(hundred: MoneyPile, fifty: MoneyPile, twenty: MoneyPile, ten: MoneyPile) { self.hundred = hundred self.fifty = fifty self.twenty = twenty self.ten = ten } func canWithdraw(amount: Int) -> String { return "Can withdraw: \(self.startPile.canWithdraw(amount: amount))" } } /*: ### Usage */ // Create piles of money and link them together 10 < 20 < 50 < 100.** let ten = MoneyPile(value: 10, quantity: 6, nextPile: nil) let twenty = MoneyPile(value: 20, quantity: 2, nextPile: ten) let fifty = MoneyPile(value: 50, quantity: 2, nextPile: twenty) let hundred = MoneyPile(value: 100, quantity: 1, nextPile: fifty) // Build ATM. var atm = ATM(hundred: hundred, fifty: fifty, twenty: twenty, ten: ten) atm.canWithdraw(amount: 310) // Cannot because ATM has only 300 atm.canWithdraw(amount: 100) // Can withdraw - 1x100 atm.canWithdraw(amount: 165) // Cannot withdraw because ATM doesn't has bill with value of 5 atm.canWithdraw(amount: 30) // Can withdraw - 1x20, 2x10 /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Chain-Of-Responsibility) */ /*: 👫 Command ---------- The command pattern is used to express a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use. ### Example: */ protocol DoorCommand { func execute() -> String } class OpenCommand : DoorCommand { let doors:String required init(doors: String) { self.doors = doors } func execute() -> String { return "Opened \(doors)" } } class CloseCommand : DoorCommand { let doors:String required init(doors: String) { self.doors = doors } func execute() -> String { return "Closed \(doors)" } } class HAL9000DoorsOperations { let openCommand: DoorCommand let closeCommand: DoorCommand init(doors: String) { self.openCommand = OpenCommand(doors:doors) self.closeCommand = CloseCommand(doors:doors) } func close() -> String { return closeCommand.execute() } func open() -> String { return openCommand.execute() } } /*: ### Usage: */ let podBayDoors = "Pod Bay Doors" let doorModule = HAL9000DoorsOperations(doors:podBayDoors) doorModule.open() doorModule.close() /*: 🎶 Interpreter -------------- The interpreter pattern is used to evaluate sentences in a language. ### Example */ protocol IntegerExpression { func evaluate(_ context: IntegerContext) -> Int func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression func copied() -> IntegerExpression } final class IntegerContext { private var data: [Character:Int] = [:] func lookup(name: Character) -> Int { return self.data[name]! } func assign(expression: IntegerVariableExpression, value: Int) { self.data[expression.name] = value } } final class IntegerVariableExpression: IntegerExpression { let name: Character init(name: Character) { self.name = name } func evaluate(_ context: IntegerContext) -> Int { return context.lookup(name: self.name) } func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression { if name == self.name { return integerExpression.copied() } else { return IntegerVariableExpression(name: self.name) } } func copied() -> IntegerExpression { return IntegerVariableExpression(name: self.name) } } final class AddExpression: IntegerExpression { private var operand1: IntegerExpression private var operand2: IntegerExpression init(op1: IntegerExpression, op2: IntegerExpression) { self.operand1 = op1 self.operand2 = op2 } func evaluate(_ context: IntegerContext) -> Int { return self.operand1.evaluate(context) + self.operand2.evaluate(context) } func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression { return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression), op2: operand2.replace(character: character, integerExpression: integerExpression)) } func copied() -> IntegerExpression { return AddExpression(op1: self.operand1, op2: self.operand2) } } /*: ### Usage */ var context = IntegerContext() var a = IntegerVariableExpression(name: "A") var b = IntegerVariableExpression(name: "B") var c = IntegerVariableExpression(name: "C") var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c) context.assign(expression: a, value: 2) context.assign(expression: b, value: 1) context.assign(expression: c, value: 3) var result = expression.evaluate(context) /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Interpreter) */ /*: 🍫 Iterator ----------- The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure. ### Example: */ struct Novella { let name: String } struct Novellas { let novellas: [Novella] } struct NovellasIterator: IteratorProtocol { private var current = 0 private let novellas: [Novella] init(novellas: [Novella]) { self.novellas = novellas } mutating func next() -> Novella? { defer { current += 1 } return novellas.count > current ? novellas[current] : nil } } extension Novellas: Sequence { func makeIterator() -> NovellasIterator { return NovellasIterator(novellas: novellas) } } /*: ### Usage */ let greatNovellas = Novellas(novellas: [Novella(name: "The Mist")] ) for novella in greatNovellas { print("I've read: \(novella)") } /*: 💐 Mediator ----------- The mediator pattern is used to reduce coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object. ### Example */ struct Programmer { let name: String init(name: String) { self.name = name } func receive(message: String) { print("\(name) received: \(message)") } } protocol MessageSending { func send(message: String) } final class MessageMediator: MessageSending { private var recipients: [Programmer] = [] func add(recipient: Programmer) { recipients.append(recipient) } func send(message: String) { for recipient in recipients { recipient.receive(message: message) } } } /*: ### Usage */ func spamMonster(message: String, worker: MessageSending) { worker.send(message: message) } let messagesMediator = MessageMediator() let user0 = Programmer(name: "Linus Torvalds") let user1 = Programmer(name: "Avadis 'Avie' Tevanian") messagesMediator.add(recipient: user0) messagesMediator.add(recipient: user1) spamMonster(message: "I'd Like to Add you to My Professional Network", worker: messagesMediator) /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Mediator) */ /*: 💾 Memento ---------- The memento pattern is used to capture the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation. ### Example */ typealias Memento = NSDictionary /*: Originator */ protocol MementoConvertible { var memento: Memento { get } init?(memento: Memento) } struct GameState: MementoConvertible { private struct Keys { static let chapter = "com.valve.halflife.chapter" static let weapon = "com.valve.halflife.weapon" } var chapter: String var weapon: String init(chapter: String, weapon: String) { self.chapter = chapter self.weapon = weapon } init?(memento: Memento) { guard let mementoChapter = memento[Keys.chapter] as? String, let mementoWeapon = memento[Keys.weapon] as? String else { return nil } chapter = mementoChapter weapon = mementoWeapon } var memento: Memento { return [ Keys.chapter: chapter, Keys.weapon: weapon ] } } /*: Caretaker */ enum CheckPoint { static func save(_ state: MementoConvertible, saveName: String) { let defaults = UserDefaults.standard defaults.set(state.memento, forKey: saveName) defaults.synchronize() } static func restore(saveName: String) -> Memento? { let defaults = UserDefaults.standard return defaults.object(forKey: saveName) as? Memento } } /*: ### Usage */ var gameState = GameState(chapter: "Black Mesa Inbound", weapon: "Crowbar") gameState.chapter = "Anomalous Materials" gameState.weapon = "Glock 17" CheckPoint.save(gameState, saveName: "gameState1") gameState.chapter = "Unforeseen Consequences" gameState.weapon = "MP5" CheckPoint.save(gameState, saveName: "gameState2") gameState.chapter = "Office Complex" gameState.weapon = "Crossbow" CheckPoint.save(gameState, saveName: "gameState3") if let memento = CheckPoint.restore(saveName: "gameState1") { let finalState = GameState(memento: memento) dump(finalState) } /*: 👓 Observer ----------- The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes. ### Example */ protocol PropertyObserver : class { func willChange(propertyName: String, newPropertyValue: Any?) func didChange(propertyName: String, oldPropertyValue: Any?) } final class TestChambers { weak var observer:PropertyObserver? private let testChamberNumberName = "testChamberNumber" var testChamberNumber: Int = 0 { willSet(newValue) { observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue) } didSet { observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue) } } } final class Observer : PropertyObserver { func willChange(propertyName: String, newPropertyValue: Any?) { if newPropertyValue as? Int == 1 { print("Okay. Look. We both said a lot of things that you're going to regret.") } } func didChange(propertyName: String, oldPropertyValue: Any?) { if oldPropertyValue as? Int == 0 { print("Sorry about the mess. I've really let the place go since you killed me.") } } } /*: ### Usage */ var observerInstance = Observer() var testChambers = TestChambers() testChambers.observer = observerInstance testChambers.testChamberNumber += 1 /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Observer) */ /*: 🐉 State --------- The state pattern is used to alter the behaviour of an object as its internal state changes. The pattern allows the class for an object to apparently change at run-time. ### Example */ final class Context { private var state: State = UnauthorizedState() var isAuthorized: Bool { get { return state.isAuthorized(context: self) } } var userId: String? { get { return state.userId(context: self) } } func changeStateToAuthorized(userId: String) { state = AuthorizedState(userId: userId) } func changeStateToUnauthorized() { state = UnauthorizedState() } } protocol State { func isAuthorized(context: Context) -> Bool func userId(context: Context) -> String? } class UnauthorizedState: State { func isAuthorized(context: Context) -> Bool { return false } func userId(context: Context) -> String? { return nil } } class AuthorizedState: State { let userId: String init(userId: String) { self.userId = userId } func isAuthorized(context: Context) -> Bool { return true } func userId(context: Context) -> String? { return userId } } /*: ### Usage */ let userContext = Context() (userContext.isAuthorized, userContext.userId) userContext.changeStateToAuthorized(userId: "admin") (userContext.isAuthorized, userContext.userId) // now logged in as "admin" userContext.changeStateToUnauthorized() (userContext.isAuthorized, userContext.userId) /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-State) */ /*: 💡 Strategy ----------- The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time. ### Example */ protocol PrintStrategy { func print(_ string: String) -> String } final class Printer { private let strategy: PrintStrategy func print(_ string: String) -> String { return self.strategy.print(string) } init(strategy: PrintStrategy) { self.strategy = strategy } } final class UpperCaseStrategy: PrintStrategy { func print(_ string: String) -> String { return string.uppercased() } } final class LowerCaseStrategy: PrintStrategy { func print(_ string:String) -> String { return string.lowercased() } } /*: ### Usage */ var lower = Printer(strategy: LowerCaseStrategy()) lower.print("O tempora, o mores!") var upper = Printer(strategy: UpperCaseStrategy()) upper.print("O tempora, o mores!") /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Strategy) */ /*: 🏃 Visitor ---------- The visitor pattern is used to separate a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold. ### Example */ protocol PlanetVisitor { func visit(planet: PlanetAlderaan) func visit(planet: PlanetCoruscant) func visit(planet: PlanetTatooine) func visit(planet: MoonJedah) } protocol Planet { func accept(visitor: PlanetVisitor) } class MoonJedah: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) } } class PlanetAlderaan: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) } } class PlanetCoruscant: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) } } class PlanetTatooine: Planet { func accept(visitor: PlanetVisitor) { visitor.visit(planet: self) } } class NameVisitor: PlanetVisitor { var name = "" func visit(planet: PlanetAlderaan) { name = "Alderaan" } func visit(planet: PlanetCoruscant) { name = "Coruscant" } func visit(planet: PlanetTatooine) { name = "Tatooine" } func visit(planet: MoonJedah) { name = "Jedah" } } /*: ### Usage */ let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine(), MoonJedah()] let names = planets.map { (planet: Planet) -> String in let visitor = NameVisitor() planet.accept(visitor: visitor) return visitor.name } names /*: >**Further Examples:** [Design Patterns in Swift](https://github.com/kingreza/Swift-Visitor) */
mit
3dabfcc93a176f5ff3e43ebf550800a9
24.233533
245
0.675012
3.916357
false
false
false
false
johnno1962c/swift-corelibs-foundation
Foundation/PersonNameComponents.swift
9
7494
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// public struct PersonNameComponents : ReferenceConvertible, Hashable, Equatable, _MutableBoxing { public typealias ReferenceType = NSPersonNameComponents internal var _handle: _MutableHandle<NSPersonNameComponents> public init() { _handle = _MutableHandle(adoptingReference: NSPersonNameComponents()) } fileprivate init(reference: NSPersonNameComponents) { _handle = _MutableHandle(reference: reference) } /* The below examples all assume the full name Dr. Johnathan Maple Appleseed Esq., nickname "Johnny" */ /* Pre-nominal letters denoting title, salutation, or honorific, e.g. Dr., Mr. */ public var namePrefix: String? { get { return _handle.map { $0.namePrefix } } set { _applyMutation { $0.namePrefix = newValue } } } /* Name bestowed upon an individual by one's parents, e.g. Johnathan */ public var givenName: String? { get { return _handle.map { $0.givenName } } set { _applyMutation { $0.givenName = newValue } } } /* Secondary given name chosen to differentiate those with the same first name, e.g. Maple */ public var middleName: String? { get { return _handle.map { $0.middleName } } set { _applyMutation { $0.middleName = newValue } } } /* Name passed from one generation to another to indicate lineage, e.g. Appleseed */ public var familyName: String? { get { return _handle.map { $0.familyName } } set { _applyMutation { $0.familyName = newValue } } } /* Post-nominal letters denoting degree, accreditation, or other honor, e.g. Esq., Jr., Ph.D. */ public var nameSuffix: String? { get { return _handle.map { $0.nameSuffix } } set { _applyMutation { $0.nameSuffix = newValue } } } /* Name substituted for the purposes of familiarity, e.g. "Johnny"*/ public var nickname: String? { get { return _handle.map { $0.nickname } } set { _applyMutation { $0.nickname = newValue } } } /* Each element of the phoneticRepresentation should correspond to an element of the original PersonNameComponents instance. The phoneticRepresentation of the phoneticRepresentation object itself will be ignored. nil by default, must be instantiated. */ public var phoneticRepresentation: PersonNameComponents? { get { return _handle.map { $0.phoneticRepresentation } } set { _applyMutation { $0.phoneticRepresentation = newValue } } } public var hashValue : Int { return _handle.map { $0.hash } } public static func ==(lhs : PersonNameComponents, rhs: PersonNameComponents) -> Bool { // Don't copy references here; no one should be storing anything return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference()) } } extension PersonNameComponents : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public var description: String { return self.customMirror.children.reduce("") { $0.appending("\($1.label ?? ""): \($1.value) ") } } public var debugDescription: String { return self.description } public var customMirror: Mirror { var c: [(label: String?, value: Any)] = [] if let r = namePrefix { c.append((label: "namePrefix", value: r)) } if let r = givenName { c.append((label: "givenName", value: r)) } if let r = middleName { c.append((label: "middleName", value: r)) } if let r = familyName { c.append((label: "familyName", value: r)) } if let r = nameSuffix { c.append((label: "nameSuffix", value: r)) } if let r = nickname { c.append((label: "nickname", value: r)) } if let r = phoneticRepresentation { c.append((label: "phoneticRepresentation", value: r)) } return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) } } extension PersonNameComponents : _ObjectTypeBridgeable { public static func _getObjectiveCType() -> Any.Type { return NSPersonNameComponents.self } @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSPersonNameComponents { return _handle._copiedReference() } public static func _forceBridgeFromObjectiveC(_ personNameComponents: NSPersonNameComponents, result: inout PersonNameComponents?) { if !_conditionallyBridgeFromObjectiveC(personNameComponents, result: &result) { fatalError("Unable to bridge \(NSPersonNameComponents.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ personNameComponents: NSPersonNameComponents, result: inout PersonNameComponents?) -> Bool { result = PersonNameComponents(reference: personNameComponents) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSPersonNameComponents?) -> PersonNameComponents { var result: PersonNameComponents? = nil _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension NSPersonNameComponents : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self._bridgeToSwift()) } } extension PersonNameComponents : Codable { private enum CodingKeys : Int, CodingKey { case namePrefix case givenName case middleName case familyName case nameSuffix case nickname } public init(from decoder: Decoder) throws { self.init() let container = try decoder.container(keyedBy: CodingKeys.self) self.namePrefix = try container.decodeIfPresent(String.self, forKey: .namePrefix) self.givenName = try container.decodeIfPresent(String.self, forKey: .givenName) self.middleName = try container.decodeIfPresent(String.self, forKey: .middleName) self.familyName = try container.decodeIfPresent(String.self, forKey: .familyName) self.nameSuffix = try container.decodeIfPresent(String.self, forKey: .nameSuffix) self.nickname = try container.decodeIfPresent(String.self, forKey: .nickname) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if let np = self.namePrefix { try container.encode(np, forKey: .namePrefix) } if let gn = self.givenName { try container.encode(gn, forKey: .givenName) } if let mn = self.middleName { try container.encode(mn, forKey: .middleName) } if let fn = self.familyName { try container.encode(fn, forKey: .familyName) } if let ns = self.nameSuffix { try container.encode(ns, forKey: .nameSuffix) } if let nn = self.nickname { try container.encode(nn, forKey: .nickname) } } }
apache-2.0
b4669f84e4ace396f9606f862d95c181
42.569767
152
0.65479
4.764145
false
false
false
false
andreacremaschi/CopyPaper
CopyPaper/UIViewController+CopyPaper.swift
1
1161
import Foundation import UIKit var isOverlaidAssociationKey: UInt8 = 0 extension UIViewController { override public class func initialize() { guard self === UIViewController.self else { return } swizzleMethodSelector("viewDidLoad", withSelector: "cp_viewDidLoad", forClass: self) } func cp_viewDidLoad() { cp_viewDidLoad() if self.overlay || (self.parentViewController?.overlay ?? false) { view.passThrough = true view.backgroundColor = UIColor.clearColor() } } @IBInspectable public var overlay: Bool { get { return objc_getAssociatedObject(self, &isOverlaidAssociationKey) as? Bool ?? false } set(newValue) { objc_setAssociatedObject(self, &isOverlaidAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public func overlayViewController(viewController: UIViewController) { self.addChildViewController(viewController) viewController.overlay = true viewController.view.frame = self.view.frame self.view.addSubview(viewController.view) } }
mit
e586ff64cfe54ec1b193cf82d2d0a5fd
31.277778
115
0.656331
5.114537
false
false
false
false
clarenceji/Clarence-Ji
Clarence Ji/CJProjectDetailPopupView.swift
1
9888
// // CJProjectDetailPopupView.swift // Clarence Ji // // Created by Clarence Ji on 4/21/15. // Copyright (c) 2015 Clarence Ji. All rights reserved. // import UIKit class CJProjectDetailPopupView: UIView, UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource { @IBOutlet var scrollView_Images: UIScrollView! @IBOutlet var scrollViewHeightConstraint: NSLayoutConstraint! @IBOutlet var label_Title: UILabel! @IBOutlet var label_Description: UILabel! @IBOutlet var tableView_Details: UITableView! var prevTableVC: CJTableView2! var btn_Details: UIButton! var btn_Done: UIButton! var urlString: String! var dict_ProjectInfo: [String: AnyObject]! var dict_CurrentProject: [String: AnyObject]? var array_Keys: [String]? var array_Values: [String]? let screen = UIScreen.main.bounds let selfWidth = UIScreen.main.bounds.width let selfHeight = UIScreen.main.bounds.height var numberOfImages = 3 var pageControl: UIPageControl! let darkMode = UserDefaults.standard.bool(forKey: "DarkMode") required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { // screen.height + selfHeight: Prepare for animation let selfFrame = CGRect(x: 0, y: screen.height + selfHeight, width: selfWidth, height: selfHeight) self.frame = selfFrame // Blur View var blurEffect = UIBlurEffect(style: .dark) if darkMode { blurEffect = UIBlurEffect(style: .light) } let blurView = UIVisualEffectView(effect: blurEffect) blurView.frame = self.bounds self.backgroundColor = .clear self.addSubview(blurView) self.sendSubview(toBack: blurView) // Add buttons self.addButtons() self.layer.cornerRadius = 8.0 self.clipsToBounds = true self.scrollView_Images.delegate = self self.scrollView_Images.isPagingEnabled = true // Image takes up 1/3 of whole view self.scrollViewHeightConstraint.constant = selfHeight / 3 self.layoutIfNeeded() self.tableView_Details.delegate = self self.tableView_Details.dataSource = self self.tableView_Details.estimatedRowHeight = 35.0 self.tableView_Details.rowHeight = UITableViewAutomaticDimension // Read & save json file self.dict_ProjectInfo = jsonToDict() } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if scrollView == self.scrollView_Images { let offsetLooping = 1 let page = (scrollView.contentOffset.x - selfWidth / CGFloat(2)) / selfWidth + CGFloat(offsetLooping) pageControl.currentPage = Int(page) % numberOfImages } } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView_Images.contentOffset.y != 0 { scrollView_Images.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: 0) } } override func removeFromSuperview() { UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.5, options: UIViewAnimationOptions(), animations: { self.center = CGPoint(x: self.center.x, y: self.selfHeight * 2) self.prevTableVC.btn_GoBack.alpha = 1.0 self.alpha = 0 self.superview!.transform = CGAffineTransform(scaleX: 1, y: 1) self.superview!.layer.cornerRadius = 0 }) { (complete) -> Void in self.prevTableVC.tableView.isScrollEnabled = true super.removeFromSuperview() } } func addImages(_ fileNames: [String]) { self.numberOfImages = fileNames.count // Populate ScrollView with Images for i in 0 ..< numberOfImages { let frame = CGRect( x: self.frame.size.width * CGFloat(i), y: 0, width: self.frame.size.width, height: scrollView_Images.frame.size.height ) let imageView = UIImageView(frame: frame) imageView.contentMode = .scaleAspectFill imageView.image = UIImage(named: fileNames[i])! imageView.clipsToBounds = true scrollView_Images.addSubview(imageView) } scrollView_Images.contentSize = CGSize(width: selfWidth * CGFloat(numberOfImages), height: selfHeight / 3); // Add PageControl pageControl = UIPageControl(frame: CGRect(x: 0, y: scrollView_Images.frame.size.height + scrollView_Images.frame.origin.y - 20, width: selfWidth, height: 20)) pageControl.numberOfPages = numberOfImages self.addSubview(pageControl) } func addButtons() { let font_Reg = UIFont(name: "MyriadPro-Regular", size: 17.0) let font_Light = UIFont(name: "MyriadPro-Light", size: 17.0) var bgColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5) if darkMode { bgColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) } btn_Details = UIButton(frame: CGRect(x: 0, y: selfHeight - 44, width: selfWidth / 2, height: 44)) btn_Details.setTitle("More Details", for: UIControlState()) btn_Details.titleLabel?.font = font_Reg btn_Details.backgroundColor = bgColor btn_Details.addTarget(self, action: #selector(CJProjectDetailPopupView.btn_Details_Pressed(_:)), for: .touchUpInside) btn_Done = UIButton(frame: CGRect(x: selfWidth / 2, y: selfHeight - 44, width: selfWidth / 2, height: 44)) btn_Done.setTitle("Done", for: UIControlState()) btn_Done.titleLabel?.font = font_Light btn_Done.backgroundColor = bgColor btn_Done.addTarget(self, action: #selector(CJProjectDetailPopupView.btn_Done_Pressed(_:)), for: .touchUpInside) self.addSubview(btn_Details) self.addSubview(btn_Done) } @objc func btn_Done_Pressed(_ sender: AnyObject) { removeFromSuperview() } @objc func btn_Details_Pressed(_ sender: AnyObject) { UIApplication.shared.openURL(URL(string: self.urlString)!) } func jsonToDict() -> [String: AnyObject] { let path = Bundle.main.path(forResource: "Project_Info", ofType: "json") do { let data = try Data(contentsOf: URL(fileURLWithPath: path!), options: .mappedIfSafe) // var error: NSError? let json = try! JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: AnyObject] return json } catch _ { } return [String: AnyObject]() } func addContents(_ title: String) { self.dict_CurrentProject = dict_ProjectInfo[title] as? [String: AnyObject] label_Title.text = title if let currentDict = self.dict_CurrentProject { // 1 - Images addImages(currentDict["image"] as! [String]) // 2 - URL var urlStringFromDict = currentDict["url"] as! String if urlStringFromDict[urlStringFromDict.startIndex] == "•" { urlStringFromDict.remove(at: urlStringFromDict.startIndex) btn_Details.setImage(UIImage(named: "Troll-face"), for: UIControlState()) btn_Details.imageView?.contentMode = .scaleAspectFit } self.urlString = urlStringFromDict // 3 - Description let string = currentDict["description"] as? String let attrStyle = NSMutableParagraphStyle() attrStyle.lineSpacing = 7 let attributes = [ NSAttributedStringKey.paragraphStyle: attrStyle ] let attrString = NSMutableAttributedString(string: string!, attributes: attributes) self.label_Description.attributedText = attrString self.label_Description.textAlignment = .center // 4 - Details array_Keys = [String]() array_Values = [String]() for (key, value) in (currentDict["details"] as! [String: String]) { array_Keys?.append(key) array_Values?.append(value) } } self.tableView_Details.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if array_Keys != nil { return array_Keys!.count } return 0 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = Bundle.main.loadNibNamed("CJProjectDetailPopupView", owner: self, options: nil)?[1] as! CJProjectDetailPopupView_Cell cell.selectionStyle = .none let attrStyle = NSMutableParagraphStyle() attrStyle.lineSpacing = 7 let attributes = [ NSAttributedStringKey.paragraphStyle: attrStyle ] if array_Keys != nil && array_Values != nil { let attrString_Key = NSMutableAttributedString(string: array_Keys![indexPath.row], attributes: attributes) let attrString_Value = NSMutableAttributedString(string: array_Values![indexPath.row], attributes: attributes) cell.label_Key.attributedText = attrString_Key cell.label_Value.attributedText = attrString_Value cell.label_Key.textAlignment = .right cell.label_Key_ConstraintWidth.constant = self.frame.size.width * 0.32 cell.layoutIfNeeded() } return cell } }
gpl-3.0
977b13044beced56cc44570dca311c4d
38.230159
166
0.615112
4.789729
false
false
false
false
swifteroid/reactiveoauth
source/ReactiveOAuth/Auth/Auth.Credential.swift
1
680
import Foundation import OAuthSwift public struct Credential { public var accessToken: String public var refreshToken: String? public var expireDate: Date? public init(accessToken: String, refreshToken: String? = nil, expireDate: Date? = nil) { self.accessToken = accessToken self.refreshToken = refreshToken self.expireDate = expireDate } internal init(credential: OAuthSwiftCredential) { self.init( accessToken: credential.oauthToken, refreshToken: credential.oauthRefreshToken == "" ? nil : credential.oauthRefreshToken, expireDate: credential.oauthTokenExpiresAt ) } }
mit
b16104532be6fe5454c97e2c875127ad
29.909091
98
0.679412
5.44
false
false
false
false
hmuronaka/SwiftlySalesforce
Pod/Classes/Model.swift
1
3214
// // Model.swift // SwiftlySalesforce // // For license & details see: https://www.github.com/mike4aday/SwiftlySalesforce // Copyright (c) 2016. All rights reserved. // /// Holds the result of a SOQL query /// See https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query.htm public struct QueryResult { public let totalSize: Int public let isDone: Bool public let records: [[String: Any]] public let nextRecordsPath: String? init(json: [String: Any]) throws { guard let totalSize = json["totalSize"] as? Int, let isDone = json["done"] as? Bool, let records = json["records"] as? [[String: Any]] else { throw SalesforceError.jsonDeserializationFailure(elementName: nil, json: json) } self.totalSize = totalSize self.isDone = isDone self.records = records self.nextRecordsPath = json["nextRecordsUrl"] as? String if !isDone && self.nextRecordsPath == nil { throw SalesforceError.invalidity(message: "Missing next records path for query result!") } } } /// Represents a limited Salesforce resource /// See: https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_limits.htm public struct Limit { public let name: String public let maximum: Int public let remaining: Int public init(name: String, maximum: Int, remaining: Int) { self.name = name self.maximum = maximum self.remaining = remaining } } /// Holds result of call to identity URL /// See: https://help.salesforce.com/HTViewHelpDoc?id=remoteaccess_using_openid.htm public struct UserInfo { public let dictionary: [String: Any] public var displayName: String? { return dictionary["display_name"] as? String } public var mobilePhone: String? { return dictionary["mobile_phone"] as? String } public var username: String? { return dictionary["username"] as? String } public var userID: String? { return dictionary["user_id"] as? String } public var orgID: String? { return dictionary["organization_id"] as? String } public var userType: String? { return dictionary["user_type"] as? String } public var language: String? { return dictionary["language"] as? String } public var lastModifiedDate: Date? { return dictionary.dateValue(forKey: "last_modified_date") } public var locale: String? { return dictionary["locale"] as? String } public var photoURL: URL? { guard let photos = dictionary["photos"] as? [String: String], let photoURL = URL(string: photos["picture"]) else { return nil } return photoURL } public var thumbnailURL: URL? { guard let photos = dictionary["photos"] as? [String: String], let thumbnailURL = URL(string: photos["thumbnail"]) else { return nil } return thumbnailURL } public var profileURL: URL? { guard let urls = dictionary["urls"] as? [String: String], let profileURL = URL(string: urls["profile"]) else { return nil } return profileURL } public var recentRecordsURL: URL? { guard let urls = dictionary["urls"] as? [String: String], let recentRecordsURL = URL(string: urls["recent"]) else { return nil } return recentRecordsURL } /// Initializer init(json: [String: Any]) throws { self.dictionary = json } }
mit
80633255c47aa0994bdb09f66672c411
25.561983
143
0.702551
3.463362
false
false
false
false
chengxianghe/MissGe
MissGe/MissGe/Class/Helper/XHImageGifHelper.swift
1
4745
// // XHImageGifHelper.swift // MissGe // // Created by chengxianghe on 2017/5/18. // Copyright © 2017年 cn. All rights reserved. // import Foundation import AssetsLibrary import Photos import MobileCoreServices typealias kGIFCheckClosure = (_ isGif: Bool, _ gifData: Data?) -> Void typealias kGetImageDataClosure = (_ isGif: Bool, _ imageData: Data?, _ error: Error?) -> Void class XHImageGifHelper { class func checkGIFWithAsset(asset: AnyObject, completion: kGIFCheckClosure?) { if let alAsset = asset as? ALAsset { let isGif = (alAsset.representation(forUTI: (kUTTypeGIF as String)) != nil) completion?(isGif, nil) } else if let phAsset = asset as? PHAsset { if #available(iOS 9.0, *) { let resourceList = PHAssetResource.assetResources(for: phAsset) var isGif = false for resource in resourceList.enumerated() { if resource.element.uniformTypeIdentifier == (kUTTypeGIF as String) { isGif = true break } } completion?(isGif, nil) } else { // Fallback on earlier versions let imageManager = PHCachingImageManager.init() let options = PHImageRequestOptions.init(); options.resizeMode = .fast options.isSynchronous = true imageManager.requestImageData(for: phAsset, options: options, resultHandler: { (imageData, dataUTI, orientation, info) in guard let uti = dataUTI else { completion?(false, nil) return; } print("dataUTI:\(uti)") //gif 图片 if (uti == (kUTTypeGIF as String)) { //这里获取gif图片的NSData数据 completion?(true, imageData) // let cache = (info?[PHImageCancelledKey] as! NSString).boolValue // let error: NSError? = info?[PHImageErrorKey] as? NSError // let downloadFinined = !cache && error == nil; // // if (downloadFinined && (imageData != nil)) { // completion?(true, imageData!) // } else { // completion?(true, imageData) // } } else { //其他格式的图片 completion?(false, imageData) } }) } } } private class func getGIFDataWithAsset(asset: AnyObject, completion: ((_ imageData: Data?, _ error: Error?) -> Void)?) { if let alAsset = asset as? ALAsset { let representation = alAsset.defaultRepresentation()! let error = NSErrorPointer.init(nilLiteral: ()) let imageBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(representation.size())) let bufferSize = representation.getBytes(imageBuffer, fromOffset: Int64(0), length: Int(representation.size()), error: error) let imageData:NSData = NSData(bytesNoCopy:imageBuffer ,length:bufferSize, freeWhenDone:true) completion?(imageData as Data, error as? Error); } else if let phAsset = asset as? PHAsset { let imageManager = PHCachingImageManager.init() let options = PHImageRequestOptions.init(); options.resizeMode = .fast options.isSynchronous = true imageManager.requestImageData(for: phAsset, options: options, resultHandler: { (imageData, dataUTI, orientation, info) in print("dataUTI:\(String(describing: dataUTI))") completion?(imageData, info?[PHImageErrorKey] as? Error) }) } } /// 获取图片ALAsset/PHAsset的图片data 兼容gif /// /// - Parameters: /// - asset: ALAsset/PHAsset /// - completion: isGif imageData error class func getImageDataWithAsset(asset: AnyObject, completion: kGetImageDataClosure?) { self.checkGIFWithAsset(asset: asset) { (isGif, gifData) in if gifData != nil { completion?(isGif, gifData, nil); } else { self.getGIFDataWithAsset(asset: asset, completion: { (imageData: Data?, error: Error?) in completion?(isGif, imageData, error) }) } } } }
mit
0bf2f54da761e1079ad6c4df44ab114e
41.234234
137
0.526664
5.18011
false
false
false
false
emilstahl/swift
test/decl/class/override.swift
11
14943
// RUN: %target-parse-verify-swift -parse-as-library class A { func ret_sametype() -> Int { return 0 } func ret_subclass() -> A { return self } func ret_subclass_rev() -> B { return B() } func ret_nonclass_optional() -> Int? { return .None } func ret_nonclass_optional_rev() -> Int { return 0 } func ret_class_optional() -> B? { return .None } func ret_class_optional_rev() -> A { return self } func ret_class_uoptional() -> B! { return B() } func ret_class_uoptional_rev() -> A { return self } func ret_class_optional_uoptional() -> B? { return .None } func ret_class_optional_uoptional_rev() -> A! { return self } func param_sametype(x : Int) {} func param_subclass(x : B) {} func param_subclass_rev(x : A) {} func param_nonclass_optional(x : Int) {} func param_nonclass_optional_rev(x : Int?) {} func param_class_optional(x : B) {} func param_class_optional_rev(x : B?) {} func param_class_uoptional(x : B) {} func param_class_uoptional_rev(x : B!) {} func param_class_optional_uoptional(x : B!) {} func param_class_optional_uoptional_rev(x : B?) {} } class B : A { override func ret_sametype() -> Int { return 1 } override func ret_subclass() -> B { return self } func ret_subclass_rev() -> A { return self } override func ret_nonclass_optional() -> Int { return 0 } func ret_nonclass_optional_rev() -> Int? { return 0 } override func ret_class_optional() -> B { return self } func ret_class_optional_rev() -> A? { return self } override func ret_class_uoptional() -> B { return self } func ret_class_uoptional_rev() -> A! { return self } override func ret_class_optional_uoptional() -> B! { return self } override func ret_class_optional_uoptional_rev() -> A? { return self } override func param_sametype(x : Int) {} override func param_subclass(x : A) {} func param_subclass_rev(x : B) {} override func param_nonclass_optional(x : Int?) {} func param_nonclass_optional_rev(x : Int) {} override func param_class_optional(x : B?) {} func param_class_optional_rev(x : B) {} override func param_class_uoptional(x : B!) {} func param_class_uoptional_rev(x : B) {} override func param_class_optional_uoptional(x : B?) {} override func param_class_optional_uoptional_rev(x : B!) {} } class C<T> { func ret_T() -> T {} } class D<T> : C<[T]> { override func ret_T() -> [T] {} } class E { var var_sametype: Int { get { return 0 } set {} } var var_subclass: E { get { return self } set {} } // expected-note{{attempt to override property here}} var var_subclass_rev: F { get { return F() } set {} } // expected-note{{attempt to override property here}} var var_nonclass_optional: Int? { get { return .None } set {} } // expected-note{{attempt to override property here}} var var_nonclass_optional_rev: Int { get { return 0 } set {} } // expected-note{{attempt to override property here}} var var_class_optional: F? { get { return .None } set {} } // expected-note{{attempt to override property here}} var var_class_optional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}} var var_class_uoptional: F! { get { return F() } set {} } // expected-note{{attempt to override property here}} var var_class_uoptional_rev: E { get { return self } set {} } // expected-note{{attempt to override property here}} var var_class_optional_uoptional: F? { get { return .None } set {} } var var_class_optional_uoptional_rev: E! { get { return self } set {} } var ro_sametype: Int { return 0 } var ro_subclass: E { return self } var ro_subclass_rev: F { return F() } var ro_nonclass_optional: Int? { return 0 } var ro_nonclass_optional_rev: Int { return 0 } // expected-note{{attempt to override property here}} var ro_class_optional: F? { return .None } var ro_class_optional_rev: E { return self } // expected-note{{attempt to override property here}} var ro_class_uoptional: F! { return F() } var ro_class_uoptional_rev: E { return self } // expected-note{{attempt to override property here}} var ro_class_optional_uoptional: F? { return .None } var ro_class_optional_uoptional_rev: E! { return self } } class F : E { override var var_sametype: Int { get { return 0 } set {} } override var var_subclass: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_subclass' of type 'E' with covariant type 'F'}} override var var_subclass_rev: E { get { return F() } set {} } // expected-error{{property 'var_subclass_rev' with type 'E' cannot override a property with type 'F}} override var var_nonclass_optional: Int { get { return 0 } set {} } // expected-error{{cannot override mutable property 'var_nonclass_optional' of type 'Int?' with covariant type 'Int'}} override var var_nonclass_optional_rev: Int? { get { return 0 } set {} } // expected-error{{property 'var_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}} override var var_class_optional: F { get { return self } set {} } // expected-error{{cannot override mutable property 'var_class_optional' of type 'F?' with covariant type 'F'}} override var var_class_optional_rev: E? { get { return self } set {} } // expected-error{{property 'var_class_optional_rev' with type 'E?' cannot override a property with type 'E'}} override var var_class_uoptional: F { get { return F() } set {} } // expected-error{{cannot override mutable property 'var_class_uoptional' of type 'F!' with covariant type 'F'}} override var var_class_uoptional_rev: E! { get { return self } set {} } // expected-error{{property 'var_class_uoptional_rev' with type 'E!' cannot override a property with type 'E'}} override var var_class_optional_uoptional: F! { get { return .None } set {} } override var var_class_optional_uoptional_rev: E? { get { return self } set {} } override var ro_sametype: Int { return 0 } override var ro_subclass: E { return self } override var ro_subclass_rev: F { return F() } override var ro_nonclass_optional: Int { return 0 } override var ro_nonclass_optional_rev: Int? { return 0 } // expected-error{{property 'ro_nonclass_optional_rev' with type 'Int?' cannot override a property with type 'Int'}} override var ro_class_optional: F { return self } override var ro_class_optional_rev: E? { return self } // expected-error{{property 'ro_class_optional_rev' with type 'E?' cannot override a property with type 'E'}} override var ro_class_uoptional: F { return F() } override var ro_class_uoptional_rev: E! { return self } // expected-error{{property 'ro_class_uoptional_rev' with type 'E!' cannot override a property with type 'E'}} override var ro_class_optional_uoptional: F! { return .None } override var ro_class_optional_uoptional_rev: E? { return self } } class G { func f1(_: Int, int: Int) { } func f2(_: Int, int: Int) { } func f3(_: Int, int: Int) { } func f4(_: Int, int: Int) { } func f5(_: Int, int: Int) { } func f6(_: Int, int: Int) { } func f7(_: Int, int: Int) { } func g1(_: Int, string: String) { } // expected-note{{potential overridden method 'g1(_:string:)' here}} {{28-28=string }} func g1(_: Int, path: String) { } // expected-note{{potential overridden method 'g1(_:path:)' here}} {{28-28=path }} } class H : G { override func f1(_: Int, _: Int) { } // expected-error{{argument names for method 'f1' do not match those of overridden method 'f1(_:int:)'}}{{28-28=int }} override func f2(_: Int, value: Int) { } // expected-error{{argument names for method 'f2(_:value:)' do not match those of overridden method 'f2(_:int:)'}}{{28-28=int }} override func f3(_: Int, value int: Int) { } // expected-error{{argument names for method 'f3(_:value:)' do not match those of overridden method 'f3(_:int:)'}}{{28-34=}} override func f4(_: Int, _ int: Int) { } // expected-error{{argument names for method 'f4' do not match those of overridden method 'f4(_:int:)'}}{{28-30=}} override func f5(_: Int, value inValue: Int) { } // expected-error{{argument names for method 'f5(_:value:)' do not match those of overridden method 'f5(_:int:)'}}{{28-33=int}} override func f6(_: Int, _ inValue: Int) { } // expected-error{{argument names for method 'f6' do not match those of overridden method 'f6(_:int:)'}}{{28-29=int}} override func f7(_: Int, int value: Int) { } // okay override func g1(_: Int, s: String) { } // expected-error{{declaration 'g1(_:s:)' has different argument names from any potential overrides}} } @objc class IUOTestBaseClass { func none() {} func oneA(_: AnyObject) {} func oneB(x x: AnyObject) {} func oneC(x x: AnyObject) {} func oneD(x: AnyObject) {} func manyA(_: AnyObject, _: AnyObject) {} func manyB(a: AnyObject, b: AnyObject) {} func manyC(a: AnyObject, b: AnyObject) {} func result() -> AnyObject? { return nil } func both(x: AnyObject) -> AnyObject? { return x } init(_: AnyObject) {} init(one: AnyObject) {} init(a: AnyObject, b: AnyObject) {} } class IUOTestSubclass : IUOTestBaseClass { override func oneA(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} override func oneB(x x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}} // expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}} override func oneC(x x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}} // expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}} override func oneD(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} override func manyA(_: AnyObject!, _: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 2 {{remove '!' to make the parameter required}} // expected-note@-2 2 {{add parentheses to silence this warning}} override func manyB(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 2 {{remove '!' to make the parameter required}} // expected-note@-2 2 {{add parentheses to silence this warning}} override func manyC(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 2 {{remove '!' to make the parameter required}} // expected-note@-2 2 {{add parentheses to silence this warning}} override func result() -> AnyObject! { return nil } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{use '?' to make the result optional}} {{38-39=?}} // expected-note@-2 {{add parentheses to silence this warning}} {{29-29=(}} {{39-39=)}} override func both(x: AnyObject!) -> AnyObject! { return x } // expected-warning {{overriding instance method optional result type 'AnyObject?' with implicitly unwrapped optional type 'AnyObject!'}} expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{use '?' to make the result optional}} {{49-50=?}} expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 2 {{add parentheses to silence this warning}} override init(_: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{29-30=}} // expected-note@-2 {{add parentheses to silence this warning}} {{20-20=(}} {{30-30=)}} override init(one: AnyObject!) {} // expected-warning {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{31-32=}} // expected-note@-2 {{add parentheses to silence this warning}} {{22-22=(}} {{32-32=)}} override init(a: AnyObject!, b: AnyObject!) {} // expected-warning 2 {{overriding initializer parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 2 {{remove '!' to make the parameter required}} // expected-note@-2 2 {{add parentheses to silence this warning}} } class IUOTestSubclass2 : IUOTestBaseClass { override func oneA(x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} override func oneB(x x: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{36-37=}} // expected-note@-2 {{add parentheses to silence this warning}} {{27-27=(}} {{37-37=)}} override func oneD(_: AnyObject!) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'AnyObject!'}} // expected-note@-1 {{remove '!' to make the parameter required}} {{34-35=}} // expected-note@-2 {{add parentheses to silence this warning}} {{25-25=(}} {{35-35=)}} override func oneC(x x: ImplicitlyUnwrappedOptional<AnyObject>) {} // expected-warning {{overriding instance method parameter of type 'AnyObject' with implicitly unwrapped optional type 'ImplicitlyUnwrappedOptional<AnyObject>'}} // expected-note@-1 {{add parentheses to silence this warning}} {{27-27=(}} {{65-65=)}} } class IUOTestSubclassOkay : IUOTestBaseClass { override func oneA(_: AnyObject?) {} override func oneB(x x: (AnyObject!)) {} override func oneC(x x: AnyObject) {} override func result() -> (AnyObject!) { return nil } }
apache-2.0
a3357fcb4e6b84a8bace171bcbed5a26
65.119469
331
0.677374
3.817833
false
false
false
false
ZhangZhiyuanZZY/emtionLittleTest
表情测试/表情测试/ViewController.swift
1
931
// // ViewController.swift // 表情测试 // // Created by 章芝源 on 15/11/10. // Copyright © 2015年 ZZY. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() let str = "0x1f623" //1. 扫描 let scanner = NSScanner(string: str); // UnsafeMutablePointer 参数传递 &,必须使用 var var value: UInt32 = 0 //把16进制数转化成, int32类型 scanner.scanHexInt(&value); print(value) //2.将scalar类型的数值转化成unicode字符 let c = Character(UnicodeScalar(value)) print(c) //转化成字符串 let result = String(c) print(result) label.text = result } }
mit
e2822a5e966105d5fbb09ea93bc6f842
17.26087
48
0.520238
4.137931
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01695-swift-pattern-operator.swift
1
1931
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck extension Array { class C(A<Int } } var b return g> Void>) { return z() protocol a { } struct A : (a((x: A, A.a)))) func c<I : Sequence where d<3] == T) + seq: d where T : T! { } protocol d { let a { } struct A<T, a(true } } protocol A { } typealias f = b(") class A, let i> String { import Foundation protocol A { var b = d<T) { print(") private class A, (h: a { } func f.A.a() init(array: (#object1, f: b } } } deinit { protocol P { return { x } f : b = { protocol P { case c<b> { protocol P { } extension NSSet { return m: A<T.startIndex) protocol b in case s: X<T.dynamicType.h == 1 init(Any) { } } let c<T>>Bool)(() case C } protocol a { let i<T where k) { } d>>() import Foundation } } struct c = compose<T>(g<d { } class C() class func f((() -> [1] } } protocol a { class C) { let c(c, d>Bool)? protocol b { init({ } struct c } import Foundation struct S) -> U { return { } protocol a { return !) class b protocol d { deinit { } self.c: C = a: Any) -> Void>(Any) -> { var a(seq: Boolean, Any) -> : T.Type extension A { func a)) { return m: b: Int typealias f = F> protocol b where f: a c) { } func e() for (A, k : T>() -> String { func a: Int { self[T: Array) { } } typealias f = nil self, self, c() } enum S() class A, Bool) -> (AnyObject)) func a: Bool) { protocol a : Any, object2: A, "") protocol a { } } var e(i<T -> S : Sequence, e == { _, Bool) { typealias e = 1 init(c == A> S { return "foobar"") class c<T where f.g : c() -> (bytes: String { protocol b { typealias A { } } return " 0) { typealias e = Swift.startInde
apache-2.0
d3167905e337c7edcec4b140a0a07286
14.325397
79
0.617297
2.648834
false
false
false
false
wyzzarz/SwiftCollection
SwiftCollection/SwiftCollection/SCOrderedSet.swift
1
35352
// // SCOrderedSet.swift // // Copyright 2017 Warner Zee // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation public protocol SCOrderedSetDelegate { associatedtype Document /// Tells the delegate that there will be changes to the collection. func willStartChanges() /// Tells the delegate that changes have been performed to he collection. func didEndChanges() /// Tells the delegate that a document will be inserted into the collection. /// /// - Parameters: /// - document: Document to be inserted. /// - i: Position to insert document. /// - Returns: `true` if the document can be inserted; `false` otherwise. func willInsert(_ document: Document, at i: Int) throws -> Bool /// Tells the delegate that a document was inserted. /// /// - Parameters: /// - document: Document that was inserted. /// - i: Position of inserted document. /// - success: `true` if the document was inserted; `false` otherwise. Documents are not /// inserted if they already exist in the collection. func didInsert(_ document: Document, at i: Int, success: Bool) /// Tells the delegate that a document will be appended to the collection. /// /// - Parameter document: Document to be appended. /// - Returns: `true` if the document can be appended; `false` otherwise. func willAppend(_ document: Document) throws -> Bool /// Tells the delegate that a document was appended to the collection. /// /// - Parameters: /// - document: Document that was appended. /// - success: `true` if the document was appended; `false` otherwise. Documents are not /// appended if they already exist in the collection. func didAppend(_ document: Document, success: Bool) /// Tells the delegate that a document will be added into the collection. /// /// - Parameters: /// - document: Document to be added. /// - i: Position to add document. /// - Returns: `true` if the document can be added; `false` otherwise. func willAdd(_ document: Document, at i: Int) throws -> Bool /// Tells the delegate that a document was added. /// /// - Parameters: /// - document: Document that was added. /// - i: Position of added document. /// - success: `true` if the document was added; `false` otherwise. Documents are not /// added if they already exist in the collection. func didAdd(_ document: Document, at i: Int, success: Bool) /// Tells the delegate that a document will be removed from the collection. /// /// - Parameter document: Document to be removed. /// - Returns: `true` if the document can be removed; `false` otherwise. func willRemove(_ document: Document) -> Bool /// Tells the delegate that a document was removed from the collection. /// /// - Parameters: /// - document: Document that was removed /// - i: Position of removed document. /// - success: `true` if the document was removed; `false` otherwise. Documents are not /// removed if they do not exist in the collection. func didRemove(_ document: Document, at i: Int, success: Bool) /// Tells the delegate that all documents will be removed from the collection. /// - Returns: `true` if all documents in the collection can be removed; `false` otherwise. func willRemoveAll() -> Bool /// Tells the delegate that all documents were removed from the collection. func didRemoveAll() /// Tells the delegate that a document will be replaced. /// /// - Parameters: /// - document: Document to be replaced. /// - with: Document to be used as a replacement. /// - i: Location of document to be replaced. /// - Returns: `true` if the document can be replaced; `false` otherwise. func willReplace(_ document: Document, with: Document, at i: Int) throws -> Bool /// Tells the delegate that a document was replaced. /// /// - Parameters: /// - document: Document that was replaced. /// - with: Document used as a replacement. /// - i: Location of replaced document. /// - success: `true` if the document was replaced; `false` otherwise. Documents are not /// replaced if they do not exist in the collection. func didReplace(_ document: Document, with: Document, at i: Int, success: Bool) } /// `SCOrderedSet` holds `SCDocument` objects. Documents added to this collection must include a /// primary key. /// /// The collection automatically arranges elements by the sort keys. /// open class SCOrderedSet<Element: SCDocument>: SCJsonObject, SCOrderedSetDelegate { // Holds an array of elements. fileprivate var elements: [Element] = [] // Holds a set of ids that corresponds to each element in elements. fileprivate var ids = NSMutableOrderedSet() // Temporarily holds a set of ids for elements that have been created, but have not been added to // elements. fileprivate var createdIds: Set<SwiftCollection.Id> = [] /// Creates an instance of `SCOrderedSet`. public required init() { super.init() self.sorting.needsSort = { self.sort() } } public required init(json: AnyObject) throws { try super.init(json: json) } /// Creates an instance of `SCOrderedSet` populated by documents in the collection. /// /// - Parameter collection: Documents to be added. /// - Throws: `missingId` if a document has no id. public convenience init<C: Collection>(_ collection: C) throws where C.Iterator.Element == Element { self.init() for element in collection { try add(element) } } /// Creates an instance of `SCOrderedSet` populated by documents in the array. /// /// - Parameter array: Documents to be added. /// - Throws: `missingId` if a document has no id. public convenience init<S: Sequence>(_ sequence: S) throws where S.Iterator.Element == Element { self.init() for element in sequence { try add(element) } } /* * ----------------------------------------------------------------------------------------------- * MARK: - CustomStringConvertible * ----------------------------------------------------------------------------------------------- */ override open var description: String { return String(describing: elements) } /* * ----------------------------------------------------------------------------------------------- * MARK: - Document * ----------------------------------------------------------------------------------------------- */ /// Creates a document stub with a valid id. The id will be randomly generated and unique for /// documents in the collection. /// /// The document will not be added to the collection. The document needs to be added by either /// `insert()` or `append()`. /// /// - Parameter id: Optional id to be applied to the document. /// - Returns: A document that can be added to the collection. /// - Throws: `existingId` the `id` already exists in the collection. `generateId` if an id could /// not be generated. open func create(withId id: SwiftCollection.Id? = nil) throws -> Element { // get an id let anId = try generateId(hint: id) // verify supplied id can be used if let id = id { // generateId will return the supplied id, unless it already exists. in that case a new id // will be returned if anId != id { throw SwiftCollection.Errors.existingId } } // done return Element(id: anId) } /// For documents with an id, if the id is not being used in the collection then the document /// will be registered with its id. /// /// Otherwise an id is added to this document. The id will be randomly generated and unique for /// documents in the collection. /// /// In either case, the document will not be added to the collection. The document needs to be /// added by either `insert()` or `append()`. /// /// - Parameters: /// - element: Document to register. /// - hint: Id to be used as a hint. If it isn't used in the collection, then the document will /// be updated with this id. Otherwise a new id will be generated. /// - Throws: `generateId` if an id could not be generated. open func register(_ element: Element, hint id: SwiftCollection.Id? = nil) throws { // exit if this element already has an id if element.hasId() && !(createdIds.contains(element.id) || ids.contains(element.id)) { createdIds.insert(element.id) return } // get an id let id = try generateId(hint: id) // store this id element.setId(id) } /// Returns the last document from the collection. final public var last: Iterator.Element? { return elements.last } /* * ----------------------------------------------------------------------------------------------- * MARK: - Document Id * ----------------------------------------------------------------------------------------------- */ fileprivate func generateId(hint id: SwiftCollection.Id? = nil) throws -> SwiftCollection.Id { // get existing ids let existing = createdIds.union(ids.set as! Set<SwiftCollection.Id>) // check if this id can be used if let id = id { if !existing.contains(id) { // remember this id until the document is stored in this collection createdIds.insert(id) // done return id } } // otherwise randomly pick an id // limit attempts to generate id // TODO: scan for an id if random attempts fail var i: Int = Int.max / 10 repeat { let r = SwiftCollection.Id.random() if !existing.contains(r) { // remember this id until the document is stored in this collection createdIds.insert(r) // done return r } i -= 1 } while i > 0 // failed throw SwiftCollection.Errors.generateId } /// Returns a document from the collection. /// /// - Parameter id: `id` of document to return. /// - Returns: A document with the specified id. final public func document(withId id: SwiftCollection.Id?) -> Element? { guard let id = id else { return nil } let i = ids.index(of: id) return i == NSNotFound ? nil : elements[i] } /// Returns the first document id in the collection. final public var firstId: SwiftCollection.Id? { return ids.firstObject as? SwiftCollection.Id } /// Returns the last document id in the collection. final public var lastId: SwiftCollection.Id? { return ids.lastObject as? SwiftCollection.Id } /// Checks whether the document id exists in this set. /// /// - Parameter id: `id` of document to be located. /// - Returns: `true` if the document id exists; `false` otherwise. final public func contains(id: SwiftCollection.Id) -> Bool { return ids.index(of: id) != NSNotFound } /// The document id in the collection offset from the specified id. /// /// - Parameters: /// - id: `id` of document to be located. /// - offset: Distance from the specified id. /// - Returns: `id` of the document. Or `nil` if the offset is out of bounds. final public func id(id: SwiftCollection.Id?, offset: Int) -> SwiftCollection.Id? { guard let id = id else { return nil } let i = ids.index(of: id) if i == NSNotFound { return nil } let ni = i + offset return ni >= 0 && ni < ids.count ? ids[ni] as? SwiftCollection.Id : nil } /// The next document id in the collection after the specified id. /// /// - Parameter id: `id` of document to be located. /// - Returns: `id` of next document. Or `nil` if this is the last document. final public func id(after id: SwiftCollection.Id?) -> SwiftCollection.Id? { return self.id(id: id, offset: +1) } /// The previous document id in the collection before the specified id. /// /// - Parameter id: `id` of document to be located. /// - Returns: `id` of previous document. Or `nil` if this is the first document. final public func id(before id: SwiftCollection.Id?) -> SwiftCollection.Id? { return self.id(id: id, offset: -1) } /* * ----------------------------------------------------------------------------------------------- * MARK: - Add * ----------------------------------------------------------------------------------------------- */ /// Adds the document to the collection at the specified index. Existing documents are ignored. /// /// - Parameters: /// - document: Document to be added. /// - i: Position to insert the document. `i` must be a valid index into the collection. /// - Throws: `missingId` if the document has no id. open func insert(_ document: Element, at i: Int) throws { try insert(document, at: i, multipleChanges: false) } /// Adds the document to the collection at the specified index. Existing documents are ignored. /// /// - Parameters: /// - document: Document to be added. /// - i: Position to insert the document. `i` must be a valid index into the collection. /// - multipleChanges: `true` if willStartChanges() and didEndChanges() will be executed from another /// routine; `false` otherwise. Defuault is `false`. /// - Throws: `missingId` if the document has no id. fileprivate func insert(_ document: Element, at i: Int, multipleChanges: Bool) throws { if !multipleChanges { willStartChanges() } guard try willInsert(document, at: i) else { didInsert(document, at: i, success: false) if !multipleChanges { didEndChanges() } return } // ensure the document has an id guard document.hasId() else { throw SwiftCollection.Errors.missingId } guard !ids.contains(document.id) else { didInsert(document, at: i, success: false) if !multipleChanges { didEndChanges() } return } elements.insert(document, at: i) ids.insert(document.id, at: i) createdIds.remove(document.id) didInsert(document, at: i, success: true) if !multipleChanges { didEndChanges() SwiftCollection.Notifications.postChange(self, inserted: [SwiftCollection.Notifications.Change(document, atIndex: i)], updated: nil, deleted: nil) } } /// Adds the documents to the end of the collection. /// /// - Parameters: /// - newDocuments: Documents to be added. /// - i: Position to insert the documents. `i` must be a valid index into the collection. /// - Throws: `missingId` if a document has no id. open func insert<C : Collection>(contentsOf newDocuments: C, at i: Int) throws where C.Iterator.Element == Element { willStartChanges() let newTotal = ids.count + Int(newDocuments.count.toIntMax()) elements.reserveCapacity(newTotal) var changes: [SwiftCollection.Notifications.Change] = [] let lastIndex = i + newDocuments.count for (idx, d) in newDocuments.reversed().enumerated() { try self.insert(d, at: i, multipleChanges: true) changes.append(SwiftCollection.Notifications.Change(d, atIndex: lastIndex - idx - 1)) } didEndChanges() SwiftCollection.Notifications.postChange(self, inserted: changes, updated: nil, deleted: nil) } /// Adds the document to the end of the collection. /// /// - Parameters: /// - document: Document to be added. /// - Throws: `missingId` if the document has no id. open func append(_ document: Element) throws { try append(document, multipleChanges: false) } /// Adds the document to the end of the collection. /// /// - Parameters: /// - document: Document to be added. /// - multipleChanges: `true` if willStartChanges() and didEndChanges() will be executed from another /// routine; `false` otherwise. Defuault is `false`. /// - Throws: `missingId` if the document has no id. fileprivate func append(_ document: Element, multipleChanges: Bool) throws { if !multipleChanges { willStartChanges() } guard try willAppend(document) else { didAppend(document, success: false) if !multipleChanges { didEndChanges() } return } // ensure the document has an id guard document.hasId() else { throw SwiftCollection.Errors.missingId } guard !ids.contains(document.id) else { didAppend(document, success: false) if !multipleChanges { didEndChanges() } return } elements.append(document) ids.add(document.id) createdIds.remove(document.id) didAppend(document, success: true) if !multipleChanges { didEndChanges() SwiftCollection.Notifications.postChange(self, inserted: [SwiftCollection.Notifications.Change(document, atIndex: elements.count - 1)], updated: nil, deleted: nil) } } /// Adds documents to the end of the collection. Existing documents are ignored. /// /// - Parameter newDocuments: A collection of documents to be added. /// - Throws: `missingId` if a document has no id. open func append<C : Collection>(contentsOf newDocuments: C) throws where C.Iterator.Element == Element { willStartChanges() let newTotal = ids.count + Int(newDocuments.count.toIntMax()) elements.reserveCapacity(newTotal) var changes: [SwiftCollection.Notifications.Change] = [] for d in newDocuments { if ids.contains(d.id) { continue } try self.append(d, multipleChanges: true) changes.append(SwiftCollection.Notifications.Change(d, atIndex: self.count - 1)) } didEndChanges() SwiftCollection.Notifications.postChange(self, inserted: changes, updated: nil, deleted: nil) } /// Inserts the document into the collection based on the default sort. If there is no sort, then /// the document is added to the end of the collection. /// /// - Parameters: /// - document: Document to be added. /// - Throws: `missingId` if the document has no id. open func add(_ document: Element) throws { try add(document, multipleChanges: false) } /// Inserts the document into the collection based on the default sort. If there is no sort, then /// the document is added to the end of the collection. /// /// - Parameters: /// - document: Document to be added. /// - multipleChanges: `true` if willStartChanges() and didEndChanges() will be executed from another /// routine; `false` otherwise. Defuault is `false`. /// - Throws: `missingId` if the document has no id. fileprivate func add(_ document: Element, multipleChanges: Bool) throws { if !multipleChanges { willStartChanges() } // get location to insert let i = sortedIndex(document) guard try willAdd(document, at: i) else { didAdd(document, at: i, success: false) if !multipleChanges { didEndChanges() } return } // ensure the document has an id guard document.hasId() else { throw SwiftCollection.Errors.missingId } guard !ids.contains(document.id) else { didAdd(document, at: i, success: false) if !multipleChanges { didEndChanges() } return } elements.insert(document, at: i) ids.insert(document.id, at: i) createdIds.remove(document.id) didAdd(document, at: i, success: true) if !multipleChanges { didEndChanges() SwiftCollection.Notifications.postChange(self, inserted: [SwiftCollection.Notifications.Change(document, atIndex: i)], updated: nil, deleted: nil) } } /// Inserts the documents into the collection based on the default sort. If there is no sort, /// then the documents are added to the end of the collection. /// /// - Parameter newDocuments: A collection of documents to be added. /// - Throws: `missingId` if a document has no id. open func add<C : Collection>(contentsOf newDocuments: C) throws where C.Iterator.Element == Element { willStartChanges() let newTotal = ids.count + Int(newDocuments.count.toIntMax()) elements.reserveCapacity(newTotal) var changes: [SwiftCollection.Notifications.Change] = [] for d in newDocuments { if ids.contains(d.id) { continue } try self.add(d, multipleChanges: true) if let idx = self.index(of: d) { changes.append(SwiftCollection.Notifications.Change(d, atIndex: self.distance(from: self.startIndex, to: idx))) } } didEndChanges() SwiftCollection.Notifications.postChange(self, inserted: changes, updated: nil, deleted: nil) } /* * ----------------------------------------------------------------------------------------------- * MARK: - Remove * ----------------------------------------------------------------------------------------------- */ /// Removes the document from the collection. /// /// - Parameters: /// - document: Document to be removed. open func remove(_ document: Element) -> Element? { let (d, _) = remove(document, multipleChanges: false) return d } /// Removes the document from the collection. /// /// - Parameters: /// - document: Document to be removed. /// - multipleChanges: `true` if willStartChanges() and didEndChanges() will be executed from another /// routine; `false` otherwise. Defuault is `false`. fileprivate func remove(_ document: Element, multipleChanges: Bool) -> (Element?, Int?) { if !multipleChanges { willStartChanges() } guard willRemove(document) else { didRemove(document, at: NSNotFound, success: false) if !multipleChanges { didEndChanges() } return (nil, nil) } var removed: Element? var idx: Int? var changes: [SwiftCollection.Notifications.Change] = [] if let i = index(of: document) { removed = elements.remove(at: i.index) idx = i.index ids.removeObject(at: i.index) didRemove(document, at: i.index, success: true) changes.append(SwiftCollection.Notifications.Change(document, atIndex: i.index)) } else { didRemove(document, at: NSNotFound, success: false) } createdIds.remove(document.id) if !multipleChanges { didEndChanges() if changes.count > 0 { SwiftCollection.Notifications.postChange(self, inserted: nil, updated: nil, deleted: changes) } } return (removed, idx) } /// Removes documents from the collection. /// /// - Parameter newDocuments: A collection of documents to be removed. /// - Throws: `missingId` if a document has no id. open func remove<C : Collection>(contentsOf newDocuments: C) -> [Element] where C.Iterator.Element == Element { willStartChanges() var removed: [Element] = [] var changes: [SwiftCollection.Notifications.Change] = [] for d in newDocuments { let (r, i) = remove(d, multipleChanges: true) if r == nil || i == nil { continue } removed.append(r!) changes.append(SwiftCollection.Notifications.Change(r!, atIndex: i!)) } didEndChanges() SwiftCollection.Notifications.postChange(self, inserted: nil, updated: nil, deleted: changes) return removed } /// Removes all documents from the collection. open func removeAll() { willStartChanges() guard willRemoveAll() else { return } var changes: [SwiftCollection.Notifications.Change] = [] for element in elements { changes.append(SwiftCollection.Notifications.Change(element, atIndex: 0)) } elements.removeAll() ids.removeAllObjects() createdIds.removeAll() didRemoveAll() didEndChanges() SwiftCollection.Notifications.postChange(self, inserted: nil, updated: nil, deleted: changes) } /* * ----------------------------------------------------------------------------------------------- * MARK: - Replace * ----------------------------------------------------------------------------------------------- */ /// Replaces document with the new document. /// /// The id of the new document will be replaced by the id of the existing document. /// /// - Parameters: /// - document: Document to be replaced. /// - with: Document to be used as a replacement. /// - Throws: `notFound` if the document does not exist in the collection. open func replace(_ document: Element, with: Element) throws { guard let i = elements.index(of: document) else { throw SwiftCollection.Errors.notFound } try replace(at: i, with: with) } /// Replaces document at the specified index with the new document. /// /// The id of the new document will be replaced by the id of the existing document. /// /// - Parameters: /// - i: Location of document to be replaced. /// - with: Document to be used as a replacement. /// - Throws: `notFound` if the document does not exist in the collection. open func replace(at index: Index, with: Element) throws { try replace(at: index.index, with: with) } /// Replaces document at the specified index with the new document. /// /// The id of the new document will be replaced by the id of the existing document. /// /// - Parameters: /// - i: Location of document to be replaced. /// - with: Document to be used as a replacement. /// - Throws: `notFound` if the document does not exist in the collection. open func replace(at i: Int, with: Element) throws { guard (0..<elements.count).contains(i) else { throw SwiftCollection.Errors.notFound } willStartChanges() let existing = elements[i] guard try willReplace(existing, with: with, at: i) else { didReplace(existing, with: with, at: i, success: false) return } with.setId(existing.id) elements[i] = with didReplace(existing, with: with, at: i, success: true) didEndChanges() SwiftCollection.Notifications.postChange(self, inserted: nil, updated: [SwiftCollection.Notifications.Change(with, atIndex: i)], deleted: nil) } /* * ----------------------------------------------------------------------------------------------- * MARK: - Combine * ----------------------------------------------------------------------------------------------- */ /// Returns a new set that is a combination of this set and the other set. /// /// - Parameter other: Other set to combine. /// - Returns: A new set with unique elements from both sets. /// - Throws: `missingId` if the document has no id. open func union(_ other: SCOrderedSet<Element>) throws -> SCOrderedSet<Element> { let set = self for (_, element) in other.enumerated() { if !set.contains(element) { try set.add(element) } } return set } /// Removes any element in this set that is not present in the other set. /// /// - Parameter other: Other set to perform the intersection. open func intersect(_ other: SCOrderedSet<Element>) { var changes: [SwiftCollection.Notifications.Change] = [] var i = 0 while i < elements.count { let element = elements[i] if !other.contains(element) { elements.remove(at: i) ids.removeObject(at: i) changes.append(SwiftCollection.Notifications.Change(element, atIndex: i)) } else { i += 1 } } SwiftCollection.Notifications.postChange(self, inserted: nil, updated: nil, deleted: changes) } /// Removes any element in this set that is present in the other set. /// /// - Parameter other: Other set to perform the subtraction. open func minus(_ other: SCOrderedSet<Element>) { var changes: [SwiftCollection.Notifications.Change] = [] var i = 0 while i < elements.count { let element = elements[i] if other.contains(element) { elements.remove(at: i) ids.removeObject(at: i) changes.append(SwiftCollection.Notifications.Change(element, atIndex: i)) } else { i += 1 } } SwiftCollection.Notifications.postChange(self, inserted: nil, updated: nil, deleted: changes) } /* * ----------------------------------------------------------------------------------------------- * MARK: - Sort * ----------------------------------------------------------------------------------------------- */ public class Sort { public typealias SortId = String /// Tests whether `e1` should be ordered before `e2`. /// /// - Parameters: /// - e1: First argument. /// - e2: Second argument. /// - Returns: `true` if `e1` should be ordered before `e2`; `false` otherwise. public typealias SortComparator = (_ e1: Element, _ e2: Element) -> Bool fileprivate var needsSort: (() -> Void)? /// Default sort identifier to be used when adding an element to this collection. public var sortId: SortId? { get { return _sortId } set { _sortId = newValue if let needsSort = self.needsSort { needsSort() } } } fileprivate var _sortId: SortId? /// Returns a sort comparator for this sort id. /// /// - Parameter sortId: Sort id to be used. /// - Returns: The sort comparator for this id. public func comparator(_ sortId: SortId? = nil) -> SortComparator? { let aSortId = sortId ?? self.sortId guard aSortId != nil else { return nil } return sortComparators[aSortId!] } fileprivate var sortComparators: [SortId: SortComparator] = [:] /// Adds a sort comparator for this sort id. /// /// - Parameters: /// - sortId: Sort id to be used. /// - comparator: The sort comparator to be added. public func add(_ sortId: SortId, comparator: @escaping SortComparator) { sortComparators[sortId] = comparator guard let needsSort = self.needsSort else { return } guard let aSortId = self.sortId else { return } if aSortId == sortId { needsSort() } } /// Removes a sort comparator for this sort id. /// /// - Parameter sortId: Sort id to be removed. public func remove(_ sortId: SortId) { sortComparators.removeValue(forKey: sortId) } /// Removes all sort comparators. public func removeAll() { sortComparators.removeAll() } } /// Default sort and sorting comparators for the collection. public var sorting = Sort() /// Returns the index in the collection to add this document using the default sort. /// /// - Parameter document: Document to add. /// - Returns: Index to insert; or the end index of the collection. fileprivate func sortedIndex(_ document: Element) -> Int { // if there is no comparator, then return index for end of collection. guard let c = sorting.comparator() else { return elements.endIndex } // if there are no documents, then return index for end of collection. guard elements.count > 0 else { return elements.endIndex } // check if the document should be last. if !c(document, elements.last!) { return elements.endIndex } // find the location in the collection. for (i, element) in elements.enumerated() { if !c(document, element) { continue } return i } // otherwise return the end index of the collection return elements.endIndex } public func sort() { guard let c = sorting.comparator() else { return } elements = sorted(by: c) ids.removeAllObjects() var changes: [SwiftCollection.Notifications.Change] = [] for (i, element) in elements.enumerated() { ids.add(element.id) changes.append(SwiftCollection.Notifications.Change(element, atIndex: i)) } SwiftCollection.Notifications.postChange(self, inserted: nil, updated: changes, deleted: nil) } /* * ----------------------------------------------------------------------------------------------- * MARK: - Delegate * ----------------------------------------------------------------------------------------------- */ public typealias Document = Element open func willStartChanges() { } open func didEndChanges() { } open func willInsert(_ document: Document, at i: Int) throws -> Bool { return true } open func didInsert(_ document: Document, at i: Int, success: Bool) { } open func willAppend(_ document: Document) throws -> Bool { return true } open func didAppend(_ document: Document, success: Bool) { } open func willAdd(_ document: Document, at i: Int) throws -> Bool { return true } open func didAdd(_ document: Document, at i: Int, success: Bool) { } open func willRemove(_ document: Document) -> Bool { return true } open func didRemove(_ document: Document, at i: Int, success: Bool) { } open func willRemoveAll() -> Bool { return true } open func didRemoveAll() { } open func willReplace(_ document: Element, with: Element, at i: Int) throws -> Bool { return true } open func didReplace(_ document: Element, with: Element, at i: Int, success: Bool) { } } /* * ----------------------------------------------------------------------------------------------- * MARK: - Sequence * ----------------------------------------------------------------------------------------------- */ extension SCOrderedSet: Sequence { public typealias Iterator = AnyIterator<Element> public func makeIterator() -> Iterator { var iterator = elements.makeIterator() return AnyIterator { return iterator.next() } } } /* * ----------------------------------------------------------------------------------------------- * MARK: - Collection * ----------------------------------------------------------------------------------------------- */ public struct SCOrderedSetIndex<Element: Hashable>: Comparable { fileprivate let index: Int fileprivate init(_ index: Int) { self.index = index } public static func == (lhs: SCOrderedSetIndex, rhs: SCOrderedSetIndex) -> Bool { return lhs.index == rhs.index } public static func < (lhs: SCOrderedSetIndex, rhs: SCOrderedSetIndex) -> Bool { return lhs.index < rhs.index } } extension SCOrderedSet: BidirectionalCollection { public typealias Index = SCOrderedSetIndex<Element> final public var startIndex: Index { return SCOrderedSetIndex(elements.startIndex) } final public var endIndex: Index { return SCOrderedSetIndex(elements.endIndex) } final public func index(after i: Index) -> Index { return Index(elements.index(after: i.index)) } final public func index(before i: Index) -> Index { return Index(elements.index(before: i.index)) } final public subscript (position: Index) -> Iterator.Element { return elements[position.index] } } /* * ----------------------------------------------------------------------------------------------- * MARK: - Persistence * ----------------------------------------------------------------------------------------------- */ extension SCOrderedSet: SCJsonCollectionProtocol { open func jsonCollectionElements() -> [Any] { return elements } }
apache-2.0
9b19700630cfb7d7512fd4c53b1d003b
35.748441
169
0.615382
4.354231
false
false
false
false
breadwallet/breadwallet-core
Swift/BRCryptoTests/BRCryptoWalletManagerTests.swift
1
16606
// // BRCryptoWalletManagerTests.swift // BRCryptoTests // // Created by Ed Gamble on 1/11/19. // Copyright © 2019 Breadwallet AG. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // import XCTest @testable import BRCrypto class BRCryptoWalletManagerTests: BRCryptoSystemBaseTests { override func setUp() { super.setUp() } override func tearDown() { } func testWalletManagerMode () { let modes = [WalletManagerMode.api_only, WalletManagerMode.api_with_p2p_submit, WalletManagerMode.p2p_with_api_sync, WalletManagerMode.p2p_only] for mode in modes { XCTAssertEqual (mode, WalletManagerMode (serialization: mode.serialization)) XCTAssertEqual (mode, WalletManagerMode (core: mode.core)) } for syncModeInteger in 0..<4 { XCTAssertNil (WalletManagerMode (serialization: UInt8 (syncModeInteger))) } } func testWalletManagerBTC() { isMainnet = false currencyCodesToMode = ["btc":WalletManagerMode.api_only] prepareAccount() prepareSystem() let walletManagerDisconnectExpectation = XCTestExpectation (description: "Wallet Manager Disconnect") listener.managerHandlers += [ { (system: System, manager:WalletManager, event: WalletManagerEvent) in if case let .changed(_, newState) = event, case .disconnected = newState { walletManagerDisconnectExpectation.fulfill() } }] let network: Network! = system.networks.first { "btc" == $0.currency.code && isMainnet == $0.isMainnet } XCTAssertNotNil (network) let manager: WalletManager! = system.managers.first { $0.network == network } let wallet = manager.primaryWallet XCTAssertNotNil (manager) XCTAssertTrue (system === manager.system) XCTAssertTrue (self.query === manager.query) XCTAssertEqual (network, manager.network) XCTAssertEqual (WalletManagerState.created, manager.state) XCTAssertTrue (manager.height > 0) XCTAssertEqual (manager.primaryWallet.manager, manager) XCTAssertEqual (1, manager.wallets.count) XCTAssertTrue (manager.wallets.contains(manager.primaryWallet)) XCTAssertTrue (network.fees.contains(manager.defaultNetworkFee)) XCTAssertTrue (network.supportedModes.contains(manager.mode)) XCTAssertEqual (network.defaultAddressScheme, manager.addressScheme) let otherAddressScheme = network.supportedAddressSchemes.first { $0 != manager.addressScheme }! manager.addressScheme = otherAddressScheme XCTAssertEqual (otherAddressScheme, manager.addressScheme) manager.addressScheme = network.defaultAddressScheme XCTAssertEqual (network.defaultAddressScheme, manager.addressScheme) XCTAssertNotNil (manager.baseUnit) XCTAssertNotNil (manager.defaultUnit) XCTAssertFalse (manager.isActive) XCTAssertEqual (manager, manager) XCTAssertEqual("btc", manager.description) XCTAssertFalse (system.wallets.isEmpty) // Events XCTAssertTrue (listener.checkSystemEventsCommonlyWith (network: network, manager: manager)) XCTAssertTrue (listener.checkManagerEvents( [WalletManagerEvent.created, WalletManagerEvent.walletAdded(wallet: wallet)], strict: true)) XCTAssertTrue (listener.checkWalletEvents( [WalletEvent.created], strict: true)) XCTAssertTrue (listener.checkTransferEvents( [], strict: true)) // Connect listener.transferCount = 5 manager.connect() wait (for: [self.listener.transferExpectation], timeout: 5) manager.disconnect() wait (for: [walletManagerDisconnectExpectation], timeout: 5) XCTAssertTrue (listener.checkManagerEventsCommonlyWith (mode: manager.mode, wallet: wallet)) } func testWalletManagerETH () { isMainnet = false registerCurrencyCodes = ["brd"] currencyCodesToMode = ["eth":WalletManagerMode.api_only] prepareAccount() let listener = CryptoTestSystemListener (networkCurrencyCodesToMode: currencyCodesToMode, registerCurrencyCodes: registerCurrencyCodes, isMainnet: isMainnet) // Listen for a non-primary wallet - specifically the BRD wallet var walletBRD: Wallet! = nil let walletBRDExpectation = XCTestExpectation (description: "BRD Wallet") listener.managerHandlers += [ { (system: System, manager:WalletManager, event: WalletManagerEvent) in if case let .walletAdded(wallet) = event, "brd" == wallet.name { walletBRD = wallet walletBRDExpectation.fulfill() } }] let walletManagerDisconnectExpectation = XCTestExpectation (description: "Wallet Manager Disconnect") listener.managerHandlers += [ { (system: System, manager:WalletManager, event: WalletManagerEvent) in if case let .changed(_, newState) = event, case .disconnected = newState { walletManagerDisconnectExpectation.fulfill() } }] prepareSystem (listener: listener) let network: Network! = system.networks.first { "eth" == $0.currency.code && isMainnet == $0.isMainnet } XCTAssertNotNil (network) let manager: WalletManager! = system.managers.first { $0.network == network } XCTAssertNotNil (manager) let walletETH = manager.primaryWallet wait (for: [walletBRDExpectation], timeout: 30) // Events XCTAssertTrue (listener.checkSystemEventsCommonlyWith (network: network, manager: manager)) XCTAssertTrue (listener.checkManagerEvents( [EventMatcher (event: WalletManagerEvent.created), EventMatcher (event: WalletManagerEvent.walletAdded(wallet: walletETH), strict: true, scan: false), EventMatcher (event: WalletManagerEvent.walletAdded(wallet: walletBRD), strict: true, scan: true) ])) XCTAssertTrue (listener.checkWalletEvents( [WalletEvent.created, WalletEvent.created], strict: true)) XCTAssertTrue (listener.checkTransferEvents( [], strict: true)) // Connect listener.transferCount = 2 manager.connect() wait (for: [self.listener.transferExpectation], timeout: 60) sleep (30) // allow some 'ongoing' syncs to occur; don't want to see events for these. manager.disconnect() wait (for: [walletManagerDisconnectExpectation], timeout: 5) // TODO: We have an 'extra' syncStarted in here; the disconnect reason is 'unknown'? XCTAssertTrue (listener.checkManagerEvents ( [EventMatcher (event: WalletManagerEvent.created), EventMatcher (event: WalletManagerEvent.walletAdded(wallet: walletETH)), EventMatcher (event: WalletManagerEvent.walletAdded(wallet: walletBRD), strict: true, scan: true), EventMatcher (event: WalletManagerEvent.changed(oldState: WalletManagerState.created, newState: WalletManagerState.connected), strict: true, scan: true), // wallet changed? EventMatcher (event: WalletManagerEvent.syncStarted, strict: true, scan: true), EventMatcher (event: WalletManagerEvent.changed(oldState: WalletManagerState.connected, newState: WalletManagerState.syncing)), // We might not see `syncProgress` // EventMatcher (event: WalletManagerEvent.syncProgress(timestamp: nil, percentComplete: 0), strict: false), EventMatcher (event: WalletManagerEvent.syncEnded(reason: WalletManagerSyncStoppedReason.complete), strict: false, scan: true), EventMatcher (event: WalletManagerEvent.changed(oldState: WalletManagerState.syncing, newState: WalletManagerState.connected)), // Can have another sync started here... so scan EventMatcher (event: WalletManagerEvent.changed(oldState: WalletManagerState.connected, newState: WalletManagerState.disconnected (reason: WalletManagerDisconnectReason.unknown)), strict: true, scan: true), ])) } func testWalletManagerMigrateBTC () { isMainnet = false currencyCodesToMode = ["btc":WalletManagerMode.api_only] prepareAccount (AccountSpecification (dict: [ "identifier": "ginger", "paperKey": "ginger settle marine tissue robot crane night number ramp coast roast critic", "timestamp": "2018-01-01", "network": (isMainnet ? "mainnet" : "testnet") ])) prepareSystem () let walletManagerDisconnectExpectation = XCTestExpectation (description: "Wallet Manager Disconnect") listener.managerHandlers += [ { (system: System, manager:WalletManager, event: WalletManagerEvent) in if case let .changed(_, newState) = event, case .disconnected = newState { walletManagerDisconnectExpectation.fulfill() } }] let network: Network! = system.networks.first { "btc" == $0.currency.code && isMainnet == $0.isMainnet } XCTAssertNotNil (network) let manager: WalletManager! = system.managers.first { $0.network == network } XCTAssertNotNil (manager) let wallet = manager.primaryWallet XCTAssertNotNil(wallet) // Connect listener.transferCount = 25 manager.connect() wait (for: [self.listener.transferExpectation], timeout: 120) sleep (10) // allow some 'ongoing' syncs to occur; don't want to see events for these. manager.disconnect() wait (for: [walletManagerDisconnectExpectation], timeout: 5) let transfers = wallet.transfers XCTAssertTrue (transfers.count >= 25) XCTAssertTrue (transfers.allSatisfy { nil != $0.hash }) // Get the blobs (for testing) let transferBlobs = transfers.map { system.asBlob(transfer: $0)! } // Create a new system with MigrateSystemListener (see below). This listener will // create a BTC wallet manager with transfers migrated from `TransferBlobs` let migrateListener = MigrateSystemListener (transactionBlobs: transferBlobs) let migrateQuery = system.query let migratePath = system.path + "Migrate" let migrateSystem = System (listener: migrateListener, account: system.account, onMainnet: system.onMainnet, path: migratePath, query: migrateQuery) // transfers announced on `configure` migrateListener.transferCount = transferBlobs.count migrateSystem.configure(withCurrencyModels: []) wait (for: [migrateListener.migratedManagerExpectation], timeout: 30) wait (for: [migrateListener.transferExpectation], timeout: 30) XCTAssertFalse (migrateListener.migratedFailed) // Get the transfers from the migratedManager's primary wallet. let migratedTransfers = migrateListener.migratedManager.primaryWallet.transfers // Compare the count; then compare the hash sets as equal. XCTAssertEqual (transfers.count, migratedTransfers.count) XCTAssertEqual (Set (transfers.map { $0.hash! }), Set (migratedTransfers.map { $0.hash! })) // // Produce an invalid transferBlobs and check for a failure // let muckedTransferBlobs = [System.TransactionBlob.btc (bytes: [UInt8](arrayLiteral: 0, 1, 2), blockHeight: UInt32(0), timestamp: UInt32(0))] let muckedListener = MigrateSystemListener (transactionBlobs: muckedTransferBlobs) let muckedQuery = system.query let muckedPath = system.path + "mucked" let muckedSystem = System (listener: muckedListener, account: system.account, onMainnet: system.onMainnet, path: muckedPath, query: muckedQuery) // transfers annonced on `configure` muckedSystem.configure(withCurrencyModels: []) wait (for: [muckedListener.migratedManagerExpectation], timeout: 30) XCTAssertTrue (muckedListener.migratedFailed) } } class MigrateSystemListener: SystemListener { let transactionBlobs: [System.TransactionBlob] var migratedNetwork: Network! = nil var migratedManager: WalletManager! = nil var migratedManagerExpectation = XCTestExpectation (description: "Migrated Manager") init (transactionBlobs: [System.TransactionBlob]) { self.transactionBlobs = transactionBlobs } var migratedFailed = false func handleSystemEvent(system: System, event: SystemEvent) { switch event { case .created: break case .networkAdded(let network): // Network of interest if system.onMainnet == network.isMainnet && network.currency.code == "btc" && nil == migratedNetwork { migratedNetwork = network // Migrate if (system.migrateRequired(network: network)) { do { try system.migrateStorage (network: network, transactionBlobs: transactionBlobs, blockBlobs: [], peerBlobs: []) } catch { migratedFailed = true } } // Wallet Manager let _ = system.createWalletManager (network: network, mode: network.defaultMode, addressScheme: network.defaultAddressScheme, currencies: Set<Currency>()) } case .managerAdded(let manager): if nil == migratedManager && manager.network == migratedNetwork { migratedManager = manager migratedManagerExpectation.fulfill() } case .discoveredNetworks: break } } func handleManagerEvent(system: System, manager: WalletManager, event: WalletManagerEvent) { } func handleWalletEvent(system: System, manager: WalletManager, wallet: Wallet, event: WalletEvent) { } var transferIncluded: Bool = false var transferCount: Int = 0; // var transferHandlers: [TransferEventHandler] = [] // var transferEvents: [TransferEvent] = [] var transferExpectation = XCTestExpectation (description: "TransferExpectation") func handleTransferEvent(system: System, manager: WalletManager, wallet: Wallet, transfer: Transfer, event: TransferEvent) { if transferIncluded, case .included = transfer.state { if 1 == transferCount { transferExpectation.fulfill()} if 1 <= transferCount { transferCount -= 1 } } else if case .created = transfer.state { if 1 == transferCount { transferExpectation.fulfill()} if 1 <= transferCount { transferCount -= 1 } } // TODO: We sometimes see a TransferEvent.created with TransferState.included - Racy? else if case .created = event, case .included = transfer.state { if 1 == transferCount { transferExpectation.fulfill()} if 1 <= transferCount { transferCount -= 1 } } } func handleNetworkEvent(system: System, network: Network, event: NetworkEvent) { } }
mit
11f7e723725750f2410328595491a7f5
41.796392
152
0.614694
5.229921
false
true
false
false
OSzhou/MyTestDemo
17_SwiftTestCode/TestCode/OtherPro/MeetupTableViewHeader.swift
1
1582
// // MeetupTableViewHeader.swift // TestCode // // Created by Zhouheng on 2020/7/16. // Copyright © 2020 tataUFO. All rights reserved. // import UIKit import SnapKit class MeetupTableViewHeader: UIView { override init(frame: CGRect) { super.init(frame: frame) setupUI() } private func setupUI() { addSubview(containerView) containerView.snp.makeConstraints { (make) in make.top.bottom.equalTo(0) make.left.equalTo(15) make.right.equalTo(-15) } containerView.addSubview(icon) icon.snp.makeConstraints { (make) in make.top.equalTo(20) make.left.equalTo(0) make.height.width.equalTo(17) } containerView.addSubview(titleLabel) titleLabel.snp.makeConstraints { (make) in make.left.equalTo(icon.snp.right).offset(4) make.centerY.equalTo(icon) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// MARK: --- lazy loading lazy var containerView: UIView = { let view = UIView() return view }() lazy var icon: UIImageView = { let iv = UIImageView() iv.image = UIImage(named: "btn-check-selected") return iv }() lazy var titleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 18) label.textColor = .black label.text = "test string" return label }() }
apache-2.0
1004ba7f13d6723e48e6b689add4061c
24.095238
59
0.56926
4.284553
false
false
false
false
waywalker/HouseWarmer
HouseWarmer/GatewayListViewController.swift
1
2926
import Siesta import UIKit final class GatewayListViewController: UITableViewController { fileprivate let gatewayResource = NeviWebAPI.shared.gateway fileprivate var selectedGatewayID: String? fileprivate var gateways: [Gateway] = [] { didSet { tableView.reloadData() } } var statusOverlay = ResourceStatusOverlay() } // MARK: - Configuration extension GatewayListViewController { fileprivate func configureResourceObserver() { _ = gatewayResource .addObserver(self) .addObserver(statusOverlay, owner: self) .loadIfNeeded() } fileprivate func configureStatusOverlay() { statusOverlay.embed(in: self) } } // MARK: - Lifecycle extension GatewayListViewController { override func viewDidLoad() { super.viewDidLoad() configureStatusOverlay() configureResourceObserver() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let deviceListVC = segue.destination as? DeviceListViewController { guard let selectedGatewayID = selectedGatewayID else { return } deviceListVC.gatewayID = selectedGatewayID } } } // MARK: - UITableViewDataSource extension GatewayListViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return gateways.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let gateway = gateways[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "GatewayCell", for: indexPath) cell.textLabel?.text = "\(gateway.name), \(gateway.city)" return cell } } // MARK: - UITableViewDelegate extension GatewayListViewController { override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { let index = indexPath.row guard gateways.indices.contains(index) else { return indexPath } let gateway = gateways[index] selectedGatewayID = "\(gateway.id)" return indexPath } } // MARK: - ResourceObserver extension GatewayListViewController: ResourceObserver { func resourceChanged(_ resource: Resource, event: ResourceEvent) { gateways = gatewayResource.typedContent() ?? [] } }
unlicense
8ddf0574df3203cb85ef10946acc3098
21
109
0.590909
5.794059
false
false
false
false
mattfenwick/TodoRx
TodoRx/TodoFlowDefaultInteractor.swift
1
4169
// // TodoFlowDefaultInteractor.swift // TodoRx // // Created by Matt Fenwick on 7/19/17. // Copyright © 2017 mf. All rights reserved. // import Foundation import RxSwift import CoreData private let dateFormatter = ISO8601DateFormatter() private extension CDTodo { // MARK: - priority func setPriority(priority: TodoPriority) { self.priority = Int16(priority.rawValue) } func getPriority() -> TodoPriority { return TodoPriority(rawValue: Int(priority))! } // MARK: - created func setCreated(date: Date) { created = dateFormatter.string(from: date) } func getCreated() -> Date { // horrible hack to get around NSDate vs. Date issue return dateFormatter.date(from: created!)! } } // MARK: - interactor class TodoFlowDefaultInteractor: TodoFlowInteractor { private let coreDataController: CoreDataController init(coreDataController: CoreDataController) { self.coreDataController = coreDataController } func fetchTodos() -> Single<[TodoItem]> { return coreDataController.childContext(concurrencyType: .privateQueueConcurrencyType) .rx.perform(block: { context in let request: NSFetchRequest<CDTodo> = CDTodo.fetchRequest() return try context.fetch(request) .map { cdTodo -> TodoItem in TodoItem( id: cdTodo.id!, name: cdTodo.name!, priority: cdTodo.getPriority(), isFinished: cdTodo.isFinished, created: cdTodo.getCreated()) } }) } func saveTodo(item: TodoItem) -> Single<Void> { return coreDataController.childContext(concurrencyType: .privateQueueConcurrencyType) .rx.perform(block: { context in guard let cdTodo = NSEntityDescription.insertNewObject(forEntityName: "CDTodo", into: context) as? CDTodo else { throw CoreDataError.insertType } cdTodo.id = item.id cdTodo.name = item.name cdTodo.setPriority(priority: item.priority) cdTodo.setCreated(date: item.created) cdTodo.isFinished = item.isFinished try context.save() }) } func updateTodo(item: TodoItem) -> Single<Void> { return coreDataController.childContext(concurrencyType: .privateQueueConcurrencyType) .rx.perform(block: { context in let request: NSFetchRequest<CDTodo> = CDTodo.fetchRequest() request.predicate = NSPredicate(format: "id == %@", item.id) let results = try context.fetch(request) if let first = results.first { first.isFinished = item.isFinished first.name = item.name first.setPriority(priority: item.priority) try context.save() return } if results.count != 1 { assert(false, "expected exactly 1 item of id \(item.id), found \(results.count)") throw CoreDataError.invalidItemId(item.id) } }) } func deleteTodo(itemId: String) -> Single<Void> { return coreDataController.childContext(concurrencyType: .privateQueueConcurrencyType) .rx.perform(block: { context in let request: NSFetchRequest<CDTodo> = CDTodo.fetchRequest() request.predicate = NSPredicate(format: "id == %@", itemId) let results = try context.fetch(request) if let first = results.first { context.delete(first) try context.save() return } if results.count != 1 { assert(false, "expected exactly 1 item of id \(itemId), found \(results.count)") throw CoreDataError.invalidItemId(itemId) } }) } }
mit
c24d24328297da8b4bb21537f54fc5dc
34.322034
128
0.56166
5.039903
false
false
false
false
yasuoza/graphPON
graphPON iOS/Views/ChartInformationView.swift
1
1028
import UIKit class ChartInformationView: UIView { @IBOutlet private var titleLabel: UILabel! = UILabel() private let kJBChartValueViewPadding = CGFloat(0.0) private let kJBChartValueViewSeparatorSize = CGFloat(0.5) private let kJBChartValueViewTitleHeight = CGFloat(50.0) func setHidden(hidden: Bool, animated: Bool) { if animated { if hidden { UIView.animateWithDuration(0.25, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.titleLabel.alpha = 0.0 }, completion:nil) } else { UIView.animateWithDuration(0.25, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: { self.titleLabel.alpha = 1.0 }, completion:nil) } } else { self.titleLabel.alpha = hidden ? 0.0 : 1.0 } } func setTitleText(titleText: String) { self.titleLabel.text = titleText } }
mit
95fead2c26f5965143a80dd412f2c0eb
33.266667
127
0.610895
4.651584
false
false
false
false
naokits/my-programming-marathon
RxSwiftDemo/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/SimpleTableViewExampleSectioned/SimpleTableViewExampleSectionedViewController.swift
6
2177
// // SimpleTableViewExampleSectionedViewController.swift // RxExample // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif class SimpleTableViewExampleSectionedViewController : ViewController , UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Double>>() override func viewDidLoad() { super.viewDidLoad() let dataSource = self.dataSource let items = Observable.just([ SectionModel(model: "First section", items: [ 1.0, 2.0, 3.0 ]), SectionModel(model: "Second section", items: [ 1.0, 2.0, 3.0 ]), SectionModel(model: "Second section", items: [ 1.0, 2.0, 3.0 ]) ]) dataSource.cellFactory = { (tv, indexPath, element) in let cell = tv.dequeueReusableCellWithIdentifier("Cell")! cell.textLabel?.text = "\(element) @ row \(indexPath.row)" return cell } items .bindTo(tableView.rx_itemsWithDataSource(dataSource)) .addDisposableTo(disposeBag) tableView .rx_itemSelected .map { indexPath in return (indexPath, dataSource.itemAtIndexPath(indexPath)) } .subscribeNext { indexPath, model in DefaultWireframe.presentAlert("Tapped `\(model)` @ \(indexPath)") } .addDisposableTo(disposeBag) tableView .rx_setDelegate(self) .addDisposableTo(disposeBag) } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let label = UILabel(frame: CGRect.zero) label.text = dataSource.sectionAtIndex(section).model ?? "" return label } }
mit
751d9657d195946981f280b61d39cd44
27.644737
92
0.556985
5.320293
false
false
false
false
WalterCreazyBear/Swifter30
VedioDemo/VedioDemo/VideoCutter.swift
1
2724
// // VideoCutter.swift // VedioDemo // // Created by Bear on 2017/6/29. // Copyright © 2017年 Bear. All rights reserved. // import UIKit import AVFoundation extension String { var convert: NSString { return (self as NSString) } } class VideoCutter: NSObject { /** Block based method for crop video url @param videoUrl Video url @param startTime The starting point of the video segments @param duration Total time, video length */ open func cropVideoWithUrl(videoUrl url: URL, startTime: CGFloat, duration: CGFloat, completion: ((_ videoPath: URL?, _ error: NSError?) -> Void)?) { DispatchQueue.global().async { let asset = AVURLAsset(url: url, options: nil) let exportSession = AVAssetExportSession(asset: asset, presetName: "AVAssetExportPresetHighestQuality") let paths: NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray var outputURL = paths.object(at: 0) as! String let manager = FileManager.default do { try manager.createDirectory(atPath: outputURL, withIntermediateDirectories: true, attributes: nil) } catch _ { } outputURL = outputURL.convert.appendingPathComponent("output.mp4") do { try manager.removeItem(atPath: outputURL) } catch _ { } if let exportSession = exportSession as AVAssetExportSession? { exportSession.outputURL = URL(fileURLWithPath: outputURL) exportSession.shouldOptimizeForNetworkUse = true exportSession.outputFileType = AVFileTypeMPEG4 let start = CMTimeMakeWithSeconds(Float64(startTime), 600) let duration = CMTimeMakeWithSeconds(Float64(duration), 600) let range = CMTimeRangeMake(start, duration) exportSession.timeRange = range exportSession.exportAsynchronously { () -> Void in switch exportSession.status { case AVAssetExportSessionStatus.completed: completion?(exportSession.outputURL, nil) case AVAssetExportSessionStatus.failed: print("Failed: \(String(describing: exportSession.error))") case AVAssetExportSessionStatus.cancelled: print("Failed: \(String(describing: exportSession.error))") default: print("default case") } } } DispatchQueue.main.async { } } } }
mit
dd0ff4395e85b8ebaef8263644d50749
38.434783
151
0.594267
5.656965
false
false
false
false
SpriteKitAlliance/SKAControlSprite
Example/SKAControlExample/SKAControlExample/Sprites/SKASprite.swift
1
3208
// // SKASprite.swift // SKAControlExample // // Created by Marc Vandehey on 4/20/17. // Copyright © 2017 SpriteKit Alliance. All rights reserved. // import SpriteKit class SKASprite : SKSpriteNode { private let atlas = SKTextureAtlas(named: "SKA") private var currentState = SKASpriteState.Standing init() { let texture = atlas.textureNamed("ska-stand") super.init(texture: texture, color: .green, size: texture.size()) colorBlendFactor = 1 } required init?(coder aDecoder: NSCoder) { let texture = atlas.textureNamed("ska-stand") super.init(texture: texture, color: .white, size: texture.size()) colorBlendFactor = 1 } func playActionForState(state : SKASpriteState) { if currentState == state { return } removeAllActions() currentState = state switch state { case .Happy: run(SKAction.repeatForever(getHappyAnimation())) case .Dance: run(SKAction.repeatForever(getDanceAnimation())) case .Yawn: run(SKAction.repeatForever(getYawnAnimation())) default: texture = getStandingTexture() } } private func getStandingTexture() -> SKTexture { return atlas.textureNamed("ska-stand") } private func getHappyAnimation() -> SKAction { let standingTexture = getStandingTexture() let frame1 = atlas.textureNamed("ska-happy-1") let frame2 = atlas.textureNamed("ska-happy-2") var textureFrames = [standingTexture] for _ in 0...5 { textureFrames.append(frame1) textureFrames.append(frame2) } textureFrames.append(standingTexture) textureFrames.append(standingTexture) textureFrames.append(standingTexture) return createAnimationFromFrames(frames: textureFrames, timePerFrame: 0.12) } private func getDanceAnimation() -> SKAction { let standingTexture = getStandingTexture() let frame1 = atlas.textureNamed("ska-dance-1") let frame2 = atlas.textureNamed("ska-dance-2") let frame3 = atlas.textureNamed("ska-dance-3") var textureFrames = [standingTexture] for _ in 0...4 { textureFrames.append(frame1) textureFrames.append(frame2) textureFrames.append(frame1) textureFrames.append(frame3) } textureFrames.append(frame1) textureFrames.append(standingTexture) textureFrames.append(standingTexture) textureFrames.append(standingTexture) return createAnimationFromFrames(frames: textureFrames, timePerFrame: 0.12) } private func getYawnAnimation() -> SKAction { let standingTexture = getStandingTexture() var textureFrames = [standingTexture] for i in 1...6 { textureFrames.append(atlas.textureNamed("ska-yawn-\(i)")) } textureFrames.append(standingTexture) textureFrames.append(standingTexture) textureFrames.append(standingTexture) return createAnimationFromFrames(frames: textureFrames, timePerFrame: 0.18) } private func createAnimationFromFrames(frames : [SKTexture], timePerFrame: TimeInterval) -> SKAction { return SKAction.animate(with: frames, timePerFrame: timePerFrame, resize: true, restore: true) } enum SKASpriteState { case Standing case Happy case Dance case Yawn } }
mit
33f1941f2bb0328af3def427c5437d22
25.94958
104
0.705644
4.069797
false
false
false
false
EclipseSoundscapes/EclipseSoundscapes
EclipseSoundscapes/Features/About/Settings/Sections/Language/LanguageSettingItem.swift
1
741
// // LanguageSettingItem.swift // EclipseSoundscapes // // Created by Arlindo on 12/26/20. // Copyright © 2020 Eclipse Soundscapes. All rights reserved. // import RxCocoa class LanguageSettingItem: SettingItem, ReactiveViewModel, EventViewModel { let cellIdentifier: String = LanguageCell.identifier let info: String = localizedString(key: "SettingsLanguageInstructions") let setingsButtonTitle: String = localizedString(key: "SettingsLanguageButton") let eventRelay = PublishRelay<Event>() lazy var event: Signal<Event> = eventRelay.asSignal() func react(to action: Action) { switch action { case .openDeviceSettings: eventRelay.accept(.openDeviceSettings) } } }
gpl-3.0
98340f4848ed9b9400c2004692fe37e8
29.833333
83
0.710811
4.457831
false
false
false
false
LiwxCoder/Swift-Weibo
Weibo/Weibo/Classes/Home(首页)/StatusViewModel.swift
1
3310
// // StatusViewModel.swift // Weibo // // Created by liwx on 16/3/2. // Copyright © 2016年 liwx. All rights reserved. // import UIKit class StatusViewModel { // MARK: ====================================================================== // MARK: - Property (懒加载,属性监听) // MARK: - 微博对象属性 var status : Status? /// 微博来源数据处理 var sourceText : String? /// 认证显示的图片 var verifiedImage : UIImage? /// 会员显示的图片 var vipImage : UIImage? // MARK: - 计算属性 var createdAtText : String? { return String.createTimeString(status?.created_at ?? "") } /// 头像的URL var iconURL : NSURL? /// 微博配图的URLs var picURLs : [NSURL] = [NSURL]() // MARK: - 构造函数 init(status: Status) { self.status = status // 1.微博的非nil校验 guard let tempStatus = self.status else { return } // 2.来源处理 // 1.nil值的校验,在guard判断多个条件可以通过where连接 if let tempSource = tempStatus.source where tempStatus.source != "" { // 2.处理来源数据: <a href=\"http://weibo.com/\" rel=\"nofollow\">微博 weibo.com</a> // 2.1 获取起始 let startIndex = (tempSource as NSString).rangeOfString(">").location + 1 // 2.2 计算长度 let length = (tempSource as NSString).rangeOfString("</").location - startIndex // 2.3 截取字符串 sourceText = (tempSource as NSString).substringWithRange(NSRange(location: startIndex, length: length)) } // 3.处理认证图片 let verified_type = tempStatus.user?.verified_type ?? -1 switch verified_type { case 0: verifiedImage = UIImage(named: "avatar_vip") case 2, 3, 5: verifiedImage = UIImage(named: "avatar_enterprise_vip") case 220: verifiedImage = UIImage(named: "avatar_grassroot") default: verifiedImage = nil } // 4.处理会员图片 let vipRank = tempStatus.user?.mbrank ?? -1 if vipRank >= 1 && vipRank <= 6 { vipImage = UIImage(named: "common_icon_membership_level\(vipRank)") } // 5.头像的URL if let iconURLString = tempStatus.user?.profile_image_url { iconURL = NSURL(string: iconURLString) } // 6.微博配图URL处理 let tempPicURLStringDicts = status.pic_urls?.count != 0 ? status.pic_urls : status.retweeted_status?.pic_urls if let picURLStringDicts = tempPicURLStringDicts { // 6.1.遍历数组字典,拿到每一个字典 for picURLStringDict in picURLStringDicts { // 6.2.在字典中根据thumbnail_pic取出对应的urlString guard let picURLString = picURLStringDict["thumbnail_pic"] as? String else { continue } // 6.3.创建对应的URL,并且放入到picURLs数组 picURLs.append(NSURL(string: picURLString)!) } } } }
mit
d82a600a2e09aa3569375fb8a98a066b
28.95
117
0.52621
4.236209
false
false
false
false
milseman/swift
test/DebugInfo/mangling.swift
14
1940
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s // Type: // Swift.Dictionary<Swift.Int64, Swift.String> func markUsed<T>(_ t: T) {} // Variable: // mangling.myDict : Swift.Dictionary<Swift.Int64, Swift.String> // CHECK: !DIGlobalVariable(name: "myDict", // CHECK-SAME: linkageName: "_T08mangling6myDicts10DictionaryVys5Int64VSSGv", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[DT:[0-9]+]] // CHECK: ![[DT]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Dictionary" var myDict = Dictionary<Int64, String>() myDict[12] = "Hello!" // mangling.myTuple1 : (Name : Swift.String, Id : Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple1", // CHECK-SAME: linkageName: "_T08mangling8myTuple1SS4Name_s5Int64V2Idtv", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT1:[0-9]+]] // CHECK: ![[TT1]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T0SS4Name_s5Int64V2IdtD" var myTuple1 : (Name: String, Id: Int64) = ("A", 1) // mangling.myTuple2 : (Swift.String, Id : Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple2", // CHECK-SAME: linkageName: "_T08mangling8myTuple2SS_s5Int64V2Idtv", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT2:[0-9]+]] // CHECK: ![[TT2]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T0SS_s5Int64V2IdtD" var myTuple2 : ( String, Id: Int64) = ("B", 2) // mangling.myTuple3 : (Swift.String, Swift.Int64) // CHECK: !DIGlobalVariable(name: "myTuple3", // CHECK-SAME: linkageName: "_T08mangling8myTuple3SS_s5Int64Vtv", // CHECK-SAME: line: [[@LINE+3]] // CHECK-SAME: type: ![[TT3:[0-9]+]] // CHECK: ![[TT3]] = !DICompositeType(tag: DW_TAG_structure_type, name: "_T0SS_s5Int64VtD" var myTuple3 : ( String, Int64) = ("C", 3) markUsed(myTuple1.Id) markUsed(myTuple2.Id) markUsed({ $0.1 }(myTuple3))
apache-2.0
17af8b82317818bf6a8a623af542ce88
45.190476
98
0.623196
2.899851
false
false
false
false
allenlinli/Wildlife-League
Wildlife League/Board.swift
1
1889
// // Board.swift // Wildlife League // // Created by allenlin on 7/9/14. // Copyright (c) 2014 Raccoonism. All rights reserved. // import Foundation let NumColumns = 6 let NumRows = 5 class Board { var grid :Array2D<Beed> var chains = Set<Chain>() init(){ self.grid = Array2D<Beed>(columns: NumColumns, rows: NumRows) do{ chains = Set<Chain>() for row in 0..<NumRows{ for column in 0..<NumColumns{ grid[column, row] = Beed(column: column, row: row, beedType:BeedType.randomType()) } } self.findMergedChains() } while (chains.count()>0) } subscript (column:Int, row:Int) -> Beed? { get{ if(column<0 || column>NumColumns-1 || row<0 || row>NumRows-1) { return nil } return grid[column , row] } set (newValue) { if let beed = newValue as Beed?{ grid[beed.column,beed.row] = beed } } } func insertBeed (beed:Beed) { self[beed.column,beed.row] = beed } func printBoard () { for r in 0..<NumRows{ for c in 0..<NumColumns{ print("\(self.grid[c,r]?.beedType.toRaw()) ") } println("") } println("----------------") } func copy() -> Board { var boardCopy = Board() boardCopy.grid = self.grid boardCopy.chains = self.chains return boardCopy } func eraseChains () { for chain in chains{ for beed in chain { beed.beedType = BeedType.BeedTypeEmpty self.insertBeed(beed) } } self.chains = Set<Chain>() } }
apache-2.0
639f7ae20ad18fbfe07a9b778c97203a
22.04878
102
0.463208
4.053648
false
false
false
false
nodes-vapor/admin-panel
Sources/AdminPanel/Tags/AvatarURLTag.swift
1
683
import Leaf import TemplateKit public final class AvatarURLTag: TagRenderer { public func render(tag: TagContext) throws -> Future<TemplateData> { var identifier = "" var url: String? for index in 0...1 { if let param = tag.parameters[safe: index]?.string, !param.isEmpty { switch index { case 0: identifier = param case 1: url = param default: () } } } let avatarURL = url ?? "https://api.adorable.io/avatars/150/\(identifier).png" return tag.future(.string(avatarURL)) } }
mit
f2f4c98b6350d56cd4c86dc99b9f6a43
25.269231
86
0.502196
4.776224
false
false
false
false
notohiro/NowCastMapView
NowCastMapView/BaseTime.swift
1
3361
// // BaseTime.swift // NowCastMapView // // Created by Hiroshi Noto on 9/15/15. // Copyright © 2015 Hiroshi Noto. All rights reserved. // import Foundation /** A `BaseTime` structure contains a set of indexes represents forecast timeline as of specific forecast time. A `BaseTime` instances are parsed and instantiated from a simple xml data fetched from "http://www.jma.go.jp/jp/highresorad/highresorad_tile/tile_basetime.xml". */ public struct BaseTime { // MARK: - Public Properties public let range: CountableClosedRange<Int> // -35...0..12 public var count: Int { return range.count } // MARK: - Private Properties private let ftStrings: [String] private let ftDates: [Date] // MARK: - Functions public init?(baseTimeData data: Data) { // parse xml let parser = XMLParser(data: data) let parserDelegate = BaseTimeParser() parser.delegate = parserDelegate if !parser.parse() { return nil } // inputFormatter let inputFormatter = DateFormatter() inputFormatter.dateFormat = "yyyyMMddHHmm" inputFormatter.timeZone = TimeZone(abbreviation: "UTC") // create ftDates from baseTime // contains only past date var ftDates = [Date]() for index in 0 ..< parserDelegate.parsedArr.count { guard let date = inputFormatter.date(from: parserDelegate.parsedArr[index]) else { return nil } ftDates.append(date) } // create ftDates with fts for forecast let base = ftDates[0] BaseTimeModel.Constants.fts.enumerated().forEach { _, minutes in if minutes == 0 { return } ftDates.insert(base.addingTimeInterval(TimeInterval(minutes * 60)), at: 0) } // outputFormatter let outputFormatter = DateFormatter() outputFormatter.dateFormat = "yyyyMMddHHmm" outputFormatter.timeZone = TimeZone(abbreviation: "UTC") // create ftStrings from ftDates var ftStrings = [String]() ftDates.forEach { date in ftStrings.append(outputFormatter.string(from: date)) } self.ftDates = ftDates self.ftStrings = ftStrings range = BaseTime.index(from: ftDates.endIndex - 1) ... BaseTime.index(from: ftDates.startIndex) return } public subscript(index: Int) -> String { return ftStrings[BaseTime.arrayIndex(from: index)] } public subscript(index: Int) -> Date { return ftDates[BaseTime.arrayIndex(from: index)] } } // MARK: - Static Functions extension BaseTime { /// convert from 0...47 to -35...12 private static func index(from arrayIndex: Int) -> Int { return -(arrayIndex - (BaseTimeModel.Constants.fts.count - 1)) } /// convert from -35...12 to 0...47 private static func arrayIndex(from index: Int) -> Int { return (-index) + (BaseTimeModel.Constants.fts.count - 1) } } // MARK: - CustomStringConvertible extension BaseTime: CustomStringConvertible { public var description: String { return self[0] } } // MARK: - CustomDebugStringConvertible extension BaseTime: CustomDebugStringConvertible { public var debugDescription: String { // var output: [String] = [] // // output.append("[url]: \(url)") // output.append(image != nil ? "[image]: not nil" : "[image]: nil") // // return output.joined(separator: "\n") return description } }
mit
d6cf3024a2a83481181af667f51d6be8
27.474576
107
0.6625
4.019139
false
false
false
false
Istered/FrameManager
Source/Extensions/CustomCacheableState+Extensions.swift
1
834
// // Created by Anton Romanov on 12.03.17. // Copyright (c) 2017 Istered. All rights reserved. // import Foundation internal extension CustomCacheableState { func asHashableKey() -> HashSetKey { let keys = Self.customKeys() let mirror = Mirror(reflecting: self) return HashSetKey(hashes: keys.map(keyToHash(mirror))) } func keyToHash(_ mirror: Mirror) -> (String) -> (Int) { return { key in guard let child = mirror.children.first(where: { $0.label == key }) else { fatalError("Custom key \"\(key)\" not found for \(self)") } guard let hashableValue = child.value as? AnyHashable else { fatalError("Custom key \"\(key)\" should be hashable") } return hashableValue.hashValue } } }
mit
03b7fda8a3ac56363a4b3a7f88856042
28.821429
86
0.583933
4.233503
false
false
false
false
belatrix/iOSAllStars
AllStarsV2/AllStarsV2/CommonClasses/CoredataMedia/CDMWebResponse.swift
1
3089
// // CDMWebResponse.swift // // // Created by Kenyi Rodriguez on 8/04/16. // Copyright © 2016 Core Data Media. All rights reserved. // import UIKit public class CDMWebResponse: NSObject { public var JSON : Any? public var statusCode : Int = 404 public var respuestaNSData : Data? public var error : Error? public var datosCabecera : [String : Any]? public var token : String? public var cookie : String? public var successful : Bool = false //MARK: - Métodos auxiliares public class func getArray(_ value : Any?) -> [Any] { if value == nil || value is NSNull || !(value is [Any]){ return [] }else{ return value as! [Any] } } public class func getDictionary(_ value : Any?) -> [String : Any] { if value == nil || value is NSNull || !(value is [String : Any]){ return [:] }else{ return value as! [String : Any] } } public class func getArrayDictionary(_ value : Any?) -> [[String : Any]] { if value == nil || value is NSNull || !(value is [[String : Any]]){ return [] }else{ return value as! [[String : Any]] } } public class func getColor(_ value : Any?) -> UIColor { if value == nil || value is NSNull || !(value is String){ return .black }else{ return CDMColorManager.colorFromHexString(value as! String, withAlpha: 1) } } public class func getString(_ value : Any?) -> String { if value == nil || value is NSNull || !(value is String){ return "" }else{ return value as! String } } public class func getBool(_ value : Any?) -> Bool { if value == nil || value is NSNull || !(value is Bool){ return false }else{ return value as! Bool } } public class func getInt(_ value : Any?) -> Int { if value == nil || value is NSNull || !(value is Int){ return 0 }else{ return value as! Int } } public class func getDouble(_ value : Any?) -> Double { if value == nil || value is NSNull || !(value is Double){ return 0 }else{ return value as! Double } } public class func getFloat(_ value : Any?) -> Float { if value == nil || value is NSNull || !(value is Float){ return 0 }else{ return value as! Float } } }
apache-2.0
eec08014faa278965396f2028c636cba
22.386364
85
0.429219
5.188235
false
false
false
false