repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
GreenCom-Networks/ios-charts
Charts/Classes/Data/Implementations/Standard/BarChartData.swift
1
1566
// // BarChartData.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics public class BarChartData: BarLineScatterCandleBubbleChartData { private var _allowBarSuperposition:Bool = false public override init() { super.init() } public override init(xVals: [String?]?, dataSets: [IChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } public override init(xVals: [NSObject]?, dataSets: [IChartDataSet]?) { super.init(xVals: xVals, dataSets: dataSets) } private var _groupSpace = CGFloat(0.8) /// The spacing is relative to a full bar width public var groupSpace: CGFloat { get { if (_dataSets.count <= 1) { return 0.0 } return _groupSpace } set { _groupSpace = newValue } } /// - returns: true if this BarData object contains grouped DataSets (more than 1 DataSet). public var isGrouped: Bool { return _dataSets.count > 1 ? true : false } public var allowBarSuperposition: Bool { get { return _allowBarSuperposition } set { _allowBarSuperposition = newValue } } }
apache-2.0
c58584c309c90ad29e77df33cc42ae69
20.452055
95
0.566411
4.565598
false
false
false
false
Sajjon/Zeus
Examples/ApiOfIceAndFire/ApiOfIceAndFire/ZeusConfigurator.swift
1
1176
// // ZeusConfigurator.swift // ApiOfIceAndFire // // Created by Cyon Alexander (Ext. Netlight) on 23/08/16. // Copyright © 2016 com.cyon. All rights reserved. // import Foundation import Zeus private let baseUrl = "http://anapioficeandfire.com/api/" class ZeusConfigurator { var store: DataStoreProtocol! var modelManager: ModelManagerProtocol! init() { setup() } fileprivate func setup() { setupCoreDataStack() setupLogging() setupMapping() } fileprivate func setupLogging() { Zeus.logLevel = .Warning } fileprivate func setupCoreDataStack() { store = DataStore() modelManager = ModelManager(baseUrl: baseUrl, store: store) DataStore.sharedInstance = store ModelManager.sharedInstance = modelManager } fileprivate func setupMapping() { modelManager.map(Character.entityMapping(store), House.entityMapping(store)) { character, house in character == Router.characters character == Router.characterById(nil) house == Router.houses house == Router.houseById(nil) } } }
apache-2.0
4711c6ea2fc09bb4786f84fa89175875
23.479167
86
0.635745
4.450758
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutInfoStorable/ViewInfo.swift
1
1849
// // ViewInfo.swift // NotAutoLayout // // Created by 史翔新 on 2017/03/02. // Copyright © 2017年 史翔新. All rights reserved. // import UIKit public struct ViewInfo<InfoType> { typealias InfoValue = [UIView.NAL.Hash: () -> InfoType] typealias ViewClosureInfoValue = [UIView: () -> InfoType] typealias HashInfoTypeInfoValue = [UIView.NAL.Hash: InfoType] typealias SimplifiedInfoValue = [UIView: InfoType] private var value: InfoValue } extension ViewInfo { subscript (_ viewHash: UIView.NAL.Hash) -> InfoType? { guard let result = self.value[viewHash] else { return nil } return result() } public subscript (_ view: UIView) -> InfoType? { return self[view.nal.hash] } subscript (_ viewHash: UIView.NAL.Hash, `default` defaultValue: InfoType) -> InfoType { return self[viewHash] ?? defaultValue } public subscript (_ view: UIView, `default` defaultValue: InfoType) -> InfoType { return self[view] ?? defaultValue } } extension ViewInfo { mutating func set(_ info: InfoType, for view: UIView) { self.value[view.nal.hash] = { info } } mutating func set(_ info: @escaping () -> InfoType, for view: UIView) { self.value[view.nal.hash] = info } } extension ViewInfo { func containsInfo(for view: UIView) -> Bool { return self.value.containsKey(view.nal.hash) } } extension ViewInfo: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (UIView, InfoType)...) { self.value = [UIView.NAL.Hash: () -> InfoType].init(minimumCapacity: elements.count) for element in elements { self.value[element.0.nal.hash] = { element.1 } } } } public typealias LayoutInfo = ViewInfo<IndividualProperty.Layout> public typealias OrderInfo = ViewInfo<Int> public typealias ZIndexInfo = ViewInfo<Int>
apache-2.0
51ae62ad66a78c0ebf584d6734512da1
17.714286
88
0.678299
3.377532
false
false
false
false
silence0201/Swift-Study
Learn/19.Foundation/NSNumber/数字格式化.playground/Contents.swift
1
1318
import Foundation let number = 1_2345_6789 let numberObj = NSNumber(value: number) let formatter = NumberFormatter() //十进制数字 formatter.numberStyle = .decimal //NumberFormatter.Style.decimal var stringNumber = formatter.string(from: numberObj) print("DecimalStyle : \(stringNumber!)") //科学计数法 formatter.numberStyle = .scientific stringNumber = formatter.string(from: numberObj) print("ScientificStyle : \(stringNumber!)") //百分数 formatter.numberStyle = .percent stringNumber = formatter.string(from: numberObj) print("PercentStyle : \(stringNumber!)") //货币 formatter.numberStyle = .currency stringNumber = formatter.string(from: numberObj) print("CurrencyStyle : \(stringNumber!)") //大写数字 formatter.numberStyle = .spellOut stringNumber = formatter.string(from: numberObj) print("SpellOutStyle : \(stringNumber!)") //设置本地化标识 for localId in ["en_US", "fr_FR", "zh_CN"] { formatter.locale = Locale(identifier: localId) //货币 formatter.numberStyle = .currency stringNumber = formatter.string(from: numberObj) print("\(localId) : CurrencyStyle : \(stringNumber!)") //大写数字 formatter.numberStyle = .spellOut stringNumber = formatter.string(from: numberObj) print("\(localId) : SpellOutStyle : \(stringNumber!)") }
mit
d08adb408a7fa835fceadeb48650a53d
26.26087
64
0.730463
3.732143
false
false
false
false
kesun421/firefox-ios
SyncTelemetry/SyncTelemetry.swift
1
4029
/* 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 Alamofire import Foundation import XCGLogger import SwiftyJSON import Shared private let log = Logger.browserLogger private let ServerURL = "https://incoming.telemetry.mozilla.org".asURL! private let AppName = "Fennec" public enum TelemetryDocType: String { case core = "core" case sync = "sync" } public protocol SyncTelemetryEvent { func record(_ prefs: Prefs) } open class SyncTelemetry { private static var prefs: Prefs? private static var telemetryVersion: Int = 4 open class func initWithPrefs(_ prefs: Prefs) { assert(self.prefs == nil, "Prefs already initialized") self.prefs = prefs } open class func recordEvent(_ event: SyncTelemetryEvent) { guard let prefs = prefs else { assertionFailure("Prefs not initialized") return } event.record(prefs) } open class func send(ping: SyncTelemetryPing, docType: TelemetryDocType) { let docID = UUID().uuidString let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String let buildID = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String let channel = AppConstants.BuildChannel.rawValue let path = "/submit/telemetry/\(docID)/\(docType.rawValue)/\(AppName)/\(appVersion)/\(channel)/\(buildID)" let url = ServerURL.appendingPathComponent(path) var request = URLRequest(url: url) log.debug("Ping URL: \(url)") log.debug("Ping payload: \(ping.payload.stringValue() ?? "")") // Don't add the common ping format for the mobile core ping. let pingString: String? if docType != .core { var json = JSON(commonPingFormat(forType: docType)) json["payload"] = ping.payload pingString = json.stringValue() } else { pingString = ping.payload.stringValue() } guard let body = pingString?.data(using: String.Encoding.utf8) else { log.error("Invalid data!") assertionFailure() return } guard channel != "default" else { log.debug("Non-release build; not sending ping") return } request.httpMethod = "POST" request.httpBody = body request.addValue(Date().toRFC822String(), forHTTPHeaderField: "Date") request.setValue("application/json", forHTTPHeaderField: "Content-Type") SessionManager.default.request(request).response { response in log.debug("Ping response: \(response.response?.statusCode ?? -1).") } } private static func commonPingFormat(forType type: TelemetryDocType) -> [String: Any] { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let date = formatter.string(from: NSDate() as Date) let displayVersion = [ AppInfo.appVersion, "b", AppInfo.buildNumber ].joined() let version = ProcessInfo.processInfo.operatingSystemVersion let osVersion = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" return [ "type": type.rawValue, "id": UUID().uuidString, "creationDate": date, "version": SyncTelemetry.telemetryVersion, "application": [ "architecture": "arm", "buildId": AppInfo.buildNumber, "name": AppInfo.displayName, "version": AppInfo.appVersion, "displayVersion": displayVersion, "platformVersion": osVersion, "channel": AppConstants.BuildChannel.rawValue ] ] } } public protocol SyncTelemetryPing { var payload: JSON { get } }
mpl-2.0
8e76ed60b63e9d52bc680a1b5b8826a4
33.144068
114
0.620005
4.790725
false
false
false
false
AvdLee/Moya-SwiftyJSONMapper
Example/Moya-SwiftyJSONMapper/ExampleAPI.swift
1
3108
// // ExampleAPI.swift // Moya-SwiftyJSONMapper // // Created by Antoine van der Lee on 25/01/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import Moya import Moya_SwiftyJSONMapper import ReactiveSwift import SwiftyJSON let stubbedProvider = MoyaProvider<ExampleAPI>(stubClosure: MoyaProvider.immediatelyStub) enum ExampleAPI { case GetObject case GetArray } extension ExampleAPI: JSONMappableTargetType { var baseURL: URL { return URL(string: "https://httpbin.org")! } var path: String { switch self { case .GetObject: return "/get" case .GetArray: return "/getarray" // Does not really works, but will work for stubbed response } } var method: Moya.Method { return .get } var parameters: [String: Any]? { return nil } var sampleData: Data { switch self { case .GetObject: return stubbedResponseFromJSONFile(filename: "object_response") case .GetArray: return stubbedResponseFromJSONFile(filename: "array_response") } } var responseType: ALSwiftyJSONAble.Type { switch self { case .GetObject: return GetResponse.self case .GetArray: return GetResponse.self } } var multipartBody: [MultipartFormData]? { return nil } var task: Task { return .requestPlain } var parameterEncoding: ParameterEncoding { return URLEncoding.default } var headers: [String: String]? { return nil } } // Then add an additional request method // Is not working: //func requestType<T:ALSwiftyJSONAble>(target: ExampleAPI) -> SignalProducer<T, Moya.Error> { // return RCStubbedProvider.request(target).mapObject(target.responseType) //} // Works but has al the mapping logic in it, I don't want that! func requestType<T:ALSwiftyJSONAble>(target: ExampleAPI) -> SignalProducer<T, MoyaError> { return stubbedProvider.reactive.request(target).flatMap(FlattenStrategy.latest, { (response) -> SignalProducer<T, MoyaError> in do { let jsonObject = try response.mapJSON() guard let mappedObject = T(jsonData: JSON(jsonObject)) else { throw MoyaError.jsonMapping(response) } return SignalProducer(value: mappedObject) } catch let error { return SignalProducer(error: MoyaError.underlying(error as NSError, response)) } }) } protocol JSONMappableTargetType: TargetType { var responseType: ALSwiftyJSONAble.Type { get } } private func stubbedResponseFromJSONFile(filename: String, inDirectory subpath: String = "", bundle:Bundle = Bundle.main ) -> Data { guard let path = bundle.path(forResource: filename, ofType: "json", inDirectory: subpath) else { return Data() } if let dataString = try? String(contentsOfFile: path), let data = dataString.data(using: String.Encoding.utf8){ return data } else { return Data() } }
mit
4e1003d7fb0a350d316d38b405b47b14
29.165049
132
0.646926
4.651198
false
false
false
false
thomasrzhao/TRZNumberScrollView
TRZNumberScrollViewDemoOSX/ViewController.swift
1
3244
// // ViewController.swift // TRZNumberScrollViewDemoOSX // // Created by Thomas Zhao on 3/11/16. // Copyright © 2016 Thomas Zhao. All rights reserved. // import Cocoa class ViewController: NSSplitViewController, NumberScrollViewParametersViewControllerDelegate { var numberScrollViewContainer:NumberScrollViewContainerViewController! var parametersViewController:NumberScrollViewParametersViewController! override func viewDidLoad() { super.viewDidLoad() numberScrollViewContainer = splitViewItems[0].viewController as? NumberScrollViewContainerViewController parametersViewController = splitViewItems[1].viewController as? NumberScrollViewParametersViewController parametersViewController.delegate = self let numberScrollView = numberScrollViewContainer.numberScrollView numberScrollView?.text = parametersViewController.text numberScrollView?.animationDuration = parametersViewController.animationDuration numberScrollView?.animationCurve = parametersViewController.animationCurve numberScrollView?.setFont(parametersViewController.font, textColor: parametersViewController.textColor) } func parametersViewControllerDidCommit(_ sender: NumberScrollViewParametersViewController) { numberScrollViewContainer.numberScrollView.setText(parametersViewController.text, animated: parametersViewController.animationEnabled) } func parametersViewController(_ sender: NumberScrollViewParametersViewController, didChangeAnimationCurve animationCurve: CAMediaTimingFunction) { numberScrollViewContainer.numberScrollView.animationCurve = animationCurve } func parametersViewController(_ sender: NumberScrollViewParametersViewController, didChangeAnimationDuration animationDuration: TimeInterval) { numberScrollViewContainer.numberScrollView.animationDuration = animationDuration } func parametersViewController(_ sender: NumberScrollViewParametersViewController, didChangeFont font: NSFont) { numberScrollViewContainer.numberScrollView.font = font } func parametersViewController(_ sender: NumberScrollViewParametersViewController, didChangeTextColor textColor: NSColor) { numberScrollViewContainer.numberScrollView.textColor = textColor } func parametersViewController(_ sender: NumberScrollViewParametersViewController, didChangeAnimationDirection animationDirection: NumberScrollView.AnimationDirection) { numberScrollViewContainer.numberScrollView.animationDirection = animationDirection } } class NumberScrollViewContainerViewController: NSViewController { @IBOutlet weak var numberScrollView: NumberScrollView! @IBOutlet var backgroundColorView: BackgroundColorView! override func viewDidLoad() { backgroundColorView.backgroundColor = NSColor.white numberScrollView.backgroundColor = backgroundColorView.backgroundColor } } class BackgroundColorView: NSView { var backgroundColor:NSColor? { didSet { needsDisplay = true } } override func draw(_ dirtyRect: NSRect) { backgroundColor?.setFill() NSRectFill(bounds) } }
mit
5f1a85e962358e246370b9fb9876d037
42.24
172
0.78415
6.321637
false
false
false
false
natecook1000/swift
test/PrintAsObjC/imports.swift
3
2014
// Please keep this file in alphabetical order! // RUN: %empty-directory(%t) // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules/ -F %S/Inputs/ -emit-module -o %t %s -disable-objc-attr-requires-foundation-module // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules/ -F %S/Inputs/ -parse-as-library %t/imports.swiftmodule -typecheck -emit-objc-header-path %t/imports.h -import-objc-header %S/../Inputs/empty.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck %s < %t/imports.h // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/imports.h // RUN: %check-in-clang %t/imports.h -I %S/Inputs/custom-modules/ -F %S/Inputs/ // REQUIRES: objc_interop // CHECK: @import Base; // CHECK-NEXT: @import Base.ExplicitSub; // CHECK-NEXT: @import Base.ExplicitSub.ExSub; // CHECK-NEXT: @import Base.ImplicitSub.ExSub; // CHECK-NEXT: @import Foundation; // CHECK-NEXT: @import MostlyPrivate1; // CHECK-NEXT: @import MostlyPrivate1_Private; // CHECK-NEXT: @import MostlyPrivate2_Private; // CHECK-NEXT: @import ctypes.bits; // NEGATIVE-NOT: ctypes; // NEGATIVE-NOT: ImSub; // NEGATIVE-NOT: ImplicitSub; // NEGATIVE-NOT: MostlyPrivate2; import ctypes.bits import Foundation import Base import Base.ImplicitSub import Base.ImplicitSub.ImSub import Base.ImplicitSub.ExSub import Base.ExplicitSub import Base.ExplicitSub.ImSub import Base.ExplicitSub.ExSub import MostlyPrivate1 import MostlyPrivate1_Private // Deliberately not importing MostlyPrivate2 import MostlyPrivate2_Private @objc class Test { @objc let word: DWORD = 0 @objc let number: TimeInterval = 0.0 @objc let baseI: BaseI = 0 @objc let baseII: BaseII = 0 @objc let baseIE: BaseIE = 0 @objc let baseE: BaseE = 0 @objc let baseEI: BaseEI = 0 @objc let baseEE: BaseEE = 0 // Deliberately use the private type before the public type. @objc let mp1priv: MP1PrivateType = 0 @objc let mp1pub: MP1PublicType = 0 @objc let mp2priv: MP2PrivateType = 0 }
apache-2.0
1d6ba2dd3778ca8c398944a31afdb804
33.135593
279
0.734359
3.088957
false
false
false
false
iosyaowei/Weibo
WeiBo/Classes/View(视图和控制器)/Compose/YWComposeViewController.swift
1
5631
// // YWComposeViewController.swift // WeiBo // // Created by 姚巍 on 16/10/6. // Copyright © 2016年 yao wei. All rights reserved. // 撰写微博控制器 import UIKit import SVProgressHUD class YWComposeViewController: UIViewController { @IBOutlet weak var textView: YWComposeTextView! @IBOutlet weak var toolBar: UIToolbar! ///发布按钮 @IBOutlet var sendBtn: UIButton! /// 标题视图 @IBOutlet var titleLab: UILabel! /// 工具栏底部约束 @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint! /// 表情输入视图 lazy var emoticonView: YWEmoticonInputView = YWEmoticonInputView.inputView { [weak self] (emoticon) in self?.textView.insterEmoticon(em: emoticon) } override func viewDidLoad() { super.viewDidLoad() steupUI() NotificationCenter.default.addObserver(self, selector: #selector(keyBoardChanged), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) textView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(true) //关闭键盘 textView.resignFirstResponder() } deinit { //注销通知 NotificationCenter.default.removeObserver(self) } @objc fileprivate func keyBoardChanged(noti: Notification){ //目标rect guard let rect = (noti.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue, let duartion = (noti.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else{ return } //可以设置底部约束的高度 let offset = view.bounds.height - rect.origin.y toolBarBottomCons.constant = offset UIView.animate(withDuration: duartion) { self.view.layoutIfNeeded() } } @objc fileprivate func backAction() { dismiss(animated: true, completion: nil) } /// 发布微博 @IBAction func sendAction(_ sender: AnyObject) { //获得发送微博的纯文本字符串 let text = textView.emoticonText ///测试发送图片 let image = UIImage(named: "icon_small_kangaroo_loading_1") YWNetworkManager.shared.postStatus(text: text, image:nil) { (result,isSuccess) in let messaage = isSuccess ?"发布成功":"网络不给力" SVProgressHUD.setDefaultStyle(.dark) SVProgressHUD.showInfo(withStatus: messaage) if isSuccess { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { //恢复样式 SVProgressHUD.setDefaultStyle(.light) self.backAction() }) } } } //切换表情键盘 @objc fileprivate func emoticonKeyboard() { textView.inputView = (textView.inputView == nil) ? emoticonView : nil //刷新键盘 textView.reloadInputViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension YWComposeViewController:UITextViewDelegate{ func textViewDidChange(_ textView: UITextView) { sendBtn.isEnabled = textView.hasText } } fileprivate extension YWComposeViewController{ func steupUI() { view.backgroundColor = UIColor.white; steupNavigationBar() steupToolbar() } /// 设置工具栏 func steupToolbar() { let itemSettings = [["imageName": "compose_toolbar_picture"], ["imageName": "compose_mentionbutton_background"], ["imageName": "compose_trendbutton_background"], ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"], ["imageName": "compose_add_background"]] var itemArr = [UIBarButtonItem]() //遍历数组 for item in itemSettings { guard let imageName = item["imageName"] else { return } let image = UIImage(named: imageName); let imageHL = UIImage(named: imageName + "_highlighted") let btn = UIButton(); btn.setImage(image, for:.normal); btn.setImage(imageHL, for: .highlighted) btn.sizeToFit() //判断 actionName if let actionName = item["actionName"] { //添加监听方法 btn.addTarget(self, action: #selector(emoticonKeyboard), for: .touchUpInside) } //追加按钮 itemArr.append(UIBarButtonItem(customView: btn)) //追加弹簧 itemArr.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)) } //删除末尾弹簧 itemArr.removeLast() toolBar.items = itemArr } func steupNavigationBar(){ navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(backAction)) //设置发送按钮 navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn) sendBtn.isEnabled = false navigationItem.titleView = titleLab } }
mit
b20fda14b13a3bed3a241752b2626bb4
31.26506
156
0.593167
5.130268
false
false
false
false
apple/swift-nio-http2
Sources/NIOHPACK/HuffmanTables.swift
1
179197
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// typealias HuffmanTableEntry = (bits: UInt32, nbits: Int) /// Base-64 decoding has been jovially purloined from swift-corelibs-foundation/.../NSData.swift. /// The ranges of ASCII characters that are used to encode data in Base64. private let base64ByteMappings: [Range<UInt8>] = [ 65 ..< 91, // A-Z 97 ..< 123, // a-z 48 ..< 58, // 0-9 43 ..< 44, // + 47 ..< 48, // / ] /** Padding character used when the number of bytes to encode is not divisible by 3 */ private let base64Padding : UInt8 = 61 // = /** This method takes a byte with a character from Base64-encoded string and gets the binary value that the character corresponds to. - parameter byte: The byte with the Base64 character. - returns: Base64DecodedByte value containing the result (Valid , Invalid, Padding) */ private enum Base64DecodedByte { case valid(UInt8) case invalid case padding } private func base64DecodeByte(_ byte: UInt8) -> Base64DecodedByte { guard byte != base64Padding else {return .padding} var decodedStart: UInt8 = 0 for range in base64ByteMappings { if range.contains(byte) { let result = decodedStart + (byte - range.lowerBound) return .valid(result) } decodedStart += range.upperBound - range.lowerBound } return .invalid } /** This method decodes Base64-encoded data. If the input contains any bytes that are not valid Base64 characters, this will return nil. - parameter bytes: The Base64 bytes - parameter options: Options for handling invalid input - returns: The decoded bytes. */ private func base64DecodeBytes<C: Collection>(_ bytes: C, ignoreUnknownCharacters: Bool = false) -> [UInt8]? where C.Element == UInt8 { var decodedBytes = [UInt8]() decodedBytes.reserveCapacity((bytes.count/3)*2) var currentByte : UInt8 = 0 var validCharacterCount = 0 var paddingCount = 0 var index = 0 for base64Char in bytes { let value : UInt8 switch base64DecodeByte(base64Char) { case .valid(let v): value = v validCharacterCount += 1 case .invalid: if ignoreUnknownCharacters { continue } else { return nil } case .padding: paddingCount += 1 continue } //padding found in the middle of the sequence is invalid if paddingCount > 0 { return nil } switch index%4 { case 0: currentByte = (value << 2) case 1: currentByte |= (value >> 4) decodedBytes.append(currentByte) currentByte = (value << 4) case 2: currentByte |= (value >> 2) decodedBytes.append(currentByte) currentByte = (value << 6) case 3: currentByte |= value decodedBytes.append(currentByte) default: fatalError() } index += 1 } guard (validCharacterCount + paddingCount)%4 == 0 else { //invalid character count return nil } return decodedBytes } internal let StaticHuffmanTable: [HuffmanTableEntry] = [ (0x1ff8, 13), (0x7fffd8, 23), (0xfffffe2, 28), (0xfffffe3, 28), (0xfffffe4, 28), (0xfffffe5, 28), (0xfffffe6, 28), (0xfffffe7, 28), (0xfffffe8, 28), (0xffffea, 24), (0x3ffffffc, 30), (0xfffffe9, 28), (0xfffffea, 28), (0x3ffffffd, 30), (0xfffffeb, 28), (0xfffffec, 28), (0xfffffed, 28), (0xfffffee, 28), (0xfffffef, 28), (0xffffff0, 28), (0xffffff1, 28), (0xffffff2, 28), (0x3ffffffe, 30), (0xffffff3, 28), (0xffffff4, 28), (0xffffff5, 28), (0xffffff6, 28), (0xffffff7, 28), (0xffffff8, 28), (0xffffff9, 28), (0xffffffa, 28), (0xffffffb, 28), (0x14, 6), (0x3f8, 10), (0x3f9, 10), (0xffa, 12), (0x1ff9, 13), (0x15, 6), (0xf8, 8), (0x7fa, 11), (0x3fa, 10), (0x3fb, 10), (0xf9, 8), (0x7fb, 11), (0xfa, 8), (0x16, 6), (0x17, 6), (0x18, 6), (0x0, 5), (0x1, 5), (0x2, 5), (0x19, 6), (0x1a, 6), (0x1b, 6), (0x1c, 6), (0x1d, 6), (0x1e, 6), (0x1f, 6), (0x5c, 7), (0xfb, 8), (0x7ffc, 15), (0x20, 6), (0xffb, 12), (0x3fc, 10), (0x1ffa, 13), (0x21, 6), (0x5d, 7), (0x5e, 7), (0x5f, 7), (0x60, 7), (0x61, 7), (0x62, 7), (0x63, 7), (0x64, 7), (0x65, 7), (0x66, 7), (0x67, 7), (0x68, 7), (0x69, 7), (0x6a, 7), (0x6b, 7), (0x6c, 7), (0x6d, 7), (0x6e, 7), (0x6f, 7), (0x70, 7), (0x71, 7), (0x72, 7), (0xfc, 8), (0x73, 7), (0xfd, 8), (0x1ffb, 13), (0x7fff0, 19), (0x1ffc, 13), (0x3ffc, 14), (0x22, 6), (0x7ffd, 15), (0x3, 5), (0x23, 6), (0x4, 5), (0x24, 6), (0x5, 5), (0x25, 6), (0x26, 6), (0x27, 6), (0x6, 5), (0x74, 7), (0x75, 7), (0x28, 6), (0x29, 6), (0x2a, 6), (0x7, 5), (0x2b, 6), (0x76, 7), (0x2c, 6), (0x8, 5), (0x9, 5), (0x2d, 6), (0x77, 7), (0x78, 7), (0x79, 7), (0x7a, 7), (0x7b, 7), (0x7ffe, 15), (0x7fc, 11), (0x3ffd, 14), (0x1ffd, 13), (0xffffffc, 28), (0xfffe6, 20), (0x3fffd2, 22), (0xfffe7, 20), (0xfffe8, 20), (0x3fffd3, 22), (0x3fffd4, 22), (0x3fffd5, 22), (0x7fffd9, 23), (0x3fffd6, 22), (0x7fffda, 23), (0x7fffdb, 23), (0x7fffdc, 23), (0x7fffdd, 23), (0x7fffde, 23), (0xffffeb, 24), (0x7fffdf, 23), (0xffffec, 24), (0xffffed, 24), (0x3fffd7, 22), (0x7fffe0, 23), (0xffffee, 24), (0x7fffe1, 23), (0x7fffe2, 23), (0x7fffe3, 23), (0x7fffe4, 23), (0x1fffdc, 21), (0x3fffd8, 22), (0x7fffe5, 23), (0x3fffd9, 22), (0x7fffe6, 23), (0x7fffe7, 23), (0xffffef, 24), (0x3fffda, 22), (0x1fffdd, 21), (0xfffe9, 20), (0x3fffdb, 22), (0x3fffdc, 22), (0x7fffe8, 23), (0x7fffe9, 23), (0x1fffde, 21), (0x7fffea, 23), (0x3fffdd, 22), (0x3fffde, 22), (0xfffff0, 24), (0x1fffdf, 21), (0x3fffdf, 22), (0x7fffeb, 23), (0x7fffec, 23), (0x1fffe0, 21), (0x1fffe1, 21), (0x3fffe0, 22), (0x1fffe2, 21), (0x7fffed, 23), (0x3fffe1, 22), (0x7fffee, 23), (0x7fffef, 23), (0xfffea, 20), (0x3fffe2, 22), (0x3fffe3, 22), (0x3fffe4, 22), (0x7ffff0, 23), (0x3fffe5, 22), (0x3fffe6, 22), (0x7ffff1, 23), (0x3ffffe0, 26), (0x3ffffe1, 26), (0xfffeb, 20), (0x7fff1, 19), (0x3fffe7, 22), (0x7ffff2, 23), (0x3fffe8, 22), (0x1ffffec, 25), (0x3ffffe2, 26), (0x3ffffe3, 26), (0x3ffffe4, 26), (0x7ffffde, 27), (0x7ffffdf, 27), (0x3ffffe5, 26), (0xfffff1, 24), (0x1ffffed, 25), (0x7fff2, 19), (0x1fffe3, 21), (0x3ffffe6, 26), (0x7ffffe0, 27), (0x7ffffe1, 27), (0x3ffffe7, 26), (0x7ffffe2, 27), (0xfffff2, 24), (0x1fffe4, 21), (0x1fffe5, 21), (0x3ffffe8, 26), (0x3ffffe9, 26), (0xffffffd, 28), (0x7ffffe3, 27), (0x7ffffe4, 27), (0x7ffffe5, 27), (0xfffec, 20), (0xfffff3, 24), (0xfffed, 20), (0x1fffe6, 21), (0x3fffe9, 22), (0x1fffe7, 21), (0x1fffe8, 21), (0x7ffff3, 23), (0x3fffea, 22), (0x3fffeb, 22), (0x1ffffee, 25), (0x1ffffef, 25), (0xfffff4, 24), (0xfffff5, 24), (0x3ffffea, 26), (0x7ffff4, 23), (0x3ffffeb, 26), (0x7ffffe6, 27), (0x3ffffec, 26), (0x3ffffed, 26), (0x7ffffe7, 27), (0x7ffffe8, 27), (0x7ffffe9, 27), (0x7ffffea, 27), (0x7ffffeb, 27), (0xffffffe, 28), (0x7ffffec, 27), (0x7ffffed, 27), (0x7ffffee, 27), (0x7ffffef, 27), (0x7fffff0, 27), (0x3ffffee, 26), (0x3fffffff, 30) ] // Great googly-moogly that's a large array! This comes from the nice folks at nghttp. /* This implementation of a Huffman decoding table for HTTP/2 is essentially a Swift port of the C tables from nghttp2's Huffman decoding implementation, and is thus clearly a derivative work of the nghttp2 file ``nghttp2_hd_huffman_data.c``, obtained from https://github.com/tatsuhiro-t/nghttp2/. That work is also available under the Apache 2.0 license under the following terms: Copyright (c) 2013 Tatsuhiro Tsujikawa 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. */ typealias HuffmanDecodeEntry = (state: UInt8, flags: HuffmanDecoderFlags, sym: UInt8) internal struct HuffmanDecoderFlags : OptionSet { var rawValue: UInt8 static let none = HuffmanDecoderFlags([]) static let accepted = HuffmanDecoderFlags(rawValue: 0b001) static let symbol = HuffmanDecoderFlags(rawValue: 0b010) static let failure = HuffmanDecoderFlags(rawValue: 0b100) } /** This was described nicely by `@Lukasa` in his Python implementation: The essence of this approach is that it builds a finite state machine out of 4-bit nybbles of Huffman coded data. The input function passes 4 bits worth of data to the state machine each time, which uses those 4 bits of data along with the current accumulated state data to process the data given. For the sake of efficiency, the in-memory representation of the states, transitions, and result values of the state machine are represented as a long list containing three-tuples. This list is enormously long, and viewing it as an in-memory representation is not very clear, but it is laid out here in a way that is intended to be *somewhat* more clear. Essentially, the list is structured as 256 collections of 16 entries (one for each nybble) of three-tuples. Each collection is called a "node", and the zeroth collection is called the "root node". The state machine tracks one value: the "state" byte. For each nybble passed to the state machine, it first multiplies the "state" byte by 16 and adds the numerical value of the nybble. This number is the index into the large flat list. The three-tuple that is found by looking up that index consists of three values: - a new state value, used for subsequent decoding - a collection of flags, used to determine whether data is emitted or whether the state machine is complete. - the byte value to emit, assuming that emitting a byte is required. The flags are consulted, if necessary a byte is emitted, and then the next nybble is used. This continues until the state machine believes it has completely Huffman-decoded the data. This approach has relatively little indirection, and therefore performs relatively well. The total number of loop iterations is 4x the number of bytes passed to the decoder. */ internal struct HuffmanDecoderTable { subscript(state state: UInt8, nybble nybble: UInt8) -> HuffmanDecodeEntry { assert(nybble < 16) let index = (Int(state) * 16) + Int(nybble) return HuffmanDecoderTable.rawTable[index] } // You would not *believe* how much faster this compiles now. // TODO(jim): decide if it's worth dropping the un-encoded raw bytes into // a segment of the binary, i.e. __DATA,__huffman_decode_table. I don't know // how to do that (automatically) via SwiftPM though, only via Xcode. private static let rawTable: [HuffmanDecodeEntry] = { let base64_table_bytes: StaticString = """ BAAABQAABwAACAAACwAADAAAEAAAEwAAGQAAHAAAIAAAIwAAKgAAMQAAOQAAQAEA AAMwAAMxAAMyAANhAANjAANlAANpAANvAANzAAN0DQAADgAAEQAAEgAAFAAAFQAA AQIwFgMwAQIxFgMxAQIyFgMyAQJhFgNhAQJjFgNjAQJlFgNlAQJpFgNpAQJvFgNv AgIwCQIwFwIwKAMwAgIxCQIxFwIxKAMxAgIyCQIyFwIyKAMyAgJhCQJhFwJhKANh AwIwBgIwCgIwDwIwGAIwHwIwKQIwOAMwAwIxBgIxCgIxDwIxGAIxHwIxKQIxOAMx AwIyBgIyCgIyDwIyGAIyHwIyKQIyOAMyAwJhBgJhCgJhDwJhGAJhHwJhKQJhOANh AgJjCQJjFwJjKANjAgJlCQJlFwJlKANlAgJpCQJpFwJpKANpAgJvCQJvFwJvKANv AwJjBgJjCgJjDwJjGAJjHwJjKQJjOANjAwJlBgJlCgJlDwJlGAJlHwJlKQJlOANl AwJpBgJpCgJpDwJpGAJpHwJpKQJpOANpAwJvBgJvCgJvDwJvGAJvHwJvKQJvOANv AQJzFgNzAQJ0FgN0AAMgAAMlAAMtAAMuAAMvAAMzAAM0AAM1AAM2AAM3AAM4AAM5 AgJzCQJzFwJzKANzAgJ0CQJ0FwJ0KAN0AQIgFgMgAQIlFgMlAQItFgMtAQIuFgMu AwJzBgJzCgJzDwJzGAJzHwJzKQJzOANzAwJ0BgJ0CgJ0DwJ0GAJ0HwJ0KQJ0OAN0 AgIgCQIgFwIgKAMgAgIlCQIlFwIlKAMlAgItCQItFwItKAMtAgIuCQIuFwIuKAMu AwIgBgIgCgIgDwIgGAIgHwIgKQIgOAMgAwIlBgIlCgIlDwIlGAIlHwIlKQIlOAMl AwItBgItCgItDwItGAItHwItKQItOAMtAwIuBgIuCgIuDwIuGAIuHwIuKQIuOAMu AQIvFgMvAQIzFgMzAQI0FgM0AQI1FgM1AQI2FgM2AQI3FgM3AQI4FgM4AQI5FgM5 AgIvCQIvFwIvKAMvAgIzCQIzFwIzKAMzAgI0CQI0FwI0KAM0AgI1CQI1FwI1KAM1 AwIvBgIvCgIvDwIvGAIvHwIvKQIvOAMvAwIzBgIzCgIzDwIzGAIzHwIzKQIzOAMz AwI0BgI0CgI0DwI0GAI0HwI0KQI0OAM0AwI1BgI1CgI1DwI1GAI1HwI1KQI1OAM1 AgI2CQI2FwI2KAM2AgI3CQI3FwI3KAM3AgI4CQI4FwI4KAM4AgI5CQI5FwI5KAM5 AwI2BgI2CgI2DwI2GAI2HwI2KQI2OAM2AwI3BgI3CgI3DwI3GAI3HwI3KQI3OAM3 AwI4BgI4CgI4DwI4GAI4HwI4KQI4OAM4AwI5BgI5CgI5DwI5GAI5HwI5KQI5OAM5 GgAAGwAAHQAAHgAAIQAAIgAAJAAAJQAAKwAALgAAMgAANQAAOgAAPQAAQQAARAEA AAM9AANBAANfAANiAANkAANmAANnAANoAANsAANtAANuAANwAANyAAN1JgAAJwAA AQI9FgM9AQJBFgNBAQJfFgNfAQJiFgNiAQJkFgNkAQJmFgNmAQJnFgNnAQJoFgNo AgI9CQI9FwI9KAM9AgJBCQJBFwJBKANBAgJfCQJfFwJfKANfAgJiCQJiFwJiKANi AwI9BgI9CgI9DwI9GAI9HwI9KQI9OAM9AwJBBgJBCgJBDwJBGAJBHwJBKQJBOANB AwJfBgJfCgJfDwJfGAJfHwJfKQJfOANfAwJiBgJiCgJiDwJiGAJiHwJiKQJiOANi AgJkCQJkFwJkKANkAgJmCQJmFwJmKANmAgJnCQJnFwJnKANnAgJoCQJoFwJoKANo AwJkBgJkCgJkDwJkGAJkHwJkKQJkOANkAwJmBgJmCgJmDwJmGAJmHwJmKQJmOANm AwJnBgJnCgJnDwJnGAJnHwJnKQJnOANnAwJoBgJoCgJoDwJoGAJoHwJoKQJoOANo AQJsFgNsAQJtFgNtAQJuFgNuAQJwFgNwAQJyFgNyAQJ1FgN1AAM6AANCAANDAANE AgJsCQJsFwJsKANsAgJtCQJtFwJtKANtAgJuCQJuFwJuKANuAgJwCQJwFwJwKANw AwJsBgJsCgJsDwJsGAJsHwJsKQJsOANsAwJtBgJtCgJtDwJtGAJtHwJtKQJtOANt AwJuBgJuCgJuDwJuGAJuHwJuKQJuOANuAwJwBgJwCgJwDwJwGAJwHwJwKQJwOANw AgJyCQJyFwJyKANyAgJ1CQJ1FwJ1KAN1AQI6FgM6AQJCFgNCAQJDFgNDAQJEFgNE AwJyBgJyCgJyDwJyGAJyHwJyKQJyOANyAwJ1BgJ1CgJ1DwJ1GAJ1HwJ1KQJ1OAN1 AgI6CQI6FwI6KAM6AgJCCQJCFwJCKANCAgJDCQJDFwJDKANDAgJECQJEFwJEKANE AwI6BgI6CgI6DwI6GAI6HwI6KQI6OAM6AwJCBgJCCgJCDwJCGAJCHwJCKQJCOANC AwJDBgJDCgJDDwJDGAJDHwJDKQJDOANDAwJEBgJECgJEDwJEGAJEHwJEKQJEOANE LAAALQAALwAAMAAAMwAANAAANgAANwAAOwAAPAAAPgAAPwAAQgAAQwAARQAASAEA AANFAANGAANHAANIAANJAANKAANLAANMAANNAANOAANPAANQAANRAANSAANTAANU AQJFFgNFAQJGFgNGAQJHFgNHAQJIFgNIAQJJFgNJAQJKFgNKAQJLFgNLAQJMFgNM AgJFCQJFFwJFKANFAgJGCQJGFwJGKANGAgJHCQJHFwJHKANHAgJICQJIFwJIKANI AwJFBgJFCgJFDwJFGAJFHwJFKQJFOANFAwJGBgJGCgJGDwJGGAJGHwJGKQJGOANG AwJHBgJHCgJHDwJHGAJHHwJHKQJHOANHAwJIBgJICgJIDwJIGAJIHwJIKQJIOANI AgJJCQJJFwJJKANJAgJKCQJKFwJKKANKAgJLCQJLFwJLKANLAgJMCQJMFwJMKANM AwJJBgJJCgJJDwJJGAJJHwJJKQJJOANJAwJKBgJKCgJKDwJKGAJKHwJKKQJKOANK AwJLBgJLCgJLDwJLGAJLHwJLKQJLOANLAwJMBgJMCgJMDwJMGAJMHwJMKQJMOANM AQJNFgNNAQJOFgNOAQJPFgNPAQJQFgNQAQJRFgNRAQJSFgNSAQJTFgNTAQJUFgNU AgJNCQJNFwJNKANNAgJOCQJOFwJOKANOAgJPCQJPFwJPKANPAgJQCQJQFwJQKANQ AwJNBgJNCgJNDwJNGAJNHwJNKQJNOANNAwJOBgJOCgJODwJOGAJOHwJOKQJOOANO AwJPBgJPCgJPDwJPGAJPHwJPKQJPOANPAwJQBgJQCgJQDwJQGAJQHwJQKQJQOANQ AgJRCQJRFwJRKANRAgJSCQJSFwJSKANSAgJTCQJTFwJTKANTAgJUCQJUFwJUKANU AwJRBgJRCgJRDwJRGAJRHwJRKQJROANRAwJSBgJSCgJSDwJSGAJSHwJSKQJSOANS AwJTBgJTCgJTDwJTGAJTHwJTKQJTOANTAwJUBgJUCgJUDwJUGAJUHwJUKQJUOANU AANVAANWAANXAANZAANqAANrAANxAAN2AAN3AAN4AAN5AAN6RgAARwAASQAASgEA AQJVFgNVAQJWFgNWAQJXFgNXAQJZFgNZAQJqFgNqAQJrFgNrAQJxFgNxAQJ2FgN2 AgJVCQJVFwJVKANVAgJWCQJWFwJWKANWAgJXCQJXFwJXKANXAgJZCQJZFwJZKANZ AwJVBgJVCgJVDwJVGAJVHwJVKQJVOANVAwJWBgJWCgJWDwJWGAJWHwJWKQJWOANW AwJXBgJXCgJXDwJXGAJXHwJXKQJXOANXAwJZBgJZCgJZDwJZGAJZHwJZKQJZOANZ AgJqCQJqFwJqKANqAgJrCQJrFwJrKANrAgJxCQJxFwJxKANxAgJ2CQJ2FwJ2KAN2 AwJqBgJqCgJqDwJqGAJqHwJqKQJqOANqAwJrBgJrCgJrDwJrGAJrHwJrKQJrOANr AwJxBgJxCgJxDwJxGAJxHwJxKQJxOANxAwJ2BgJ2CgJ2DwJ2GAJ2HwJ2KQJ2OAN2 AQJ3FgN3AQJ4FgN4AQJ5FgN5AQJ6FgN6AAMmAAMqAAMsAAM7AANYAANaSwAATgAA AgJ3CQJ3FwJ3KAN3AgJ4CQJ4FwJ4KAN4AgJ5CQJ5FwJ5KAN5AgJ6CQJ6FwJ6KAN6 AwJ3BgJ3CgJ3DwJ3GAJ3HwJ3KQJ3OAN3AwJ4BgJ4CgJ4DwJ4GAJ4HwJ4KQJ4OAN4 AwJ5BgJ5CgJ5DwJ5GAJ5HwJ5KQJ5OAN5AwJ6BgJ6CgJ6DwJ6GAJ6HwJ6KQJ6OAN6 AQImFgMmAQIqFgMqAQIsFgMsAQI7FgM7AQJYFgNYAQJaFgNaTAAATQAATwAAUQAA AgImCQImFwImKAMmAgIqCQIqFwIqKAMqAgIsCQIsFwIsKAMsAgI7CQI7FwI7KAM7 AwImBgImCgImDwImGAImHwImKQImOAMmAwIqBgIqCgIqDwIqGAIqHwIqKQIqOAMq AwIsBgIsCgIsDwIsGAIsHwIsKQIsOAMsAwI7BgI7CgI7DwI7GAI7HwI7KQI7OAM7 AgJYCQJYFwJYKANYAgJaCQJaFwJaKANaAAMhAAMiAAMoAAMpAAM/UAAAUgAAVAAA AwJYBgJYCgJYDwJYGAJYHwJYKQJYOANYAwJaBgJaCgJaDwJaGAJaHwJaKQJaOANa AQIhFgMhAQIiFgMiAQIoFgMoAQIpFgMpAQI/FgM/AAMnAAMrAAN8UwAAVQAAWAAA AgIhCQIhFwIhKAMhAgIiCQIiFwIiKAMiAgIoCQIoFwIoKAMoAgIpCQIpFwIpKAMp AwIhBgIhCgIhDwIhGAIhHwIhKQIhOAMhAwIiBgIiCgIiDwIiGAIiHwIiKQIiOAMi AwIoBgIoCgIoDwIoGAIoHwIoKQIoOAMoAwIpBgIpCgIpDwIpGAIpHwIpKQIpOAMp AgI/CQI/FwI/KAM/AQInFgMnAQIrFgMrAQJ8FgN8AAMjAAM+VgAAVwAAWQAAWgAA AwI/BgI/CgI/DwI/GAI/HwI/KQI/OAM/AgInCQInFwInKAMnAgIrCQIrFwIrKAMr AwInBgInCgInDwInGAInHwInKQInOAMnAwIrBgIrCgIrDwIrGAIrHwIrKQIrOAMr AgJ8CQJ8FwJ8KAN8AQIjFgMjAQI+FgM+AAMAAAMkAANAAANbAANdAAN+WwAAXAAA AwJ8BgJ8CgJ8DwJ8GAJ8HwJ8KQJ8OAN8AgIjCQIjFwIjKAMjAgI+CQI+FwI+KAM+ AwIjBgIjCgIjDwIjGAIjHwIjKQIjOAMjAwI+BgI+CgI+DwI+GAI+HwI+KQI+OAM+ AQIAFgMAAQIkFgMkAQJAFgNAAQJbFgNbAQJdFgNdAQJ+FgN+AANeAAN9XQAAXgAA AgIACQIAFwIAKAMAAgIkCQIkFwIkKAMkAgJACQJAFwJAKANAAgJbCQJbFwJbKANb AwIABgIACgIADwIAGAIAHwIAKQIAOAMAAwIkBgIkCgIkDwIkGAIkHwIkKQIkOAMk AwJABgJACgJADwJAGAJAHwJAKQJAOANAAwJbBgJbCgJbDwJbGAJbHwJbKQJbOANb AgJdCQJdFwJdKANdAgJ+CQJ+FwJ+KAN+AQJeFgNeAQJ9FgN9AAM8AANgAAN7XwAA AwJdBgJdCgJdDwJdGAJdHwJdKQJdOANdAwJ+BgJ+CgJ+DwJ+GAJ+HwJ+KQJ+OAN+ AgJeCQJeFwJeKANeAgJ9CQJ9FwJ9KAN9AQI8FgM8AQJgFgNgAQJ7FgN7YAAAbgAA AwJeBgJeCgJeDwJeGAJeHwJeKQJeOANeAwJ9BgJ9CgJ9DwJ9GAJ9HwJ9KQJ9OAN9 AgI8CQI8FwI8KAM8AgJgCQJgFwJgKANgAgJ7CQJ7FwJ7KAN7YQAAZQAAbwAAhQAA AwI8BgI8CgI8DwI8GAI8HwI8KQI8OAM8AwJgBgJgCgJgDwJgGAJgHwJgKQJgOANg AwJ7BgJ7CgJ7DwJ7GAJ7HwJ7KQJ7OAN7YgAAYwAAZgAAaQAAcAAAdwAAhgAAmQAA AANcAAPDAAPQZAAAZwAAaAAAagAAawAAcQAAdAAAeAAAfgAAhwAAjgAAmgAAqQAA AQJcFgNcAQLDFgPDAQLQFgPQAAOAAAOCAAODAAOiAAO4AAPCAAPgAAPibAAAbQAA AgJcCQJcFwJcKANcAgLDCQLDFwLDKAPDAgLQCQLQFwLQKAPQAQKAFgOAAQKCFgOC AwJcBgJcCgJcDwJcGAJcHwJcKQJcOANcAwLDBgLDCgLDDwLDGALDHwLDKQLDOAPD AwLQBgLQCgLQDwLQGALQHwLQKQLQOAPQAgKACQKAFwKAKAOAAgKCCQKCFwKCKAOC AwKABgKACgKADwKAGAKAHwKAKQKAOAOAAwKCBgKCCgKCDwKCGAKCHwKCKQKCOAOC AQKDFgODAQKiFgOiAQK4FgO4AQLCFgPCAQLgFgPgAQLiFgPiAAOZAAOhAAOnAAOs AgKDCQKDFwKDKAODAgKiCQKiFwKiKAOiAgK4CQK4FwK4KAO4AgLCCQLCFwLCKAPC AwKDBgKDCgKDDwKDGAKDHwKDKQKDOAODAwKiBgKiCgKiDwKiGAKiHwKiKQKiOAOi AwK4BgK4CgK4DwK4GAK4HwK4KQK4OAO4AwLCBgLCCgLCDwLCGALCHwLCKQLCOAPC AgLgCQLgFwLgKAPgAgLiCQLiFwLiKAPiAQKZFgOZAQKhFgOhAQKnFgOnAQKsFgOs AwLgBgLgCgLgDwLgGALgHwLgKQLgOAPgAwLiBgLiCgLiDwLiGALiHwLiKQLiOAPi AgKZCQKZFwKZKAOZAgKhCQKhFwKhKAOhAgKnCQKnFwKnKAOnAgKsCQKsFwKsKAOs AwKZBgKZCgKZDwKZGAKZHwKZKQKZOAOZAwKhBgKhCgKhDwKhGAKhHwKhKQKhOAOh AwKnBgKnCgKnDwKnGAKnHwKnKQKnOAOnAwKsBgKsCgKsDwKsGAKsHwKsKQKsOAOs cgAAcwAAdQAAdgAAeQAAewAAfwAAggAAiAAAiwAAjwAAkgAAmwAAogAAqgAAtAAA AAOwAAOxAAOzAAPRAAPYAAPZAAPjAAPlAAPmegAAfAAAfQAAgAAAgQAAgwAAhAAA AQKwFgOwAQKxFgOxAQKzFgOzAQLRFgPRAQLYFgPYAQLZFgPZAQLjFgPjAQLlFgPl AgKwCQKwFwKwKAOwAgKxCQKxFwKxKAOxAgKzCQKzFwKzKAOzAgLRCQLRFwLRKAPR AwKwBgKwCgKwDwKwGAKwHwKwKQKwOAOwAwKxBgKxCgKxDwKxGAKxHwKxKQKxOAOx AwKzBgKzCgKzDwKzGAKzHwKzKQKzOAOzAwLRBgLRCgLRDwLRGALRHwLRKQLROAPR AgLYCQLYFwLYKAPYAgLZCQLZFwLZKAPZAgLjCQLjFwLjKAPjAgLlCQLlFwLlKAPl AwLYBgLYCgLYDwLYGALYHwLYKQLYOAPYAwLZBgLZCgLZDwLZGALZHwLZKQLZOAPZ AwLjBgLjCgLjDwLjGALjHwLjKQLjOAPjAwLlBgLlCgLlDwLlGALlHwLlKQLlOAPl AQLmFgPmAAOBAAOEAAOFAAOGAAOIAAOSAAOaAAOcAAOgAAOjAAOkAAOpAAOqAAOt AgLmCQLmFwLmKAPmAQKBFgOBAQKEFgOEAQKFFgOFAQKGFgOGAQKIFgOIAQKSFgOS AwLmBgLmCgLmDwLmGALmHwLmKQLmOAPmAgKBCQKBFwKBKAOBAgKECQKEFwKEKAOE AwKBBgKBCgKBDwKBGAKBHwKBKQKBOAOBAwKEBgKECgKEDwKEGAKEHwKEKQKEOAOE AgKFCQKFFwKFKAOFAgKGCQKGFwKGKAOGAgKICQKIFwKIKAOIAgKSCQKSFwKSKAOS AwKFBgKFCgKFDwKFGAKFHwKFKQKFOAOFAwKGBgKGCgKGDwKGGAKGHwKGKQKGOAOG AwKIBgKICgKIDwKIGAKIHwKIKQKIOAOIAwKSBgKSCgKSDwKSGAKSHwKSKQKSOAOS AQKaFgOaAQKcFgOcAQKgFgOgAQKjFgOjAQKkFgOkAQKpFgOpAQKqFgOqAQKtFgOt AgKaCQKaFwKaKAOaAgKcCQKcFwKcKAOcAgKgCQKgFwKgKAOgAgKjCQKjFwKjKAOj AwKaBgKaCgKaDwKaGAKaHwKaKQKaOAOaAwKcBgKcCgKcDwKcGAKcHwKcKQKcOAOc AwKgBgKgCgKgDwKgGAKgHwKgKQKgOAOgAwKjBgKjCgKjDwKjGAKjHwKjKQKjOAOj AgKkCQKkFwKkKAOkAgKpCQKpFwKpKAOpAgKqCQKqFwKqKAOqAgKtCQKtFwKtKAOt AwKkBgKkCgKkDwKkGAKkHwKkKQKkOAOkAwKpBgKpCgKpDwKpGAKpHwKpKQKpOAOp AwKqBgKqCgKqDwKqGAKqHwKqKQKqOAOqAwKtBgKtCgKtDwKtGAKtHwKtKQKtOAOt iQAAigAAjAAAjQAAkAAAkQAAkwAAlgAAnAAAnwAAowAApgAAqwAArgAAtQAAvgAA AAOyAAO1AAO5AAO6AAO7AAO9AAO+AAPEAAPGAAPkAAPoAAPplAAAlQAAlwAAmAAA AQKyFgOyAQK1FgO1AQK5FgO5AQK6FgO6AQK7FgO7AQK9FgO9AQK+FgO+AQLEFgPE AgKyCQKyFwKyKAOyAgK1CQK1FwK1KAO1AgK5CQK5FwK5KAO5AgK6CQK6FwK6KAO6 AwKyBgKyCgKyDwKyGAKyHwKyKQKyOAOyAwK1BgK1CgK1DwK1GAK1HwK1KQK1OAO1 AwK5BgK5CgK5DwK5GAK5HwK5KQK5OAO5AwK6BgK6CgK6DwK6GAK6HwK6KQK6OAO6 AgK7CQK7FwK7KAO7AgK9CQK9FwK9KAO9AgK+CQK+FwK+KAO+AgLECQLEFwLEKAPE AwK7BgK7CgK7DwK7GAK7HwK7KQK7OAO7AwK9BgK9CgK9DwK9GAK9HwK9KQK9OAO9 AwK+BgK+CgK+DwK+GAK+HwK+KQK+OAO+AwLEBgLECgLEDwLEGALEHwLEKQLEOAPE AQLGFgPGAQLkFgPkAQLoFgPoAQLpFgPpAAMBAAOHAAOJAAOKAAOLAAOMAAONAAOP AgLGCQLGFwLGKAPGAgLkCQLkFwLkKAPkAgLoCQLoFwLoKAPoAgLpCQLpFwLpKAPp AwLGBgLGCgLGDwLGGALGHwLGKQLGOAPGAwLkBgLkCgLkDwLkGALkHwLkKQLkOAPk AwLoBgLoCgLoDwLoGALoHwLoKQLoOAPoAwLpBgLpCgLpDwLpGALpHwLpKQLpOAPp AQIBFgMBAQKHFgOHAQKJFgOJAQKKFgOKAQKLFgOLAQKMFgOMAQKNFgONAQKPFgOP AgIBCQIBFwIBKAMBAgKHCQKHFwKHKAOHAgKJCQKJFwKJKAOJAgKKCQKKFwKKKAOK AwIBBgIBCgIBDwIBGAIBHwIBKQIBOAMBAwKHBgKHCgKHDwKHGAKHHwKHKQKHOAOH AwKJBgKJCgKJDwKJGAKJHwKJKQKJOAOJAwKKBgKKCgKKDwKKGAKKHwKKKQKKOAOK AgKLCQKLFwKLKAOLAgKMCQKMFwKMKAOMAgKNCQKNFwKNKAONAgKPCQKPFwKPKAOP AwKLBgKLCgKLDwKLGAKLHwKLKQKLOAOLAwKMBgKMCgKMDwKMGAKMHwKMKQKMOAOM AwKNBgKNCgKNDwKNGAKNHwKNKQKNOAONAwKPBgKPCgKPDwKPGAKPHwKPKQKPOAOP nQAAngAAoAAAoQAApAAApQAApwAAqAAArAAArQAArwAAsQAAtgAAuQAAvwAAzwAA AAOTAAOVAAOWAAOXAAOYAAObAAOdAAOeAAOlAAOmAAOoAAOuAAOvAAO0AAO2AAO3 AQKTFgOTAQKVFgOVAQKWFgOWAQKXFgOXAQKYFgOYAQKbFgObAQKdFgOdAQKeFgOe AgKTCQKTFwKTKAOTAgKVCQKVFwKVKAOVAgKWCQKWFwKWKAOWAgKXCQKXFwKXKAOX AwKTBgKTCgKTDwKTGAKTHwKTKQKTOAOTAwKVBgKVCgKVDwKVGAKVHwKVKQKVOAOV AwKWBgKWCgKWDwKWGAKWHwKWKQKWOAOWAwKXBgKXCgKXDwKXGAKXHwKXKQKXOAOX AgKYCQKYFwKYKAOYAgKbCQKbFwKbKAObAgKdCQKdFwKdKAOdAgKeCQKeFwKeKAOe AwKYBgKYCgKYDwKYGAKYHwKYKQKYOAOYAwKbBgKbCgKbDwKbGAKbHwKbKQKbOAOb AwKdBgKdCgKdDwKdGAKdHwKdKQKdOAOdAwKeBgKeCgKeDwKeGAKeHwKeKQKeOAOe AQKlFgOlAQKmFgOmAQKoFgOoAQKuFgOuAQKvFgOvAQK0FgO0AQK2FgO2AQK3FgO3 AgKlCQKlFwKlKAOlAgKmCQKmFwKmKAOmAgKoCQKoFwKoKAOoAgKuCQKuFwKuKAOu AwKlBgKlCgKlDwKlGAKlHwKlKQKlOAOlAwKmBgKmCgKmDwKmGAKmHwKmKQKmOAOm AwKoBgKoCgKoDwKoGAKoHwKoKQKoOAOoAwKuBgKuCgKuDwKuGAKuHwKuKQKuOAOu AgKvCQKvFwKvKAOvAgK0CQK0FwK0KAO0AgK2CQK2FwK2KAO2AgK3CQK3FwK3KAO3 AwKvBgKvCgKvDwKvGAKvHwKvKQKvOAOvAwK0BgK0CgK0DwK0GAK0HwK0KQK0OAO0 AwK2BgK2CgK2DwK2GAK2HwK2KQK2OAO2AwK3BgK3CgK3DwK3GAK3HwK3KQK3OAO3 AAO8AAO/AAPFAAPnAAPvsAAAsgAAswAAtwAAuAAAugAAuwAAwAAAxwAA0AAA3wAA AQK8FgO8AQK/FgO/AQLFFgPFAQLnFgPnAQLvFgPvAAMJAAOOAAOQAAORAAOUAAOf AgK8CQK8FwK8KAO8AgK/CQK/FwK/KAO/AgLFCQLFFwLFKAPFAgLnCQLnFwLnKAPn AwK8BgK8CgK8DwK8GAK8HwK8KQK8OAO8AwK/BgK/CgK/DwK/GAK/HwK/KQK/OAO/ AwLFBgLFCgLFDwLFGALFHwLFKQLFOAPFAwLnBgLnCgLnDwLnGALnHwLnKQLnOAPn AgLvCQLvFwLvKAPvAQIJFgMJAQKOFgOOAQKQFgOQAQKRFgORAQKUFgOUAQKfFgOf AwLvBgLvCgLvDwLvGALvHwLvKQLvOAPvAgIJCQIJFwIJKAMJAgKOCQKOFwKOKAOO AwIJBgIJCgIJDwIJGAIJHwIJKQIJOAMJAwKOBgKOCgKODwKOGAKOHwKOKQKOOAOO AgKQCQKQFwKQKAOQAgKRCQKRFwKRKAORAgKUCQKUFwKUKAOUAgKfCQKfFwKfKAOf AwKQBgKQCgKQDwKQGAKQHwKQKQKQOAOQAwKRBgKRCgKRDwKRGAKRHwKRKQKROAOR AwKUBgKUCgKUDwKUGAKUHwKUKQKUOAOUAwKfBgKfCgKfDwKfGAKfHwKfKQKfOAOf AAOrAAPOAAPXAAPhAAPsAAPtvAAAvQAAwQAAxAAAyAAAywAA0QAA2AAA4AAA7gAA AQKrFgOrAQLOFgPOAQLXFgPXAQLhFgPhAQLsFgPsAQLtFgPtAAPHAAPPAAPqAAPr AgKrCQKrFwKrKAOrAgLOCQLOFwLOKAPOAgLXCQLXFwLXKAPXAgLhCQLhFwLhKAPh AwKrBgKrCgKrDwKrGAKrHwKrKQKrOAOrAwLOBgLOCgLODwLOGALOHwLOKQLOOAPO AwLXBgLXCgLXDwLXGALXHwLXKQLXOAPXAwLhBgLhCgLhDwLhGALhHwLhKQLhOAPh AgLsCQLsFwLsKAPsAgLtCQLtFwLtKAPtAQLHFgPHAQLPFgPPAQLqFgPqAQLrFgPr AwLsBgLsCgLsDwLsGALsHwLsKQLsOAPsAwLtBgLtCgLtDwLtGALtHwLtKQLtOAPt AgLHCQLHFwLHKAPHAgLPCQLPFwLPKAPPAgLqCQLqFwLqKAPqAgLrCQLrFwLrKAPr AwLHBgLHCgLHDwLHGALHHwLHKQLHOAPHAwLPBgLPCgLPDwLPGALPHwLPKQLPOAPP AwLqBgLqCgLqDwLqGALqHwLqKQLqOAPqAwLrBgLrCgLrDwLrGALrHwLrKQLrOAPr wgAAwwAAxQAAxgAAyQAAygAAzAAAzQAA0gAA1QAA2QAA3AAA4QAA5wAA7wAA9gAA AAPAAAPBAAPIAAPJAAPKAAPNAAPSAAPVAAPaAAPbAAPuAAPwAAPyAAPzAAP/zgAA AQLAFgPAAQLBFgPBAQLIFgPIAQLJFgPJAQLKFgPKAQLNFgPNAQLSFgPSAQLVFgPV AgLACQLAFwLAKAPAAgLBCQLBFwLBKAPBAgLICQLIFwLIKAPIAgLJCQLJFwLJKAPJ AwLABgLACgLADwLAGALAHwLAKQLAOAPAAwLBBgLBCgLBDwLBGALBHwLBKQLBOAPB AwLIBgLICgLIDwLIGALIHwLIKQLIOAPIAwLJBgLJCgLJDwLJGALJHwLJKQLJOAPJ AgLKCQLKFwLKKAPKAgLNCQLNFwLNKAPNAgLSCQLSFwLSKAPSAgLVCQLVFwLVKAPV AwLKBgLKCgLKDwLKGALKHwLKKQLKOAPKAwLNBgLNCgLNDwLNGALNHwLNKQLNOAPN AwLSBgLSCgLSDwLSGALSHwLSKQLSOAPSAwLVBgLVCgLVDwLVGALVHwLVKQLVOAPV AQLaFgPaAQLbFgPbAQLuFgPuAQLwFgPwAQLyFgPyAQLzFgPzAQL/FgP/AAPLAAPM AgLaCQLaFwLaKAPaAgLbCQLbFwLbKAPbAgLuCQLuFwLuKAPuAgLwCQLwFwLwKAPw AwLaBgLaCgLaDwLaGALaHwLaKQLaOAPaAwLbBgLbCgLbDwLbGALbHwLbKQLbOAPb AwLuBgLuCgLuDwLuGALuHwLuKQLuOAPuAwLwBgLwCgLwDwLwGALwHwLwKQLwOAPw AgLyCQLyFwLyKAPyAgLzCQLzFwLzKAPzAgL/CQL/FwL/KAP/AQLLFgPLAQLMFgPM AwLyBgLyCgLyDwLyGALyHwLyKQLyOAPyAwLzBgLzCgLzDwLzGALzHwLzKQLzOAPz AwL/BgL/CgL/DwL/GAL/HwL/KQL/OAP/AgLLCQLLFwLLKAPLAgLMCQLMFwLMKAPM AwLLBgLLCgLLDwLLGALLHwLLKQLLOAPLAwLMBgLMCgLMDwLMGALMHwLMKQLMOAPM 0wAA1AAA1gAA1wAA2gAA2wAA3QAA3gAA4gAA5AAA6AAA6wAA8AAA8wAA9wAA+gAA AAPTAAPUAAPWAAPdAAPeAAPfAAPxAAP0AAP1AAP2AAP3AAP4AAP6AAP7AAP8AAP9 AQLTFgPTAQLUFgPUAQLWFgPWAQLdFgPdAQLeFgPeAQLfFgPfAQLxFgPxAQL0FgP0 AgLTCQLTFwLTKAPTAgLUCQLUFwLUKAPUAgLWCQLWFwLWKAPWAgLdCQLdFwLdKAPd AwLTBgLTCgLTDwLTGALTHwLTKQLTOAPTAwLUBgLUCgLUDwLUGALUHwLUKQLUOAPU AwLWBgLWCgLWDwLWGALWHwLWKQLWOAPWAwLdBgLdCgLdDwLdGALdHwLdKQLdOAPd AgLeCQLeFwLeKAPeAgLfCQLfFwLfKAPfAgLxCQLxFwLxKAPxAgL0CQL0FwL0KAP0 AwLeBgLeCgLeDwLeGALeHwLeKQLeOAPeAwLfBgLfCgLfDwLfGALfHwLfKQLfOAPf AwLxBgLxCgLxDwLxGALxHwLxKQLxOAPxAwL0BgL0CgL0DwL0GAL0HwL0KQL0OAP0 AQL1FgP1AQL2FgP2AQL3FgP3AQL4FgP4AQL6FgP6AQL7FgP7AQL8FgP8AQL9FgP9 AgL1CQL1FwL1KAP1AgL2CQL2FwL2KAP2AgL3CQL3FwL3KAP3AgL4CQL4FwL4KAP4 AwL1BgL1CgL1DwL1GAL1HwL1KQL1OAP1AwL2BgL2CgL2DwL2GAL2HwL2KQL2OAP2 AwL3BgL3CgL3DwL3GAL3HwL3KQL3OAP3AwL4BgL4CgL4DwL4GAL4HwL4KQL4OAP4 AgL6CQL6FwL6KAP6AgL7CQL7FwL7KAP7AgL8CQL8FwL8KAP8AgL9CQL9FwL9KAP9 AwL6BgL6CgL6DwL6GAL6HwL6KQL6OAP6AwL7BgL7CgL7DwL7GAL7HwL7KQL7OAP7 AwL8BgL8CgL8DwL8GAL8HwL8KQL8OAP8AwL9BgL9CgL9DwL9GAL9HwL9KQL9OAP9 AAP+4wAA5QAA5gAA6QAA6gAA7AAA7QAA8QAA8gAA9AAA9QAA+AAA+QAA+wAA/AAA AQL+FgP+AAMCAAMDAAMEAAMFAAMGAAMHAAMIAAMLAAMMAAMOAAMPAAMQAAMRAAMS AgL+CQL+FwL+KAP+AQICFgMCAQIDFgMDAQIEFgMEAQIFFgMFAQIGFgMGAQIHFgMH AwL+BgL+CgL+DwL+GAL+HwL+KQL+OAP+AgICCQICFwICKAMCAgIDCQIDFwIDKAMD AwICBgICCgICDwICGAICHwICKQICOAMCAwIDBgIDCgIDDwIDGAIDHwIDKQIDOAMD AgIECQIEFwIEKAMEAgIFCQIFFwIFKAMFAgIGCQIGFwIGKAMGAgIHCQIHFwIHKAMH AwIEBgIECgIEDwIEGAIEHwIEKQIEOAMEAwIFBgIFCgIFDwIFGAIFHwIFKQIFOAMF AwIGBgIGCgIGDwIGGAIGHwIGKQIGOAMGAwIHBgIHCgIHDwIHGAIHHwIHKQIHOAMH AQIIFgMIAQILFgMLAQIMFgMMAQIOFgMOAQIPFgMPAQIQFgMQAQIRFgMRAQISFgMS AgIICQIIFwIIKAMIAgILCQILFwILKAMLAgIMCQIMFwIMKAMMAgIOCQIOFwIOKAMO AwIIBgIICgIIDwIIGAIIHwIIKQIIOAMIAwILBgILCgILDwILGAILHwILKQILOAML AwIMBgIMCgIMDwIMGAIMHwIMKQIMOAMMAwIOBgIOCgIODwIOGAIOHwIOKQIOOAMO AgIPCQIPFwIPKAMPAgIQCQIQFwIQKAMQAgIRCQIRFwIRKAMRAgISCQISFwISKAMS AwIPBgIPCgIPDwIPGAIPHwIPKQIPOAMPAwIQBgIQCgIQDwIQGAIQHwIQKQIQOAMQ AwIRBgIRCgIRDwIRGAIRHwIRKQIROAMRAwISBgISCgISDwISGAISHwISKQISOAMS AAMTAAMUAAMVAAMXAAMYAAMZAAMaAAMbAAMcAAMdAAMeAAMfAAN/AAPcAAP5/QAA AQITFgMTAQIUFgMUAQIVFgMVAQIXFgMXAQIYFgMYAQIZFgMZAQIaFgMaAQIbFgMb AgITCQITFwITKAMTAgIUCQIUFwIUKAMUAgIVCQIVFwIVKAMVAgIXCQIXFwIXKAMX AwITBgITCgITDwITGAITHwITKQITOAMTAwIUBgIUCgIUDwIUGAIUHwIUKQIUOAMU AwIVBgIVCgIVDwIVGAIVHwIVKQIVOAMVAwIXBgIXCgIXDwIXGAIXHwIXKQIXOAMX AgIYCQIYFwIYKAMYAgIZCQIZFwIZKAMZAgIaCQIaFwIaKAMaAgIbCQIbFwIbKAMb AwIYBgIYCgIYDwIYGAIYHwIYKQIYOAMYAwIZBgIZCgIZDwIZGAIZHwIZKQIZOAMZ AwIaBgIaCgIaDwIaGAIaHwIaKQIaOAMaAwIbBgIbCgIbDwIbGAIbHwIbKQIbOAMb AQIcFgMcAQIdFgMdAQIeFgMeAQIfFgMfAQJ/FgN/AQLcFgPcAQL5FgP5/gAA/wAA AgIcCQIcFwIcKAMcAgIdCQIdFwIdKAMdAgIeCQIeFwIeKAMeAgIfCQIfFwIfKAMf AwIcBgIcCgIcDwIcGAIcHwIcKQIcOAMcAwIdBgIdCgIdDwIdGAIdHwIdKQIdOAMd AwIeBgIeCgIeDwIeGAIeHwIeKQIeOAMeAwIfBgIfCgIfDwIfGAIfHwIfKQIfOAMf AgJ/CQJ/FwJ/KAN/AgLcCQLcFwLcKAPcAgL5CQL5FwL5KAP5AAMKAAMNAAMWAAQA AwJ/BgJ/CgJ/DwJ/GAJ/HwJ/KQJ/OAN/AwLcBgLcCgLcDwLcGALcHwLcKQLcOAPc AwL5BgL5CgL5DwL5GAL5HwL5KQL5OAP5AQIKFgMKAQINFgMNAQIWFgMWAAQAAAQA AgIKCQIKFwIKKAMKAgINCQINFwINKAMNAgIWCQIWFwIWKAMWAAQAAAQAAAQAAAQA AwIKBgIKCgIKDwIKGAIKHwIKKQIKOAMKAwINBgINCgINDwINGAINHwINKQINOAMN AwIWBgIWCgIWDwIWGAIWHwIWKQIWOAMWAAQAAAQAAAQAAAQAAAQAAAQAAAQAAAQA """ return base64_table_bytes.withUTF8Buffer { buf in // ignore newlines in the input guard let result = base64DecodeBytes(buf, ignoreUnknownCharacters: true) else { fatalError("Failed to decode huffman decoder table from base-64 encoding") } return result.withUnsafeBytes { ptr in assert(ptr.count % 3 == 0) let dptr = ptr.baseAddress!.assumingMemoryBound(to: HuffmanDecodeEntry.self) let dbuf = UnsafeBufferPointer(start: dptr, count: ptr.count / 3) return Array(dbuf) } } }() // for posterity, here's what the table effectively looks like: /* private static let rawTable: [HuffmanDecodeEntry] = [ /* 0 */ (4, .none, 0), (5, .none, 0), (7, .none, 0), (8, .none, 0), (11, .none, 0), (12, .none, 0), (16, .none, 0), (19, .none, 0), (25, .none, 0), (28, .none, 0), (32, .none, 0), (35, .none, 0), (42, .none, 0), (49, .none, 0), (57, .none, 0), (64, .accepted, 0), /* 1 */ (0, [.accepted, .symbol], 48), (0, [.accepted, .symbol], 49), (0, [.accepted, .symbol], 50), (0, [.accepted, .symbol], 97), (0, [.accepted, .symbol], 99), (0, [.accepted, .symbol], 101), (0, [.accepted, .symbol], 105), (0, [.accepted, .symbol], 111), (0, [.accepted, .symbol], 115), (0, [.accepted, .symbol], 116), (13, .none, 0), (14, .none, 0), (17, .none, 0), (18, .none, 0), (20, .none, 0), (21, .none, 0), /* 2 */ (1, .symbol, 48), (22, [.accepted, .symbol], 48), (1, .symbol, 49), (22, [.accepted, .symbol], 49), (1, .symbol, 50), (22, [.accepted, .symbol], 50), (1, .symbol, 97), (22, [.accepted, .symbol], 97), (1, .symbol, 99), (22, [.accepted, .symbol], 99), (1, .symbol, 101), (22, [.accepted, .symbol], 101), (1, .symbol, 105), (22, [.accepted, .symbol], 105), (1, .symbol, 111), (22, [.accepted, .symbol], 111), /* 3 */ (2, .symbol, 48), (9, .symbol, 48), (23, .symbol, 48), (40, [.accepted, .symbol], 48), (2, .symbol, 49), (9, .symbol, 49), (23, .symbol, 49), (40, [.accepted, .symbol], 49), (2, .symbol, 50), (9, .symbol, 50), (23, .symbol, 50), (40, [.accepted, .symbol], 50), (2, .symbol, 97), (9, .symbol, 97), (23, .symbol, 97), (40, [.accepted, .symbol], 97), /* 4 */ (3, .symbol, 48), (6, .symbol, 48), (10, .symbol, 48), (15, .symbol, 48), (24, .symbol, 48), (31, .symbol, 48), (41, .symbol, 48), (56, [.accepted, .symbol], 48), (3, .symbol, 49), (6, .symbol, 49), (10, .symbol, 49), (15, .symbol, 49), (24, .symbol, 49), (31, .symbol, 49), (41, .symbol, 49), (56, [.accepted, .symbol], 49), /* 5 */ (3, .symbol, 50), (6, .symbol, 50), (10, .symbol, 50), (15, .symbol, 50), (24, .symbol, 50), (31, .symbol, 50), (41, .symbol, 50), (56, [.accepted, .symbol], 50), (3, .symbol, 97), (6, .symbol, 97), (10, .symbol, 97), (15, .symbol, 97), (24, .symbol, 97), (31, .symbol, 97), (41, .symbol, 97), (56, [.accepted, .symbol], 97), /* 6 */ (2, .symbol, 99), (9, .symbol, 99), (23, .symbol, 99), (40, [.accepted, .symbol], 99), (2, .symbol, 101), (9, .symbol, 101), (23, .symbol, 101), (40, [.accepted, .symbol], 101), (2, .symbol, 105), (9, .symbol, 105), (23, .symbol, 105), (40, [.accepted, .symbol], 105), (2, .symbol, 111), (9, .symbol, 111), (23, .symbol, 111), (40, [.accepted, .symbol], 111), /* 7 */ (3, .symbol, 99), (6, .symbol, 99), (10, .symbol, 99), (15, .symbol, 99), (24, .symbol, 99), (31, .symbol, 99), (41, .symbol, 99), (56, [.accepted, .symbol], 99), (3, .symbol, 101), (6, .symbol, 101), (10, .symbol, 101), (15, .symbol, 101), (24, .symbol, 101), (31, .symbol, 101), (41, .symbol, 101), (56, [.accepted, .symbol], 101), /* 8 */ (3, .symbol, 105), (6, .symbol, 105), (10, .symbol, 105), (15, .symbol, 105), (24, .symbol, 105), (31, .symbol, 105), (41, .symbol, 105), (56, [.accepted, .symbol], 105), (3, .symbol, 111), (6, .symbol, 111), (10, .symbol, 111), (15, .symbol, 111), (24, .symbol, 111), (31, .symbol, 111), (41, .symbol, 111), (56, [.accepted, .symbol], 111), /* 9 */ (1, .symbol, 115), (22, [.accepted, .symbol], 115), (1, .symbol, 116), (22, [.accepted, .symbol], 116), (0, [.accepted, .symbol], 32), (0, [.accepted, .symbol], 37), (0, [.accepted, .symbol], 45), (0, [.accepted, .symbol], 46), (0, [.accepted, .symbol], 47), (0, [.accepted, .symbol], 51), (0, [.accepted, .symbol], 52), (0, [.accepted, .symbol], 53), (0, [.accepted, .symbol], 54), (0, [.accepted, .symbol], 55), (0, [.accepted, .symbol], 56), (0, [.accepted, .symbol], 57), /* 10 */ (2, .symbol, 115), (9, .symbol, 115), (23, .symbol, 115), (40, [.accepted, .symbol], 115), (2, .symbol, 116), (9, .symbol, 116), (23, .symbol, 116), (40, [.accepted, .symbol], 116), (1, .symbol, 32), (22, [.accepted, .symbol], 32), (1, .symbol, 37), (22, [.accepted, .symbol], 37), (1, .symbol, 45), (22, [.accepted, .symbol], 45), (1, .symbol, 46), (22, [.accepted, .symbol], 46), /* 11 */ (3, .symbol, 115), (6, .symbol, 115), (10, .symbol, 115), (15, .symbol, 115), (24, .symbol, 115), (31, .symbol, 115), (41, .symbol, 115), (56, [.accepted, .symbol], 115), (3, .symbol, 116), (6, .symbol, 116), (10, .symbol, 116), (15, .symbol, 116), (24, .symbol, 116), (31, .symbol, 116), (41, .symbol, 116), (56, [.accepted, .symbol], 116), /* 12 */ (2, .symbol, 32), (9, .symbol, 32), (23, .symbol, 32), (40, [.accepted, .symbol], 32), (2, .symbol, 37), (9, .symbol, 37), (23, .symbol, 37), (40, [.accepted, .symbol], 37), (2, .symbol, 45), (9, .symbol, 45), (23, .symbol, 45), (40, [.accepted, .symbol], 45), (2, .symbol, 46), (9, .symbol, 46), (23, .symbol, 46), (40, [.accepted, .symbol], 46), /* 13 */ (3, .symbol, 32), (6, .symbol, 32), (10, .symbol, 32), (15, .symbol, 32), (24, .symbol, 32), (31, .symbol, 32), (41, .symbol, 32), (56, [.accepted, .symbol], 32), (3, .symbol, 37), (6, .symbol, 37), (10, .symbol, 37), (15, .symbol, 37), (24, .symbol, 37), (31, .symbol, 37), (41, .symbol, 37), (56, [.accepted, .symbol], 37), /* 14 */ (3, .symbol, 45), (6, .symbol, 45), (10, .symbol, 45), (15, .symbol, 45), (24, .symbol, 45), (31, .symbol, 45), (41, .symbol, 45), (56, [.accepted, .symbol], 45), (3, .symbol, 46), (6, .symbol, 46), (10, .symbol, 46), (15, .symbol, 46), (24, .symbol, 46), (31, .symbol, 46), (41, .symbol, 46), (56, [.accepted, .symbol], 46), /* 15 */ (1, .symbol, 47), (22, [.accepted, .symbol], 47), (1, .symbol, 51), (22, [.accepted, .symbol], 51), (1, .symbol, 52), (22, [.accepted, .symbol], 52), (1, .symbol, 53), (22, [.accepted, .symbol], 53), (1, .symbol, 54), (22, [.accepted, .symbol], 54), (1, .symbol, 55), (22, [.accepted, .symbol], 55), (1, .symbol, 56), (22, [.accepted, .symbol], 56), (1, .symbol, 57), (22, [.accepted, .symbol], 57), /* 16 */ (2, .symbol, 47), (9, .symbol, 47), (23, .symbol, 47), (40, [.accepted, .symbol], 47), (2, .symbol, 51), (9, .symbol, 51), (23, .symbol, 51), (40, [.accepted, .symbol], 51), (2, .symbol, 52), (9, .symbol, 52), (23, .symbol, 52), (40, [.accepted, .symbol], 52), (2, .symbol, 53), (9, .symbol, 53), (23, .symbol, 53), (40, [.accepted, .symbol], 53), /* 17 */ (3, .symbol, 47), (6, .symbol, 47), (10, .symbol, 47), (15, .symbol, 47), (24, .symbol, 47), (31, .symbol, 47), (41, .symbol, 47), (56, [.accepted, .symbol], 47), (3, .symbol, 51), (6, .symbol, 51), (10, .symbol, 51), (15, .symbol, 51), (24, .symbol, 51), (31, .symbol, 51), (41, .symbol, 51), (56, [.accepted, .symbol], 51), /* 18 */ (3, .symbol, 52), (6, .symbol, 52), (10, .symbol, 52), (15, .symbol, 52), (24, .symbol, 52), (31, .symbol, 52), (41, .symbol, 52), (56, [.accepted, .symbol], 52), (3, .symbol, 53), (6, .symbol, 53), (10, .symbol, 53), (15, .symbol, 53), (24, .symbol, 53), (31, .symbol, 53), (41, .symbol, 53), (56, [.accepted, .symbol], 53), /* 19 */ (2, .symbol, 54), (9, .symbol, 54), (23, .symbol, 54), (40, [.accepted, .symbol], 54), (2, .symbol, 55), (9, .symbol, 55), (23, .symbol, 55), (40, [.accepted, .symbol], 55), (2, .symbol, 56), (9, .symbol, 56), (23, .symbol, 56), (40, [.accepted, .symbol], 56), (2, .symbol, 57), (9, .symbol, 57), (23, .symbol, 57), (40, [.accepted, .symbol], 57), /* 20 */ (3, .symbol, 54), (6, .symbol, 54), (10, .symbol, 54), (15, .symbol, 54), (24, .symbol, 54), (31, .symbol, 54), (41, .symbol, 54), (56, [.accepted, .symbol], 54), (3, .symbol, 55), (6, .symbol, 55), (10, .symbol, 55), (15, .symbol, 55), (24, .symbol, 55), (31, .symbol, 55), (41, .symbol, 55), (56, [.accepted, .symbol], 55), /* 21 */ (3, .symbol, 56), (6, .symbol, 56), (10, .symbol, 56), (15, .symbol, 56), (24, .symbol, 56), (31, .symbol, 56), (41, .symbol, 56), (56, [.accepted, .symbol], 56), (3, .symbol, 57), (6, .symbol, 57), (10, .symbol, 57), (15, .symbol, 57), (24, .symbol, 57), (31, .symbol, 57), (41, .symbol, 57), (56, [.accepted, .symbol], 57), /* 22 */ (26, .none, 0), (27, .none, 0), (29, .none, 0), (30, .none, 0), (33, .none, 0), (34, .none, 0), (36, .none, 0), (37, .none, 0), (43, .none, 0), (46, .none, 0), (50, .none, 0), (53, .none, 0), (58, .none, 0), (61, .none, 0), (65, .none, 0), (68, .accepted, 0), /* 23 */ (0, [.accepted, .symbol], 61), (0, [.accepted, .symbol], 65), (0, [.accepted, .symbol], 95), (0, [.accepted, .symbol], 98), (0, [.accepted, .symbol], 100), (0, [.accepted, .symbol], 102), (0, [.accepted, .symbol], 103), (0, [.accepted, .symbol], 104), (0, [.accepted, .symbol], 108), (0, [.accepted, .symbol], 109), (0, [.accepted, .symbol], 110), (0, [.accepted, .symbol], 112), (0, [.accepted, .symbol], 114), (0, [.accepted, .symbol], 117), (38, .none, 0), (39, .none, 0), /* 24 */ (1, .symbol, 61), (22, [.accepted, .symbol], 61), (1, .symbol, 65), (22, [.accepted, .symbol], 65), (1, .symbol, 95), (22, [.accepted, .symbol], 95), (1, .symbol, 98), (22, [.accepted, .symbol], 98), (1, .symbol, 100), (22, [.accepted, .symbol], 100), (1, .symbol, 102), (22, [.accepted, .symbol], 102), (1, .symbol, 103), (22, [.accepted, .symbol], 103), (1, .symbol, 104), (22, [.accepted, .symbol], 104), /* 25 */ (2, .symbol, 61), (9, .symbol, 61), (23, .symbol, 61), (40, [.accepted, .symbol], 61), (2, .symbol, 65), (9, .symbol, 65), (23, .symbol, 65), (40, [.accepted, .symbol], 65), (2, .symbol, 95), (9, .symbol, 95), (23, .symbol, 95), (40, [.accepted, .symbol], 95), (2, .symbol, 98), (9, .symbol, 98), (23, .symbol, 98), (40, [.accepted, .symbol], 98), /* 26 */ (3, .symbol, 61), (6, .symbol, 61), (10, .symbol, 61), (15, .symbol, 61), (24, .symbol, 61), (31, .symbol, 61), (41, .symbol, 61), (56, [.accepted, .symbol], 61), (3, .symbol, 65), (6, .symbol, 65), (10, .symbol, 65), (15, .symbol, 65), (24, .symbol, 65), (31, .symbol, 65), (41, .symbol, 65), (56, [.accepted, .symbol], 65), /* 27 */ (3, .symbol, 95), (6, .symbol, 95), (10, .symbol, 95), (15, .symbol, 95), (24, .symbol, 95), (31, .symbol, 95), (41, .symbol, 95), (56, [.accepted, .symbol], 95), (3, .symbol, 98), (6, .symbol, 98), (10, .symbol, 98), (15, .symbol, 98), (24, .symbol, 98), (31, .symbol, 98), (41, .symbol, 98), (56, [.accepted, .symbol], 98), /* 28 */ (2, .symbol, 100), (9, .symbol, 100), (23, .symbol, 100), (40, [.accepted, .symbol], 100), (2, .symbol, 102), (9, .symbol, 102), (23, .symbol, 102), (40, [.accepted, .symbol], 102), (2, .symbol, 103), (9, .symbol, 103), (23, .symbol, 103), (40, [.accepted, .symbol], 103), (2, .symbol, 104), (9, .symbol, 104), (23, .symbol, 104), (40, [.accepted, .symbol], 104), /* 29 */ (3, .symbol, 100), (6, .symbol, 100), (10, .symbol, 100), (15, .symbol, 100), (24, .symbol, 100), (31, .symbol, 100), (41, .symbol, 100), (56, [.accepted, .symbol], 100), (3, .symbol, 102), (6, .symbol, 102), (10, .symbol, 102), (15, .symbol, 102), (24, .symbol, 102), (31, .symbol, 102), (41, .symbol, 102), (56, [.accepted, .symbol], 102), /* 30 */ (3, .symbol, 103), (6, .symbol, 103), (10, .symbol, 103), (15, .symbol, 103), (24, .symbol, 103), (31, .symbol, 103), (41, .symbol, 103), (56, [.accepted, .symbol], 103), (3, .symbol, 104), (6, .symbol, 104), (10, .symbol, 104), (15, .symbol, 104), (24, .symbol, 104), (31, .symbol, 104), (41, .symbol, 104), (56, [.accepted, .symbol], 104), /* 31 */ (1, .symbol, 108), (22, [.accepted, .symbol], 108), (1, .symbol, 109), (22, [.accepted, .symbol], 109), (1, .symbol, 110), (22, [.accepted, .symbol], 110), (1, .symbol, 112), (22, [.accepted, .symbol], 112), (1, .symbol, 114), (22, [.accepted, .symbol], 114), (1, .symbol, 117), (22, [.accepted, .symbol], 117), (0, [.accepted, .symbol], 58), (0, [.accepted, .symbol], 66), (0, [.accepted, .symbol], 67), (0, [.accepted, .symbol], 68), /* 32 */ (2, .symbol, 108), (9, .symbol, 108), (23, .symbol, 108), (40, [.accepted, .symbol], 108), (2, .symbol, 109), (9, .symbol, 109), (23, .symbol, 109), (40, [.accepted, .symbol], 109), (2, .symbol, 110), (9, .symbol, 110), (23, .symbol, 110), (40, [.accepted, .symbol], 110), (2, .symbol, 112), (9, .symbol, 112), (23, .symbol, 112), (40, [.accepted, .symbol], 112), /* 33 */ (3, .symbol, 108), (6, .symbol, 108), (10, .symbol, 108), (15, .symbol, 108), (24, .symbol, 108), (31, .symbol, 108), (41, .symbol, 108), (56, [.accepted, .symbol], 108), (3, .symbol, 109), (6, .symbol, 109), (10, .symbol, 109), (15, .symbol, 109), (24, .symbol, 109), (31, .symbol, 109), (41, .symbol, 109), (56, [.accepted, .symbol], 109), /* 34 */ (3, .symbol, 110), (6, .symbol, 110), (10, .symbol, 110), (15, .symbol, 110), (24, .symbol, 110), (31, .symbol, 110), (41, .symbol, 110), (56, [.accepted, .symbol], 110), (3, .symbol, 112), (6, .symbol, 112), (10, .symbol, 112), (15, .symbol, 112), (24, .symbol, 112), (31, .symbol, 112), (41, .symbol, 112), (56, [.accepted, .symbol], 112), /* 35 */ (2, .symbol, 114), (9, .symbol, 114), (23, .symbol, 114), (40, [.accepted, .symbol], 114), (2, .symbol, 117), (9, .symbol, 117), (23, .symbol, 117), (40, [.accepted, .symbol], 117), (1, .symbol, 58), (22, [.accepted, .symbol], 58), (1, .symbol, 66), (22, [.accepted, .symbol], 66), (1, .symbol, 67), (22, [.accepted, .symbol], 67), (1, .symbol, 68), (22, [.accepted, .symbol], 68), /* 36 */ (3, .symbol, 114), (6, .symbol, 114), (10, .symbol, 114), (15, .symbol, 114), (24, .symbol, 114), (31, .symbol, 114), (41, .symbol, 114), (56, [.accepted, .symbol], 114), (3, .symbol, 117), (6, .symbol, 117), (10, .symbol, 117), (15, .symbol, 117), (24, .symbol, 117), (31, .symbol, 117), (41, .symbol, 117), (56, [.accepted, .symbol], 117), /* 37 */ (2, .symbol, 58), (9, .symbol, 58), (23, .symbol, 58), (40, [.accepted, .symbol], 58), (2, .symbol, 66), (9, .symbol, 66), (23, .symbol, 66), (40, [.accepted, .symbol], 66), (2, .symbol, 67), (9, .symbol, 67), (23, .symbol, 67), (40, [.accepted, .symbol], 67), (2, .symbol, 68), (9, .symbol, 68), (23, .symbol, 68), (40, [.accepted, .symbol], 68), /* 38 */ (3, .symbol, 58), (6, .symbol, 58), (10, .symbol, 58), (15, .symbol, 58), (24, .symbol, 58), (31, .symbol, 58), (41, .symbol, 58), (56, [.accepted, .symbol], 58), (3, .symbol, 66), (6, .symbol, 66), (10, .symbol, 66), (15, .symbol, 66), (24, .symbol, 66), (31, .symbol, 66), (41, .symbol, 66), (56, [.accepted, .symbol], 66), /* 39 */ (3, .symbol, 67), (6, .symbol, 67), (10, .symbol, 67), (15, .symbol, 67), (24, .symbol, 67), (31, .symbol, 67), (41, .symbol, 67), (56, [.accepted, .symbol], 67), (3, .symbol, 68), (6, .symbol, 68), (10, .symbol, 68), (15, .symbol, 68), (24, .symbol, 68), (31, .symbol, 68), (41, .symbol, 68), (56, [.accepted, .symbol], 68), /* 40 */ (44, .none, 0), (45, .none, 0), (47, .none, 0), (48, .none, 0), (51, .none, 0), (52, .none, 0), (54, .none, 0), (55, .none, 0), (59, .none, 0), (60, .none, 0), (62, .none, 0), (63, .none, 0), (66, .none, 0), (67, .none, 0), (69, .none, 0), (72, .accepted, 0), /* 41 */ (0, [.accepted, .symbol], 69), (0, [.accepted, .symbol], 70), (0, [.accepted, .symbol], 71), (0, [.accepted, .symbol], 72), (0, [.accepted, .symbol], 73), (0, [.accepted, .symbol], 74), (0, [.accepted, .symbol], 75), (0, [.accepted, .symbol], 76), (0, [.accepted, .symbol], 77), (0, [.accepted, .symbol], 78), (0, [.accepted, .symbol], 79), (0, [.accepted, .symbol], 80), (0, [.accepted, .symbol], 81), (0, [.accepted, .symbol], 82), (0, [.accepted, .symbol], 83), (0, [.accepted, .symbol], 84), /* 42 */ (1, .symbol, 69), (22, [.accepted, .symbol], 69), (1, .symbol, 70), (22, [.accepted, .symbol], 70), (1, .symbol, 71), (22, [.accepted, .symbol], 71), (1, .symbol, 72), (22, [.accepted, .symbol], 72), (1, .symbol, 73), (22, [.accepted, .symbol], 73), (1, .symbol, 74), (22, [.accepted, .symbol], 74), (1, .symbol, 75), (22, [.accepted, .symbol], 75), (1, .symbol, 76), (22, [.accepted, .symbol], 76), /* 43 */ (2, .symbol, 69), (9, .symbol, 69), (23, .symbol, 69), (40, [.accepted, .symbol], 69), (2, .symbol, 70), (9, .symbol, 70), (23, .symbol, 70), (40, [.accepted, .symbol], 70), (2, .symbol, 71), (9, .symbol, 71), (23, .symbol, 71), (40, [.accepted, .symbol], 71), (2, .symbol, 72), (9, .symbol, 72), (23, .symbol, 72), (40, [.accepted, .symbol], 72), /* 44 */ (3, .symbol, 69), (6, .symbol, 69), (10, .symbol, 69), (15, .symbol, 69), (24, .symbol, 69), (31, .symbol, 69), (41, .symbol, 69), (56, [.accepted, .symbol], 69), (3, .symbol, 70), (6, .symbol, 70), (10, .symbol, 70), (15, .symbol, 70), (24, .symbol, 70), (31, .symbol, 70), (41, .symbol, 70), (56, [.accepted, .symbol], 70), /* 45 */ (3, .symbol, 71), (6, .symbol, 71), (10, .symbol, 71), (15, .symbol, 71), (24, .symbol, 71), (31, .symbol, 71), (41, .symbol, 71), (56, [.accepted, .symbol], 71), (3, .symbol, 72), (6, .symbol, 72), (10, .symbol, 72), (15, .symbol, 72), (24, .symbol, 72), (31, .symbol, 72), (41, .symbol, 72), (56, [.accepted, .symbol], 72), /* 46 */ (2, .symbol, 73), (9, .symbol, 73), (23, .symbol, 73), (40, [.accepted, .symbol], 73), (2, .symbol, 74), (9, .symbol, 74), (23, .symbol, 74), (40, [.accepted, .symbol], 74), (2, .symbol, 75), (9, .symbol, 75), (23, .symbol, 75), (40, [.accepted, .symbol], 75), (2, .symbol, 76), (9, .symbol, 76), (23, .symbol, 76), (40, [.accepted, .symbol], 76), /* 47 */ (3, .symbol, 73), (6, .symbol, 73), (10, .symbol, 73), (15, .symbol, 73), (24, .symbol, 73), (31, .symbol, 73), (41, .symbol, 73), (56, [.accepted, .symbol], 73), (3, .symbol, 74), (6, .symbol, 74), (10, .symbol, 74), (15, .symbol, 74), (24, .symbol, 74), (31, .symbol, 74), (41, .symbol, 74), (56, [.accepted, .symbol], 74), /* 48 */ (3, .symbol, 75), (6, .symbol, 75), (10, .symbol, 75), (15, .symbol, 75), (24, .symbol, 75), (31, .symbol, 75), (41, .symbol, 75), (56, [.accepted, .symbol], 75), (3, .symbol, 76), (6, .symbol, 76), (10, .symbol, 76), (15, .symbol, 76), (24, .symbol, 76), (31, .symbol, 76), (41, .symbol, 76), (56, [.accepted, .symbol], 76), /* 49 */ (1, .symbol, 77), (22, [.accepted, .symbol], 77), (1, .symbol, 78), (22, [.accepted, .symbol], 78), (1, .symbol, 79), (22, [.accepted, .symbol], 79), (1, .symbol, 80), (22, [.accepted, .symbol], 80), (1, .symbol, 81), (22, [.accepted, .symbol], 81), (1, .symbol, 82), (22, [.accepted, .symbol], 82), (1, .symbol, 83), (22, [.accepted, .symbol], 83), (1, .symbol, 84), (22, [.accepted, .symbol], 84), /* 50 */ (2, .symbol, 77), (9, .symbol, 77), (23, .symbol, 77), (40, [.accepted, .symbol], 77), (2, .symbol, 78), (9, .symbol, 78), (23, .symbol, 78), (40, [.accepted, .symbol], 78), (2, .symbol, 79), (9, .symbol, 79), (23, .symbol, 79), (40, [.accepted, .symbol], 79), (2, .symbol, 80), (9, .symbol, 80), (23, .symbol, 80), (40, [.accepted, .symbol], 80), /* 51 */ (3, .symbol, 77), (6, .symbol, 77), (10, .symbol, 77), (15, .symbol, 77), (24, .symbol, 77), (31, .symbol, 77), (41, .symbol, 77), (56, [.accepted, .symbol], 77), (3, .symbol, 78), (6, .symbol, 78), (10, .symbol, 78), (15, .symbol, 78), (24, .symbol, 78), (31, .symbol, 78), (41, .symbol, 78), (56, [.accepted, .symbol], 78), /* 52 */ (3, .symbol, 79), (6, .symbol, 79), (10, .symbol, 79), (15, .symbol, 79), (24, .symbol, 79), (31, .symbol, 79), (41, .symbol, 79), (56, [.accepted, .symbol], 79), (3, .symbol, 80), (6, .symbol, 80), (10, .symbol, 80), (15, .symbol, 80), (24, .symbol, 80), (31, .symbol, 80), (41, .symbol, 80), (56, [.accepted, .symbol], 80), /* 53 */ (2, .symbol, 81), (9, .symbol, 81), (23, .symbol, 81), (40, [.accepted, .symbol], 81), (2, .symbol, 82), (9, .symbol, 82), (23, .symbol, 82), (40, [.accepted, .symbol], 82), (2, .symbol, 83), (9, .symbol, 83), (23, .symbol, 83), (40, [.accepted, .symbol], 83), (2, .symbol, 84), (9, .symbol, 84), (23, .symbol, 84), (40, [.accepted, .symbol], 84), /* 54 */ (3, .symbol, 81), (6, .symbol, 81), (10, .symbol, 81), (15, .symbol, 81), (24, .symbol, 81), (31, .symbol, 81), (41, .symbol, 81), (56, [.accepted, .symbol], 81), (3, .symbol, 82), (6, .symbol, 82), (10, .symbol, 82), (15, .symbol, 82), (24, .symbol, 82), (31, .symbol, 82), (41, .symbol, 82), (56, [.accepted, .symbol], 82), /* 55 */ (3, .symbol, 83), (6, .symbol, 83), (10, .symbol, 83), (15, .symbol, 83), (24, .symbol, 83), (31, .symbol, 83), (41, .symbol, 83), (56, [.accepted, .symbol], 83), (3, .symbol, 84), (6, .symbol, 84), (10, .symbol, 84), (15, .symbol, 84), (24, .symbol, 84), (31, .symbol, 84), (41, .symbol, 84), (56, [.accepted, .symbol], 84), /* 56 */ (0, [.accepted, .symbol], 85), (0, [.accepted, .symbol], 86), (0, [.accepted, .symbol], 87), (0, [.accepted, .symbol], 89), (0, [.accepted, .symbol], 106), (0, [.accepted, .symbol], 107), (0, [.accepted, .symbol], 113), (0, [.accepted, .symbol], 118), (0, [.accepted, .symbol], 119), (0, [.accepted, .symbol], 120), (0, [.accepted, .symbol], 121), (0, [.accepted, .symbol], 122), (70, .none, 0), (71, .none, 0), (73, .none, 0), (74, .accepted, 0), /* 57 */ (1, .symbol, 85), (22, [.accepted, .symbol], 85), (1, .symbol, 86), (22, [.accepted, .symbol], 86), (1, .symbol, 87), (22, [.accepted, .symbol], 87), (1, .symbol, 89), (22, [.accepted, .symbol], 89), (1, .symbol, 106), (22, [.accepted, .symbol], 106), (1, .symbol, 107), (22, [.accepted, .symbol], 107), (1, .symbol, 113), (22, [.accepted, .symbol], 113), (1, .symbol, 118), (22, [.accepted, .symbol], 118), /* 58 */ (2, .symbol, 85), (9, .symbol, 85), (23, .symbol, 85), (40, [.accepted, .symbol], 85), (2, .symbol, 86), (9, .symbol, 86), (23, .symbol, 86), (40, [.accepted, .symbol], 86), (2, .symbol, 87), (9, .symbol, 87), (23, .symbol, 87), (40, [.accepted, .symbol], 87), (2, .symbol, 89), (9, .symbol, 89), (23, .symbol, 89), (40, [.accepted, .symbol], 89), /* 59 */ (3, .symbol, 85), (6, .symbol, 85), (10, .symbol, 85), (15, .symbol, 85), (24, .symbol, 85), (31, .symbol, 85), (41, .symbol, 85), (56, [.accepted, .symbol], 85), (3, .symbol, 86), (6, .symbol, 86), (10, .symbol, 86), (15, .symbol, 86), (24, .symbol, 86), (31, .symbol, 86), (41, .symbol, 86), (56, [.accepted, .symbol], 86), /* 60 */ (3, .symbol, 87), (6, .symbol, 87), (10, .symbol, 87), (15, .symbol, 87), (24, .symbol, 87), (31, .symbol, 87), (41, .symbol, 87), (56, [.accepted, .symbol], 87), (3, .symbol, 89), (6, .symbol, 89), (10, .symbol, 89), (15, .symbol, 89), (24, .symbol, 89), (31, .symbol, 89), (41, .symbol, 89), (56, [.accepted, .symbol], 89), /* 61 */ (2, .symbol, 106), (9, .symbol, 106), (23, .symbol, 106), (40, [.accepted, .symbol], 106), (2, .symbol, 107), (9, .symbol, 107), (23, .symbol, 107), (40, [.accepted, .symbol], 107), (2, .symbol, 113), (9, .symbol, 113), (23, .symbol, 113), (40, [.accepted, .symbol], 113), (2, .symbol, 118), (9, .symbol, 118), (23, .symbol, 118), (40, [.accepted, .symbol], 118), /* 62 */ (3, .symbol, 106), (6, .symbol, 106), (10, .symbol, 106), (15, .symbol, 106), (24, .symbol, 106), (31, .symbol, 106), (41, .symbol, 106), (56, [.accepted, .symbol], 106), (3, .symbol, 107), (6, .symbol, 107), (10, .symbol, 107), (15, .symbol, 107), (24, .symbol, 107), (31, .symbol, 107), (41, .symbol, 107), (56, [.accepted, .symbol], 107), /* 63 */ (3, .symbol, 113), (6, .symbol, 113), (10, .symbol, 113), (15, .symbol, 113), (24, .symbol, 113), (31, .symbol, 113), (41, .symbol, 113), (56, [.accepted, .symbol], 113), (3, .symbol, 118), (6, .symbol, 118), (10, .symbol, 118), (15, .symbol, 118), (24, .symbol, 118), (31, .symbol, 118), (41, .symbol, 118), (56, [.accepted, .symbol], 118), /* 64 */ (1, .symbol, 119), (22, [.accepted, .symbol], 119), (1, .symbol, 120), (22, [.accepted, .symbol], 120), (1, .symbol, 121), (22, [.accepted, .symbol], 121), (1, .symbol, 122), (22, [.accepted, .symbol], 122), (0, [.accepted, .symbol], 38), (0, [.accepted, .symbol], 42), (0, [.accepted, .symbol], 44), (0, [.accepted, .symbol], 59), (0, [.accepted, .symbol], 88), (0, [.accepted, .symbol], 90), (75, .none, 0), (78, .none, 0), /* 65 */ (2, .symbol, 119), (9, .symbol, 119), (23, .symbol, 119), (40, [.accepted, .symbol], 119), (2, .symbol, 120), (9, .symbol, 120), (23, .symbol, 120), (40, [.accepted, .symbol], 120), (2, .symbol, 121), (9, .symbol, 121), (23, .symbol, 121), (40, [.accepted, .symbol], 121), (2, .symbol, 122), (9, .symbol, 122), (23, .symbol, 122), (40, [.accepted, .symbol], 122), /* 66 */ (3, .symbol, 119), (6, .symbol, 119), (10, .symbol, 119), (15, .symbol, 119), (24, .symbol, 119), (31, .symbol, 119), (41, .symbol, 119), (56, [.accepted, .symbol], 119), (3, .symbol, 120), (6, .symbol, 120), (10, .symbol, 120), (15, .symbol, 120), (24, .symbol, 120), (31, .symbol, 120), (41, .symbol, 120), (56, [.accepted, .symbol], 120), /* 67 */ (3, .symbol, 121), (6, .symbol, 121), (10, .symbol, 121), (15, .symbol, 121), (24, .symbol, 121), (31, .symbol, 121), (41, .symbol, 121), (56, [.accepted, .symbol], 121), (3, .symbol, 122), (6, .symbol, 122), (10, .symbol, 122), (15, .symbol, 122), (24, .symbol, 122), (31, .symbol, 122), (41, .symbol, 122), (56, [.accepted, .symbol], 122), /* 68 */ (1, .symbol, 38), (22, [.accepted, .symbol], 38), (1, .symbol, 42), (22, [.accepted, .symbol], 42), (1, .symbol, 44), (22, [.accepted, .symbol], 44), (1, .symbol, 59), (22, [.accepted, .symbol], 59), (1, .symbol, 88), (22, [.accepted, .symbol], 88), (1, .symbol, 90), (22, [.accepted, .symbol], 90), (76, .none, 0), (77, .none, 0), (79, .none, 0), (81, .none, 0), /* 69 */ (2, .symbol, 38), (9, .symbol, 38), (23, .symbol, 38), (40, [.accepted, .symbol], 38), (2, .symbol, 42), (9, .symbol, 42), (23, .symbol, 42), (40, [.accepted, .symbol], 42), (2, .symbol, 44), (9, .symbol, 44), (23, .symbol, 44), (40, [.accepted, .symbol], 44), (2, .symbol, 59), (9, .symbol, 59), (23, .symbol, 59), (40, [.accepted, .symbol], 59), /* 70 */ (3, .symbol, 38), (6, .symbol, 38), (10, .symbol, 38), (15, .symbol, 38), (24, .symbol, 38), (31, .symbol, 38), (41, .symbol, 38), (56, [.accepted, .symbol], 38), (3, .symbol, 42), (6, .symbol, 42), (10, .symbol, 42), (15, .symbol, 42), (24, .symbol, 42), (31, .symbol, 42), (41, .symbol, 42), (56, [.accepted, .symbol], 42), /* 71 */ (3, .symbol, 44), (6, .symbol, 44), (10, .symbol, 44), (15, .symbol, 44), (24, .symbol, 44), (31, .symbol, 44), (41, .symbol, 44), (56, [.accepted, .symbol], 44), (3, .symbol, 59), (6, .symbol, 59), (10, .symbol, 59), (15, .symbol, 59), (24, .symbol, 59), (31, .symbol, 59), (41, .symbol, 59), (56, [.accepted, .symbol], 59), /* 72 */ (2, .symbol, 88), (9, .symbol, 88), (23, .symbol, 88), (40, [.accepted, .symbol], 88), (2, .symbol, 90), (9, .symbol, 90), (23, .symbol, 90), (40, [.accepted, .symbol], 90), (0, [.accepted, .symbol], 33), (0, [.accepted, .symbol], 34), (0, [.accepted, .symbol], 40), (0, [.accepted, .symbol], 41), (0, [.accepted, .symbol], 63), (80, .none, 0), (82, .none, 0), (84, .none, 0), /* 73 */ (3, .symbol, 88), (6, .symbol, 88), (10, .symbol, 88), (15, .symbol, 88), (24, .symbol, 88), (31, .symbol, 88), (41, .symbol, 88), (56, [.accepted, .symbol], 88), (3, .symbol, 90), (6, .symbol, 90), (10, .symbol, 90), (15, .symbol, 90), (24, .symbol, 90), (31, .symbol, 90), (41, .symbol, 90), (56, [.accepted, .symbol], 90), /* 74 */ (1, .symbol, 33), (22, [.accepted, .symbol], 33), (1, .symbol, 34), (22, [.accepted, .symbol], 34), (1, .symbol, 40), (22, [.accepted, .symbol], 40), (1, .symbol, 41), (22, [.accepted, .symbol], 41), (1, .symbol, 63), (22, [.accepted, .symbol], 63), (0, [.accepted, .symbol], 39), (0, [.accepted, .symbol], 43), (0, [.accepted, .symbol], 124), (83, .none, 0), (85, .none, 0), (88, .none, 0), /* 75 */ (2, .symbol, 33), (9, .symbol, 33), (23, .symbol, 33), (40, [.accepted, .symbol], 33), (2, .symbol, 34), (9, .symbol, 34), (23, .symbol, 34), (40, [.accepted, .symbol], 34), (2, .symbol, 40), (9, .symbol, 40), (23, .symbol, 40), (40, [.accepted, .symbol], 40), (2, .symbol, 41), (9, .symbol, 41), (23, .symbol, 41), (40, [.accepted, .symbol], 41), /* 76 */ (3, .symbol, 33), (6, .symbol, 33), (10, .symbol, 33), (15, .symbol, 33), (24, .symbol, 33), (31, .symbol, 33), (41, .symbol, 33), (56, [.accepted, .symbol], 33), (3, .symbol, 34), (6, .symbol, 34), (10, .symbol, 34), (15, .symbol, 34), (24, .symbol, 34), (31, .symbol, 34), (41, .symbol, 34), (56, [.accepted, .symbol], 34), /* 77 */ (3, .symbol, 40), (6, .symbol, 40), (10, .symbol, 40), (15, .symbol, 40), (24, .symbol, 40), (31, .symbol, 40), (41, .symbol, 40), (56, [.accepted, .symbol], 40), (3, .symbol, 41), (6, .symbol, 41), (10, .symbol, 41), (15, .symbol, 41), (24, .symbol, 41), (31, .symbol, 41), (41, .symbol, 41), (56, [.accepted, .symbol], 41), /* 78 */ (2, .symbol, 63), (9, .symbol, 63), (23, .symbol, 63), (40, [.accepted, .symbol], 63), (1, .symbol, 39), (22, [.accepted, .symbol], 39), (1, .symbol, 43), (22, [.accepted, .symbol], 43), (1, .symbol, 124), (22, [.accepted, .symbol], 124), (0, [.accepted, .symbol], 35), (0, [.accepted, .symbol], 62), (86, .none, 0), (87, .none, 0), (89, .none, 0), (90, .none, 0), /* 79 */ (3, .symbol, 63), (6, .symbol, 63), (10, .symbol, 63), (15, .symbol, 63), (24, .symbol, 63), (31, .symbol, 63), (41, .symbol, 63), (56, [.accepted, .symbol], 63), (2, .symbol, 39), (9, .symbol, 39), (23, .symbol, 39), (40, [.accepted, .symbol], 39), (2, .symbol, 43), (9, .symbol, 43), (23, .symbol, 43), (40, [.accepted, .symbol], 43), /* 80 */ (3, .symbol, 39), (6, .symbol, 39), (10, .symbol, 39), (15, .symbol, 39), (24, .symbol, 39), (31, .symbol, 39), (41, .symbol, 39), (56, [.accepted, .symbol], 39), (3, .symbol, 43), (6, .symbol, 43), (10, .symbol, 43), (15, .symbol, 43), (24, .symbol, 43), (31, .symbol, 43), (41, .symbol, 43), (56, [.accepted, .symbol], 43), /* 81 */ (2, .symbol, 124), (9, .symbol, 124), (23, .symbol, 124), (40, [.accepted, .symbol], 124), (1, .symbol, 35), (22, [.accepted, .symbol], 35), (1, .symbol, 62), (22, [.accepted, .symbol], 62), (0, [.accepted, .symbol], 0), (0, [.accepted, .symbol], 36), (0, [.accepted, .symbol], 64), (0, [.accepted, .symbol], 91), (0, [.accepted, .symbol], 93), (0, [.accepted, .symbol], 126), (91, .none, 0), (92, .none, 0), /* 82 */ (3, .symbol, 124), (6, .symbol, 124), (10, .symbol, 124), (15, .symbol, 124), (24, .symbol, 124), (31, .symbol, 124), (41, .symbol, 124), (56, [.accepted, .symbol], 124), (2, .symbol, 35), (9, .symbol, 35), (23, .symbol, 35), (40, [.accepted, .symbol], 35), (2, .symbol, 62), (9, .symbol, 62), (23, .symbol, 62), (40, [.accepted, .symbol], 62), /* 83 */ (3, .symbol, 35), (6, .symbol, 35), (10, .symbol, 35), (15, .symbol, 35), (24, .symbol, 35), (31, .symbol, 35), (41, .symbol, 35), (56, [.accepted, .symbol], 35), (3, .symbol, 62), (6, .symbol, 62), (10, .symbol, 62), (15, .symbol, 62), (24, .symbol, 62), (31, .symbol, 62), (41, .symbol, 62), (56, [.accepted, .symbol], 62), /* 84 */ (1, .symbol, 0), (22, [.accepted, .symbol], 0), (1, .symbol, 36), (22, [.accepted, .symbol], 36), (1, .symbol, 64), (22, [.accepted, .symbol], 64), (1, .symbol, 91), (22, [.accepted, .symbol], 91), (1, .symbol, 93), (22, [.accepted, .symbol], 93), (1, .symbol, 126), (22, [.accepted, .symbol], 126), (0, [.accepted, .symbol], 94), (0, [.accepted, .symbol], 125), (93, .none, 0), (94, .none, 0), /* 85 */ (2, .symbol, 0), (9, .symbol, 0), (23, .symbol, 0), (40, [.accepted, .symbol], 0), (2, .symbol, 36), (9, .symbol, 36), (23, .symbol, 36), (40, [.accepted, .symbol], 36), (2, .symbol, 64), (9, .symbol, 64), (23, .symbol, 64), (40, [.accepted, .symbol], 64), (2, .symbol, 91), (9, .symbol, 91), (23, .symbol, 91), (40, [.accepted, .symbol], 91), /* 86 */ (3, .symbol, 0), (6, .symbol, 0), (10, .symbol, 0), (15, .symbol, 0), (24, .symbol, 0), (31, .symbol, 0), (41, .symbol, 0), (56, [.accepted, .symbol], 0), (3, .symbol, 36), (6, .symbol, 36), (10, .symbol, 36), (15, .symbol, 36), (24, .symbol, 36), (31, .symbol, 36), (41, .symbol, 36), (56, [.accepted, .symbol], 36), /* 87 */ (3, .symbol, 64), (6, .symbol, 64), (10, .symbol, 64), (15, .symbol, 64), (24, .symbol, 64), (31, .symbol, 64), (41, .symbol, 64), (56, [.accepted, .symbol], 64), (3, .symbol, 91), (6, .symbol, 91), (10, .symbol, 91), (15, .symbol, 91), (24, .symbol, 91), (31, .symbol, 91), (41, .symbol, 91), (56, [.accepted, .symbol], 91), /* 88 */ (2, .symbol, 93), (9, .symbol, 93), (23, .symbol, 93), (40, [.accepted, .symbol], 93), (2, .symbol, 126), (9, .symbol, 126), (23, .symbol, 126), (40, [.accepted, .symbol], 126), (1, .symbol, 94), (22, [.accepted, .symbol], 94), (1, .symbol, 125), (22, [.accepted, .symbol], 125), (0, [.accepted, .symbol], 60), (0, [.accepted, .symbol], 96), (0, [.accepted, .symbol], 123), (95, .none, 0), /* 89 */ (3, .symbol, 93), (6, .symbol, 93), (10, .symbol, 93), (15, .symbol, 93), (24, .symbol, 93), (31, .symbol, 93), (41, .symbol, 93), (56, [.accepted, .symbol], 93), (3, .symbol, 126), (6, .symbol, 126), (10, .symbol, 126), (15, .symbol, 126), (24, .symbol, 126), (31, .symbol, 126), (41, .symbol, 126), (56, [.accepted, .symbol], 126), /* 90 */ (2, .symbol, 94), (9, .symbol, 94), (23, .symbol, 94), (40, [.accepted, .symbol], 94), (2, .symbol, 125), (9, .symbol, 125), (23, .symbol, 125), (40, [.accepted, .symbol], 125), (1, .symbol, 60), (22, [.accepted, .symbol], 60), (1, .symbol, 96), (22, [.accepted, .symbol], 96), (1, .symbol, 123), (22, [.accepted, .symbol], 123), (96, .none, 0), (110, .none, 0), /* 91 */ (3, .symbol, 94), (6, .symbol, 94), (10, .symbol, 94), (15, .symbol, 94), (24, .symbol, 94), (31, .symbol, 94), (41, .symbol, 94), (56, [.accepted, .symbol], 94), (3, .symbol, 125), (6, .symbol, 125), (10, .symbol, 125), (15, .symbol, 125), (24, .symbol, 125), (31, .symbol, 125), (41, .symbol, 125), (56, [.accepted, .symbol], 125), /* 92 */ (2, .symbol, 60), (9, .symbol, 60), (23, .symbol, 60), (40, [.accepted, .symbol], 60), (2, .symbol, 96), (9, .symbol, 96), (23, .symbol, 96), (40, [.accepted, .symbol], 96), (2, .symbol, 123), (9, .symbol, 123), (23, .symbol, 123), (40, [.accepted, .symbol], 123), (97, .none, 0), (101, .none, 0), (111, .none, 0), (133, .none, 0), /* 93 */ (3, .symbol, 60), (6, .symbol, 60), (10, .symbol, 60), (15, .symbol, 60), (24, .symbol, 60), (31, .symbol, 60), (41, .symbol, 60), (56, [.accepted, .symbol], 60), (3, .symbol, 96), (6, .symbol, 96), (10, .symbol, 96), (15, .symbol, 96), (24, .symbol, 96), (31, .symbol, 96), (41, .symbol, 96), (56, [.accepted, .symbol], 96), /* 94 */ (3, .symbol, 123), (6, .symbol, 123), (10, .symbol, 123), (15, .symbol, 123), (24, .symbol, 123), (31, .symbol, 123), (41, .symbol, 123), (56, [.accepted, .symbol], 123), (98, .none, 0), (99, .none, 0), (102, .none, 0), (105, .none, 0), (112, .none, 0), (119, .none, 0), (134, .none, 0), (153, .none, 0), /* 95 */ (0, [.accepted, .symbol], 92), (0, [.accepted, .symbol], 195), (0, [.accepted, .symbol], 208), (100, .none, 0), (103, .none, 0), (104, .none, 0), (106, .none, 0), (107, .none, 0), (113, .none, 0), (116, .none, 0), (120, .none, 0), (126, .none, 0), (135, .none, 0), (142, .none, 0), (154, .none, 0), (169, .none, 0), /* 96 */ (1, .symbol, 92), (22, [.accepted, .symbol], 92), (1, .symbol, 195), (22, [.accepted, .symbol], 195), (1, .symbol, 208), (22, [.accepted, .symbol], 208), (0, [.accepted, .symbol], 128), (0, [.accepted, .symbol], 130), (0, [.accepted, .symbol], 131), (0, [.accepted, .symbol], 162), (0, [.accepted, .symbol], 184), (0, [.accepted, .symbol], 194), (0, [.accepted, .symbol], 224), (0, [.accepted, .symbol], 226), (108, .none, 0), (109, .none, 0), /* 97 */ (2, .symbol, 92), (9, .symbol, 92), (23, .symbol, 92), (40, [.accepted, .symbol], 92), (2, .symbol, 195), (9, .symbol, 195), (23, .symbol, 195), (40, [.accepted, .symbol], 195), (2, .symbol, 208), (9, .symbol, 208), (23, .symbol, 208), (40, [.accepted, .symbol], 208), (1, .symbol, 128), (22, [.accepted, .symbol], 128), (1, .symbol, 130), (22, [.accepted, .symbol], 130), /* 98 */ (3, .symbol, 92), (6, .symbol, 92), (10, .symbol, 92), (15, .symbol, 92), (24, .symbol, 92), (31, .symbol, 92), (41, .symbol, 92), (56, [.accepted, .symbol], 92), (3, .symbol, 195), (6, .symbol, 195), (10, .symbol, 195), (15, .symbol, 195), (24, .symbol, 195), (31, .symbol, 195), (41, .symbol, 195), (56, [.accepted, .symbol], 195), /* 99 */ (3, .symbol, 208), (6, .symbol, 208), (10, .symbol, 208), (15, .symbol, 208), (24, .symbol, 208), (31, .symbol, 208), (41, .symbol, 208), (56, [.accepted, .symbol], 208), (2, .symbol, 128), (9, .symbol, 128), (23, .symbol, 128), (40, [.accepted, .symbol], 128), (2, .symbol, 130), (9, .symbol, 130), (23, .symbol, 130), (40, [.accepted, .symbol], 130), /* 100 */ (3, .symbol, 128), (6, .symbol, 128), (10, .symbol, 128), (15, .symbol, 128), (24, .symbol, 128), (31, .symbol, 128), (41, .symbol, 128), (56, [.accepted, .symbol], 128), (3, .symbol, 130), (6, .symbol, 130), (10, .symbol, 130), (15, .symbol, 130), (24, .symbol, 130), (31, .symbol, 130), (41, .symbol, 130), (56, [.accepted, .symbol], 130), /* 101 */ (1, .symbol, 131), (22, [.accepted, .symbol], 131), (1, .symbol, 162), (22, [.accepted, .symbol], 162), (1, .symbol, 184), (22, [.accepted, .symbol], 184), (1, .symbol, 194), (22, [.accepted, .symbol], 194), (1, .symbol, 224), (22, [.accepted, .symbol], 224), (1, .symbol, 226), (22, [.accepted, .symbol], 226), (0, [.accepted, .symbol], 153), (0, [.accepted, .symbol], 161), (0, [.accepted, .symbol], 167), (0, [.accepted, .symbol], 172), /* 102 */ (2, .symbol, 131), (9, .symbol, 131), (23, .symbol, 131), (40, [.accepted, .symbol], 131), (2, .symbol, 162), (9, .symbol, 162), (23, .symbol, 162), (40, [.accepted, .symbol], 162), (2, .symbol, 184), (9, .symbol, 184), (23, .symbol, 184), (40, [.accepted, .symbol], 184), (2, .symbol, 194), (9, .symbol, 194), (23, .symbol, 194), (40, [.accepted, .symbol], 194), /* 103 */ (3, .symbol, 131), (6, .symbol, 131), (10, .symbol, 131), (15, .symbol, 131), (24, .symbol, 131), (31, .symbol, 131), (41, .symbol, 131), (56, [.accepted, .symbol], 131), (3, .symbol, 162), (6, .symbol, 162), (10, .symbol, 162), (15, .symbol, 162), (24, .symbol, 162), (31, .symbol, 162), (41, .symbol, 162), (56, [.accepted, .symbol], 162), /* 104 */ (3, .symbol, 184), (6, .symbol, 184), (10, .symbol, 184), (15, .symbol, 184), (24, .symbol, 184), (31, .symbol, 184), (41, .symbol, 184), (56, [.accepted, .symbol], 184), (3, .symbol, 194), (6, .symbol, 194), (10, .symbol, 194), (15, .symbol, 194), (24, .symbol, 194), (31, .symbol, 194), (41, .symbol, 194), (56, [.accepted, .symbol], 194), /* 105 */ (2, .symbol, 224), (9, .symbol, 224), (23, .symbol, 224), (40, [.accepted, .symbol], 224), (2, .symbol, 226), (9, .symbol, 226), (23, .symbol, 226), (40, [.accepted, .symbol], 226), (1, .symbol, 153), (22, [.accepted, .symbol], 153), (1, .symbol, 161), (22, [.accepted, .symbol], 161), (1, .symbol, 167), (22, [.accepted, .symbol], 167), (1, .symbol, 172), (22, [.accepted, .symbol], 172), /* 106 */ (3, .symbol, 224), (6, .symbol, 224), (10, .symbol, 224), (15, .symbol, 224), (24, .symbol, 224), (31, .symbol, 224), (41, .symbol, 224), (56, [.accepted, .symbol], 224), (3, .symbol, 226), (6, .symbol, 226), (10, .symbol, 226), (15, .symbol, 226), (24, .symbol, 226), (31, .symbol, 226), (41, .symbol, 226), (56, [.accepted, .symbol], 226), /* 107 */ (2, .symbol, 153), (9, .symbol, 153), (23, .symbol, 153), (40, [.accepted, .symbol], 153), (2, .symbol, 161), (9, .symbol, 161), (23, .symbol, 161), (40, [.accepted, .symbol], 161), (2, .symbol, 167), (9, .symbol, 167), (23, .symbol, 167), (40, [.accepted, .symbol], 167), (2, .symbol, 172), (9, .symbol, 172), (23, .symbol, 172), (40, [.accepted, .symbol], 172), /* 108 */ (3, .symbol, 153), (6, .symbol, 153), (10, .symbol, 153), (15, .symbol, 153), (24, .symbol, 153), (31, .symbol, 153), (41, .symbol, 153), (56, [.accepted, .symbol], 153), (3, .symbol, 161), (6, .symbol, 161), (10, .symbol, 161), (15, .symbol, 161), (24, .symbol, 161), (31, .symbol, 161), (41, .symbol, 161), (56, [.accepted, .symbol], 161), /* 109 */ (3, .symbol, 167), (6, .symbol, 167), (10, .symbol, 167), (15, .symbol, 167), (24, .symbol, 167), (31, .symbol, 167), (41, .symbol, 167), (56, [.accepted, .symbol], 167), (3, .symbol, 172), (6, .symbol, 172), (10, .symbol, 172), (15, .symbol, 172), (24, .symbol, 172), (31, .symbol, 172), (41, .symbol, 172), (56, [.accepted, .symbol], 172), /* 110 */ (114, .none, 0), (115, .none, 0), (117, .none, 0), (118, .none, 0), (121, .none, 0), (123, .none, 0), (127, .none, 0), (130, .none, 0), (136, .none, 0), (139, .none, 0), (143, .none, 0), (146, .none, 0), (155, .none, 0), (162, .none, 0), (170, .none, 0), (180, .none, 0), /* 111 */ (0, [.accepted, .symbol], 176), (0, [.accepted, .symbol], 177), (0, [.accepted, .symbol], 179), (0, [.accepted, .symbol], 209), (0, [.accepted, .symbol], 216), (0, [.accepted, .symbol], 217), (0, [.accepted, .symbol], 227), (0, [.accepted, .symbol], 229), (0, [.accepted, .symbol], 230), (122, .none, 0), (124, .none, 0), (125, .none, 0), (128, .none, 0), (129, .none, 0), (131, .none, 0), (132, .none, 0), /* 112 */ (1, .symbol, 176), (22, [.accepted, .symbol], 176), (1, .symbol, 177), (22, [.accepted, .symbol], 177), (1, .symbol, 179), (22, [.accepted, .symbol], 179), (1, .symbol, 209), (22, [.accepted, .symbol], 209), (1, .symbol, 216), (22, [.accepted, .symbol], 216), (1, .symbol, 217), (22, [.accepted, .symbol], 217), (1, .symbol, 227), (22, [.accepted, .symbol], 227), (1, .symbol, 229), (22, [.accepted, .symbol], 229), /* 113 */ (2, .symbol, 176), (9, .symbol, 176), (23, .symbol, 176), (40, [.accepted, .symbol], 176), (2, .symbol, 177), (9, .symbol, 177), (23, .symbol, 177), (40, [.accepted, .symbol], 177), (2, .symbol, 179), (9, .symbol, 179), (23, .symbol, 179), (40, [.accepted, .symbol], 179), (2, .symbol, 209), (9, .symbol, 209), (23, .symbol, 209), (40, [.accepted, .symbol], 209), /* 114 */ (3, .symbol, 176), (6, .symbol, 176), (10, .symbol, 176), (15, .symbol, 176), (24, .symbol, 176), (31, .symbol, 176), (41, .symbol, 176), (56, [.accepted, .symbol], 176), (3, .symbol, 177), (6, .symbol, 177), (10, .symbol, 177), (15, .symbol, 177), (24, .symbol, 177), (31, .symbol, 177), (41, .symbol, 177), (56, [.accepted, .symbol], 177), /* 115 */ (3, .symbol, 179), (6, .symbol, 179), (10, .symbol, 179), (15, .symbol, 179), (24, .symbol, 179), (31, .symbol, 179), (41, .symbol, 179), (56, [.accepted, .symbol], 179), (3, .symbol, 209), (6, .symbol, 209), (10, .symbol, 209), (15, .symbol, 209), (24, .symbol, 209), (31, .symbol, 209), (41, .symbol, 209), (56, [.accepted, .symbol], 209), /* 116 */ (2, .symbol, 216), (9, .symbol, 216), (23, .symbol, 216), (40, [.accepted, .symbol], 216), (2, .symbol, 217), (9, .symbol, 217), (23, .symbol, 217), (40, [.accepted, .symbol], 217), (2, .symbol, 227), (9, .symbol, 227), (23, .symbol, 227), (40, [.accepted, .symbol], 227), (2, .symbol, 229), (9, .symbol, 229), (23, .symbol, 229), (40, [.accepted, .symbol], 229), /* 117 */ (3, .symbol, 216), (6, .symbol, 216), (10, .symbol, 216), (15, .symbol, 216), (24, .symbol, 216), (31, .symbol, 216), (41, .symbol, 216), (56, [.accepted, .symbol], 216), (3, .symbol, 217), (6, .symbol, 217), (10, .symbol, 217), (15, .symbol, 217), (24, .symbol, 217), (31, .symbol, 217), (41, .symbol, 217), (56, [.accepted, .symbol], 217), /* 118 */ (3, .symbol, 227), (6, .symbol, 227), (10, .symbol, 227), (15, .symbol, 227), (24, .symbol, 227), (31, .symbol, 227), (41, .symbol, 227), (56, [.accepted, .symbol], 227), (3, .symbol, 229), (6, .symbol, 229), (10, .symbol, 229), (15, .symbol, 229), (24, .symbol, 229), (31, .symbol, 229), (41, .symbol, 229), (56, [.accepted, .symbol], 229), /* 119 */ (1, .symbol, 230), (22, [.accepted, .symbol], 230), (0, [.accepted, .symbol], 129), (0, [.accepted, .symbol], 132), (0, [.accepted, .symbol], 133), (0, [.accepted, .symbol], 134), (0, [.accepted, .symbol], 136), (0, [.accepted, .symbol], 146), (0, [.accepted, .symbol], 154), (0, [.accepted, .symbol], 156), (0, [.accepted, .symbol], 160), (0, [.accepted, .symbol], 163), (0, [.accepted, .symbol], 164), (0, [.accepted, .symbol], 169), (0, [.accepted, .symbol], 170), (0, [.accepted, .symbol], 173), /* 120 */ (2, .symbol, 230), (9, .symbol, 230), (23, .symbol, 230), (40, [.accepted, .symbol], 230), (1, .symbol, 129), (22, [.accepted, .symbol], 129), (1, .symbol, 132), (22, [.accepted, .symbol], 132), (1, .symbol, 133), (22, [.accepted, .symbol], 133), (1, .symbol, 134), (22, [.accepted, .symbol], 134), (1, .symbol, 136), (22, [.accepted, .symbol], 136), (1, .symbol, 146), (22, [.accepted, .symbol], 146), /* 121 */ (3, .symbol, 230), (6, .symbol, 230), (10, .symbol, 230), (15, .symbol, 230), (24, .symbol, 230), (31, .symbol, 230), (41, .symbol, 230), (56, [.accepted, .symbol], 230), (2, .symbol, 129), (9, .symbol, 129), (23, .symbol, 129), (40, [.accepted, .symbol], 129), (2, .symbol, 132), (9, .symbol, 132), (23, .symbol, 132), (40, [.accepted, .symbol], 132), /* 122 */ (3, .symbol, 129), (6, .symbol, 129), (10, .symbol, 129), (15, .symbol, 129), (24, .symbol, 129), (31, .symbol, 129), (41, .symbol, 129), (56, [.accepted, .symbol], 129), (3, .symbol, 132), (6, .symbol, 132), (10, .symbol, 132), (15, .symbol, 132), (24, .symbol, 132), (31, .symbol, 132), (41, .symbol, 132), (56, [.accepted, .symbol], 132), /* 123 */ (2, .symbol, 133), (9, .symbol, 133), (23, .symbol, 133), (40, [.accepted, .symbol], 133), (2, .symbol, 134), (9, .symbol, 134), (23, .symbol, 134), (40, [.accepted, .symbol], 134), (2, .symbol, 136), (9, .symbol, 136), (23, .symbol, 136), (40, [.accepted, .symbol], 136), (2, .symbol, 146), (9, .symbol, 146), (23, .symbol, 146), (40, [.accepted, .symbol], 146), /* 124 */ (3, .symbol, 133), (6, .symbol, 133), (10, .symbol, 133), (15, .symbol, 133), (24, .symbol, 133), (31, .symbol, 133), (41, .symbol, 133), (56, [.accepted, .symbol], 133), (3, .symbol, 134), (6, .symbol, 134), (10, .symbol, 134), (15, .symbol, 134), (24, .symbol, 134), (31, .symbol, 134), (41, .symbol, 134), (56, [.accepted, .symbol], 134), /* 125 */ (3, .symbol, 136), (6, .symbol, 136), (10, .symbol, 136), (15, .symbol, 136), (24, .symbol, 136), (31, .symbol, 136), (41, .symbol, 136), (56, [.accepted, .symbol], 136), (3, .symbol, 146), (6, .symbol, 146), (10, .symbol, 146), (15, .symbol, 146), (24, .symbol, 146), (31, .symbol, 146), (41, .symbol, 146), (56, [.accepted, .symbol], 146), /* 126 */ (1, .symbol, 154), (22, [.accepted, .symbol], 154), (1, .symbol, 156), (22, [.accepted, .symbol], 156), (1, .symbol, 160), (22, [.accepted, .symbol], 160), (1, .symbol, 163), (22, [.accepted, .symbol], 163), (1, .symbol, 164), (22, [.accepted, .symbol], 164), (1, .symbol, 169), (22, [.accepted, .symbol], 169), (1, .symbol, 170), (22, [.accepted, .symbol], 170), (1, .symbol, 173), (22, [.accepted, .symbol], 173), /* 127 */ (2, .symbol, 154), (9, .symbol, 154), (23, .symbol, 154), (40, [.accepted, .symbol], 154), (2, .symbol, 156), (9, .symbol, 156), (23, .symbol, 156), (40, [.accepted, .symbol], 156), (2, .symbol, 160), (9, .symbol, 160), (23, .symbol, 160), (40, [.accepted, .symbol], 160), (2, .symbol, 163), (9, .symbol, 163), (23, .symbol, 163), (40, [.accepted, .symbol], 163), /* 128 */ (3, .symbol, 154), (6, .symbol, 154), (10, .symbol, 154), (15, .symbol, 154), (24, .symbol, 154), (31, .symbol, 154), (41, .symbol, 154), (56, [.accepted, .symbol], 154), (3, .symbol, 156), (6, .symbol, 156), (10, .symbol, 156), (15, .symbol, 156), (24, .symbol, 156), (31, .symbol, 156), (41, .symbol, 156), (56, [.accepted, .symbol], 156), /* 129 */ (3, .symbol, 160), (6, .symbol, 160), (10, .symbol, 160), (15, .symbol, 160), (24, .symbol, 160), (31, .symbol, 160), (41, .symbol, 160), (56, [.accepted, .symbol], 160), (3, .symbol, 163), (6, .symbol, 163), (10, .symbol, 163), (15, .symbol, 163), (24, .symbol, 163), (31, .symbol, 163), (41, .symbol, 163), (56, [.accepted, .symbol], 163), /* 130 */ (2, .symbol, 164), (9, .symbol, 164), (23, .symbol, 164), (40, [.accepted, .symbol], 164), (2, .symbol, 169), (9, .symbol, 169), (23, .symbol, 169), (40, [.accepted, .symbol], 169), (2, .symbol, 170), (9, .symbol, 170), (23, .symbol, 170), (40, [.accepted, .symbol], 170), (2, .symbol, 173), (9, .symbol, 173), (23, .symbol, 173), (40, [.accepted, .symbol], 173), /* 131 */ (3, .symbol, 164), (6, .symbol, 164), (10, .symbol, 164), (15, .symbol, 164), (24, .symbol, 164), (31, .symbol, 164), (41, .symbol, 164), (56, [.accepted, .symbol], 164), (3, .symbol, 169), (6, .symbol, 169), (10, .symbol, 169), (15, .symbol, 169), (24, .symbol, 169), (31, .symbol, 169), (41, .symbol, 169), (56, [.accepted, .symbol], 169), /* 132 */ (3, .symbol, 170), (6, .symbol, 170), (10, .symbol, 170), (15, .symbol, 170), (24, .symbol, 170), (31, .symbol, 170), (41, .symbol, 170), (56, [.accepted, .symbol], 170), (3, .symbol, 173), (6, .symbol, 173), (10, .symbol, 173), (15, .symbol, 173), (24, .symbol, 173), (31, .symbol, 173), (41, .symbol, 173), (56, [.accepted, .symbol], 173), /* 133 */ (137, .none, 0), (138, .none, 0), (140, .none, 0), (141, .none, 0), (144, .none, 0), (145, .none, 0), (147, .none, 0), (150, .none, 0), (156, .none, 0), (159, .none, 0), (163, .none, 0), (166, .none, 0), (171, .none, 0), (174, .none, 0), (181, .none, 0), (190, .none, 0), /* 134 */ (0, [.accepted, .symbol], 178), (0, [.accepted, .symbol], 181), (0, [.accepted, .symbol], 185), (0, [.accepted, .symbol], 186), (0, [.accepted, .symbol], 187), (0, [.accepted, .symbol], 189), (0, [.accepted, .symbol], 190), (0, [.accepted, .symbol], 196), (0, [.accepted, .symbol], 198), (0, [.accepted, .symbol], 228), (0, [.accepted, .symbol], 232), (0, [.accepted, .symbol], 233), (148, .none, 0), (149, .none, 0), (151, .none, 0), (152, .none, 0), /* 135 */ (1, .symbol, 178), (22, [.accepted, .symbol], 178), (1, .symbol, 181), (22, [.accepted, .symbol], 181), (1, .symbol, 185), (22, [.accepted, .symbol], 185), (1, .symbol, 186), (22, [.accepted, .symbol], 186), (1, .symbol, 187), (22, [.accepted, .symbol], 187), (1, .symbol, 189), (22, [.accepted, .symbol], 189), (1, .symbol, 190), (22, [.accepted, .symbol], 190), (1, .symbol, 196), (22, [.accepted, .symbol], 196), /* 136 */ (2, .symbol, 178), (9, .symbol, 178), (23, .symbol, 178), (40, [.accepted, .symbol], 178), (2, .symbol, 181), (9, .symbol, 181), (23, .symbol, 181), (40, [.accepted, .symbol], 181), (2, .symbol, 185), (9, .symbol, 185), (23, .symbol, 185), (40, [.accepted, .symbol], 185), (2, .symbol, 186), (9, .symbol, 186), (23, .symbol, 186), (40, [.accepted, .symbol], 186), /* 137 */ (3, .symbol, 178), (6, .symbol, 178), (10, .symbol, 178), (15, .symbol, 178), (24, .symbol, 178), (31, .symbol, 178), (41, .symbol, 178), (56, [.accepted, .symbol], 178), (3, .symbol, 181), (6, .symbol, 181), (10, .symbol, 181), (15, .symbol, 181), (24, .symbol, 181), (31, .symbol, 181), (41, .symbol, 181), (56, [.accepted, .symbol], 181), /* 138 */ (3, .symbol, 185), (6, .symbol, 185), (10, .symbol, 185), (15, .symbol, 185), (24, .symbol, 185), (31, .symbol, 185), (41, .symbol, 185), (56, [.accepted, .symbol], 185), (3, .symbol, 186), (6, .symbol, 186), (10, .symbol, 186), (15, .symbol, 186), (24, .symbol, 186), (31, .symbol, 186), (41, .symbol, 186), (56, [.accepted, .symbol], 186), /* 139 */ (2, .symbol, 187), (9, .symbol, 187), (23, .symbol, 187), (40, [.accepted, .symbol], 187), (2, .symbol, 189), (9, .symbol, 189), (23, .symbol, 189), (40, [.accepted, .symbol], 189), (2, .symbol, 190), (9, .symbol, 190), (23, .symbol, 190), (40, [.accepted, .symbol], 190), (2, .symbol, 196), (9, .symbol, 196), (23, .symbol, 196), (40, [.accepted, .symbol], 196), /* 140 */ (3, .symbol, 187), (6, .symbol, 187), (10, .symbol, 187), (15, .symbol, 187), (24, .symbol, 187), (31, .symbol, 187), (41, .symbol, 187), (56, [.accepted, .symbol], 187), (3, .symbol, 189), (6, .symbol, 189), (10, .symbol, 189), (15, .symbol, 189), (24, .symbol, 189), (31, .symbol, 189), (41, .symbol, 189), (56, [.accepted, .symbol], 189), /* 141 */ (3, .symbol, 190), (6, .symbol, 190), (10, .symbol, 190), (15, .symbol, 190), (24, .symbol, 190), (31, .symbol, 190), (41, .symbol, 190), (56, [.accepted, .symbol], 190), (3, .symbol, 196), (6, .symbol, 196), (10, .symbol, 196), (15, .symbol, 196), (24, .symbol, 196), (31, .symbol, 196), (41, .symbol, 196), (56, [.accepted, .symbol], 196), /* 142 */ (1, .symbol, 198), (22, [.accepted, .symbol], 198), (1, .symbol, 228), (22, [.accepted, .symbol], 228), (1, .symbol, 232), (22, [.accepted, .symbol], 232), (1, .symbol, 233), (22, [.accepted, .symbol], 233), (0, [.accepted, .symbol], 1), (0, [.accepted, .symbol], 135), (0, [.accepted, .symbol], 137), (0, [.accepted, .symbol], 138), (0, [.accepted, .symbol], 139), (0, [.accepted, .symbol], 140), (0, [.accepted, .symbol], 141), (0, [.accepted, .symbol], 143), /* 143 */ (2, .symbol, 198), (9, .symbol, 198), (23, .symbol, 198), (40, [.accepted, .symbol], 198), (2, .symbol, 228), (9, .symbol, 228), (23, .symbol, 228), (40, [.accepted, .symbol], 228), (2, .symbol, 232), (9, .symbol, 232), (23, .symbol, 232), (40, [.accepted, .symbol], 232), (2, .symbol, 233), (9, .symbol, 233), (23, .symbol, 233), (40, [.accepted, .symbol], 233), /* 144 */ (3, .symbol, 198), (6, .symbol, 198), (10, .symbol, 198), (15, .symbol, 198), (24, .symbol, 198), (31, .symbol, 198), (41, .symbol, 198), (56, [.accepted, .symbol], 198), (3, .symbol, 228), (6, .symbol, 228), (10, .symbol, 228), (15, .symbol, 228), (24, .symbol, 228), (31, .symbol, 228), (41, .symbol, 228), (56, [.accepted, .symbol], 228), /* 145 */ (3, .symbol, 232), (6, .symbol, 232), (10, .symbol, 232), (15, .symbol, 232), (24, .symbol, 232), (31, .symbol, 232), (41, .symbol, 232), (56, [.accepted, .symbol], 232), (3, .symbol, 233), (6, .symbol, 233), (10, .symbol, 233), (15, .symbol, 233), (24, .symbol, 233), (31, .symbol, 233), (41, .symbol, 233), (56, [.accepted, .symbol], 233), /* 146 */ (1, .symbol, 1), (22, [.accepted, .symbol], 1), (1, .symbol, 135), (22, [.accepted, .symbol], 135), (1, .symbol, 137), (22, [.accepted, .symbol], 137), (1, .symbol, 138), (22, [.accepted, .symbol], 138), (1, .symbol, 139), (22, [.accepted, .symbol], 139), (1, .symbol, 140), (22, [.accepted, .symbol], 140), (1, .symbol, 141), (22, [.accepted, .symbol], 141), (1, .symbol, 143), (22, [.accepted, .symbol], 143), /* 147 */ (2, .symbol, 1), (9, .symbol, 1), (23, .symbol, 1), (40, [.accepted, .symbol], 1), (2, .symbol, 135), (9, .symbol, 135), (23, .symbol, 135), (40, [.accepted, .symbol], 135), (2, .symbol, 137), (9, .symbol, 137), (23, .symbol, 137), (40, [.accepted, .symbol], 137), (2, .symbol, 138), (9, .symbol, 138), (23, .symbol, 138), (40, [.accepted, .symbol], 138), /* 148 */ (3, .symbol, 1), (6, .symbol, 1), (10, .symbol, 1), (15, .symbol, 1), (24, .symbol, 1), (31, .symbol, 1), (41, .symbol, 1), (56, [.accepted, .symbol], 1), (3, .symbol, 135), (6, .symbol, 135), (10, .symbol, 135), (15, .symbol, 135), (24, .symbol, 135), (31, .symbol, 135), (41, .symbol, 135), (56, [.accepted, .symbol], 135), /* 149 */ (3, .symbol, 137), (6, .symbol, 137), (10, .symbol, 137), (15, .symbol, 137), (24, .symbol, 137), (31, .symbol, 137), (41, .symbol, 137), (56, [.accepted, .symbol], 137), (3, .symbol, 138), (6, .symbol, 138), (10, .symbol, 138), (15, .symbol, 138), (24, .symbol, 138), (31, .symbol, 138), (41, .symbol, 138), (56, [.accepted, .symbol], 138), /* 150 */ (2, .symbol, 139), (9, .symbol, 139), (23, .symbol, 139), (40, [.accepted, .symbol], 139), (2, .symbol, 140), (9, .symbol, 140), (23, .symbol, 140), (40, [.accepted, .symbol], 140), (2, .symbol, 141), (9, .symbol, 141), (23, .symbol, 141), (40, [.accepted, .symbol], 141), (2, .symbol, 143), (9, .symbol, 143), (23, .symbol, 143), (40, [.accepted, .symbol], 143), /* 151 */ (3, .symbol, 139), (6, .symbol, 139), (10, .symbol, 139), (15, .symbol, 139), (24, .symbol, 139), (31, .symbol, 139), (41, .symbol, 139), (56, [.accepted, .symbol], 139), (3, .symbol, 140), (6, .symbol, 140), (10, .symbol, 140), (15, .symbol, 140), (24, .symbol, 140), (31, .symbol, 140), (41, .symbol, 140), (56, [.accepted, .symbol], 140), /* 152 */ (3, .symbol, 141), (6, .symbol, 141), (10, .symbol, 141), (15, .symbol, 141), (24, .symbol, 141), (31, .symbol, 141), (41, .symbol, 141), (56, [.accepted, .symbol], 141), (3, .symbol, 143), (6, .symbol, 143), (10, .symbol, 143), (15, .symbol, 143), (24, .symbol, 143), (31, .symbol, 143), (41, .symbol, 143), (56, [.accepted, .symbol], 143), /* 153 */ (157, .none, 0), (158, .none, 0), (160, .none, 0), (161, .none, 0), (164, .none, 0), (165, .none, 0), (167, .none, 0), (168, .none, 0), (172, .none, 0), (173, .none, 0), (175, .none, 0), (177, .none, 0), (182, .none, 0), (185, .none, 0), (191, .none, 0), (207, .none, 0), /* 154 */ (0, [.accepted, .symbol], 147), (0, [.accepted, .symbol], 149), (0, [.accepted, .symbol], 150), (0, [.accepted, .symbol], 151), (0, [.accepted, .symbol], 152), (0, [.accepted, .symbol], 155), (0, [.accepted, .symbol], 157), (0, [.accepted, .symbol], 158), (0, [.accepted, .symbol], 165), (0, [.accepted, .symbol], 166), (0, [.accepted, .symbol], 168), (0, [.accepted, .symbol], 174), (0, [.accepted, .symbol], 175), (0, [.accepted, .symbol], 180), (0, [.accepted, .symbol], 182), (0, [.accepted, .symbol], 183), /* 155 */ (1, .symbol, 147), (22, [.accepted, .symbol], 147), (1, .symbol, 149), (22, [.accepted, .symbol], 149), (1, .symbol, 150), (22, [.accepted, .symbol], 150), (1, .symbol, 151), (22, [.accepted, .symbol], 151), (1, .symbol, 152), (22, [.accepted, .symbol], 152), (1, .symbol, 155), (22, [.accepted, .symbol], 155), (1, .symbol, 157), (22, [.accepted, .symbol], 157), (1, .symbol, 158), (22, [.accepted, .symbol], 158), /* 156 */ (2, .symbol, 147), (9, .symbol, 147), (23, .symbol, 147), (40, [.accepted, .symbol], 147), (2, .symbol, 149), (9, .symbol, 149), (23, .symbol, 149), (40, [.accepted, .symbol], 149), (2, .symbol, 150), (9, .symbol, 150), (23, .symbol, 150), (40, [.accepted, .symbol], 150), (2, .symbol, 151), (9, .symbol, 151), (23, .symbol, 151), (40, [.accepted, .symbol], 151), /* 157 */ (3, .symbol, 147), (6, .symbol, 147), (10, .symbol, 147), (15, .symbol, 147), (24, .symbol, 147), (31, .symbol, 147), (41, .symbol, 147), (56, [.accepted, .symbol], 147), (3, .symbol, 149), (6, .symbol, 149), (10, .symbol, 149), (15, .symbol, 149), (24, .symbol, 149), (31, .symbol, 149), (41, .symbol, 149), (56, [.accepted, .symbol], 149), /* 158 */ (3, .symbol, 150), (6, .symbol, 150), (10, .symbol, 150), (15, .symbol, 150), (24, .symbol, 150), (31, .symbol, 150), (41, .symbol, 150), (56, [.accepted, .symbol], 150), (3, .symbol, 151), (6, .symbol, 151), (10, .symbol, 151), (15, .symbol, 151), (24, .symbol, 151), (31, .symbol, 151), (41, .symbol, 151), (56, [.accepted, .symbol], 151), /* 159 */ (2, .symbol, 152), (9, .symbol, 152), (23, .symbol, 152), (40, [.accepted, .symbol], 152), (2, .symbol, 155), (9, .symbol, 155), (23, .symbol, 155), (40, [.accepted, .symbol], 155), (2, .symbol, 157), (9, .symbol, 157), (23, .symbol, 157), (40, [.accepted, .symbol], 157), (2, .symbol, 158), (9, .symbol, 158), (23, .symbol, 158), (40, [.accepted, .symbol], 158), /* 160 */ (3, .symbol, 152), (6, .symbol, 152), (10, .symbol, 152), (15, .symbol, 152), (24, .symbol, 152), (31, .symbol, 152), (41, .symbol, 152), (56, [.accepted, .symbol], 152), (3, .symbol, 155), (6, .symbol, 155), (10, .symbol, 155), (15, .symbol, 155), (24, .symbol, 155), (31, .symbol, 155), (41, .symbol, 155), (56, [.accepted, .symbol], 155), /* 161 */ (3, .symbol, 157), (6, .symbol, 157), (10, .symbol, 157), (15, .symbol, 157), (24, .symbol, 157), (31, .symbol, 157), (41, .symbol, 157), (56, [.accepted, .symbol], 157), (3, .symbol, 158), (6, .symbol, 158), (10, .symbol, 158), (15, .symbol, 158), (24, .symbol, 158), (31, .symbol, 158), (41, .symbol, 158), (56, [.accepted, .symbol], 158), /* 162 */ (1, .symbol, 165), (22, [.accepted, .symbol], 165), (1, .symbol, 166), (22, [.accepted, .symbol], 166), (1, .symbol, 168), (22, [.accepted, .symbol], 168), (1, .symbol, 174), (22, [.accepted, .symbol], 174), (1, .symbol, 175), (22, [.accepted, .symbol], 175), (1, .symbol, 180), (22, [.accepted, .symbol], 180), (1, .symbol, 182), (22, [.accepted, .symbol], 182), (1, .symbol, 183), (22, [.accepted, .symbol], 183), /* 163 */ (2, .symbol, 165), (9, .symbol, 165), (23, .symbol, 165), (40, [.accepted, .symbol], 165), (2, .symbol, 166), (9, .symbol, 166), (23, .symbol, 166), (40, [.accepted, .symbol], 166), (2, .symbol, 168), (9, .symbol, 168), (23, .symbol, 168), (40, [.accepted, .symbol], 168), (2, .symbol, 174), (9, .symbol, 174), (23, .symbol, 174), (40, [.accepted, .symbol], 174), /* 164 */ (3, .symbol, 165), (6, .symbol, 165), (10, .symbol, 165), (15, .symbol, 165), (24, .symbol, 165), (31, .symbol, 165), (41, .symbol, 165), (56, [.accepted, .symbol], 165), (3, .symbol, 166), (6, .symbol, 166), (10, .symbol, 166), (15, .symbol, 166), (24, .symbol, 166), (31, .symbol, 166), (41, .symbol, 166), (56, [.accepted, .symbol], 166), /* 165 */ (3, .symbol, 168), (6, .symbol, 168), (10, .symbol, 168), (15, .symbol, 168), (24, .symbol, 168), (31, .symbol, 168), (41, .symbol, 168), (56, [.accepted, .symbol], 168), (3, .symbol, 174), (6, .symbol, 174), (10, .symbol, 174), (15, .symbol, 174), (24, .symbol, 174), (31, .symbol, 174), (41, .symbol, 174), (56, [.accepted, .symbol], 174), /* 166 */ (2, .symbol, 175), (9, .symbol, 175), (23, .symbol, 175), (40, [.accepted, .symbol], 175), (2, .symbol, 180), (9, .symbol, 180), (23, .symbol, 180), (40, [.accepted, .symbol], 180), (2, .symbol, 182), (9, .symbol, 182), (23, .symbol, 182), (40, [.accepted, .symbol], 182), (2, .symbol, 183), (9, .symbol, 183), (23, .symbol, 183), (40, [.accepted, .symbol], 183), /* 167 */ (3, .symbol, 175), (6, .symbol, 175), (10, .symbol, 175), (15, .symbol, 175), (24, .symbol, 175), (31, .symbol, 175), (41, .symbol, 175), (56, [.accepted, .symbol], 175), (3, .symbol, 180), (6, .symbol, 180), (10, .symbol, 180), (15, .symbol, 180), (24, .symbol, 180), (31, .symbol, 180), (41, .symbol, 180), (56, [.accepted, .symbol], 180), /* 168 */ (3, .symbol, 182), (6, .symbol, 182), (10, .symbol, 182), (15, .symbol, 182), (24, .symbol, 182), (31, .symbol, 182), (41, .symbol, 182), (56, [.accepted, .symbol], 182), (3, .symbol, 183), (6, .symbol, 183), (10, .symbol, 183), (15, .symbol, 183), (24, .symbol, 183), (31, .symbol, 183), (41, .symbol, 183), (56, [.accepted, .symbol], 183), /* 169 */ (0, [.accepted, .symbol], 188), (0, [.accepted, .symbol], 191), (0, [.accepted, .symbol], 197), (0, [.accepted, .symbol], 231), (0, [.accepted, .symbol], 239), (176, .none, 0), (178, .none, 0), (179, .none, 0), (183, .none, 0), (184, .none, 0), (186, .none, 0), (187, .none, 0), (192, .none, 0), (199, .none, 0), (208, .none, 0), (223, .none, 0), /* 170 */ (1, .symbol, 188), (22, [.accepted, .symbol], 188), (1, .symbol, 191), (22, [.accepted, .symbol], 191), (1, .symbol, 197), (22, [.accepted, .symbol], 197), (1, .symbol, 231), (22, [.accepted, .symbol], 231), (1, .symbol, 239), (22, [.accepted, .symbol], 239), (0, [.accepted, .symbol], 9), (0, [.accepted, .symbol], 142), (0, [.accepted, .symbol], 144), (0, [.accepted, .symbol], 145), (0, [.accepted, .symbol], 148), (0, [.accepted, .symbol], 159), /* 171 */ (2, .symbol, 188), (9, .symbol, 188), (23, .symbol, 188), (40, [.accepted, .symbol], 188), (2, .symbol, 191), (9, .symbol, 191), (23, .symbol, 191), (40, [.accepted, .symbol], 191), (2, .symbol, 197), (9, .symbol, 197), (23, .symbol, 197), (40, [.accepted, .symbol], 197), (2, .symbol, 231), (9, .symbol, 231), (23, .symbol, 231), (40, [.accepted, .symbol], 231), /* 172 */ (3, .symbol, 188), (6, .symbol, 188), (10, .symbol, 188), (15, .symbol, 188), (24, .symbol, 188), (31, .symbol, 188), (41, .symbol, 188), (56, [.accepted, .symbol], 188), (3, .symbol, 191), (6, .symbol, 191), (10, .symbol, 191), (15, .symbol, 191), (24, .symbol, 191), (31, .symbol, 191), (41, .symbol, 191), (56, [.accepted, .symbol], 191), /* 173 */ (3, .symbol, 197), (6, .symbol, 197), (10, .symbol, 197), (15, .symbol, 197), (24, .symbol, 197), (31, .symbol, 197), (41, .symbol, 197), (56, [.accepted, .symbol], 197), (3, .symbol, 231), (6, .symbol, 231), (10, .symbol, 231), (15, .symbol, 231), (24, .symbol, 231), (31, .symbol, 231), (41, .symbol, 231), (56, [.accepted, .symbol], 231), /* 174 */ (2, .symbol, 239), (9, .symbol, 239), (23, .symbol, 239), (40, [.accepted, .symbol], 239), (1, .symbol, 9), (22, [.accepted, .symbol], 9), (1, .symbol, 142), (22, [.accepted, .symbol], 142), (1, .symbol, 144), (22, [.accepted, .symbol], 144), (1, .symbol, 145), (22, [.accepted, .symbol], 145), (1, .symbol, 148), (22, [.accepted, .symbol], 148), (1, .symbol, 159), (22, [.accepted, .symbol], 159), /* 175 */ (3, .symbol, 239), (6, .symbol, 239), (10, .symbol, 239), (15, .symbol, 239), (24, .symbol, 239), (31, .symbol, 239), (41, .symbol, 239), (56, [.accepted, .symbol], 239), (2, .symbol, 9), (9, .symbol, 9), (23, .symbol, 9), (40, [.accepted, .symbol], 9), (2, .symbol, 142), (9, .symbol, 142), (23, .symbol, 142), (40, [.accepted, .symbol], 142), /* 176 */ (3, .symbol, 9), (6, .symbol, 9), (10, .symbol, 9), (15, .symbol, 9), (24, .symbol, 9), (31, .symbol, 9), (41, .symbol, 9), (56, [.accepted, .symbol], 9), (3, .symbol, 142), (6, .symbol, 142), (10, .symbol, 142), (15, .symbol, 142), (24, .symbol, 142), (31, .symbol, 142), (41, .symbol, 142), (56, [.accepted, .symbol], 142), /* 177 */ (2, .symbol, 144), (9, .symbol, 144), (23, .symbol, 144), (40, [.accepted, .symbol], 144), (2, .symbol, 145), (9, .symbol, 145), (23, .symbol, 145), (40, [.accepted, .symbol], 145), (2, .symbol, 148), (9, .symbol, 148), (23, .symbol, 148), (40, [.accepted, .symbol], 148), (2, .symbol, 159), (9, .symbol, 159), (23, .symbol, 159), (40, [.accepted, .symbol], 159), /* 178 */ (3, .symbol, 144), (6, .symbol, 144), (10, .symbol, 144), (15, .symbol, 144), (24, .symbol, 144), (31, .symbol, 144), (41, .symbol, 144), (56, [.accepted, .symbol], 144), (3, .symbol, 145), (6, .symbol, 145), (10, .symbol, 145), (15, .symbol, 145), (24, .symbol, 145), (31, .symbol, 145), (41, .symbol, 145), (56, [.accepted, .symbol], 145), /* 179 */ (3, .symbol, 148), (6, .symbol, 148), (10, .symbol, 148), (15, .symbol, 148), (24, .symbol, 148), (31, .symbol, 148), (41, .symbol, 148), (56, [.accepted, .symbol], 148), (3, .symbol, 159), (6, .symbol, 159), (10, .symbol, 159), (15, .symbol, 159), (24, .symbol, 159), (31, .symbol, 159), (41, .symbol, 159), (56, [.accepted, .symbol], 159), /* 180 */ (0, [.accepted, .symbol], 171), (0, [.accepted, .symbol], 206), (0, [.accepted, .symbol], 215), (0, [.accepted, .symbol], 225), (0, [.accepted, .symbol], 236), (0, [.accepted, .symbol], 237), (188, .none, 0), (189, .none, 0), (193, .none, 0), (196, .none, 0), (200, .none, 0), (203, .none, 0), (209, .none, 0), (216, .none, 0), (224, .none, 0), (238, .none, 0), /* 181 */ (1, .symbol, 171), (22, [.accepted, .symbol], 171), (1, .symbol, 206), (22, [.accepted, .symbol], 206), (1, .symbol, 215), (22, [.accepted, .symbol], 215), (1, .symbol, 225), (22, [.accepted, .symbol], 225), (1, .symbol, 236), (22, [.accepted, .symbol], 236), (1, .symbol, 237), (22, [.accepted, .symbol], 237), (0, [.accepted, .symbol], 199), (0, [.accepted, .symbol], 207), (0, [.accepted, .symbol], 234), (0, [.accepted, .symbol], 235), /* 182 */ (2, .symbol, 171), (9, .symbol, 171), (23, .symbol, 171), (40, [.accepted, .symbol], 171), (2, .symbol, 206), (9, .symbol, 206), (23, .symbol, 206), (40, [.accepted, .symbol], 206), (2, .symbol, 215), (9, .symbol, 215), (23, .symbol, 215), (40, [.accepted, .symbol], 215), (2, .symbol, 225), (9, .symbol, 225), (23, .symbol, 225), (40, [.accepted, .symbol], 225), /* 183 */ (3, .symbol, 171), (6, .symbol, 171), (10, .symbol, 171), (15, .symbol, 171), (24, .symbol, 171), (31, .symbol, 171), (41, .symbol, 171), (56, [.accepted, .symbol], 171), (3, .symbol, 206), (6, .symbol, 206), (10, .symbol, 206), (15, .symbol, 206), (24, .symbol, 206), (31, .symbol, 206), (41, .symbol, 206), (56, [.accepted, .symbol], 206), /* 184 */ (3, .symbol, 215), (6, .symbol, 215), (10, .symbol, 215), (15, .symbol, 215), (24, .symbol, 215), (31, .symbol, 215), (41, .symbol, 215), (56, [.accepted, .symbol], 215), (3, .symbol, 225), (6, .symbol, 225), (10, .symbol, 225), (15, .symbol, 225), (24, .symbol, 225), (31, .symbol, 225), (41, .symbol, 225), (56, [.accepted, .symbol], 225), /* 185 */ (2, .symbol, 236), (9, .symbol, 236), (23, .symbol, 236), (40, [.accepted, .symbol], 236), (2, .symbol, 237), (9, .symbol, 237), (23, .symbol, 237), (40, [.accepted, .symbol], 237), (1, .symbol, 199), (22, [.accepted, .symbol], 199), (1, .symbol, 207), (22, [.accepted, .symbol], 207), (1, .symbol, 234), (22, [.accepted, .symbol], 234), (1, .symbol, 235), (22, [.accepted, .symbol], 235), /* 186 */ (3, .symbol, 236), (6, .symbol, 236), (10, .symbol, 236), (15, .symbol, 236), (24, .symbol, 236), (31, .symbol, 236), (41, .symbol, 236), (56, [.accepted, .symbol], 236), (3, .symbol, 237), (6, .symbol, 237), (10, .symbol, 237), (15, .symbol, 237), (24, .symbol, 237), (31, .symbol, 237), (41, .symbol, 237), (56, [.accepted, .symbol], 237), /* 187 */ (2, .symbol, 199), (9, .symbol, 199), (23, .symbol, 199), (40, [.accepted, .symbol], 199), (2, .symbol, 207), (9, .symbol, 207), (23, .symbol, 207), (40, [.accepted, .symbol], 207), (2, .symbol, 234), (9, .symbol, 234), (23, .symbol, 234), (40, [.accepted, .symbol], 234), (2, .symbol, 235), (9, .symbol, 235), (23, .symbol, 235), (40, [.accepted, .symbol], 235), /* 188 */ (3, .symbol, 199), (6, .symbol, 199), (10, .symbol, 199), (15, .symbol, 199), (24, .symbol, 199), (31, .symbol, 199), (41, .symbol, 199), (56, [.accepted, .symbol], 199), (3, .symbol, 207), (6, .symbol, 207), (10, .symbol, 207), (15, .symbol, 207), (24, .symbol, 207), (31, .symbol, 207), (41, .symbol, 207), (56, [.accepted, .symbol], 207), /* 189 */ (3, .symbol, 234), (6, .symbol, 234), (10, .symbol, 234), (15, .symbol, 234), (24, .symbol, 234), (31, .symbol, 234), (41, .symbol, 234), (56, [.accepted, .symbol], 234), (3, .symbol, 235), (6, .symbol, 235), (10, .symbol, 235), (15, .symbol, 235), (24, .symbol, 235), (31, .symbol, 235), (41, .symbol, 235), (56, [.accepted, .symbol], 235), /* 190 */ (194, .none, 0), (195, .none, 0), (197, .none, 0), (198, .none, 0), (201, .none, 0), (202, .none, 0), (204, .none, 0), (205, .none, 0), (210, .none, 0), (213, .none, 0), (217, .none, 0), (220, .none, 0), (225, .none, 0), (231, .none, 0), (239, .none, 0), (246, .none, 0), /* 191 */ (0, [.accepted, .symbol], 192), (0, [.accepted, .symbol], 193), (0, [.accepted, .symbol], 200), (0, [.accepted, .symbol], 201), (0, [.accepted, .symbol], 202), (0, [.accepted, .symbol], 205), (0, [.accepted, .symbol], 210), (0, [.accepted, .symbol], 213), (0, [.accepted, .symbol], 218), (0, [.accepted, .symbol], 219), (0, [.accepted, .symbol], 238), (0, [.accepted, .symbol], 240), (0, [.accepted, .symbol], 242), (0, [.accepted, .symbol], 243), (0, [.accepted, .symbol], 255), (206, .none, 0), /* 192 */ (1, .symbol, 192), (22, [.accepted, .symbol], 192), (1, .symbol, 193), (22, [.accepted, .symbol], 193), (1, .symbol, 200), (22, [.accepted, .symbol], 200), (1, .symbol, 201), (22, [.accepted, .symbol], 201), (1, .symbol, 202), (22, [.accepted, .symbol], 202), (1, .symbol, 205), (22, [.accepted, .symbol], 205), (1, .symbol, 210), (22, [.accepted, .symbol], 210), (1, .symbol, 213), (22, [.accepted, .symbol], 213), /* 193 */ (2, .symbol, 192), (9, .symbol, 192), (23, .symbol, 192), (40, [.accepted, .symbol], 192), (2, .symbol, 193), (9, .symbol, 193), (23, .symbol, 193), (40, [.accepted, .symbol], 193), (2, .symbol, 200), (9, .symbol, 200), (23, .symbol, 200), (40, [.accepted, .symbol], 200), (2, .symbol, 201), (9, .symbol, 201), (23, .symbol, 201), (40, [.accepted, .symbol], 201), /* 194 */ (3, .symbol, 192), (6, .symbol, 192), (10, .symbol, 192), (15, .symbol, 192), (24, .symbol, 192), (31, .symbol, 192), (41, .symbol, 192), (56, [.accepted, .symbol], 192), (3, .symbol, 193), (6, .symbol, 193), (10, .symbol, 193), (15, .symbol, 193), (24, .symbol, 193), (31, .symbol, 193), (41, .symbol, 193), (56, [.accepted, .symbol], 193), /* 195 */ (3, .symbol, 200), (6, .symbol, 200), (10, .symbol, 200), (15, .symbol, 200), (24, .symbol, 200), (31, .symbol, 200), (41, .symbol, 200), (56, [.accepted, .symbol], 200), (3, .symbol, 201), (6, .symbol, 201), (10, .symbol, 201), (15, .symbol, 201), (24, .symbol, 201), (31, .symbol, 201), (41, .symbol, 201), (56, [.accepted, .symbol], 201), /* 196 */ (2, .symbol, 202), (9, .symbol, 202), (23, .symbol, 202), (40, [.accepted, .symbol], 202), (2, .symbol, 205), (9, .symbol, 205), (23, .symbol, 205), (40, [.accepted, .symbol], 205), (2, .symbol, 210), (9, .symbol, 210), (23, .symbol, 210), (40, [.accepted, .symbol], 210), (2, .symbol, 213), (9, .symbol, 213), (23, .symbol, 213), (40, [.accepted, .symbol], 213), /* 197 */ (3, .symbol, 202), (6, .symbol, 202), (10, .symbol, 202), (15, .symbol, 202), (24, .symbol, 202), (31, .symbol, 202), (41, .symbol, 202), (56, [.accepted, .symbol], 202), (3, .symbol, 205), (6, .symbol, 205), (10, .symbol, 205), (15, .symbol, 205), (24, .symbol, 205), (31, .symbol, 205), (41, .symbol, 205), (56, [.accepted, .symbol], 205), /* 198 */ (3, .symbol, 210), (6, .symbol, 210), (10, .symbol, 210), (15, .symbol, 210), (24, .symbol, 210), (31, .symbol, 210), (41, .symbol, 210), (56, [.accepted, .symbol], 210), (3, .symbol, 213), (6, .symbol, 213), (10, .symbol, 213), (15, .symbol, 213), (24, .symbol, 213), (31, .symbol, 213), (41, .symbol, 213), (56, [.accepted, .symbol], 213), /* 199 */ (1, .symbol, 218), (22, [.accepted, .symbol], 218), (1, .symbol, 219), (22, [.accepted, .symbol], 219), (1, .symbol, 238), (22, [.accepted, .symbol], 238), (1, .symbol, 240), (22, [.accepted, .symbol], 240), (1, .symbol, 242), (22, [.accepted, .symbol], 242), (1, .symbol, 243), (22, [.accepted, .symbol], 243), (1, .symbol, 255), (22, [.accepted, .symbol], 255), (0, [.accepted, .symbol], 203), (0, [.accepted, .symbol], 204), /* 200 */ (2, .symbol, 218), (9, .symbol, 218), (23, .symbol, 218), (40, [.accepted, .symbol], 218), (2, .symbol, 219), (9, .symbol, 219), (23, .symbol, 219), (40, [.accepted, .symbol], 219), (2, .symbol, 238), (9, .symbol, 238), (23, .symbol, 238), (40, [.accepted, .symbol], 238), (2, .symbol, 240), (9, .symbol, 240), (23, .symbol, 240), (40, [.accepted, .symbol], 240), /* 201 */ (3, .symbol, 218), (6, .symbol, 218), (10, .symbol, 218), (15, .symbol, 218), (24, .symbol, 218), (31, .symbol, 218), (41, .symbol, 218), (56, [.accepted, .symbol], 218), (3, .symbol, 219), (6, .symbol, 219), (10, .symbol, 219), (15, .symbol, 219), (24, .symbol, 219), (31, .symbol, 219), (41, .symbol, 219), (56, [.accepted, .symbol], 219), /* 202 */ (3, .symbol, 238), (6, .symbol, 238), (10, .symbol, 238), (15, .symbol, 238), (24, .symbol, 238), (31, .symbol, 238), (41, .symbol, 238), (56, [.accepted, .symbol], 238), (3, .symbol, 240), (6, .symbol, 240), (10, .symbol, 240), (15, .symbol, 240), (24, .symbol, 240), (31, .symbol, 240), (41, .symbol, 240), (56, [.accepted, .symbol], 240), /* 203 */ (2, .symbol, 242), (9, .symbol, 242), (23, .symbol, 242), (40, [.accepted, .symbol], 242), (2, .symbol, 243), (9, .symbol, 243), (23, .symbol, 243), (40, [.accepted, .symbol], 243), (2, .symbol, 255), (9, .symbol, 255), (23, .symbol, 255), (40, [.accepted, .symbol], 255), (1, .symbol, 203), (22, [.accepted, .symbol], 203), (1, .symbol, 204), (22, [.accepted, .symbol], 204), /* 204 */ (3, .symbol, 242), (6, .symbol, 242), (10, .symbol, 242), (15, .symbol, 242), (24, .symbol, 242), (31, .symbol, 242), (41, .symbol, 242), (56, [.accepted, .symbol], 242), (3, .symbol, 243), (6, .symbol, 243), (10, .symbol, 243), (15, .symbol, 243), (24, .symbol, 243), (31, .symbol, 243), (41, .symbol, 243), (56, [.accepted, .symbol], 243), /* 205 */ (3, .symbol, 255), (6, .symbol, 255), (10, .symbol, 255), (15, .symbol, 255), (24, .symbol, 255), (31, .symbol, 255), (41, .symbol, 255), (56, [.accepted, .symbol], 255), (2, .symbol, 203), (9, .symbol, 203), (23, .symbol, 203), (40, [.accepted, .symbol], 203), (2, .symbol, 204), (9, .symbol, 204), (23, .symbol, 204), (40, [.accepted, .symbol], 204), /* 206 */ (3, .symbol, 203), (6, .symbol, 203), (10, .symbol, 203), (15, .symbol, 203), (24, .symbol, 203), (31, .symbol, 203), (41, .symbol, 203), (56, [.accepted, .symbol], 203), (3, .symbol, 204), (6, .symbol, 204), (10, .symbol, 204), (15, .symbol, 204), (24, .symbol, 204), (31, .symbol, 204), (41, .symbol, 204), (56, [.accepted, .symbol], 204), /* 207 */ (211, .none, 0), (212, .none, 0), (214, .none, 0), (215, .none, 0), (218, .none, 0), (219, .none, 0), (221, .none, 0), (222, .none, 0), (226, .none, 0), (228, .none, 0), (232, .none, 0), (235, .none, 0), (240, .none, 0), (243, .none, 0), (247, .none, 0), (250, .none, 0), /* 208 */ (0, [.accepted, .symbol], 211), (0, [.accepted, .symbol], 212), (0, [.accepted, .symbol], 214), (0, [.accepted, .symbol], 221), (0, [.accepted, .symbol], 222), (0, [.accepted, .symbol], 223), (0, [.accepted, .symbol], 241), (0, [.accepted, .symbol], 244), (0, [.accepted, .symbol], 245), (0, [.accepted, .symbol], 246), (0, [.accepted, .symbol], 247), (0, [.accepted, .symbol], 248), (0, [.accepted, .symbol], 250), (0, [.accepted, .symbol], 251), (0, [.accepted, .symbol], 252), (0, [.accepted, .symbol], 253), /* 209 */ (1, .symbol, 211), (22, [.accepted, .symbol], 211), (1, .symbol, 212), (22, [.accepted, .symbol], 212), (1, .symbol, 214), (22, [.accepted, .symbol], 214), (1, .symbol, 221), (22, [.accepted, .symbol], 221), (1, .symbol, 222), (22, [.accepted, .symbol], 222), (1, .symbol, 223), (22, [.accepted, .symbol], 223), (1, .symbol, 241), (22, [.accepted, .symbol], 241), (1, .symbol, 244), (22, [.accepted, .symbol], 244), /* 210 */ (2, .symbol, 211), (9, .symbol, 211), (23, .symbol, 211), (40, [.accepted, .symbol], 211), (2, .symbol, 212), (9, .symbol, 212), (23, .symbol, 212), (40, [.accepted, .symbol], 212), (2, .symbol, 214), (9, .symbol, 214), (23, .symbol, 214), (40, [.accepted, .symbol], 214), (2, .symbol, 221), (9, .symbol, 221), (23, .symbol, 221), (40, [.accepted, .symbol], 221), /* 211 */ (3, .symbol, 211), (6, .symbol, 211), (10, .symbol, 211), (15, .symbol, 211), (24, .symbol, 211), (31, .symbol, 211), (41, .symbol, 211), (56, [.accepted, .symbol], 211), (3, .symbol, 212), (6, .symbol, 212), (10, .symbol, 212), (15, .symbol, 212), (24, .symbol, 212), (31, .symbol, 212), (41, .symbol, 212), (56, [.accepted, .symbol], 212), /* 212 */ (3, .symbol, 214), (6, .symbol, 214), (10, .symbol, 214), (15, .symbol, 214), (24, .symbol, 214), (31, .symbol, 214), (41, .symbol, 214), (56, [.accepted, .symbol], 214), (3, .symbol, 221), (6, .symbol, 221), (10, .symbol, 221), (15, .symbol, 221), (24, .symbol, 221), (31, .symbol, 221), (41, .symbol, 221), (56, [.accepted, .symbol], 221), /* 213 */ (2, .symbol, 222), (9, .symbol, 222), (23, .symbol, 222), (40, [.accepted, .symbol], 222), (2, .symbol, 223), (9, .symbol, 223), (23, .symbol, 223), (40, [.accepted, .symbol], 223), (2, .symbol, 241), (9, .symbol, 241), (23, .symbol, 241), (40, [.accepted, .symbol], 241), (2, .symbol, 244), (9, .symbol, 244), (23, .symbol, 244), (40, [.accepted, .symbol], 244), /* 214 */ (3, .symbol, 222), (6, .symbol, 222), (10, .symbol, 222), (15, .symbol, 222), (24, .symbol, 222), (31, .symbol, 222), (41, .symbol, 222), (56, [.accepted, .symbol], 222), (3, .symbol, 223), (6, .symbol, 223), (10, .symbol, 223), (15, .symbol, 223), (24, .symbol, 223), (31, .symbol, 223), (41, .symbol, 223), (56, [.accepted, .symbol], 223), /* 215 */ (3, .symbol, 241), (6, .symbol, 241), (10, .symbol, 241), (15, .symbol, 241), (24, .symbol, 241), (31, .symbol, 241), (41, .symbol, 241), (56, [.accepted, .symbol], 241), (3, .symbol, 244), (6, .symbol, 244), (10, .symbol, 244), (15, .symbol, 244), (24, .symbol, 244), (31, .symbol, 244), (41, .symbol, 244), (56, [.accepted, .symbol], 244), /* 216 */ (1, .symbol, 245), (22, [.accepted, .symbol], 245), (1, .symbol, 246), (22, [.accepted, .symbol], 246), (1, .symbol, 247), (22, [.accepted, .symbol], 247), (1, .symbol, 248), (22, [.accepted, .symbol], 248), (1, .symbol, 250), (22, [.accepted, .symbol], 250), (1, .symbol, 251), (22, [.accepted, .symbol], 251), (1, .symbol, 252), (22, [.accepted, .symbol], 252), (1, .symbol, 253), (22, [.accepted, .symbol], 253), /* 217 */ (2, .symbol, 245), (9, .symbol, 245), (23, .symbol, 245), (40, [.accepted, .symbol], 245), (2, .symbol, 246), (9, .symbol, 246), (23, .symbol, 246), (40, [.accepted, .symbol], 246), (2, .symbol, 247), (9, .symbol, 247), (23, .symbol, 247), (40, [.accepted, .symbol], 247), (2, .symbol, 248), (9, .symbol, 248), (23, .symbol, 248), (40, [.accepted, .symbol], 248), /* 218 */ (3, .symbol, 245), (6, .symbol, 245), (10, .symbol, 245), (15, .symbol, 245), (24, .symbol, 245), (31, .symbol, 245), (41, .symbol, 245), (56, [.accepted, .symbol], 245), (3, .symbol, 246), (6, .symbol, 246), (10, .symbol, 246), (15, .symbol, 246), (24, .symbol, 246), (31, .symbol, 246), (41, .symbol, 246), (56, [.accepted, .symbol], 246), /* 219 */ (3, .symbol, 247), (6, .symbol, 247), (10, .symbol, 247), (15, .symbol, 247), (24, .symbol, 247), (31, .symbol, 247), (41, .symbol, 247), (56, [.accepted, .symbol], 247), (3, .symbol, 248), (6, .symbol, 248), (10, .symbol, 248), (15, .symbol, 248), (24, .symbol, 248), (31, .symbol, 248), (41, .symbol, 248), (56, [.accepted, .symbol], 248), /* 220 */ (2, .symbol, 250), (9, .symbol, 250), (23, .symbol, 250), (40, [.accepted, .symbol], 250), (2, .symbol, 251), (9, .symbol, 251), (23, .symbol, 251), (40, [.accepted, .symbol], 251), (2, .symbol, 252), (9, .symbol, 252), (23, .symbol, 252), (40, [.accepted, .symbol], 252), (2, .symbol, 253), (9, .symbol, 253), (23, .symbol, 253), (40, [.accepted, .symbol], 253), /* 221 */ (3, .symbol, 250), (6, .symbol, 250), (10, .symbol, 250), (15, .symbol, 250), (24, .symbol, 250), (31, .symbol, 250), (41, .symbol, 250), (56, [.accepted, .symbol], 250), (3, .symbol, 251), (6, .symbol, 251), (10, .symbol, 251), (15, .symbol, 251), (24, .symbol, 251), (31, .symbol, 251), (41, .symbol, 251), (56, [.accepted, .symbol], 251), /* 222 */ (3, .symbol, 252), (6, .symbol, 252), (10, .symbol, 252), (15, .symbol, 252), (24, .symbol, 252), (31, .symbol, 252), (41, .symbol, 252), (56, [.accepted, .symbol], 252), (3, .symbol, 253), (6, .symbol, 253), (10, .symbol, 253), (15, .symbol, 253), (24, .symbol, 253), (31, .symbol, 253), (41, .symbol, 253), (56, [.accepted, .symbol], 253), /* 223 */ (0, [.accepted, .symbol], 254), (227, .none, 0), (229, .none, 0), (230, .none, 0), (233, .none, 0), (234, .none, 0), (236, .none, 0), (237, .none, 0), (241, .none, 0), (242, .none, 0), (244, .none, 0), (245, .none, 0), (248, .none, 0), (249, .none, 0), (251, .none, 0), (252, .none, 0), /* 224 */ (1, .symbol, 254), (22, [.accepted, .symbol], 254), (0, [.accepted, .symbol], 2), (0, [.accepted, .symbol], 3), (0, [.accepted, .symbol], 4), (0, [.accepted, .symbol], 5), (0, [.accepted, .symbol], 6), (0, [.accepted, .symbol], 7), (0, [.accepted, .symbol], 8), (0, [.accepted, .symbol], 11), (0, [.accepted, .symbol], 12), (0, [.accepted, .symbol], 14), (0, [.accepted, .symbol], 15), (0, [.accepted, .symbol], 16), (0, [.accepted, .symbol], 17), (0, [.accepted, .symbol], 18), /* 225 */ (2, .symbol, 254), (9, .symbol, 254), (23, .symbol, 254), (40, [.accepted, .symbol], 254), (1, .symbol, 2), (22, [.accepted, .symbol], 2), (1, .symbol, 3), (22, [.accepted, .symbol], 3), (1, .symbol, 4), (22, [.accepted, .symbol], 4), (1, .symbol, 5), (22, [.accepted, .symbol], 5), (1, .symbol, 6), (22, [.accepted, .symbol], 6), (1, .symbol, 7), (22, [.accepted, .symbol], 7), /* 226 */ (3, .symbol, 254), (6, .symbol, 254), (10, .symbol, 254), (15, .symbol, 254), (24, .symbol, 254), (31, .symbol, 254), (41, .symbol, 254), (56, [.accepted, .symbol], 254), (2, .symbol, 2), (9, .symbol, 2), (23, .symbol, 2), (40, [.accepted, .symbol], 2), (2, .symbol, 3), (9, .symbol, 3), (23, .symbol, 3), (40, [.accepted, .symbol], 3), /* 227 */ (3, .symbol, 2), (6, .symbol, 2), (10, .symbol, 2), (15, .symbol, 2), (24, .symbol, 2), (31, .symbol, 2), (41, .symbol, 2), (56, [.accepted, .symbol], 2), (3, .symbol, 3), (6, .symbol, 3), (10, .symbol, 3), (15, .symbol, 3), (24, .symbol, 3), (31, .symbol, 3), (41, .symbol, 3), (56, [.accepted, .symbol], 3), /* 228 */ (2, .symbol, 4), (9, .symbol, 4), (23, .symbol, 4), (40, [.accepted, .symbol], 4), (2, .symbol, 5), (9, .symbol, 5), (23, .symbol, 5), (40, [.accepted, .symbol], 5), (2, .symbol, 6), (9, .symbol, 6), (23, .symbol, 6), (40, [.accepted, .symbol], 6), (2, .symbol, 7), (9, .symbol, 7), (23, .symbol, 7), (40, [.accepted, .symbol], 7), /* 229 */ (3, .symbol, 4), (6, .symbol, 4), (10, .symbol, 4), (15, .symbol, 4), (24, .symbol, 4), (31, .symbol, 4), (41, .symbol, 4), (56, [.accepted, .symbol], 4), (3, .symbol, 5), (6, .symbol, 5), (10, .symbol, 5), (15, .symbol, 5), (24, .symbol, 5), (31, .symbol, 5), (41, .symbol, 5), (56, [.accepted, .symbol], 5), /* 230 */ (3, .symbol, 6), (6, .symbol, 6), (10, .symbol, 6), (15, .symbol, 6), (24, .symbol, 6), (31, .symbol, 6), (41, .symbol, 6), (56, [.accepted, .symbol], 6), (3, .symbol, 7), (6, .symbol, 7), (10, .symbol, 7), (15, .symbol, 7), (24, .symbol, 7), (31, .symbol, 7), (41, .symbol, 7), (56, [.accepted, .symbol], 7), /* 231 */ (1, .symbol, 8), (22, [.accepted, .symbol], 8), (1, .symbol, 11), (22, [.accepted, .symbol], 11), (1, .symbol, 12), (22, [.accepted, .symbol], 12), (1, .symbol, 14), (22, [.accepted, .symbol], 14), (1, .symbol, 15), (22, [.accepted, .symbol], 15), (1, .symbol, 16), (22, [.accepted, .symbol], 16), (1, .symbol, 17), (22, [.accepted, .symbol], 17), (1, .symbol, 18), (22, [.accepted, .symbol], 18), /* 232 */ (2, .symbol, 8), (9, .symbol, 8), (23, .symbol, 8), (40, [.accepted, .symbol], 8), (2, .symbol, 11), (9, .symbol, 11), (23, .symbol, 11), (40, [.accepted, .symbol], 11), (2, .symbol, 12), (9, .symbol, 12), (23, .symbol, 12), (40, [.accepted, .symbol], 12), (2, .symbol, 14), (9, .symbol, 14), (23, .symbol, 14), (40, [.accepted, .symbol], 14), /* 233 */ (3, .symbol, 8), (6, .symbol, 8), (10, .symbol, 8), (15, .symbol, 8), (24, .symbol, 8), (31, .symbol, 8), (41, .symbol, 8), (56, [.accepted, .symbol], 8), (3, .symbol, 11), (6, .symbol, 11), (10, .symbol, 11), (15, .symbol, 11), (24, .symbol, 11), (31, .symbol, 11), (41, .symbol, 11), (56, [.accepted, .symbol], 11), /* 234 */ (3, .symbol, 12), (6, .symbol, 12), (10, .symbol, 12), (15, .symbol, 12), (24, .symbol, 12), (31, .symbol, 12), (41, .symbol, 12), (56, [.accepted, .symbol], 12), (3, .symbol, 14), (6, .symbol, 14), (10, .symbol, 14), (15, .symbol, 14), (24, .symbol, 14), (31, .symbol, 14), (41, .symbol, 14), (56, [.accepted, .symbol], 14), /* 235 */ (2, .symbol, 15), (9, .symbol, 15), (23, .symbol, 15), (40, [.accepted, .symbol], 15), (2, .symbol, 16), (9, .symbol, 16), (23, .symbol, 16), (40, [.accepted, .symbol], 16), (2, .symbol, 17), (9, .symbol, 17), (23, .symbol, 17), (40, [.accepted, .symbol], 17), (2, .symbol, 18), (9, .symbol, 18), (23, .symbol, 18), (40, [.accepted, .symbol], 18), /* 236 */ (3, .symbol, 15), (6, .symbol, 15), (10, .symbol, 15), (15, .symbol, 15), (24, .symbol, 15), (31, .symbol, 15), (41, .symbol, 15), (56, [.accepted, .symbol], 15), (3, .symbol, 16), (6, .symbol, 16), (10, .symbol, 16), (15, .symbol, 16), (24, .symbol, 16), (31, .symbol, 16), (41, .symbol, 16), (56, [.accepted, .symbol], 16), /* 237 */ (3, .symbol, 17), (6, .symbol, 17), (10, .symbol, 17), (15, .symbol, 17), (24, .symbol, 17), (31, .symbol, 17), (41, .symbol, 17), (56, [.accepted, .symbol], 17), (3, .symbol, 18), (6, .symbol, 18), (10, .symbol, 18), (15, .symbol, 18), (24, .symbol, 18), (31, .symbol, 18), (41, .symbol, 18), (56, [.accepted, .symbol], 18), /* 238 */ (0, [.accepted, .symbol], 19), (0, [.accepted, .symbol], 20), (0, [.accepted, .symbol], 21), (0, [.accepted, .symbol], 23), (0, [.accepted, .symbol], 24), (0, [.accepted, .symbol], 25), (0, [.accepted, .symbol], 26), (0, [.accepted, .symbol], 27), (0, [.accepted, .symbol], 28), (0, [.accepted, .symbol], 29), (0, [.accepted, .symbol], 30), (0, [.accepted, .symbol], 31), (0, [.accepted, .symbol], 127), (0, [.accepted, .symbol], 220), (0, [.accepted, .symbol], 249), (253, .none, 0), /* 239 */ (1, .symbol, 19), (22, [.accepted, .symbol], 19), (1, .symbol, 20), (22, [.accepted, .symbol], 20), (1, .symbol, 21), (22, [.accepted, .symbol], 21), (1, .symbol, 23), (22, [.accepted, .symbol], 23), (1, .symbol, 24), (22, [.accepted, .symbol], 24), (1, .symbol, 25), (22, [.accepted, .symbol], 25), (1, .symbol, 26), (22, [.accepted, .symbol], 26), (1, .symbol, 27), (22, [.accepted, .symbol], 27), /* 240 */ (2, .symbol, 19), (9, .symbol, 19), (23, .symbol, 19), (40, [.accepted, .symbol], 19), (2, .symbol, 20), (9, .symbol, 20), (23, .symbol, 20), (40, [.accepted, .symbol], 20), (2, .symbol, 21), (9, .symbol, 21), (23, .symbol, 21), (40, [.accepted, .symbol], 21), (2, .symbol, 23), (9, .symbol, 23), (23, .symbol, 23), (40, [.accepted, .symbol], 23), /* 241 */ (3, .symbol, 19), (6, .symbol, 19), (10, .symbol, 19), (15, .symbol, 19), (24, .symbol, 19), (31, .symbol, 19), (41, .symbol, 19), (56, [.accepted, .symbol], 19), (3, .symbol, 20), (6, .symbol, 20), (10, .symbol, 20), (15, .symbol, 20), (24, .symbol, 20), (31, .symbol, 20), (41, .symbol, 20), (56, [.accepted, .symbol], 20), /* 242 */ (3, .symbol, 21), (6, .symbol, 21), (10, .symbol, 21), (15, .symbol, 21), (24, .symbol, 21), (31, .symbol, 21), (41, .symbol, 21), (56, [.accepted, .symbol], 21), (3, .symbol, 23), (6, .symbol, 23), (10, .symbol, 23), (15, .symbol, 23), (24, .symbol, 23), (31, .symbol, 23), (41, .symbol, 23), (56, [.accepted, .symbol], 23), /* 243 */ (2, .symbol, 24), (9, .symbol, 24), (23, .symbol, 24), (40, [.accepted, .symbol], 24), (2, .symbol, 25), (9, .symbol, 25), (23, .symbol, 25), (40, [.accepted, .symbol], 25), (2, .symbol, 26), (9, .symbol, 26), (23, .symbol, 26), (40, [.accepted, .symbol], 26), (2, .symbol, 27), (9, .symbol, 27), (23, .symbol, 27), (40, [.accepted, .symbol], 27), /* 244 */ (3, .symbol, 24), (6, .symbol, 24), (10, .symbol, 24), (15, .symbol, 24), (24, .symbol, 24), (31, .symbol, 24), (41, .symbol, 24), (56, [.accepted, .symbol], 24), (3, .symbol, 25), (6, .symbol, 25), (10, .symbol, 25), (15, .symbol, 25), (24, .symbol, 25), (31, .symbol, 25), (41, .symbol, 25), (56, [.accepted, .symbol], 25), /* 245 */ (3, .symbol, 26), (6, .symbol, 26), (10, .symbol, 26), (15, .symbol, 26), (24, .symbol, 26), (31, .symbol, 26), (41, .symbol, 26), (56, [.accepted, .symbol], 26), (3, .symbol, 27), (6, .symbol, 27), (10, .symbol, 27), (15, .symbol, 27), (24, .symbol, 27), (31, .symbol, 27), (41, .symbol, 27), (56, [.accepted, .symbol], 27), /* 246 */ (1, .symbol, 28), (22, [.accepted, .symbol], 28), (1, .symbol, 29), (22, [.accepted, .symbol], 29), (1, .symbol, 30), (22, [.accepted, .symbol], 30), (1, .symbol, 31), (22, [.accepted, .symbol], 31), (1, .symbol, 127), (22, [.accepted, .symbol], 127), (1, .symbol, 220), (22, [.accepted, .symbol], 220), (1, .symbol, 249), (22, [.accepted, .symbol], 249), (254, .none, 0), (255, .none, 0), /* 247 */ (2, .symbol, 28), (9, .symbol, 28), (23, .symbol, 28), (40, [.accepted, .symbol], 28), (2, .symbol, 29), (9, .symbol, 29), (23, .symbol, 29), (40, [.accepted, .symbol], 29), (2, .symbol, 30), (9, .symbol, 30), (23, .symbol, 30), (40, [.accepted, .symbol], 30), (2, .symbol, 31), (9, .symbol, 31), (23, .symbol, 31), (40, [.accepted, .symbol], 31), /* 248 */ (3, .symbol, 28), (6, .symbol, 28), (10, .symbol, 28), (15, .symbol, 28), (24, .symbol, 28), (31, .symbol, 28), (41, .symbol, 28), (56, [.accepted, .symbol], 28), (3, .symbol, 29), (6, .symbol, 29), (10, .symbol, 29), (15, .symbol, 29), (24, .symbol, 29), (31, .symbol, 29), (41, .symbol, 29), (56, [.accepted, .symbol], 29), /* 249 */ (3, .symbol, 30), (6, .symbol, 30), (10, .symbol, 30), (15, .symbol, 30), (24, .symbol, 30), (31, .symbol, 30), (41, .symbol, 30), (56, [.accepted, .symbol], 30), (3, .symbol, 31), (6, .symbol, 31), (10, .symbol, 31), (15, .symbol, 31), (24, .symbol, 31), (31, .symbol, 31), (41, .symbol, 31), (56, [.accepted, .symbol], 31), /* 250 */ (2, .symbol, 127), (9, .symbol, 127), (23, .symbol, 127), (40, [.accepted, .symbol], 127), (2, .symbol, 220), (9, .symbol, 220), (23, .symbol, 220), (40, [.accepted, .symbol], 220), (2, .symbol, 249), (9, .symbol, 249), (23, .symbol, 249), (40, [.accepted, .symbol], 249), (0, [.accepted, .symbol], 10), (0, [.accepted, .symbol], 13), (0, [.accepted, .symbol], 22), (0, .failure, 0), /* 251 */ (3, .symbol, 127), (6, .symbol, 127), (10, .symbol, 127), (15, .symbol, 127), (24, .symbol, 127), (31, .symbol, 127), (41, .symbol, 127), (56, [.accepted, .symbol], 127), (3, .symbol, 220), (6, .symbol, 220), (10, .symbol, 220), (15, .symbol, 220), (24, .symbol, 220), (31, .symbol, 220), (41, .symbol, 220), (56, [.accepted, .symbol], 220), /* 252 */ (3, .symbol, 249), (6, .symbol, 249), (10, .symbol, 249), (15, .symbol, 249), (24, .symbol, 249), (31, .symbol, 249), (41, .symbol, 249), (56, [.accepted, .symbol], 249), (1, .symbol, 10), (22, [.accepted, .symbol], 10), (1, .symbol, 13), (22, [.accepted, .symbol], 13), (1, .symbol, 22), (22, [.accepted, .symbol], 22), (0, .failure, 0), (0, .failure, 0), /* 253 */ (2, .symbol, 10), (9, .symbol, 10), (23, .symbol, 10), (40, [.accepted, .symbol], 10), (2, .symbol, 13), (9, .symbol, 13), (23, .symbol, 13), (40, [.accepted, .symbol], 13), (2, .symbol, 22), (9, .symbol, 22), (23, .symbol, 22), (40, [.accepted, .symbol], 22), (0, .failure, 0), (0, .failure, 0), (0, .failure, 0), (0, .failure, 0), /* 254 */ (3, .symbol, 10), (6, .symbol, 10), (10, .symbol, 10), (15, .symbol, 10), (24, .symbol, 10), (31, .symbol, 10), (41, .symbol, 10), (56, [.accepted, .symbol], 10), (3, .symbol, 13), (6, .symbol, 13), (10, .symbol, 13), (15, .symbol, 13), (24, .symbol, 13), (31, .symbol, 13), (41, .symbol, 13), (56, [.accepted, .symbol], 13), /* 255 */ (3, .symbol, 22), (6, .symbol, 22), (10, .symbol, 22), (15, .symbol, 22), (24, .symbol, 22), (31, .symbol, 22), (41, .symbol, 22), (56, [.accepted, .symbol], 22), (0, .failure, 0), (0, .failure, 0), (0, .failure, 0), (0, .failure, 0), (0, .failure, 0), (0, .failure, 0), (0, .failure, 0), (0, .failure, 0), ] */ }
apache-2.0
7cf35e7b32e744767e9145085f601aa1
32.12329
135
0.415465
3.19561
false
false
false
false
powerytg/PearlCam
PearlCam/PearlCam/Components/ViewFinder.swift
2
3084
// // ViewFinder.swift // Accented // // Viewfinder provides a camera preview in addition of allowing selecting focus points // // Created by Tiangong You on 6/7/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit import AVFoundation class ViewFinder: UIView { private let focusIndicatorSize : CGFloat = 30 private let aelIndicatorSize : CGFloat = 60 private var focusIndicator = UIView() private var aelIndicator = UIView() var previewLayer : AVCaptureVideoPreviewLayer init(previewLayer : AVCaptureVideoPreviewLayer, frame: CGRect) { self.previewLayer = previewLayer super.init(frame: frame) self.isUserInteractionEnabled = true layer.addSublayer(previewLayer) focusIndicator.frame = CGRect(x: 0, y: 0, width: focusIndicatorSize, height: focusIndicatorSize) focusIndicator.layer.borderWidth = 2 focusIndicator.layer.borderColor = UIColor(red: 0, green: 222 / 255.0, blue: 136 / 255.0, alpha: 1).cgColor focusIndicator.alpha = 0 addSubview(focusIndicator) aelIndicator.frame = CGRect(x: 0, y: 0, width: aelIndicatorSize, height: aelIndicatorSize) aelIndicator.layer.borderWidth = 2 aelIndicator.layer.borderColor = UIColor(red: 247 / 255.0, green: 248 / 255.0, blue: 141 / 255.0, alpha: 1).cgColor aelIndicator.alpha = 0 addSubview(aelIndicator) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { previewLayer.frame = self.bounds } func focusPointDidChange(_ point : CGPoint) { let coord = previewLayer.pointForCaptureDevicePoint(ofInterest: point) focusIndicator.frame.origin.x = coord.x focusIndicator.frame.origin.y = coord.y } func focusDidStart() { UIView.animate(withDuration: 0.2, delay: 0, options: [.repeat, .autoreverse], animations: { [weak self] in self?.focusIndicator.alpha = 1 }, completion: nil) } func focusDidStop() { focusIndicator.layer.removeAllAnimations() DispatchQueue.main.asyncAfter(deadline: .now() + 1) { UIView.animate(withDuration: 0.2, animations: { [weak self] in self?.focusIndicator.alpha = 0 }) } } func aelPointDidChange(_ point : CGPoint) { let coord = previewLayer.pointForCaptureDevicePoint(ofInterest: point) aelIndicator.frame.origin.x = coord.x aelIndicator.frame.origin.y = coord.y } func aelDidLock() { UIView.animate(withDuration: 0.4, delay: 0, options: .curveEaseIn, animations: { [weak self] in self?.aelIndicator.alpha = 1 }, completion: nil) } func aelDidUnlock() { aelIndicator.layer.removeAllAnimations() UIView.animate(withDuration: 0.2, animations: { [weak self] in self?.aelIndicator.alpha = 0 }) } }
bsd-3-clause
78793d1a103eb466b81448c9093aeb68
32.879121
123
0.637691
4.299861
false
false
false
false
dasdom/UIStackViewPlayground
UIStackView.playground/Pages/Twiiter Profile.xcplaygroundpage/Contents.swift
1
3597
//: [Previous](@previous) import UIKit import PlaygroundSupport let avatarImageHeight: CGFloat = 100 //: First we need a `hostView` to put the different elements on. let hostView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) hostView.backgroundColor = UIColor.lightGray //XCPShowView("hostView", view: hostView) class TwitterProfileViewController : UIViewController { var profileView: TwitterProfileView { return view as! TwitterProfileView } override func loadView() { let contentView = TwitterProfileView() view = contentView } override func viewDidLoad() { title = "Profile" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) profileView.headerImage = UIImage(named: "header.jpg") profileView.avatarImageView.image = UIImage(named: "avatar.jpg") } } class TwitterProfileView : UIView { fileprivate let headerImageView: UIImageView let avatarImageView: UIImageView var headerImage: UIImage? { didSet { if let image = headerImage { let imageSize = image.size headerImageViewHeightConstraint.constant = frame.size.width * imageSize.height / imageSize.width headerImageView.image = headerImage } } } fileprivate let headerImageViewHeightConstraint: NSLayoutConstraint override init(frame: CGRect) { headerImageView = UIImageView() headerImageView.contentMode = .scaleAspectFit avatarImageView = UIImageView() avatarImageView.contentMode = .scaleAspectFit let headerStackView = UIStackView(arrangedSubviews: [headerImageView]) let avatarAndTextStackView = UIStackView(arrangedSubviews: [avatarImageView]) let stackView = UIStackView(arrangedSubviews: [headerStackView, avatarAndTextStackView]) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical headerImageViewHeightConstraint = NSLayoutConstraint(item: headerImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 0) super.init(frame: frame) backgroundColor = UIColor(red: 0.12, green: 0.12, blue: 0.14, alpha: 1.0) addSubview(stackView) let views = ["stack": stackView] var layoutConstraints = [NSLayoutConstraint]() layoutConstraints += NSLayoutConstraint.constraints(withVisualFormat: "|[stack]|", options: [], metrics: nil, views: views) layoutConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[stack]", options: [], metrics: nil, views: views) layoutConstraints.append(headerImageViewHeightConstraint) // layoutConstraints.append(avatarImageView.widthAnchor.constraintEqualToConstant(avatarImageHeight)) layoutConstraints.append(avatarImageView.heightAnchor.constraint(equalToConstant: avatarImageHeight)) NSLayoutConstraint.activate(layoutConstraints) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } let profileViewController = TwitterProfileViewController() let navigationController = UINavigationController(rootViewController: profileViewController) navigationController.view.frame = CGRect(x: 0, y: 0, width: 320, height: 480) PlaygroundPage.current.liveView = navigationController.view //: [Next](@next)
mit
6494ac1e8a1b7f1de492d4e75f95b6c7
34.97
193
0.691688
5.59409
false
false
false
false
KyleGoddard/KType
KType/KGPlayerShipNode.swift
1
2376
// // KGPlayerShipNode.swift // KType // // Created by Kyle Goddard on 2015-03-26. // Copyright (c) 2015 Kyle Goddard. All rights reserved. // import SpriteKit class KGPlayerShipNode: SKSpriteNode { /* <<< NEW TUTORIAL MAY 11 >>>> */ // var touchPoint: CGPoint? var touchPoint: UITouch? var lastInterval: CFTimeInterval? var travelling: Bool /* <<< NEW TUTORIAL MAY 11 >>>> */ let defaultScale:CGFloat = 0.5 let defaultTextureName = "SpaceFighter" let defaultSize:CGSize = CGSize(width: 200.0, height: 53.0) let brakeDistance:CGFloat = 4.0 //new let defaultShipSpeed = 250; init() { let texture = SKTexture(imageNamed: defaultTextureName) let color = UIColor.redColor() let size = defaultSize travelling = false super.init(texture: texture, color: color, size: size) loadDefaultParams() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func loadDefaultParams() { self.xScale = defaultScale self.yScale = defaultScale } /* <<< NEW TUTORIAL MAY 11 >>>> */ func travelTowardsPoint(point: CGPoint, byTimeDelta timeDelta: NSTimeInterval) { var shipSpeed = defaultShipSpeed var distanceLeft = sqrt(pow(position.x - point.x, 2) + pow(position.y - point.y, 2)) if (distanceLeft > brakeDistance) { var distanceToTravel = CGFloat(timeDelta) * CGFloat(shipSpeed) var angle = atan2(point.y - position.y, point.x - position.x) var yOffset = distanceToTravel * sin(angle) var xOffset = distanceToTravel * cos(angle) position = CGPointMake(position.x + xOffset, position.y + yOffset) } } func update(interval: CFTimeInterval) { if lastInterval == nil { lastInterval = interval } var delta: CFTimeInterval = interval - lastInterval! if (travelling) { if let destination = touchPoint?.locationInNode(scene as? GameScene) { travelTowardsPoint(destination, byTimeDelta: delta) } } lastInterval = interval } /* <<< NEW TUTORIAL MAY 11 >>>> */ }
mit
95c510d79b1128a001bf3038dadb42f8
26.952941
92
0.583333
4.367647
false
false
false
false
shvets/TVSetKit
Sources/ios/UIViewController-extension.swift
1
943
import UIKit extension UIViewController { public func getActionController() -> UIViewController? { if let controller = self as? UINavigationController { return controller.visibleViewController } else { return self } } public static func instantiate(controllerId: String, storyboardId: String, bundleId: String) -> UIViewController { if let bundle = Bundle(identifier: bundleId) { let storyboard: UIStoryboard = UIStoryboard(name: storyboardId, bundle: bundle) return storyboard.instantiateViewController(withIdentifier: controllerId) } else { return UIViewController() } } public static func instantiate(controllerId: String, storyboardId: String, bundle: Bundle=Bundle.main) -> UIViewController { let storyboard: UIStoryboard = UIStoryboard(name: storyboardId, bundle: bundle) return storyboard.instantiateViewController(withIdentifier: controllerId) } }
mit
fa120b61938b1748797dff0afa2bba06
31.517241
126
0.735949
5.41954
false
false
false
false
intelliot/Layer-Parse-iOS-Swift-Example
Code/AppDelegate.swift
1
3506
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var layerClient: LYRClient! // MARK TODO: Before first launch, update LayerAppIDString, ParseAppIDString or ParseClientKeyString values // TODO:If LayerAppIDString, ParseAppIDString or ParseClientKeyString are not set, this app will crash" let LayerAppIDString: NSURL! = NSURL(string: "") let ParseAppIDString: String = "" let ParseClientKeyString: String = "" //Please note, You must set `LYRConversation *conversation` as a property of the ViewController. var conversation: LYRConversation! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { setupParse() setupLayer() // Show View Controller let controller: ViewController = ViewController() controller.layerClient = layerClient self.window!.rootViewController = UINavigationController(rootViewController: controller) self.window!.backgroundColor = UIColor.whiteColor() self.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:. } func setupParse() { // Enable Parse local data store for user persistence Parse.enableLocalDatastore() Parse.setApplicationId(ParseAppIDString, clientKey: ParseClientKeyString) // Set default ACLs let defaultACL: PFACL = PFACL() defaultACL.setPublicReadAccess(true) PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser: true) } func setupLayer() { layerClient = LYRClient(appID: LayerAppIDString) layerClient.autodownloadMaximumContentSize = 1024 * 100 layerClient.autodownloadMIMETypes = NSSet(objects: "image/jpeg") as Set<NSObject> } }
apache-2.0
d7dd306479acaced2bff2f323b4f15e4
48.380282
285
0.732744
5.673139
false
false
false
false
khoren93/SwiftHub
SwiftHub/Modules/Contents/ContentsViewModel.swift
1
3480
// // ContentsViewModel.swift // SwiftHub // // Created by Sygnoos9 on 11/6/18. // Copyright © 2018 Khoren Markosyan. All rights reserved. // import Foundation import RxCocoa import RxSwift class ContentsViewModel: ViewModel, ViewModelType { struct Input { let headerRefresh: Observable<Void> let selection: Driver<ContentCellViewModel> let openInWebSelection: Observable<Void> } struct Output { let navigationTitle: Driver<String> let items: BehaviorRelay<[ContentCellViewModel]> let openContents: Driver<ContentsViewModel> let openUrl: Driver<URL?> let openSource: Driver<SourceViewModel> } let repository: BehaviorRelay<Repository> let content: BehaviorRelay<Content?> let ref: BehaviorRelay<String?> init(repository: Repository, content: Content?, ref: String?, provider: SwiftHubAPI) { self.repository = BehaviorRelay(value: repository) self.content = BehaviorRelay(value: content) self.ref = BehaviorRelay(value: ref) super.init(provider: provider) } func transform(input: Input) -> Output { let elements = BehaviorRelay<[ContentCellViewModel]>(value: []) input.headerRefresh.flatMapLatest({ [weak self] () -> Observable<[ContentCellViewModel]> in guard let self = self else { return Observable.just([]) } return self.request() .trackActivity(self.headerLoading) }).subscribe(onNext: { (items) in elements.accept(items) }).disposed(by: rx.disposeBag) let openContents = input.selection.map { $0.content }.filter { $0.type == .dir } .map({ (content) -> ContentsViewModel in let repository = self.repository.value let ref = self.ref.value let viewModel = ContentsViewModel(repository: repository, content: content, ref: ref, provider: self.provider) return viewModel }) let openUrl = input.openInWebSelection.map { self.content.value?.htmlUrl?.url } .filterNil().asDriver(onErrorJustReturn: nil) let openSource = input.selection.map { $0.content }.filter { $0.type != .dir }.map { (content) -> SourceViewModel in let viewModel = SourceViewModel(content: content, provider: self.provider) return viewModel } let navigationTitle = content.map({ (content) -> String in return content?.name ?? self.repository.value.fullname ?? "" }).asDriver(onErrorJustReturn: "") return Output(navigationTitle: navigationTitle, items: elements, openContents: openContents, openUrl: openUrl, openSource: openSource) } func request() -> Observable<[ContentCellViewModel]> { let fullname = repository.value.fullname ?? "" let path = content.value?.path ?? "" let ref = self.ref.value return provider.contents(fullname: fullname, path: path, ref: ref) .trackActivity(loading) .trackError(error) .map { $0.sorted(by: { (lhs, rhs) -> Bool in if lhs.type == rhs.type { return lhs.name?.lowercased() ?? "" < rhs.name?.lowercased() ?? "" } else { return lhs.type > rhs.type } }).map { ContentCellViewModel(with: $0) } } } }
mit
32bd7e6a03bd4050229b77a680830347
36.408602
124
0.606784
4.682369
false
false
false
false
Takanu/Pelican
Sources/Pelican/API/Types/Message Content/Location.swift
1
901
// // Location.swift // Pelican // // Created by Takanu Kyriako on 31/08/2017. // import Foundation /** Represents a real-world location, that when sent as the contents of a message, is represented by a map preview. */ public struct Location: TelegramType, MessageContent { // STORAGE AND IDENTIFIERS public var contentType: String = "location" public var method: String = "sendLocation" // PARAMETERS /// The latitude of the location. public var latitude: Float /// The longitude of the location. public var longitude: Float public init(latitude: Float, longitude: Float) { self.latitude = latitude self.longitude = longitude } // SendType conforming methods to send itself to Telegram under the provided method. public func getQuery() -> [String: Codable] { let keys: [String: Codable] = [ "longitude": longitude, "latitude": latitude] return keys } }
mit
9b33cdd464d89ebf5698bf3ddd5af4fc
20.97561
111
0.708102
3.72314
false
false
false
false
Hunter-Li-EF/HLAlbumPickerController
HLAlbumPickerController/Classes/HLAlbumGroupView.swift
1
4271
// // HLAlbumGroupView.swift // Pods // // Created by Hunter Li on 1/9/2016. // // import UIKit import Photos internal class HLAlbumGroupView: UIControl, UITableViewDataSource, UITableViewDelegate{ var assetGroup: [PHAssetCollection]? override init(frame: CGRect) { super.init(frame: CGRect.zero) setupTableView() addTarget(self, action: #selector(HLAlbumGroupView.dismiss(_:)), for: .touchUpInside) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var tableView: UITableView? fileprivate var bottomConstraint: NSLayoutConstraint? fileprivate let cellIdentifier = "AssetGroupCellIdentifier" fileprivate func setupTableView(){ let tableView = UITableView(frame: CGRect.zero, style: .plain) tableView.register(HLAlbumGroupCell.self, forCellReuseIdentifier: cellIdentifier) tableView.dataSource = self tableView.delegate = self tableView.estimatedRowHeight = 60 tableView.rowHeight = UITableViewAutomaticDimension tableView.tableFooterView = UIView() tableView.separatorInset = UIEdgeInsets.zero tableView.layoutMargins = UIEdgeInsets.zero tableView.separatorStyle = .singleLine tableView.translatesAutoresizingMaskIntoConstraints = false addSubview(tableView) self.tableView = tableView addConstraint(NSLayoutConstraint(item: tableView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: tableView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1.0, constant: 0)) let bottomConstraint = NSLayoutConstraint(item: tableView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0) addConstraint(bottomConstraint) self.bottomConstraint = bottomConstraint } var assetCollectionSelected: ((PHAssetCollection?) -> Void)? func show() { guard let tableView = self.tableView else{ return } UIView.animate(withDuration: 0.1, animations: { tableView.reloadData() }, completion: { (finished: Bool) in self.addConstraint(NSLayoutConstraint(item: tableView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: tableView.contentSize.height)) UIView.animate(withDuration: 0.1, animations: { self.layoutIfNeeded() }, completion: { (finished: Bool) in self.bottomConstraint?.constant = tableView.contentSize.height UIView.animate(withDuration: 0.2, animations: { self.backgroundColor = UIColor.black.withAlphaComponent(0.5) self.layoutIfNeeded() }) }) }) } func dismiss() { bottomConstraint?.constant = 0 UIView.animate(withDuration: 0.3, animations: { self.layoutIfNeeded() }, completion: { (finished: Bool) in self.removeFromSuperview() }) } func dismiss(_ albumGroupView: HLAlbumGroupView){ dismiss() assetCollectionSelected?(nil) } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return assetGroup?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! HLAlbumGroupCell let assetGroup = self.assetGroup?[(indexPath as NSIndexPath).row] cell.refreshView(assetGroup) return cell } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) dismiss() let assetGroup = self.assetGroup?[(indexPath as NSIndexPath).row] assetCollectionSelected?(assetGroup) } }
mit
fc26ba9d8912c4af48df0eaaafa04961
37.477477
202
0.653477
5.279357
false
false
false
false
WhisperSystems/Signal-iOS
SignalServiceKit/src/Contacts/SignalRecipient+SDS.swift
1
22204
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import GRDB import SignalCoreKit // NOTE: This file is generated by /Scripts/sds_codegen/sds_generate.py. // Do not manually edit it, instead run `sds_codegen.sh`. // MARK: - Record public struct SignalRecipientRecord: SDSRecord { public var tableMetadata: SDSTableMetadata { return SignalRecipientSerializer.table } public static let databaseTableName: String = SignalRecipientSerializer.table.tableName public var id: Int64? // This defines all of the columns used in the table // where this model (and any subclasses) are persisted. public let recordType: SDSRecordType public let uniqueId: String // Base class properties public let devices: Data public let recipientPhoneNumber: String? public let recipientSchemaVersion: UInt public let recipientUUID: String? public enum CodingKeys: String, CodingKey, ColumnExpression, CaseIterable { case id case recordType case uniqueId case devices case recipientPhoneNumber case recipientSchemaVersion case recipientUUID } public static func columnName(_ column: SignalRecipientRecord.CodingKeys, fullyQualified: Bool = false) -> String { return fullyQualified ? "\(databaseTableName).\(column.rawValue)" : column.rawValue } } // MARK: - Row Initializer public extension SignalRecipientRecord { static var databaseSelection: [SQLSelectable] { return CodingKeys.allCases } init(row: Row) { id = row[0] recordType = row[1] uniqueId = row[2] devices = row[3] recipientPhoneNumber = row[4] recipientSchemaVersion = row[5] recipientUUID = row[6] } } // MARK: - StringInterpolation public extension String.StringInterpolation { mutating func appendInterpolation(signalRecipientColumn column: SignalRecipientRecord.CodingKeys) { appendLiteral(SignalRecipientRecord.columnName(column)) } mutating func appendInterpolation(signalRecipientColumnFullyQualified column: SignalRecipientRecord.CodingKeys) { appendLiteral(SignalRecipientRecord.columnName(column, fullyQualified: true)) } } // MARK: - Deserialization // TODO: Rework metadata to not include, for example, columns, column indices. extension SignalRecipient { // This method defines how to deserialize a model, given a // database row. The recordType column is used to determine // the corresponding model class. class func fromRecord(_ record: SignalRecipientRecord) throws -> SignalRecipient { guard let recordId = record.id else { throw SDSError.invalidValue } switch record.recordType { case .signalRecipient: let uniqueId: String = record.uniqueId let devicesSerialized: Data = record.devices let devices: NSOrderedSet = try SDSDeserialization.unarchive(devicesSerialized, name: "devices") let recipientPhoneNumber: String? = record.recipientPhoneNumber let recipientSchemaVersion: UInt = record.recipientSchemaVersion let recipientUUID: String? = record.recipientUUID return SignalRecipient(uniqueId: uniqueId, devices: devices, recipientPhoneNumber: recipientPhoneNumber, recipientSchemaVersion: recipientSchemaVersion, recipientUUID: recipientUUID) default: owsFailDebug("Unexpected record type: \(record.recordType)") throw SDSError.invalidValue } } } // MARK: - SDSModel extension SignalRecipient: SDSModel { public var serializer: SDSSerializer { // Any subclass can be cast to it's superclass, // so the order of this switch statement matters. // We need to do a "depth first" search by type. switch self { default: return SignalRecipientSerializer(model: self) } } public func asRecord() throws -> SDSRecord { return try serializer.asRecord() } public var sdsTableName: String { return SignalRecipientRecord.databaseTableName } public static var table: SDSTableMetadata { return SignalRecipientSerializer.table } } // MARK: - Table Metadata extension SignalRecipientSerializer { // This defines all of the columns used in the table // where this model (and any subclasses) are persisted. static let idColumn = SDSColumnMetadata(columnName: "id", columnType: .primaryKey, columnIndex: 0) static let recordTypeColumn = SDSColumnMetadata(columnName: "recordType", columnType: .int64, columnIndex: 1) static let uniqueIdColumn = SDSColumnMetadata(columnName: "uniqueId", columnType: .unicodeString, isUnique: true, columnIndex: 2) // Base class properties static let devicesColumn = SDSColumnMetadata(columnName: "devices", columnType: .blob, columnIndex: 3) static let recipientPhoneNumberColumn = SDSColumnMetadata(columnName: "recipientPhoneNumber", columnType: .unicodeString, isOptional: true, columnIndex: 4) static let recipientSchemaVersionColumn = SDSColumnMetadata(columnName: "recipientSchemaVersion", columnType: .int64, columnIndex: 5) static let recipientUUIDColumn = SDSColumnMetadata(columnName: "recipientUUID", columnType: .unicodeString, isOptional: true, columnIndex: 6) // TODO: We should decide on a naming convention for // tables that store models. public static let table = SDSTableMetadata(collection: SignalRecipient.collection(), tableName: "model_SignalRecipient", columns: [ idColumn, recordTypeColumn, uniqueIdColumn, devicesColumn, recipientPhoneNumberColumn, recipientSchemaVersionColumn, recipientUUIDColumn ]) } // MARK: - Save/Remove/Update @objc public extension SignalRecipient { func anyInsert(transaction: SDSAnyWriteTransaction) { sdsSave(saveMode: .insert, transaction: transaction) } // This method is private; we should never use it directly. // Instead, use anyUpdate(transaction:block:), so that we // use the "update with" pattern. private func anyUpdate(transaction: SDSAnyWriteTransaction) { sdsSave(saveMode: .update, transaction: transaction) } @available(*, deprecated, message: "Use anyInsert() or anyUpdate() instead.") func anyUpsert(transaction: SDSAnyWriteTransaction) { let isInserting: Bool if SignalRecipient.anyFetch(uniqueId: uniqueId, transaction: transaction) != nil { isInserting = false } else { isInserting = true } sdsSave(saveMode: isInserting ? .insert : .update, transaction: transaction) } // This method is used by "updateWith..." methods. // // This model may be updated from many threads. We don't want to save // our local copy (this instance) since it may be out of date. We also // want to avoid re-saving a model that has been deleted. Therefore, we // use "updateWith..." methods to: // // a) Update a property of this instance. // b) If a copy of this model exists in the database, load an up-to-date copy, // and update and save that copy. // b) If a copy of this model _DOES NOT_ exist in the database, do _NOT_ save // this local instance. // // After "updateWith...": // // a) Any copy of this model in the database will have been updated. // b) The local property on this instance will always have been updated. // c) Other properties on this instance may be out of date. // // All mutable properties of this class have been made read-only to // prevent accidentally modifying them directly. // // This isn't a perfect arrangement, but in practice this will prevent // data loss and will resolve all known issues. func anyUpdate(transaction: SDSAnyWriteTransaction, block: (SignalRecipient) -> Void) { block(self) guard let dbCopy = type(of: self).anyFetch(uniqueId: uniqueId, transaction: transaction) else { return } // Don't apply the block twice to the same instance. // It's at least unnecessary and actually wrong for some blocks. // e.g. `block: { $0 in $0.someField++ }` if dbCopy !== self { block(dbCopy) } dbCopy.anyUpdate(transaction: transaction) } func anyRemove(transaction: SDSAnyWriteTransaction) { sdsRemove(transaction: transaction) } func anyReload(transaction: SDSAnyReadTransaction) { anyReload(transaction: transaction, ignoreMissing: false) } func anyReload(transaction: SDSAnyReadTransaction, ignoreMissing: Bool) { guard let latestVersion = type(of: self).anyFetch(uniqueId: uniqueId, transaction: transaction) else { if !ignoreMissing { owsFailDebug("`latest` was unexpectedly nil") } return } setValuesForKeys(latestVersion.dictionaryValue) } } // MARK: - SignalRecipientCursor @objc public class SignalRecipientCursor: NSObject { private let cursor: RecordCursor<SignalRecipientRecord>? init(cursor: RecordCursor<SignalRecipientRecord>?) { self.cursor = cursor } public func next() throws -> SignalRecipient? { guard let cursor = cursor else { return nil } guard let record = try cursor.next() else { return nil } return try SignalRecipient.fromRecord(record) } public func all() throws -> [SignalRecipient] { var result = [SignalRecipient]() while true { guard let model = try next() else { break } result.append(model) } return result } } // MARK: - Obj-C Fetch // TODO: We may eventually want to define some combination of: // // * fetchCursor, fetchOne, fetchAll, etc. (ala GRDB) // * Optional "where clause" parameters for filtering. // * Async flavors with completions. // // TODO: I've defined flavors that take a read transaction. // Or we might take a "connection" if we end up having that class. @objc public extension SignalRecipient { class func grdbFetchCursor(transaction: GRDBReadTransaction) -> SignalRecipientCursor { let database = transaction.database do { let cursor = try SignalRecipientRecord.fetchCursor(database) return SignalRecipientCursor(cursor: cursor) } catch { owsFailDebug("Read failed: \(error)") return SignalRecipientCursor(cursor: nil) } } // Fetches a single model by "unique id". class func anyFetch(uniqueId: String, transaction: SDSAnyReadTransaction) -> SignalRecipient? { assert(uniqueId.count > 0) switch transaction.readTransaction { case .yapRead(let ydbTransaction): return SignalRecipient.ydb_fetch(uniqueId: uniqueId, transaction: ydbTransaction) case .grdbRead(let grdbTransaction): let sql = "SELECT * FROM \(SignalRecipientRecord.databaseTableName) WHERE \(signalRecipientColumn: .uniqueId) = ?" return grdbFetchOne(sql: sql, arguments: [uniqueId], transaction: grdbTransaction) } } // Traverses all records. // Records are not visited in any particular order. class func anyEnumerate(transaction: SDSAnyReadTransaction, block: @escaping (SignalRecipient, UnsafeMutablePointer<ObjCBool>) -> Void) { anyEnumerate(transaction: transaction, batched: false, block: block) } // Traverses all records. // Records are not visited in any particular order. class func anyEnumerate(transaction: SDSAnyReadTransaction, batched: Bool = false, block: @escaping (SignalRecipient, UnsafeMutablePointer<ObjCBool>) -> Void) { let batchSize = batched ? Batching.kDefaultBatchSize : 0 anyEnumerate(transaction: transaction, batchSize: batchSize, block: block) } // Traverses all records. // Records are not visited in any particular order. // // If batchSize > 0, the enumeration is performed in autoreleased batches. class func anyEnumerate(transaction: SDSAnyReadTransaction, batchSize: UInt, block: @escaping (SignalRecipient, UnsafeMutablePointer<ObjCBool>) -> Void) { switch transaction.readTransaction { case .yapRead(let ydbTransaction): SignalRecipient.ydb_enumerateCollectionObjects(with: ydbTransaction) { (object, stop) in guard let value = object as? SignalRecipient else { owsFailDebug("unexpected object: \(type(of: object))") return } block(value, stop) } case .grdbRead(let grdbTransaction): do { let cursor = SignalRecipient.grdbFetchCursor(transaction: grdbTransaction) try Batching.loop(batchSize: batchSize, loopBlock: { stop in guard let value = try cursor.next() else { stop.pointee = true return } block(value, stop) }) } catch let error { owsFailDebug("Couldn't fetch models: \(error)") } } } // Traverses all records' unique ids. // Records are not visited in any particular order. class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction, block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) { anyEnumerateUniqueIds(transaction: transaction, batched: false, block: block) } // Traverses all records' unique ids. // Records are not visited in any particular order. class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction, batched: Bool = false, block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) { let batchSize = batched ? Batching.kDefaultBatchSize : 0 anyEnumerateUniqueIds(transaction: transaction, batchSize: batchSize, block: block) } // Traverses all records' unique ids. // Records are not visited in any particular order. // // If batchSize > 0, the enumeration is performed in autoreleased batches. class func anyEnumerateUniqueIds(transaction: SDSAnyReadTransaction, batchSize: UInt, block: @escaping (String, UnsafeMutablePointer<ObjCBool>) -> Void) { switch transaction.readTransaction { case .yapRead(let ydbTransaction): ydbTransaction.enumerateKeys(inCollection: SignalRecipient.collection()) { (uniqueId, stop) in block(uniqueId, stop) } case .grdbRead(let grdbTransaction): grdbEnumerateUniqueIds(transaction: grdbTransaction, sql: """ SELECT \(signalRecipientColumn: .uniqueId) FROM \(SignalRecipientRecord.databaseTableName) """, batchSize: batchSize, block: block) } } // Does not order the results. class func anyFetchAll(transaction: SDSAnyReadTransaction) -> [SignalRecipient] { var result = [SignalRecipient]() anyEnumerate(transaction: transaction) { (model, _) in result.append(model) } return result } // Does not order the results. class func anyAllUniqueIds(transaction: SDSAnyReadTransaction) -> [String] { var result = [String]() anyEnumerateUniqueIds(transaction: transaction) { (uniqueId, _) in result.append(uniqueId) } return result } class func anyCount(transaction: SDSAnyReadTransaction) -> UInt { switch transaction.readTransaction { case .yapRead(let ydbTransaction): return ydbTransaction.numberOfKeys(inCollection: SignalRecipient.collection()) case .grdbRead(let grdbTransaction): return SignalRecipientRecord.ows_fetchCount(grdbTransaction.database) } } // WARNING: Do not use this method for any models which do cleanup // in their anyWillRemove(), anyDidRemove() methods. class func anyRemoveAllWithoutInstantation(transaction: SDSAnyWriteTransaction) { switch transaction.writeTransaction { case .yapWrite(let ydbTransaction): ydbTransaction.removeAllObjects(inCollection: SignalRecipient.collection()) case .grdbWrite(let grdbTransaction): do { try SignalRecipientRecord.deleteAll(grdbTransaction.database) } catch { owsFailDebug("deleteAll() failed: \(error)") } } if shouldBeIndexedForFTS { FullTextSearchFinder.allModelsWereRemoved(collection: collection(), transaction: transaction) } } class func anyRemoveAllWithInstantation(transaction: SDSAnyWriteTransaction) { // To avoid mutationDuringEnumerationException, we need // to remove the instances outside the enumeration. let uniqueIds = anyAllUniqueIds(transaction: transaction) var index: Int = 0 do { try Batching.loop(batchSize: Batching.kDefaultBatchSize, loopBlock: { stop in guard index < uniqueIds.count else { stop.pointee = true return } let uniqueId = uniqueIds[index] index = index + 1 guard let instance = anyFetch(uniqueId: uniqueId, transaction: transaction) else { owsFailDebug("Missing instance.") return } instance.anyRemove(transaction: transaction) }) } catch { owsFailDebug("Error: \(error)") } if shouldBeIndexedForFTS { FullTextSearchFinder.allModelsWereRemoved(collection: collection(), transaction: transaction) } } class func anyExists(uniqueId: String, transaction: SDSAnyReadTransaction) -> Bool { assert(uniqueId.count > 0) switch transaction.readTransaction { case .yapRead(let ydbTransaction): return ydbTransaction.hasObject(forKey: uniqueId, inCollection: SignalRecipient.collection()) case .grdbRead(let grdbTransaction): let sql = "SELECT EXISTS ( SELECT 1 FROM \(SignalRecipientRecord.databaseTableName) WHERE \(signalRecipientColumn: .uniqueId) = ? )" let arguments: StatementArguments = [uniqueId] return try! Bool.fetchOne(grdbTransaction.database, sql: sql, arguments: arguments) ?? false } } } // MARK: - Swift Fetch public extension SignalRecipient { class func grdbFetchCursor(sql: String, arguments: StatementArguments = StatementArguments(), transaction: GRDBReadTransaction) -> SignalRecipientCursor { do { let sqlRequest = SQLRequest<Void>(sql: sql, arguments: arguments, cached: true) let cursor = try SignalRecipientRecord.fetchCursor(transaction.database, sqlRequest) return SignalRecipientCursor(cursor: cursor) } catch { Logger.error("sql: \(sql)") owsFailDebug("Read failed: \(error)") return SignalRecipientCursor(cursor: nil) } } class func grdbFetchOne(sql: String, arguments: StatementArguments = StatementArguments(), transaction: GRDBReadTransaction) -> SignalRecipient? { assert(sql.count > 0) do { let sqlRequest = SQLRequest<Void>(sql: sql, arguments: arguments, cached: true) guard let record = try SignalRecipientRecord.fetchOne(transaction.database, sqlRequest) else { return nil } return try SignalRecipient.fromRecord(record) } catch { owsFailDebug("error: \(error)") return nil } } } // MARK: - SDSSerializer // The SDSSerializer protocol specifies how to insert and update the // row that corresponds to this model. class SignalRecipientSerializer: SDSSerializer { private let model: SignalRecipient public required init(model: SignalRecipient) { self.model = model } // MARK: - Record func asRecord() throws -> SDSRecord { let id: Int64? = nil let recordType: SDSRecordType = .signalRecipient let uniqueId: String = model.uniqueId // Base class properties let devices: Data = requiredArchive(model.devices) let recipientPhoneNumber: String? = model.recipientPhoneNumber let recipientSchemaVersion: UInt = model.recipientSchemaVersion let recipientUUID: String? = model.recipientUUID return SignalRecipientRecord(id: id, recordType: recordType, uniqueId: uniqueId, devices: devices, recipientPhoneNumber: recipientPhoneNumber, recipientSchemaVersion: recipientSchemaVersion, recipientUUID: recipientUUID) } }
gpl-3.0
93b4266e138c2f1632b5c61eb5be9618
37.954386
228
0.628085
5.352941
false
false
false
false
FlowDK/FlowDK
FlowDK/Core/Classes/UI/GrowButton/GrowControl.swift
1
972
import SnapKit public class GrowControl: UIControl { public let contentView = UIView() override public var isHighlighted: Bool { didSet { if isHighlighted != oldValue { updateHighlighted() } } } override init(frame: CGRect) { super.init(frame: frame) addSubview(contentView) contentView.isUserInteractionEnabled = false self.isUserInteractionEnabled = true contentView.snp.makeConstraints { make in make.edges.equalTo(self).inset(50) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateHighlighted() { UIView.animate(withDuration: 0.1) { [weak self] in guard let self = self else { return } if self.isHighlighted { self.contentView.transform = CGAffineTransform(scaleX: 1.25, y: 1.25) } else { self.contentView.transform = CGAffineTransform.identity } } } }
mit
d9a6bdabb1e80d08e92afec7767ad234
22.142857
77
0.647119
4.56338
false
false
false
false
oacastefanita/PollsFramework
Example/PollsFramework/ViewControllers/BestImageViewController.swift
1
11970
// // BestImageViewController.swift // PollsFramework // // Created by Stefanita Oaca on 23/07/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import PollsFramework import CoreData class BestImageViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, FiltersViewControllerDelegate, CategoriesViewControllerDelegate { @IBOutlet weak var switchEnableFilters: UISwitch! @IBOutlet weak var switchPublic: UISwitch! @IBOutlet weak var btnAddFilter: UIButton! @IBOutlet weak var btnExpire: UIButton! @IBOutlet weak var btnExtend: UIButton! @IBOutlet weak var switchAllowAdultContent: UISwitch! @IBOutlet weak var switchDraft: UISwitch! @IBOutlet weak var switchAllowComments: UISwitch! @IBOutlet weak var txtLifetimeEndDate: CDTextField! @IBOutlet weak var txtEndDateTime: CDTextField! @IBOutlet weak var txtKeywords: CDTextField! @IBOutlet weak var txtQuestion: CDTextField! @IBOutlet weak var txtOverview: CDTextField! @IBOutlet weak var imgFirstPollImage: UIImageView! @IBOutlet weak var imgSecondPollImage: UIImageView! @IBOutlet weak var txtTitle: CDTextField! var poll: Poll! var screenType: PollScreenType! var viewObjects = [Any]() var imagePicker = UIImagePickerController() var selectedFirst = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. fillViewData() if screenType == .create{ btnExpire.isHidden = true btnExtend.isHidden = true poll.pollTypeId = PollTypes.bestImage.rawValue } self.imgFirstPollImage.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(BestImageViewController.onFirstImage))) self.imgSecondPollImage.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(BestImageViewController.onSecondImage))) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.endEditing(true) return true } @IBAction func onAddFilter(_ sender: Any) { self.performSegue(withIdentifier: "showCategories", sender: self) } @IBAction func onDone(_ sender: Any) { self.fillPollData() switch screenType! { case .view: self.navigationController?.popViewController(animated: true) break case .edit: PollsFrameworkController.sharedInstance.updatePublishedPoll(Int(poll.pollId), keywords: txtKeywords.text, pollOverview: txtOverview.text){ (success, response) in if !success { } else { } self.navigationController?.popViewController(animated: true) } break case .create: // PollsFrameworkController.sharedInstance.createBestImagePoll(poll: poll){ (success, response) in // if !success { // // } // else { // // } // self.navigationController?.popViewController(animated: true) // } break case .draft: PollsFrameworkController.sharedInstance.deleteDraftPoll(Int(poll.pollId)){ (success, response) in if !success { } else { } self.navigationController?.popViewController(animated: true) } break } } @IBAction func onDelete(_ sender: Any) { self.fillPollData() switch screenType! { case .view: break case .edit: PollsFrameworkController.sharedInstance.deletePoll(Int(poll.pollId)){ (success, response) in if !success { } else { } self.navigationController?.popViewController(animated: true) } break case .create: break case .draft: PollsFrameworkController.sharedInstance.deleteDraftPoll(Int(poll.pollId)){ (success, response) in if !success { } else { } self.navigationController?.popViewController(animated: true) } break } } @IBAction func onExpire(_ sender: Any) { PollsFrameworkController.sharedInstance.expirePoll(Int(poll.pollId)){ (success, response) in if !success { } else { } } } @IBAction func onExtend(_ sender: Any) { PollsFrameworkController.sharedInstance.extendExpireTimeWith(3600, pollId: (Int(poll.pollId))){ (success, response) in if !success { } else { } } } @IBAction func onResults(_ sender: Any) { var getObj = PollsFactory.createGetPollsViewModel() getObj.pollId = self.poll.pollId PollsFrameworkController.sharedInstance.getPollsResults(getPolls: getObj){ (success, response) in if !success { } else { self.viewObjects = response self.performSegue(withIdentifier: "viewObjectsListFromPoll", sender: self) } } } @IBAction func onAnswer(_ sender: Any) { self.performSegue(withIdentifier: "viewObjectDetailsFromPoll", sender: self) } @objc func onFirstImage(){ if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){ imagePicker.delegate = self imagePicker.sourceType = .savedPhotosAlbum; imagePicker.allowsEditing = false self.selectedFirst = true self.present(imagePicker, animated: true, completion: nil) } } @objc func onSecondImage(){ if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){ imagePicker.delegate = self imagePicker.sourceType = .savedPhotosAlbum; imagePicker.allowsEditing = false self.selectedFirst = false self.present(imagePicker, animated: true, completion: nil) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { picker.dismiss(animated: true, completion: { () -> Void in PollsFrameworkController.sharedInstance.uploadImage(info[UIImagePickerControllerOriginalImage] as! UIImage){ (success, response) in if !success { } else { if self.selectedFirst{ self.poll.firstImagePath = response!.fileName self.imgFirstPollImage.image = info[UIImagePickerControllerOriginalImage] as! UIImage }else{ self.poll.secondImagePath = response!.fileName self.imgSecondPollImage.image = info[UIImagePickerControllerOriginalImage] as! UIImage } } } }) } func fillPollData(){ poll.isFilterOption = switchEnableFilters.isOn poll.isEnablePublic = switchPublic.isOn poll.isAdult = switchAllowAdultContent.isOn poll.isEnabledComments = switchAllowComments.isOn poll.lifeTimeInSeconds = Int64(txtLifetimeEndDate.text!)! poll.assignmentDurationInSeconds = Int64(txtEndDateTime.text!)! poll.keywords = txtKeywords.text poll.pollOverview = txtOverview.text poll.question = txtQuestion.text poll.pollTitle = txtTitle.text poll.isPublished = !switchDraft.isOn } func fillViewData(){ switchEnableFilters.isOn = poll.isFilterOption switchPublic.isOn = poll.isEnablePublic switchAllowAdultContent.isOn = poll.isAdult switchAllowComments.isOn = poll.isEnabledComments txtLifetimeEndDate.text = "\(poll.lifeTimeInSeconds)" txtEndDateTime.text = "\(poll.assignmentDurationInSeconds)" txtKeywords.text = poll.keywords txtOverview.text = poll.pollOverview txtQuestion.text = poll.question txtTitle.text = poll.pollTitle switchDraft.isOn = !poll.isPublished if poll.firstImagePath != nil{ PollsFrameworkController.sharedInstance.getImage(poll.firstImagePath){ (success, response) in if !success { } else { self.imgFirstPollImage.image = response } } } if poll.secondImagePath != nil{ PollsFrameworkController.sharedInstance.getImage(poll.secondImagePath){ (success, response) in if !success { } else { self.imgSecondPollImage.image = response } } } if self.screenType == .edit{ switchEnableFilters.isUserInteractionEnabled = false switchPublic.isUserInteractionEnabled = false switchAllowAdultContent.isUserInteractionEnabled = false switchAllowComments.isUserInteractionEnabled = false txtLifetimeEndDate.isUserInteractionEnabled = false txtEndDateTime.isUserInteractionEnabled = false txtOverview.isUserInteractionEnabled = false txtQuestion.isUserInteractionEnabled = false txtTitle.isUserInteractionEnabled = false } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "addFilters"{ (segue.destination as! FiltersViewController).delegate = self } else if segue.identifier == "showCategories"{ (segue.destination as! CategoriesViewController).delegate = self } else if segue.identifier == "viewObjectDetailsFromPoll"{ let answer = (NSEntityDescription.insertNewObject(forEntityName: "PollAnswer", into: PollsFrameworkController.sharedInstance.dataController().managedObjectContext) as! PollAnswer) answer.pollId = self.poll.pollId answer.workerUserId = PollsFrameworkController.sharedInstance.user?.userId ((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).object = answer ((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).screenType = .edit ((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).objectType = .pollAnswer } else if segue.identifier == "viewObjectsListFromPoll"{ (segue.destination as! ViewObjectsListViewController).objects = self.viewObjects } } func selectedCategoryAndFilter(_ filters: [FilterNameValue], category: PollCategory?) { if category != nil{ poll.catId = category?.catId as! Int64 } for filter in filters{ poll.addToFilterNameValue(filter) } } func selectedFilter(_ filter: FilterNameValue) { poll.addToFilterNameValue(filter) } }
mit
4f8ce977b13710bc2d0ad03770a70ac5
36.996825
200
0.601721
5.447883
false
false
false
false
austinzmchen/guildOfWarWorldBosses
GoWWorldBosses/ViewModels/WBKeyStore.swift
1
3025
// // WBKeyStore.swift // GoWWorldBosses // // Created by Austin Chen on 2016-09-18. // Copyright © 2016 Austin Chen. All rights reserved. // import Foundation import Locksmith /* using both NSUserDefaults and Keychain for user session life cycle + security */ let kUserDefaultKey = "kGoWUserDefaultKey" // Pro: removed when app uninstalls, prefect for the case checking whether user should be auto signed in, Con: plain text struct WBKeyStoreItem { var likedBosses: Set<String> = Set<String>() var accountAPIKey: String = "" } class WBKeyStore: NSObject { static let kLocksmithUserAccountName = "kGoWUserAccountName" // Pro: secure. static var keyStoreItem: WBKeyStoreItem? { get { guard let _ = UserDefaults.standard.object(forKey: kUserDefaultKey) else { return nil // app is either never installed, or deleted } if let dict = Locksmith.loadDataForUserAccount(userAccount: kLocksmithUserAccountName) { if let bosses = dict["likedBosses"] as? Set<String>, let apiKey = dict["apiKey"] as? String { return WBKeyStoreItem(likedBosses: bosses, accountAPIKey: apiKey) } else { return nil } } else { print("Error: HAPKeyStore - item is registered in NSUserDefaults, but not present in Keychain") return nil } } set { if let item = newValue { let dict: [String : Any] = ["likedBosses": item.likedBosses as NSSet, "apiKey": item.accountAPIKey] do { if let _ = Locksmith.loadDataForUserAccount(userAccount: kLocksmithUserAccountName) { try Locksmith.updateData(data: dict, forUserAccount: kLocksmithUserAccountName) } else { try Locksmith.saveData(data: dict, forUserAccount: kLocksmithUserAccountName) } } catch let error as NSError { print("Error: HAPKeyStore - %@", error) } UserDefaults.standard.set(NSNumber(value: true as Bool), forKey: kUserDefaultKey) UserDefaults.standard.synchronize() } else { do { try Locksmith.deleteDataForUserAccount(userAccount: kLocksmithUserAccountName) } catch let error as NSError { print("Error: HAPKeyStore - %@", error) } UserDefaults.standard.removeObject(forKey: kUserDefaultKey) UserDefaults.standard.synchronize() } } } } extension WBKeyStore { static var isAccountAvailable: Bool { // by APIKey if WBKeyStore.keyStoreItem == nil || WBKeyStore.keyStoreItem?.accountAPIKey == "" { return false } else { return true } } }
mit
6b3ed5f2b3f6178c81f530bfede47e6b
37.278481
164
0.571759
4.869565
false
false
false
false
SwiftGFX/SwiftMath
Sources/Matrix4x4.swift
1
9404
// Copyright 2016 Stuart Carnie. // License: https://github.com/SwiftGFX/SwiftMath#license-bsd-2-clause // #if !NOSIMD import simd #endif public extension Matrix4x4f { /// Returns the identity matrix static let identity = Matrix4x4f(diagonal: vec4(1.0)) /// Creates a new instance from the values provided in row-major order init( _ m00: Float, _ m01: Float, _ m02: Float, _ m03: Float, _ m10: Float, _ m11: Float, _ m12: Float, _ m13: Float, _ m20: Float, _ m21: Float, _ m22: Float, _ m23: Float, _ m30: Float, _ m31: Float, _ m32: Float, _ m33: Float) { self.init( vec4(m00, m10, m20, m30), vec4(m01, m11, m21, m31), vec4(m02, m12, m22, m32), vec4(m03, m13, m23, m33) ) } //MARK: matrix operations static func lookAt(eye: Vector3f, at: Vector3f, up: Vector3f = Vector3f(0.0, 1.0, 0.0)) -> Matrix4x4f { return lookAtLH(eye: eye, at: at, up: up) } static func lookAtLH(eye: Vector3f, at: Vector3f, up: Vector3f) -> Matrix4x4f { let view = (at - eye).normalized return lookAt(eye: eye, view: view, up: up) } static func lookAt(eye: Vector3f, view: Vector3f, up: Vector3f) -> Matrix4x4f { let right = up.cross(view).normalized let u = view.cross(right) return Matrix4x4f( vec4(right[0], u[0], view[0], 0.0), vec4(right[1], u[1], view[1], 0.0), vec4(right[2], u[2], view[2], 0.0), vec4(-right.dot(eye), -u.dot(eye), -view.dot(eye), 1.0) ) } /// Creates a left-handed perspective projection matrix static func proj(fovy: Angle, aspect: Float, near: Float, far: Float) -> Matrix4x4f { let height = 1.0 / tan(fovy * 0.5) let width = height * 1.0/aspect; return projLH(x: 0, y: 0, w: width, h: height, near: near, far: far) } /// Creates a left-handed perspective projection matrix static func projLH(x: Float, y: Float, w: Float, h: Float, near: Float, far: Float) -> Matrix4x4f { let diff = far - near let aa = far / diff let bb = near * aa var r = Matrix4x4f() r[0,0] = w r[1,1] = h r[2,0] = -x r[2,1] = -y r[2,2] = aa r[2,3] = 1.0 r[3,2] = -bb return r } /// Creates a right-handed perspective projection matrix static func projRH(x: Float, y: Float, w: Float, h: Float, near: Float, far: Float) -> Matrix4x4f { let diff = far - near let aa = far / diff let bb = near * aa var r = Matrix4x4f() r[0,0] = w r[1,1] = h r[2,0] = x r[2,1] = y r[2,2] = -aa r[2,3] = -1.0 r[3,2] = -bb return r } /// Creates a left-handed orthographic projection matrix static func ortho(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float) -> Matrix4x4f { return orthoLH(left: left, right: right, bottom: bottom, top: top, near: near, far: far) } /// Creates a left-handed orthographic projection matrix static func orthoLH(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float, offset: Float = 0.0) -> Matrix4x4f { let aa = 2.0 / (right - left) let bb = 2.0 / (top - bottom) let cc = 1.0 / (far - near) let dd = (left + right) / (left - right) let ee = (top + bottom) / (bottom - top) let ff = near / (near - far) var r = Matrix4x4f() r[0,0] = aa r[1,1] = bb r[2,2] = cc r[3,0] = dd + offset r[3,1] = ee r[3,2] = ff r[3,3] = 1.0 return r } /// Creates a right-handed orthographic projection matrix static func orthoRH(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float, offset: Float = 0.0) -> Matrix4x4f { let aa = 2.0 / (right - left) let bb = 2.0 / (top - bottom) let cc = 1.0 / (far - near) let dd = (left + right) / (left - right) let ee = (top + bottom) / (bottom - top) let ff = near / (near - far) var r = Matrix4x4f() r[0,0] = aa r[1,1] = bb r[2,2] = -cc r[3,0] = dd + offset r[3,1] = ee r[3,2] = ff r[3,3] = 1.0 return r } //MARK: matrix operations static func scale(sx: Float, sy: Float, sz: Float) -> Matrix4x4f { return Matrix4x4f(diagonal: vec4(sx, sy, sz, 1.0)) } static func translate(tx: Float, ty: Float, tz: Float) -> Matrix4x4f { return Matrix4x4f( vec4(1.0, 0.0, 0.0, 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(0.0, 0.0, 1.0, 0.0), vec4(tx, ty, tz, 1.0) ) } /// Create a matrix with rotates around the x axis /// /// - parameter x: angle /// /// - returns: a new rotation matrix static func rotate(x: Angle) -> Matrix4x4f { let (sin: sx, cos: cx) = sincos(x) var r = Matrix4x4f() r[0,0] = 1.0 r[1,1] = cx r[1,2] = -sx r[2,1] = sx r[2,2] = cx r[3,3] = 1.0 return r } /// Returns a transformation matrix that rotates around the y axis static func rotate(y: Angle) -> Matrix4x4f { let (sin: sy, cos: cy) = sincos(y) var r = Matrix4x4f() r[0,0] = cy r[0,2] = sy r[1,1] = 1.0 r[2,0] = -sy r[2,2] = cy r[3,3] = 1.0 return r } /// Returns a transformation matrix that rotates around the z axis static func rotate(z: Angle) -> Matrix4x4f { let (sin: sz, cos: cz) = sincos(z) var r = Matrix4x4f() r[0,0] = cz r[0,1] = -sz r[1,0] = sz r[1,1] = cz r[2,2] = 1.0 r[3,3] = 1.0 return r } /// Returns a transformation matrix that rotates around the x and then y axes static func rotate(x: Angle, y: Angle) -> Matrix4x4f { let (sin: sx, cos: cx) = sincos(x) let (sin: sy, cos: cy) = sincos(y) return Matrix4x4f( vec4(cy, 0.0, sy, 0.0), vec4(sx*sy, cx, -sx*cy, 0.0), vec4(-cx*sy, sx, cx*cy, 0.0), vec4(0.0, 0.0, 0.0, 1.0) ) } /// Returns a transformation matrix that rotates around the x, y and then z axes static func rotate(x: Angle, y: Angle, z: Angle) -> Matrix4x4f { let (sin: sx, cos: cx) = sincos(x) let (sin: sy, cos: cy) = sincos(y) let (sin: sz, cos: cz) = sincos(z) var r = Matrix4x4f() r[0,0] = cy*cz r[0,1] = -cy*sz r[0,2] = sy r[1,0] = cz*sx*sy + cx*sz r[1,1] = cx*cz - sx*sy*sz r[1,2] = -cy*sx r[2,0] = -cx*cz*sy + sx*sz r[2,1] = cz*sx + cx*sy*sz r[2,2] = cx*cy r[3,3] = 1.0 return r } /// Returns a transformation matrix that rotates around the z, y and then x axes static func rotate(z: Angle, y: Angle, x: Angle) -> Matrix4x4f { let (sin: sx, cos: cx) = sincos(x) let (sin: sy, cos: cy) = sincos(y) let (sin: sz, cos: cz) = sincos(z) var r = Matrix4x4f() r[0,0] = cy*cz r[0,1] = cz*sx*sy-cx*sz r[0,2] = cx*cz*sy+sx*sz r[1,0] = cy*sz r[1,1] = cx*cz + sx*sy*sz r[1,2] = -cz*sx + cx*sy*sz r[2,0] = -sy r[2,1] = cy*sx r[2,2] = cx*cy r[3,3] = 1.0 return r } /// Returns a transformation matrix which can be used to scale, rotate and translate vectors static func scaleRotateTranslate(sx _sx: Float, sy _sy: Float, sz _sz: Float, ax: Angle, ay: Angle, az: Angle, tx: Float, ty: Float, tz: Float) -> Matrix4x4f { let (sin: sx, cos: cx) = sincos(ax) let (sin: sy, cos: cy) = sincos(ay) let (sin: sz, cos: cz) = sincos(az) let sxsz = sx*sz let cycz = cy*cz return Matrix4x4f( vec4(_sx * (cycz - sxsz*sy), _sx * -cx*sz, _sx * (cz*sy + cy*sxsz), 0.0), vec4(_sy * (cz*sx*sy + cy*sz), _sy * cx*cz, _sy * (sy*sz - cycz*sx), 0.0), vec4(_sz * -cx*sy, _sz * sx, cx*cy, 0.0), vec4(tx, ty, tz, 1.0) ) } } extension Matrix4x4f: CustomStringConvertible { /// Displays the matrix in row-major order public var description: String { return "Matrix4x4f(\n" + "m00: \(self[0,0]), m01: \(self[1,0]), m02: \(self[2,0]), m03: \(self[3,0]),\n" + "m10: \(self[0,1]), m11: \(self[1,1]), m12: \(self[2,1]), m13: \(self[3,1]),\n" + "m20: \(self[0,2]), m21: \(self[1,2]), m22: \(self[2,2]), m23: \(self[3,2]),\n" + "m30: \(self[0,3]), m31: \(self[1,3]), m32: \(self[2,3]), m33: \(self[3,3]),\n" + ")" } }
bsd-2-clause
8e5a21e3516d663a43d35d14647d3054
31.427586
139
0.470863
2.92322
false
false
false
false
kstaring/swift
test/Generics/superclass_constraint.swift
1
2689
// RUN: %target-parse-verify-swift // RUN: %target-parse-verify-swift -parse -debug-generic-signatures %s > %t.dump 2>&1 // RUN: %FileCheck %s < %t.dump class A { func foo() { } } class B : A { func bar() { } } class Other { } func f1<T : A>(_: T) where T : Other {} // expected-error{{generic parameter 'T' cannot be a subclass of both 'A' and 'Other'}} func f2<T : A>(_: T) where T : B {} class GA<T> {} class GB<T> : GA<T> {} protocol P {} func f3<T, U>(_: T, _: U) where U : GA<T> {} func f4<T, U>(_: T, _: U) where U : GA<T> {} func f5<T, U : GA<T>>(_: T, _: U) {} func f6<U : GA<T>, T : P>(_: T, _: U) {} func f7<U, T>(_: T, _: U) where U : GA<T>, T : P {} func f8<T : GA<A>>(_: T) where T : GA<B> {} // expected-error{{generic parameter 'T' cannot be a subclass of both 'GA<A>' and 'GA<B>'}} func f9<T : GA<A>>(_: T) where T : GB<A> {} func f10<T : GB<A>>(_: T) where T : GA<A> {} func f11<T : GA<T>>(_: T) { } // expected-error{{superclass constraint 'GA<T>' is recursive}} func f12<T : GA<U>, U : GB<T>>(_: T, _: U) { } // expected-error{{superclass constraint 'GA<U>' is recursive}} func f13<T : U, U : GA<T>>(_: T, _: U) { } // expected-error{{inheritance from non-protocol, non-class type 'U'}} // rdar://problem/24730536 // Superclass constraints can be used to resolve nested types to concrete types. protocol P3 { associatedtype T } protocol P2 { associatedtype T : P3 } class C : P3 { typealias T = Int } class S : P2 { typealias T = C } extension P2 where Self.T : C { // CHECK: superclass_constraint.(file).P2.concreteTypeWitnessViaSuperclass1 // CHECK: Generic signature: <Self where Self : P2, Self.T : C> // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : P2, τ_0_0.T : C> func concreteTypeWitnessViaSuperclass1(x: Self.T.T) {} } // CHECK: superclassConformance1 // CHECK: Requirements: // CHECK-NEXT: T : C [explicit @ // CHECK-NEXT: T : P3 [inherited @ // CHECK-NEXT: T[.P3].T == C.T [redundant] // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C> func superclassConformance1<T>(t: T) where T : C, T : P3 {} // CHECK: superclassConformance2 // CHECK: Requirements: // CHECK-NEXT: T : C [explicit @ // CHECK-NEXT: T : P3 [inherited @ // CHECK-NEXT: T[.P3].T == C.T [redundant] // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C> func superclassConformance2<T>(t: T) where T : C, T : P3 {} protocol P4 { } class C2 : C, P4 { } // CHECK: superclassConformance3 // CHECK: Requirements: // CHECK-NEXT: T : C2 [explicit @ // CHECK-NEXT: T : P4 [inherited @ // CHECK: Canonical generic signature: <τ_0_0 where τ_0_0 : C2> func superclassConformance3<T>(t: T) where T : C, T : P4, T : C2 {}
apache-2.0
d1881593d19dbe0e658c1f21148cf43b
28.777778
135
0.607836
2.734694
false
false
false
false
mrchenhao/VPNOn
VPNOn/LTVPNTableViewController.swift
1
13488
// // LTVPNTableViewController.swift // VPN On // // Created by Lex Tang on 12/4/14. // Copyright (c) 2014 LexTang.com. All rights reserved. // import UIKit import CoreData import NetworkExtension import VPNOnKit let kLTVPNIDKey = "VPNID" let kVPNConnectionSection = 0 let kVPNOnDemandSection = 1 let kVPNListSectionIndex = 2 let kVPNAddSection = 3 let kConnectionCellID = "ConnectionCell" let kAddCellID = "AddCell" let kVPNCellID = "VPNCell" let kOnDemandCellID = "OnDemandCell" let kDomainsCellID = "DomainsCell" class LTVPNTableViewController: UITableViewController, SimplePingDelegate, LTVPNDomainsViewControllerDelegate { var vpns = [VPN]() var activatedVPNID: NSString? = nil var connectionStatus = NSLocalizedString("Not Connected", comment: "VPN Table - Connection Status") var connectionOn = false @IBOutlet weak var restartPingButton: UIBarButtonItem! override func loadView() { super.loadView() let backgroundView = LTViewControllerBackground() tableView.backgroundView = backgroundView } override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reloadDataAndPopDetail:"), name: kLTVPNDidCreate, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reloadDataAndPopDetail:"), name: kLTVPNDidUpdate, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reloadDataAndPopDetail:"), name: kLTVPNDidRemove, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reloadDataAndPopDetail:"), name: kLTVPNDidDuplicate, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("pingDidUpdate:"), name: "kLTPingDidUpdate", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("pingDidComplete:"), name: "kLTPingDidComplete", object: nil) NSNotificationCenter.defaultCenter().addObserver( self, selector: Selector("VPNStatusDidChange:"), name: NEVPNStatusDidChangeNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: kLTVPNDidCreate, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: kLTVPNDidUpdate, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: kLTVPNDidRemove, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: kLTVPNDidDuplicate, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: "kLTPingDidUpdate", object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: "kLTPingDidComplete", object: nil) NSNotificationCenter.defaultCenter().removeObserver( self, name: NEVPNStatusDidChangeNotification, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) vpns = VPNDataManager.sharedManager.allVPN() if let activatedVPN = VPNDataManager.sharedManager.activatedVPN { activatedVPNID = activatedVPN.ID } tableView.reloadData() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) vpns = [VPN]() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 4 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case kVPNOnDemandSection: if VPNManager.sharedManager.onDemand { return 2 } return 1 case kVPNListSectionIndex: return vpns.count default: return 1 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch indexPath.section { case kVPNConnectionSection: let cell = tableView.dequeueReusableCellWithIdentifier(kConnectionCellID, forIndexPath: indexPath) as LTVPNSwitchCell cell.titleLabel!.text = connectionStatus cell.switchButton.on = connectionOn cell.switchButton.enabled = vpns.count != 0 return cell case kVPNOnDemandSection: if indexPath.row == 0 { let switchCell = tableView.dequeueReusableCellWithIdentifier(kOnDemandCellID) as LTVPNSwitchCell switchCell.switchButton.on = VPNManager.sharedManager.onDemand return switchCell } else { let domainsCell = tableView.dequeueReusableCellWithIdentifier(kDomainsCellID) as LTVPNTableViewCell var domainsCount = 0 for domain in VPNManager.sharedManager.onDemandDomainsArray as [String] { if domain.rangeOfString("*.") == nil { domainsCount++ } } let domainsCountFormat = NSLocalizedString("%d Domains", comment: "VPN Table - Domains count") domainsCell.detailTextLabel!.text = NSString(format: domainsCountFormat, domainsCount) return domainsCell } case kVPNListSectionIndex: let cell = tableView.dequeueReusableCellWithIdentifier(kVPNCellID, forIndexPath: indexPath) as LTVPNTableViewCell let vpn = vpns[indexPath.row] cell.textLabel?.attributedText = cellTitleForIndexPath(indexPath) cell.detailTextLabel?.text = vpn.server cell.IKEv2 = vpn.ikev2 if activatedVPNID == vpns[indexPath.row].ID { cell.imageView!.image = UIImage(named: "CheckMark") } else { cell.imageView!.image = UIImage(named: "CheckMarkUnchecked") } return cell default: return tableView.dequeueReusableCellWithIdentifier(kAddCellID, forIndexPath: indexPath) as UITableViewCell } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case kVPNAddSection: VPNDataManager.sharedManager.selectedVPNID = nil let detailNavigationController = splitViewController!.viewControllers.last! as UINavigationController detailNavigationController.popToRootViewControllerAnimated(false) splitViewController!.viewControllers.last!.performSegueWithIdentifier("config", sender: nil) break case kVPNOnDemandSection: if indexPath.row == 1 { let detailNavigationController = splitViewController!.viewControllers.last! as UINavigationController detailNavigationController.popToRootViewControllerAnimated(false) splitViewController!.viewControllers.last!.performSegueWithIdentifier("domains", sender: nil) } break case kVPNListSectionIndex: activatedVPNID = vpns[indexPath.row].ID VPNManager.sharedManager.activatedVPNID = activatedVPNID tableView.reloadData() break default: () } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch indexPath.section { case kVPNListSectionIndex: return 60 default: return 44 } } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == kVPNListSectionIndex { return 20 } return 0 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == kVPNListSectionIndex && vpns.count > 0 { return NSLocalizedString("VPN CONFIGURATIONS", comment: "VPN Table - List Section Header") } return .None } // MARK: - Notifications func reloadDataAndPopDetail(notifiation: NSNotification) { vpns = VPNDataManager.sharedManager.allVPN() tableView.reloadData() popDetailViewController() } // MARK: - Navigation func popDetailViewController() { let topNavigationController = splitViewController!.viewControllers.last! as UINavigationController topNavigationController.popViewControllerAnimated(true) } override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { if indexPath.section == kVPNListSectionIndex { let VPNID = vpns[indexPath.row].objectID VPNDataManager.sharedManager.selectedVPNID = VPNID let detailNavigationController = splitViewController!.viewControllers.last! as UINavigationController detailNavigationController.popToRootViewControllerAnimated(false) detailNavigationController.performSegueWithIdentifier("config", sender: self) } } // MARK: - Cell title func cellTitleForIndexPath(indexPath: NSIndexPath) -> NSAttributedString { let vpn = vpns[indexPath.row] let latency = LTPingQueue.sharedQueue.latencyForHostname(vpn.server) let titleAttributes = [ NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleBody) ] var attributedTitle = NSMutableAttributedString(string: vpn.title, attributes: titleAttributes) if latency != -1 { var latencyColor = UIColor(red:0.39, green:0.68, blue:0.19, alpha:1) if latency > 200 { latencyColor = UIColor(red:0.73, green:0.54, blue:0.21, alpha:1) } else if latency > 500 { latencyColor = UIColor(red:0.9 , green:0.11, blue:0.34, alpha:1) } let latencyAttributes = [ NSFontAttributeName: UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote), NSForegroundColorAttributeName: latencyColor ] var attributedLatency = NSMutableAttributedString(string: " \(latency)ms", attributes: latencyAttributes) attributedTitle.appendAttributedString(attributedLatency) } return attributedTitle } // MARK: - Ping @IBAction func pingServers() { restartPingButton.enabled = false LTPingQueue.sharedQueue.restartPing() } func pingDidUpdate(notification: NSNotification) { tableView.reloadData() } func pingDidComplete(notification: NSNotification) { restartPingButton.enabled = true } // MARK: - Connection @IBAction func toggleVPN(sender: UISwitch) { if sender.on { if let vpn = VPNDataManager.sharedManager.activatedVPN { let passwordRef = VPNKeychainWrapper.passwordForVPNID(vpn.ID) let secretRef = VPNKeychainWrapper.secretForVPNID(vpn.ID) let certificate = VPNKeychainWrapper.certificateForVPNID(vpn.ID) if vpn.ikev2 { VPNManager.sharedManager.connectIKEv2(vpn.title, server: vpn.server, account: vpn.account, group: vpn.group, alwaysOn: vpn.alwaysOn, passwordRef: passwordRef, secretRef: secretRef, certificate: certificate) } else { VPNManager.sharedManager.connectIPSec(vpn.title, server: vpn.server, account: vpn.account, group: vpn.group, alwaysOn: vpn.alwaysOn, passwordRef: passwordRef, secretRef: secretRef, certificate: certificate) } } } else { VPNManager.sharedManager.disconnect() } } func VPNStatusDidChange(notification: NSNotification?) { switch VPNManager.sharedManager.status { case NEVPNStatus.Connecting: connectionStatus = NSLocalizedString("Connecting...", comment: "VPN Table - Connection Status") connectionOn = true break case NEVPNStatus.Connected: connectionStatus = NSLocalizedString("Connected", comment: "VPN Table - Connection Status") connectionOn = true break case NEVPNStatus.Disconnecting: connectionStatus = NSLocalizedString("Disconnecting...", comment: "VPN Table - Connection Status") connectionOn = false break default: connectionStatus = NSLocalizedString("Not Connected", comment: "VPN Table - Connection Status") connectionOn = false } if vpns.count > 0 { let connectionIndexPath = NSIndexPath(forRow: 0, inSection: kVPNConnectionSection) tableView.reloadRowsAtIndexPaths([connectionIndexPath], withRowAnimation: .None) } } }
mit
77a5a77723d9a12b2d7fff06b0b4d5ba
38.670588
226
0.64309
5.688739
false
false
false
false
alexburtnik/ABSwiftExtensions
ABSwiftExtensions/Classes/Geometry/GeometryTypes.swift
1
1289
// // Geometry.swift // Cropper // // Created by Alex Burtnik on 4/12/17. // Copyright © 2017 alexburtnik. All rights reserved. // import Foundation import UIKit public struct Circle { public var center: CGPoint public var radius: CGFloat public func vectorToRect(_ rect: CGRect) -> CGVector? { guard round(rect.width - 2 * radius) >= 0 && round(rect.height - 2 * radius) >= 0 else { return nil } return center.vectorToRect(rect.insetBy(dx: radius, dy: radius)) } public init(center: CGPoint, radius: CGFloat) { self.center = center self.radius = radius } } public struct Segment { public var start: CGPoint public var end: CGPoint public init(start: CGPoint, end: CGPoint) { self.start = start self.end = end } public init(startX: CGFloat, startY: CGFloat, endX: CGFloat, endY: CGFloat) { self.init(start: CGPoint(x: startX, y: startY), end: CGPoint(x: endX, y: endY)) } public var lengthSquared: CGFloat { return start.distanceSquared(toPoint: end) } public var length: CGFloat { return start.distance(toPoint: end) } public var vector: CGVector { return start.vectorToPoint(end) } }
mit
273fc6a78838a1d1d863bfa99cbfb8ba
24.254902
109
0.614907
3.963077
false
false
false
false
JOCR10/iOS-Curso
Tareas/Tarea 4/TareaDogsWithCoreData/TareaDogsWithCoreData/DogsViewController.swift
1
1985
import UIKit class DogsViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var dogs = [Dog]() override func viewDidLoad() { super.viewDidLoad() tableView.registerCustomCell(identifier: DogTableViewCell.getTableViewCellIdentifier()) createdAddButton() self.title = "Perros" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) initializeDogs() tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func initializeDogs() { guard let dogsArray = CoreDataManager.getAllDogs() else { return } dogs = dogsArray } func createdAddButton() { let addButton = UIBarButtonItem(barButtonSystemItem: .add , target: self, action: #selector(addAction)) navigationItem.rightBarButtonItem = addButton } func addAction() { let addDogViewController = storyboard!.instantiateViewController(withIdentifier: AddDogViewController.getViewControllerIdentifier()) navigationController?.pushViewController(addDogViewController, animated: true) } } extension DogsViewController : UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dogs.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = (tableView.dequeueReusableCell(withIdentifier: DogTableViewCell.getTableViewCellIdentifier())) as! DogTableViewCell let dog = dogs[indexPath.row] cell.setUpCell(dog: dog) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 250 } }
mit
3e861b18e1497aa9fe45fb6742114549
26.191781
140
0.655416
5.753623
false
false
false
false
jeroen1985/iOS-course
Map Demo/Map Demo/ViewController.swift
1
3232
// // ViewController.swift // Map Demo // // Created by Jeroen Stevens on 2015-11-27. // Copyright (c) 2015 fishsticks. All rights reserved. // import UIKit import MapKit import CoreLocation class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet var map: MKMapView! var locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() var latitude:CLLocationDegrees = 52.378695 var longitude:CLLocationDegrees = 4.899057 var latDelta:CLLocationDegrees = 1 var lonDelta:CLLocationDegrees = 1 var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) var annotation = MKPointAnnotation() map.setRegion(region, animated: true) annotation.coordinate = location annotation.title = "Beautiful Amsterdam!" annotation.subtitle = "best town" map.addAnnotation(annotation) var uilprg = UILongPressGestureRecognizer(target: self, action: "action:") uilprg.minimumPressDuration = 2 map.addGestureRecognizer(uilprg) } func action (gestureRecognizer: UIGestureRecognizer){ println("test") var touchPoint = gestureRecognizer.locationInView(self.map) var newCoordinate: CLLocationCoordinate2D = map.convertPoint(touchPoint, toCoordinateFromView: self.map) var annotation = MKPointAnnotation() annotation.coordinate = newCoordinate annotation.title = "new place" annotation.subtitle = "awesome" map.addAnnotation(annotation) } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var userLocation: CLLocation = locations[0] as CLLocation var latitude = userLocation.coordinate.latitude var longitude = userLocation.coordinate.longitude var latDelta:CLLocationDegrees = 0.01 var lonDelta:CLLocationDegrees = 0.01 var span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta) var location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude) var region:MKCoordinateRegion = MKCoordinateRegionMake(location, span) var annotation = MKPointAnnotation() self.map.setRegion(region, animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
ae6f3dcd9899df9b090048eda4c92ae3
27.60177
112
0.636757
6.215385
false
false
false
false
Donny8028/Swift-Animation
Carousel Effect/Carousel Effect/ViewController.swift
1
2564
// // ViewController.swift // Carousel Effect // // Created by 賢瑭 何 on 2016/5/15. // Copyright © 2016年 Donny. All rights reserved. // import UIKit private let reuseIdentifier = "Cool Cell" class ViewController: UIViewController,UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! private var items: [CoolImage] = [ CoolImage(image: "bodyline", caption: "you know I like it"), CoolImage(image: "darkvarder", caption: "winter is coming"), CoolImage(image: "dudu", caption: "waiting till the end of the day"), CoolImage(image: "hello", caption: "trick or treat"), CoolImage(image: "hhhhh", caption: "pain in the neck"), CoolImage(image: "run", caption: "don't let me find you"), CoolImage(image: "wave", caption: "just shining") ] var layout: UICollectionViewLayout? var reuseView: UICollectionReusableView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. collectionView.delegate = self collectionView.dataSource = self //collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) // you don't need register when you already set the cell in storyBoard } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as? CoolImageCollectionViewCell let item = items[indexPath.row] // items[index.item] is legal as well cell?.caption.text = item.caption cell?.imagView.image = UIImage(named: item.image) return cell! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
7cbfe5d4242de9b32a4d487227ef8f37
36.028986
146
0.617613
5.554348
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Nodes/Effects/Filters/Tone Filter/AKToneFilter.swift
1
3888
// // AKToneFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// A first-order recursive low-pass filter with variable frequency response. /// /// - Parameters: /// - input: Input node to process /// - halfPowerPoint: The response curve's half-power point, in Hertz. Half power is defined as peak power / root 2. /// public class AKToneFilter: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKToneFilterAudioUnit? internal var token: AUParameterObserverToken? private var halfPowerPointParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// The response curve's half-power point, in Hertz. Half power is defined as peak power / root 2. public var halfPowerPoint: Double = 1000.0 { willSet { if halfPowerPoint != newValue { if internalAU!.isSetUp() { halfPowerPointParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.halfPowerPoint = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - Parameters: /// - input: Input node to process /// - halfPowerPoint: The response curve's half-power point, in Hertz. Half power is defined as peak power / root 2. /// public init( _ input: AKNode, halfPowerPoint: Double = 1000.0) { self.halfPowerPoint = halfPowerPoint var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x746f6e65 /*'tone'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKToneFilterAudioUnit.self, asComponentDescription: description, name: "Local AKToneFilter", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKToneFilterAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } halfPowerPointParameter = tree.valueForKey("halfPowerPoint") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.halfPowerPointParameter!.address { self.halfPowerPoint = Double(value) } } } internalAU?.halfPowerPoint = Float(halfPowerPoint) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
df36684fa6ee06e7c0ba8844cda2edcc
30.868852
122
0.621142
5.225806
false
false
false
false
Cocoanetics/Kvitto
Core/Source/InAppPurchaseReceipt.swift
1
6149
// // InAppPurchaseReceipt.swift // Kvitto // // Created by Oliver Drobnik on 07/10/15. // Copyright © 2015 Oliver Drobnik. All rights reserved. // import Foundation import DTFoundation /** A purchase receipt for an In-App-Purchase. */ @objc(DTInAppPurchaseReceipt) @objcMembers public final class InAppPurchaseReceipt: NSObject { /** The number of items purchased. This value corresponds to the quantity property of the SKPayment object stored in the transaction’s payment property. */ fileprivate(set) public var quantity: Int? /** ObjectiveC support of quantity. To retrieve the value specify `quantityNumber.integerValue`. The number of items purchased. This value corresponds to the quantity property of the SKPayment object stored in the transaction’s payment property. */ public var quantityNumber : NSNumber? { get { return quantity as NSNumber? } } /** The product identifier of the item that was purchased. This value corresponds to the productIdentifier property of the `SKPayment` object stored in the transaction’s payment property. */ fileprivate(set) public var productIdentifier: String? /** The transaction identifier of the item that was purchased. This value corresponds to the transaction’s transactionIdentifier property. */ fileprivate(set) public var transactionIdentifier: String? /** For a transaction that restores a previous transaction, the transaction identifier of the original transaction. Otherwise, identical to the transaction identifier. This value corresponds to the original transaction’s transactionIdentifier property. All receipts in a chain of renewals for an auto-renewable subscription have the same value for this field. */ fileprivate(set) public var originalTransactionIdentifier: String? /** The date and time that the item was purchased. This value corresponds to the transaction’s transactionDate property. For a transaction that restores a previous transaction, the purchase date is the date of the restoration. Use Original Purchase Date to get the date of the original transaction. In an auto-renewable subscription receipt, this is always the date when the subscription was purchased or renewed, regardless of whether the transaction has been restored. */ fileprivate(set) public var purchaseDate: Date? /** For a transaction that restores a previous transaction, the date of the original transaction. This value corresponds to the original transaction’s transactionDate property. In an auto-renewable subscription receipt, this indicates the beginning of the subscription period, even if the subscription has been renewed. */ fileprivate(set) public var originalPurchaseDate: Date? /** The expiration date for the subscription. This key is only present for auto-renewable subscription receipts. */ fileprivate(set) public var subscriptionExpirationDate: Date? /** For a transaction that was canceled by Apple customer support, the time and date of the cancellation. Treat a canceled receipt the same as if no purchase had ever been made. */ fileprivate(set) public var cancellationDate: Date? /** For an auto-renewable subscription, whether or not it is in the introductory price period. */ fileprivate(set) public var isSubscriptionIntroductoryPricePeriod: Bool = false /** The primary key for identifying subscription purchases. */ fileprivate(set) public var webOrderLineItemIdentifier: Int? /** ObjectiveC support of webOrderLineItemIdentifier. Retrieve the value with `webOrderLineItemIdentifierNumber.integerValue`. The primary key for identifying subscription purchases. */ public var webOrderLineItemIdentifierNumber : NSNumber? { get { return webOrderLineItemIdentifier as NSNumber? } } /** The designated initializer */ public init?(data: Data) { super.init() do { _ = try parseData(data) } catch { return nil } } // MARK: Parsing fileprivate func parseData(_ data: Data) throws -> Bool { guard let rootArray = DTASN1Serialization.object(with: data) as? [[AnyObject]] else { throw ReceiptParsingError.invalidRootObject } for item in rootArray { guard item.count == 3, let type = (item[0] as? NSNumber)?.intValue, let version = (item[1] as? NSNumber)?.intValue, let data = item[2] as? Data , version > 0 else { throw ReceiptParsingError.invalidRootObject } try processItem(type, data: data) } return true } fileprivate func processItem(_ type: Int, data: Data) throws { switch(type) { case 1701: quantity = try _intFromData(data) case 1702: productIdentifier = try _stringFromData(data) case 1703: transactionIdentifier = try _stringFromData(data) case 1704: purchaseDate = try _dateFromData(data) case 1705: originalTransactionIdentifier = try _stringFromData(data) case 1706: originalPurchaseDate = try _dateFromData(data) case 1708: subscriptionExpirationDate = try _dateFromData(data) case 1711: webOrderLineItemIdentifier = try _intFromData(data) case 1712: cancellationDate = try _dateFromData(data) case 1719: isSubscriptionIntroductoryPricePeriod = try _intFromData(data) != 0 default: // all other types are private break; } } }
bsd-2-clause
b449616f5468c38d5d370664872550fa
33.077778
252
0.647864
5.207131
false
false
false
false
RGSSoftware/ColorHSPicker
Pod/Classes/ThumbViewControl.swift
1
1489
// // ThumbViewControl.swift // ColorPicker // // Created by PC on 3/26/16. // Copyright © 2016 Randel Smith. All rights reserved. // import UIKit class ThumbViewControl: UIControl { override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { super.beginTrackingWithTouch(touch, withEvent: event) if let superview = self.superview{ if superview.isKindOfClass(UIControl){ let control = superview as! UIControl control .beginTrackingWithTouch(touch, withEvent: event) } } return true } override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool { super.continueTrackingWithTouch(touch, withEvent: event) if let superview = self.superview{ if superview.isKindOfClass(UIControl){ let control = superview as! UIControl control .continueTrackingWithTouch(touch, withEvent: event) } } return true } override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) { super.endTrackingWithTouch(touch, withEvent: event) if let superview = self.superview{ if superview.isKindOfClass(UIControl){ let control = superview as! UIControl control .endTrackingWithTouch(touch, withEvent: event) } } } }
mit
2b5090faaa02890ec0eede0ff0dc10fa
28.76
96
0.615591
5.239437
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/ConversationList/ListContent/ConversationListContentController/ViewModel/ConversationListViewModel.swift
1
24516
// Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import DifferenceKit import WireSystem import WireDataModel import WireSyncEngine import WireRequestStrategy final class ConversationListViewModel: NSObject { typealias SectionIdentifier = String fileprivate struct Section: DifferentiableSection { enum Kind: Equatable, Hashable { /// for incoming requests case contactRequests /// for self pending requests / conversations case conversations /// one to one conversations case contacts /// group conversations case groups /// favorites case favorites /// conversations in folders case folder(label: LabelType) func hash(into hasher: inout Hasher) { hasher.combine(identifier) } var identifier: SectionIdentifier { switch self { case.folder(label: let label): return label.remoteIdentifier?.transportString() ?? "folder" default: return canonicalName } } var canonicalName: String { switch self { case .contactRequests: return "contactRequests" case .conversations: return "conversations" case .contacts: return "contacts" case .groups: return "groups" case .favorites: return "favorites" case .folder(label: let label): return label.name ?? "folder" } } var localizedName: String? { switch self { case .conversations: return nil case .contactRequests: return "list.section.requests".localized case .contacts: return "list.section.contacts".localized case .groups: return "list.section.groups".localized case .favorites: return "list.section.favorites".localized case .folder(label: let label): return label.name } } static func == (lhs: ConversationListViewModel.Section.Kind, rhs: ConversationListViewModel.Section.Kind) -> Bool { switch (lhs, rhs) { case (.conversations, .conversations): return true case (.contactRequests, .contactRequests): return true case (.contacts, .contacts): return true case (.groups, .groups): return true case (.favorites, .favorites): return true case (.folder(let lhsLabel), .folder(let rhsLabel)): return lhsLabel === rhsLabel default: return false } } } var kind: Kind var items: [SectionItem] var collapsed: Bool var elements: [SectionItem] { return collapsed ? [] : items } /// ref to AggregateArray, we return the first found item's index /// /// - Parameter item: item to search /// - Returns: the index of the item func index(for item: ConversationListItem) -> Int? { return items.firstIndex(of: SectionItem(item: item, kind: kind)) } func isContentEqual(to source: ConversationListViewModel.Section) -> Bool { return kind == source.kind } var differenceIdentifier: String { return kind.identifier } init<C>(source: ConversationListViewModel.Section, elements: C) where C: Collection, C.Element == SectionItem { self.kind = source.kind self.collapsed = source.collapsed items = Array(elements) } init(kind: Kind, conversationDirectory: ConversationDirectoryType, collapsed: Bool) { items = ConversationListViewModel.newList(for: kind, conversationDirectory: conversationDirectory) self.kind = kind self.collapsed = collapsed } } static let contactRequestsItem: ConversationListConnectRequestsItem = ConversationListConnectRequestsItem() /// current selected ZMConversaton or ConversationListConnectRequestsItem object private(set) var selectedItem: ConversationListItem? { didSet { /// expand the section if selcted item is update guard let indexPath = self.indexPath(for: selectedItem), collapsed(at: indexPath.section) else { return } setCollapsed(sectionIndex: indexPath.section, collapsed: false, batchUpdate: false) } } weak var restorationDelegate: ConversationListViewModelRestorationDelegate? { didSet { restorationDelegate?.listViewModel(self, didRestoreFolderEnabled: folderEnabled) } } weak var delegate: ConversationListViewModelDelegate? { didSet { delegateFolderEnableState(newState: state) } } var folderEnabled: Bool { get { return state.folderEnabled } set { guard newValue != state.folderEnabled else { return } state.folderEnabled = newValue updateAllSections() delegate?.listViewModelShouldBeReloaded() delegateFolderEnableState(newState: state) } } // Local copies of the lists. private var sections: [Section] = [] private typealias DiffKitSection = ArraySection<Int, SectionItem> /// make items has different hash in different sections struct SectionItem: Hashable, Differentiable { let item: ConversationListItem let isFavorite: Bool fileprivate init(item: ConversationListItem, kind: Section.Kind) { self.item = item self.isFavorite = kind == .favorites } func hash(into hasher: inout Hasher) { hasher.combine(isFavorite) let hashableItem: NSObject = item hasher.combine(hashableItem) } static func == (lhs: SectionItem, rhs: SectionItem) -> Bool { return lhs.isFavorite == rhs.isFavorite && lhs.item == rhs.item } } /// for folder enabled and collapse presistent private lazy var _state: State = { guard let persistentPath = ConversationListViewModel.persistentURL, let jsonData = try? Data(contentsOf: persistentPath) else { return State() } do { return try JSONDecoder().decode(ConversationListViewModel.State.self, from: jsonData) } catch { log.error("restore state error: \(error)") return State() } }() private var state: State { get { return _state } set { /// simulate willSet /// assign if newValue != _state { _state = newValue } /// simulate didSet saveState(state: _state) } } private var conversationDirectoryToken: Any? private let userSession: UserSessionInterface? init(userSession: UserSessionInterface? = ZMUserSession.shared()) { self.userSession = userSession super.init() setupObservers() updateAllSections() } private func delegateFolderEnableState(newState: State) { delegate?.listViewModel(self, didChangeFolderEnabled: folderEnabled) } private func setupObservers() { conversationDirectoryToken = userSession?.conversationDirectory.addObserver(self) } func sectionHeaderTitle(sectionIndex: Int) -> String? { return kind(of: sectionIndex)?.localizedName } /// return true if seaction header is visible. /// For .contactRequests section it is always invisible /// When folderEnabled == true, returns false /// /// - Parameter sectionIndex: section number of collection view /// - Returns: if the section exists and visible, return true. func sectionHeaderVisible(section: Int) -> Bool { guard sections.indices.contains(section), kind(of: section) != .contactRequests, folderEnabled else { return false } return !sections[section].items.isEmpty } private func kind(of sectionIndex: Int) -> Section.Kind? { guard sections.indices.contains(sectionIndex) else { return nil } return sections[sectionIndex].kind } /// Section's canonical name /// /// - Parameter sectionIndex: section index of the collection view /// - Returns: canonical name func sectionCanonicalName(of sectionIndex: Int) -> String? { return kind(of: sectionIndex)?.canonicalName } var sectionCount: Int { return sections.count } func numberOfItems(inSection sectionIndex: Int) -> Int { guard sections.indices.contains(sectionIndex), !collapsed(at: sectionIndex) else { return 0 } return sections[sectionIndex].elements.count } private func numberOfItems(of kind: Section.Kind) -> Int? { return sections.first(where: { $0.kind == kind })?.elements.count ?? nil } func section(at sectionIndex: Int) -> [ConversationListItem]? { if sectionIndex >= sectionCount { return nil } return sections[sectionIndex].elements.map(\.item) } func item(for indexPath: IndexPath) -> ConversationListItem? { guard let items = section(at: indexPath.section), items.indices.contains(indexPath.item) else { return nil } return items[indexPath.item] } /// TODO: Question: we may have multiple items in folders now. return array of IndexPaths? func indexPath(for item: ConversationListItem?) -> IndexPath? { guard let item = item else { return nil } for (sectionIndex, section) in sections.enumerated() { if let index = section.index(for: item) { return IndexPath(item: index, section: sectionIndex) } } return nil } private static func newList(for kind: Section.Kind, conversationDirectory: ConversationDirectoryType) -> [SectionItem] { let conversationListType: ConversationListType switch kind { case .contactRequests: conversationListType = .pending return conversationDirectory.conversations(by: conversationListType).isEmpty ? [] : [SectionItem(item: contactRequestsItem, kind: kind)] case .conversations: conversationListType = .unarchived case .contacts: conversationListType = .contacts case .groups: conversationListType = .groups case .favorites: conversationListType = .favorites case .folder(label: let label): conversationListType = .folder(label) } return conversationDirectory.conversations(by: conversationListType).map({ SectionItem(item: $0, kind: kind) }) } /// Select the item at an index path /// /// - Parameter indexPath: indexPath of the item to select /// - Returns: the item selected @discardableResult func selectItem(at indexPath: IndexPath) -> ConversationListItem? { let item = self.item(for: indexPath) select(itemToSelect: item) return item } /// Search for next items /// /// - Parameters: /// - index: index of search item /// - sectionIndex: section of search item /// - Returns: an index path for next existing item func item(after index: Int, section sectionIndex: Int) -> IndexPath? { guard let section = self.section(at: sectionIndex) else { return nil } if section.count > index + 1 { // Select next item in section return IndexPath(item: index + 1, section: sectionIndex) } else if index + 1 >= section.count { // select last item in previous section return firstItemInSection(after: sectionIndex) } return nil } private func firstItemInSection(after sectionIndex: Int) -> IndexPath? { let nextSectionIndex = sectionIndex + 1 if nextSectionIndex >= sectionCount { // we are at the end, so return nil return nil } if let section = self.section(at: nextSectionIndex) { if section.isEmpty { // Recursively move forward return firstItemInSection(after: nextSectionIndex) } else { return IndexPath(item: 0, section: nextSectionIndex) } } return nil } /// Search for previous items /// /// - Parameters: /// - index: index of search item /// - sectionIndex: section of search item /// - Returns: an index path for previous existing item func itemPrevious(to index: Int, section sectionIndex: Int) -> IndexPath? { guard let section = self.section(at: sectionIndex) else { return nil } if section.indices.contains(index - 1) { // Select previous item in section return IndexPath(item: index - 1, section: sectionIndex) } else if index == 0 { // select last item in previous section return lastItemInSectionPrevious(to: sectionIndex) } return nil } func lastItemInSectionPrevious(to sectionIndex: Int) -> IndexPath? { let previousSectionIndex = sectionIndex - 1 if previousSectionIndex < 0 { // we are at the top, so return nil return nil } guard let section = self.section(at: previousSectionIndex) else { return nil } if section.isEmpty { // Recursively move back return lastItemInSectionPrevious(to: previousSectionIndex) } else { return IndexPath(item: section.count - 1, section: previousSectionIndex) } } private func updateAllSections() { sections = createSections() } /// Create the section structure private func createSections() -> [Section] { guard let conversationDirectory = userSession?.conversationDirectory else { return [] } var kinds: [Section.Kind] if folderEnabled { kinds = [.contactRequests, .favorites, .groups, .contacts] let folders: [Section.Kind] = conversationDirectory.allFolders.map({ .folder(label: $0) }) kinds.append(contentsOf: folders) } else { kinds = [.contactRequests, .conversations] } return kinds.map { Section(kind: $0, conversationDirectory: conversationDirectory, collapsed: state.collapsed.contains($0.identifier)) } } private func sectionNumber(for kind: Section.Kind) -> Int? { for (index, section) in sections.enumerated() where section.kind == kind { return index } return nil } private func update(for kind: Section.Kind? = nil) { guard let conversationDirectory = userSession?.conversationDirectory else { return } var newValue: [Section] if let kind = kind, let sectionNumber = self.sectionNumber(for: kind) { newValue = sections let newList = ConversationListViewModel.newList(for: kind, conversationDirectory: conversationDirectory) newValue[sectionNumber].items = newList /// Refresh the section header(since it may be hidden if the sectio is empty) when a section becomes empty/from empty to non-empty if sections[sectionNumber].items.isEmpty || newList.isEmpty { sections = newValue delegate?.listViewModel(self, didUpdateSectionForReload: sectionNumber, animated: true) return } } else { newValue = createSections() } let changeset = StagedChangeset(source: sections, target: newValue) if changeset.isEmpty { sections = newValue } else { delegate?.reload(using: changeset, interrupt: { _ in return false }, setData: { data in if let data = data { self.sections = data } }) } if let kind = kind, let sectionNumber = sectionNumber(for: kind) { delegate?.listViewModel(self, didUpdateSection: sectionNumber) } else { sections.enumerated().forEach { delegate?.listViewModel(self, didUpdateSection: $0.offset) } } } @discardableResult func select(itemToSelect: ConversationListItem?) -> Bool { guard let itemToSelect = itemToSelect else { internalSelect(itemToSelect: nil) return false } if indexPath(for: itemToSelect) == nil { guard let conversation = itemToSelect as? ZMConversation else { return false } ZMUserSession.shared()?.enqueue({ conversation.isArchived = false }, completionHandler: { self.internalSelect(itemToSelect: itemToSelect) }) } else { internalSelect(itemToSelect: itemToSelect) } return true } private func internalSelect(itemToSelect: ConversationListItem?) { selectedItem = itemToSelect if let itemToSelect = itemToSelect { delegate?.listViewModel(self, didSelectItem: itemToSelect) } } // MARK: - folder badge func folderBadge(at sectionIndex: Int) -> Int { return sections[sectionIndex].items.filter({ let status = ($0.item as? ZMConversation)?.status return status?.messagesRequiringAttention.isEmpty == false && status?.showingAllMessages == true }).count } // MARK: - collapse section func collapsed(at sectionIndex: Int) -> Bool { return collapsed(at: sectionIndex, state: state) } private func collapsed(at sectionIndex: Int, state: State) -> Bool { guard let kind = kind(of: sectionIndex) else { return false } return state.collapsed.contains(kind.identifier) } /// set a collpase state of a section /// /// - Parameters: /// - sectionIndex: section to update /// - collapsed: collapsed or expanded /// - batchUpdate: true for update with difference kit comparison, false for reload the section animated func setCollapsed(sectionIndex: Int, collapsed: Bool, batchUpdate: Bool = true) { guard let conversationDirectory = userSession?.conversationDirectory else { return } guard let kind = self.kind(of: sectionIndex) else { return } guard self.collapsed(at: sectionIndex) != collapsed else { return } guard let sectionNumber = self.sectionNumber(for: kind) else { return } if collapsed { state.collapsed.insert(kind.identifier) } else { state.collapsed.remove(kind.identifier) } var newValue = sections newValue[sectionNumber] = Section(kind: kind, conversationDirectory: conversationDirectory, collapsed: collapsed) if batchUpdate { let changeset = StagedChangeset(source: sections, target: newValue) delegate?.reload(using: changeset, interrupt: { _ in return false }, setData: { data in if let data = data { self.sections = data } }) } else { sections = newValue delegate?.listViewModel(self, didUpdateSectionForReload: sectionIndex, animated: true) } } // MARK: - state presistent private struct State: Codable, Equatable { var collapsed: Set<SectionIdentifier> var folderEnabled: Bool init() { collapsed = [] folderEnabled = false } var jsonString: String? { guard let jsonData = try? JSONEncoder().encode(self) else { return nil } return String(data: jsonData, encoding: .utf8) } } var jsonString: String? { return state.jsonString } private func saveState(state: State) { guard let jsonString = state.jsonString, let persistentDirectory = ConversationListViewModel.persistentDirectory, let directoryURL = URL.directoryURL(persistentDirectory) else { return } FileManager.default.createAndProtectDirectory(at: directoryURL) do { try jsonString.write(to: directoryURL.appendingPathComponent(ConversationListViewModel.persistentFilename), atomically: true, encoding: .utf8) } catch { log.error("error writing ConversationListViewModel to \(directoryURL): \(error)") } } private static var persistentDirectory: String? { guard let userID = ZMUser.selfUser()?.remoteIdentifier else { return nil } return "UI_state/\(userID)" } private static var persistentFilename: String { let className = String(describing: self) return "\(className).json" } static var persistentURL: URL? { guard let persistentDirectory = persistentDirectory else { return nil } return URL.directoryURL(persistentDirectory)?.appendingPathComponent(ConversationListViewModel.persistentFilename) } } // MARK: - ZMUserObserver private let log = ZMSLog(tag: "ConversationListViewModel") // MARK: - ConversationDirectoryObserver extension ConversationListViewModel: ConversationDirectoryObserver { func conversationDirectoryDidChange(_ changeInfo: ConversationDirectoryChangeInfo) { if changeInfo.reloaded { // If the section was empty in certain cases collection view breaks down on the big amount of conversations, // so we prefer to do the simple reload instead. update() } else { /// TODO: When 2 sections are visible and a conversation belongs to both, the lower section's update /// animation is missing since it started after the top section update animation started. To fix this /// we should calculate the change set in one batch. /// TODO: wait for SE update for returning multiple items in changeInfo.updatedLists for updatedList in changeInfo.updatedLists { if let kind = self.kind(of: updatedList) { update(for: kind) } } } } private func kind(of conversationListType: ConversationListType) -> Section.Kind? { let kind: Section.Kind? switch conversationListType { case .unarchived: kind = .conversations case .contacts: kind = .contacts case .pending: kind = .contactRequests case .groups: kind = .groups case .favorites: kind = .favorites case .folder(let label): kind = .folder(label: label) case .archived: kind = nil } return kind } }
gpl-3.0
ee840232ead80aab16336011dff9dfef
32.264586
154
0.595978
5.305345
false
false
false
false
kingka/SwiftWeiBo
SwiftWeiBo/SwiftWeiBo/Classes/Home/PhotoBrowser/PhotoBrowserController.swift
1
5422
// // PhotoBrowserController.swift // SwiftWeiBo // // Created by Imanol on 16/5/5. // Copyright © 2016年 imanol. All rights reserved. // import UIKit import SVProgressHUD let PhotoBrowserControllerIdentifer = "PhotoBrowserControllerIdentifer" class PhotoBrowserController: UIViewController { var index : Int? var urls : [NSURL]? init(index : Int , urls : [NSURL]) { self.index = index self.urls = urls super.init(nibName: nil, bundle: nil) } //滚动到指定的cell override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let indexpath = NSIndexPath(forRow:index!, inSection: 0) collectionV.scrollToItemAtIndexPath(indexpath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false) } override func viewDidLoad() { super.viewDidLoad() setupUI() collectionV.dataSource = self closeBtn.addTarget(self, action: "dismissController", forControlEvents: UIControlEvents.TouchUpInside) saveBtn.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside) collectionV.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserControllerIdentifer) } func setupUI(){ view.backgroundColor = UIColor.blackColor() view.addSubview(collectionV) collectionV.addSubview(iconView) view.addSubview(closeBtn) view.addSubview(saveBtn) collectionV.snp_makeConstraints { (make) -> Void in make.edges.equalTo(view) } closeBtn.snp_makeConstraints { (make) -> Void in make.left.equalTo(view).offset(10) make.bottom.equalTo(view).offset(-10) make.width.equalTo(100) make.height.equalTo(30) } saveBtn.snp_makeConstraints { (make) -> Void in make.right.equalTo(view).offset(10) make.bottom.equalTo(view).offset(-10) make.width.equalTo(100) make.height.equalTo(30) } } func dismissController(){ dismissViewControllerAnimated(true, completion: nil) } func save(){ let index = collectionV.indexPathsForVisibleItems().last let cell = collectionV.cellForItemAtIndexPath(index!) as! PhotoBrowserCell let image = cell.imageV.image UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil) //// - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo; } func image(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject){ if error != nil{ SVProgressHUD.showErrorWithStatus("保存失败") }else{ SVProgressHUD.showSuccessWithStatus("保存成功") } } //MARK:- LAZY loading private var closeBtn : UIButton = { let btn = UIButton() btn.setTitle("关闭", forState: UIControlState.Normal) btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) btn.backgroundColor = UIColor(white: 0.8, alpha: 0.6) return btn }() private var saveBtn : UIButton = { let btn = UIButton() btn.setTitle("保存", forState: UIControlState.Normal) btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) btn.backgroundColor = UIColor(white: 0.8, alpha: 0.6) return btn }() private var iconView : UIImageView = UIImageView() private var collectionV : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserLayout()) override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PhotoBrowserController : UICollectionViewDataSource,PhotoBrowserCellDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { print("urls.count = \(urls?.count)") return urls?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserControllerIdentifer, forIndexPath: indexPath) as! PhotoBrowserCell cell.photoBrowserCellDelegate = self cell.imageURL = urls![indexPath.row] cell.backgroundColor = UIColor.blackColor() return cell } func photoBrowserClose(cell: PhotoBrowserCell) { dismissViewControllerAnimated(true, completion: nil) } } class PhotoBrowserLayout : UICollectionViewFlowLayout { override func prepareLayout() { itemSize = UIScreen.mainScreen().bounds.size minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = UICollectionViewScrollDirection.Horizontal collectionView?.showsHorizontalScrollIndicator = false collectionView?.pagingEnabled = true collectionView?.bounces = false } }
mit
7be9c1f9d94411d152af8ca15d0686c9
32.65
151
0.662456
5.437374
false
false
false
false
the-hypermedia-project/representor-swift
Sources/HTTPDeserialization.swift
1
1897
// // HTTPDeserialization.swift // Representor // // Created by Kyle Fuller on 23/01/2015. // Copyright (c) 2015 Apiary. All rights reserved. // import Foundation func jsonDeserializer(_ closure:@escaping (([String:AnyObject]) -> Representor<HTTPTransition>?)) -> ((_ response:HTTPURLResponse, _ body:Data) -> Representor<HTTPTransition>?) { return { (response, body) in let object: AnyObject? = try? JSONSerialization.jsonObject(with: body, options: JSONSerialization.ReadingOptions(rawValue: 0)) as AnyObject if let object = object as? [String:AnyObject] { return closure(object) } return nil } } public struct HTTPDeserialization { public typealias Deserializer = (_ response:HTTPURLResponse, _ body:Data) -> (Representor<HTTPTransition>?) /// A dictionary storing the registered HTTP deserializer's and their corresponding content type. public static var deserializers: [String: Deserializer] = [ "application/hal+json": jsonDeserializer { payload in return deserializeHAL(payload) }, "application/vnd.siren+json": jsonDeserializer { payload in return deserializeSiren(payload) }, ] /// An array of the supported content types in order of preference public static var preferredContentTypes:[String] = [ "application/vnd.siren+json", "application/hal+json", ] /** Deserialize an NSHTTPURLResponse and body into a Representor. Uses the deserializers defined in HTTPDeserializers. - parameter response: The response to deserialize - parameter body: The HTTP Body :return: representor */ public static func deserialize(_ response:HTTPURLResponse, body:Data) -> Representor<HTTPTransition>? { if let contentType = response.mimeType { if let deserializer = HTTPDeserialization.deserializers[contentType] { return deserializer(response, body) } } return nil } }
mit
a43363df2ac0dd433722d2aaf7cd26b7
31.706897
178
0.717449
4.484634
false
false
false
false
ifabijanovic/RxBattleNet
RxBattleNet/Network/Locale.swift
1
1568
// // Locale.swift // RxBattleNet // // Created by Ivan Fabijanović on 05/08/16. // Copyright © 2016 Ivan Fabijanovic. All rights reserved. // public extension WoW { public enum Locale: String { /** * Available in EU region. */ case enGB = "en_GB" /** * Available in EU region. */ case deDE = "de_DE" /** * Available in EU region. */ case esES = "es_ES" /** * Available in EU region. */ case frFR = "fr_FR" /** * Available in EU region. */ case itIT = "it_IT" /** * Available in EU region. */ case plPL = "pl_PL" /** * Available in EU region. */ case ptPT = "pt_PT" /** * Available in EU region. */ case ruRU = "ru_RU" /** * Available in KR region. */ case koKR = "ko_KR" /** * Available in TW region. */ case zhTW = "zh_TW" /** * Available in CN region. */ case zhCN = "zh_CN" /** * Available in US and SEA regions. */ case enUS = "en_US" /** * Available in US region. */ case ptBR = "pt_BR" /** * Available in US region. */ case esMX = "es_MX" } }
mit
fa4cf70e45f7570408a67aa3965346cb
17.86747
59
0.37037
4.33795
false
false
false
false
getsocial-im/getsocial-ios-sdk
example/GetSocialDemo/Views/Communities/Chats/ChatMessages/ChatMessagesModel.swift
1
4536
// // ChatModel.swift // GetSocialDemo // // Created by Gábor Vass on 16/11/2020. // Copyright © 2020 GrambleWorld. All rights reserved. // import Foundation class ChatMessagesModel { private var chat: Chat? private let chatId: ChatId private var pagingQuery: ChatMessagesPagingQuery? private var nextMessagesCursor: String? private var previousMessagesCursor: String? private var refreshCursor: String? private var messages: [ChatMessage] = [] private var otherUser: User? var onInitialDataLoaded: (() -> Void)? var onOlderMessages: ((Int) -> Void)? var onNewerMessages: ((Int) -> Void)? var onNothingToLoad: (() -> Void)? var onMessageSent: ((Int) -> Void)? var onError: ((String) -> Void)? init(_ chat: Chat) { self.chat = chat self.chatId = ChatId.create(chat.id) self.pagingQuery = ChatMessagesPagingQuery(ChatMessagesQuery.inChat(self.chatId)) self.pagingQuery?.limit = 10 } init(_ userId: UserId) { self.chatId = ChatId.create(userId) self.pagingQuery = ChatMessagesPagingQuery(ChatMessagesQuery.inChat(self.chatId)) Communities.user(userId, success: { user in self.otherUser = user Communities.chat(ChatId.create(userId), success: { chat in self.chat = chat }, failure: { error in print("Could not load chat, error: \(error)") }) }, failure: { error in self.onError?("Could not load user, error: \(error)") }) } func loadInitialChatMessages() { self.messages = [] self.loadMessages(success: { [weak self] messages in self?.messages = messages self?.onInitialDataLoaded?() }, failure: { [weak self] error in self?.onError?(error) }) } func loadNewer() { if let cursor = self.refreshCursor, !cursor.isEmpty { self.pagingQuery?.nextMessagesCursor = cursor self.loadMessages(success: { [weak self] messages in self?.messages.append(contentsOf: messages) self?.onNewerMessages?(messages.count) }, failure: { [weak self] errorMessage in self?.onError?(errorMessage) }) } else { print("nothing to load") DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: 10000000000), execute: { self.onNothingToLoad?() }) } } func loadOlder() { if let cursor = self.previousMessagesCursor, !cursor.isEmpty { self.pagingQuery?.previousMessagesCursor = cursor self.loadMessages(success: { [weak self] messages in self?.messages.insert(contentsOf: messages, at: 0) self?.onOlderMessages?(messages.count) }, failure: { [weak self] errorMessage in self?.onError?(errorMessage) }) } else { print("nothing to load") self.onNothingToLoad?() } } func chatTitle() -> String { if let chat = self.chat { return chat.title } if let user = self.otherUser { return user.displayName } return "Unknown" } func numberOfEntries() -> Int { return self.messages.count } func entry(at: Int) -> ChatMessage { return self.messages[at] } private func loadMessages(success: @escaping ([ChatMessage]) -> Void, failure: @escaping (String) -> Void) { Communities.chatMessages(self.pagingQuery!, success: { [weak self] result in self?.nextMessagesCursor = result.nextMessagesCursor self?.refreshCursor = result.refreshCursor self?.previousMessagesCursor = result.previousMessagesCursor success(result.messages) }, failure: { error in failure(error.localizedDescription) }) } func sendMessage(_ content: ChatMessageContent) { Communities.sendChatMessage(content, target: self.chatId, success: { [weak self] message in self?.messages.append(message) if let strongSelf = self { print("num of messages after post: \(strongSelf.messages.count)") strongSelf.onMessageSent?(strongSelf.messages.count) } }, failure: { [weak self] error in self?.onError?(error.localizedDescription) }) } }
apache-2.0
c75cc674ee418abce73742974e679f8f
32.835821
113
0.59131
4.589069
false
false
false
false
bbrks/osx-statusbar-countdown
StatusbarCountdown/AppDelegate.swift
1
4630
// // AppDelegate.swift // StatusbarCountdown // // Created by Ben Brooks on 31/03/2015. // Copyright (c) 2015 Ben Brooks. All rights reserved. // import Cocoa import Foundation protocol PreferencesWindowDelegate { func preferencesDidUpdate() } @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, PreferencesWindowDelegate { let DEFAULT_NAME = "Countdown Name" let DEFAULT_DATE = NSDate(timeIntervalSince1970: 1597249800) var countToDate = NSDate(timeIntervalSince1970: 1597249800) var countdownName = "Countdown Name" var showName = true var showSeconds = true var zeroPad = false var formatter = NumberFormatter() let statusItem = NSStatusBar.system.statusItem(withLength: -1) @IBOutlet weak var statusMenu: NSMenu! var preferencesWindow: PreferencesWindow! func applicationDidFinishLaunching(_ notification: Notification) { preferencesWindow = PreferencesWindow() preferencesWindow.delegate = self statusItem.title = "" statusItem.menu = statusMenu formatter.minimumIntegerDigits = zeroPad ? 2 : 1 Timer.scheduledTimer(timeInterval: 0.33, // 33ms ~ 30fps target: self, selector: #selector(tick), userInfo: nil, repeats: true) updatePreferences() } func preferencesDidUpdate() { // Delegate when setting values are updated updatePreferences() } func updatePreferences() { let defaults = UserDefaults.standard // Gets the saved values in user defaults countdownName = defaults.string(forKey: "name") ?? DEFAULT_NAME countToDate = defaults.value(forKey: "date") as? NSDate ?? DEFAULT_DATE } // Calculates the difference in time from now to the specified date and sets the statusItem title @objc func tick() { let diffSeconds = Int(countToDate.timeIntervalSinceNow) statusItem.title = (showName) ? countdownName + ": " : "" statusItem.title! += formatTime(diffSeconds) } // Convert seconds to 4 Time integers (days, hours minutes and seconds) func secondsToTime (_ seconds : Int) -> (Int, Int, Int, Int) { let days = seconds / (3600 * 24) var remainder = seconds % (3600 * 24) let hours = remainder / 3600 remainder = remainder % 3600 let minutes = remainder / 60 let seconds = remainder % 60 return (days, hours, minutes, seconds) } // Display seconds as Days, Hours, Minutes, Seconds. func formatTime(_ seconds: Int) -> (String) { let time = secondsToTime(abs(seconds)) let daysStr = (time.0 != 0) ? String(time.0) + "d " : "" let hoursStr = (time.1 != 0 || time.0 != 0) ? formatter.string(from: NSNumber(value: time.1))! + "h " : "" let minutesStr = (time.2 != 0 || time.1 != 0 || time.0 != 0) ? formatter.string(from: NSNumber(value: time.2))! + "m" : "" let secondsStr = (showSeconds) ? " " + formatter.string(from: NSNumber(value: time.3))! + "s" : "" let suffixStr = (seconds < 0) ? " ago" : "" // TODO: i18n? return daysStr + hoursStr + minutesStr + secondsStr + suffixStr } // MenuItem click event to toggle showSeconds @IBAction func toggleShowSeconds(sender: NSMenuItem) { if (showSeconds) { showSeconds = false sender.state = .off } else { showSeconds = true sender.state = .on } } // MenuItem click event to toggle showName @IBAction func toggleShowName(sender: NSMenuItem) { if (showName) { showName = false sender.state = .off } else { showName = true sender.state = .on } } // MenuItem click event to toggle zeroPad @IBAction func toggleZeroPad(sender: NSMenuItem) { if (zeroPad) { zeroPad = false sender.state = .off } else { zeroPad = true sender.state = .on } formatter.minimumIntegerDigits = zeroPad ? 2 : 1 } // MenuItem click event to open preferences popover @IBAction func configurePreferences(_ sender: Any) { preferencesWindow.showWindow(nil) } // MenuItem click event to quit application @IBAction func quitApplication(sender: NSMenuItem) { NSApplication.shared.terminate(self); } }
mit
ec90c6999ce7d8f15c759681a8d1b298
31.377622
130
0.595248
4.63
false
false
false
false
aatalyk/swift-algorithm-club
Select Minimum Maximum/Tests/MinimumTests.swift
10
1059
import XCTest class MinimumTests: XCTestCase { func testMinimumGivenAListContainingOneElement() { let array = [ 54 ] let result = minimum(array) XCTAssertEqual(result, 54) } func testMinimumGivenAListContainingMultipleElementsWithTheSameValue() { let array = [ 2, 16, 2, 16 ] let result = minimum(array) XCTAssertEqual(result, 2) } func testMinimumGivenAListOfOrderedElements() { let array = [ 3, 4, 6, 8, 9 ] let result = minimum(array) XCTAssertEqual(result, 3) } func testMinimumGivenAListOfReverseOrderedElements() { let array = [ 9, 8, 6, 4, 3 ] let result = minimum(array) XCTAssertEqual(result, 3) } func testMinimumGivenAnEmptyList() { let array = [Int]() let result = minimum(array) XCTAssertNil(result) } func testMinimumMatchesSwiftLibraryGivenARandomList() { for _ in 0...10 { for n in 1...100 { let array = createRandomList(n) let result = minimum(array) XCTAssertEqual(result, array.min()) } } } }
mit
db394330fa5bc3d20f3937e933a3d861
17.910714
74
0.645892
3.996226
false
true
false
false
SwiftOnTheServer/DrinkChooser
actions/_common.swift
1
1544
import Glibc import SwiftyJSON /// Add fromBase64() and toBase64() to the String type extension String { func fromBase64() -> String? { guard let data = Data(base64Encoded: self) else { return nil } return String(data: data, encoding: .utf8) } func toBase64() -> String { return Data(self.utf8).base64EncodedString() } } // Format the response correctly. // If it's a web action we can return the code and set headers. If it isn't, // then we can only return the data. // // We determine if it's a web action call by looking for the "__ow_method" // key in the input data func createResponse(_ body: [String: Any], code: Int = 200) -> [String:Any] { let env = ProcessInfo.processInfo.environment guard let whiskInput = env["WHISK_INPUT"] else { // No WHISK_INPUT, assume a normal action return body } if whiskInput.range(of:"__ow_method") != nil { // This is a web action as the arguments contain the "__ow_method" key let json = WhiskJsonUtils.dictionaryToJsonString(jsonDict: body) ?? "" return [ "body": json.toBase64(), "code": code, "headers": [ "Content-Type": "application/json", ], ] } // This is not a web action if code >= 400 && body["error"] == nil { // we need to set the "error" key in the array // so that OpenWhisk knows that something's gone wrong return ["error": code] } return body }
mit
ffa86f5ab17fa652886d44bdc9330952
27.592593
78
0.591969
3.89899
false
false
false
false
pjulien/flatbuffers
swift/Sources/FlatBuffers/Mutable.swift
1
2438
import Foundation /// Mutable is a protocol that allows us to mutate Scalar values within the buffer public protocol Mutable { /// makes Flatbuffer accessed within the Protocol var bb: ByteBuffer { get } /// makes position of the table/struct accessed within the Protocol var postion: Int32 { get } } extension Mutable { /// Mutates the memory in the buffer, this is only called from the access function of table and structs /// - Parameters: /// - value: New value to be inserted to the buffer /// - index: index of the Element func mutate<T: Scalar>(value: T, o: Int32) -> Bool { guard o != 0 else { return false } bb.write(value: value, index: Int(o), direct: true) return true } } extension Mutable where Self == Table { /// Mutates a value by calling mutate with respect to the position in the table /// - Parameters: /// - value: New value to be inserted to the buffer /// - index: index of the Element public func mutate<T: Scalar>(_ value: T, index: Int32) -> Bool { guard index != 0 else { return false } return mutate(value: value, o: index + postion) } /// Directly mutates the element by calling mutate /// /// Mutates the Element at index ignoring the current position by calling mutate /// - Parameters: /// - value: New value to be inserted to the buffer /// - index: index of the Element public func directMutate<T: Scalar>(_ value: T, index: Int32) -> Bool { return mutate(value: value, o: index) } } extension Mutable where Self == Struct { /// Mutates a value by calling mutate with respect to the position in the struct /// - Parameters: /// - value: New value to be inserted to the buffer /// - index: index of the Element public func mutate<T: Scalar>(_ value: T, index: Int32) -> Bool { return mutate(value: value, o: index + postion) } /// Directly mutates the element by calling mutate /// /// Mutates the Element at index ignoring the current position by calling mutate /// - Parameters: /// - value: New value to be inserted to the buffer /// - index: index of the Element public func directMutate<T: Scalar>(_ value: T, index: Int32) -> Bool { return mutate(value: value, o: index) } } extension Struct: Mutable {} extension Table: Mutable {}
apache-2.0
617424fbd0573b70e2483404a4e91ad0
34.852941
107
0.633716
4.232639
false
false
false
false
maicki/AsyncDisplayKit
examples/LayoutSpecExamples-Swift/Sample/AppDelegate.swift
12
1620
// // AppDelegate.swift // Sample // // Copyright (c) 2014-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // 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 // FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let window = UIWindow(frame: UIScreen.main.bounds) window.backgroundColor = UIColor.white window.rootViewController = UINavigationController(rootViewController: OverviewViewController()); window.makeKeyAndVisible() self.window = window UINavigationBar.appearance().barTintColor = UIColor(red: 47/255.0, green: 184/255.0, blue: 253/255.0, alpha: 1.0) UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white] return true } }
bsd-3-clause
538283b3f31f3d67bcaeb38bf63990e6
40.538462
142
0.75679
4.655172
false
false
false
false
rambler-digital-solutions/rambler-it-ios
Carthage/Checkouts/rides-ios-sdk/source/UberRidesTests/ConfigurationTests.swift
1
13097
// // ConfigurationTests.swift // UberRides // // Copyright © 2015 Uber Technologies, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest @testable import UberRides class ConfigurationTests: XCTestCase { private let defaultClientID = "testClientID" private let defaultDisplayName = "My Awesome App" private let defaultCallbackString = "testURI://uberConnect" private let defaultGeneralCallbackString = "testURI://uberConnectGeneral" private let defaultAuthorizationCodeCallbackString = "testURI://uberConnectAuthorizationCode" private let defaultImplicitCallbackString = "testURI://uberConnectImplicit" private let defaultNativeCallbackString = "testURI://uberConnectNative" private let defaultServerToken = "testServerToken" private let defaultAccessTokenIdentifier = "RidesAccessTokenKey" private let defaultSandbox = false override func setUp() { super.setUp() Configuration.bundle = Bundle(for: type(of: self)) Configuration.plistName = "testInfo" Configuration.restoreDefaults() } override func tearDown() { Configuration.restoreDefaults() super.tearDown() } //MARK: Reset Test func testConfiguration_restoreDefaults() { let newClientID = "newID" let newCallback = "newCallback://" let newDisplay = "newDisplay://" let newServerToken = "newserver" let newGroup = "new group" let newTokenId = "newTokenID" let newSandbox = true Configuration.shared.clientID = newClientID Configuration.shared.setCallbackURIString(newCallback) Configuration.shared.appDisplayName = newDisplay Configuration.shared.serverToken = newServerToken Configuration.shared.defaultKeychainAccessGroup = newGroup Configuration.shared.defaultAccessTokenIdentifier = newTokenId Configuration.shared.isSandbox = newSandbox XCTAssertEqual(newClientID, Configuration.shared.clientID) XCTAssertEqual(newCallback, Configuration.shared.getCallbackURIString()) XCTAssertEqual(newDisplay, Configuration.shared.appDisplayName) XCTAssertEqual(newServerToken, Configuration.shared.serverToken) XCTAssertEqual(newGroup, Configuration.shared.defaultKeychainAccessGroup) XCTAssertEqual(newTokenId, Configuration.shared.defaultAccessTokenIdentifier) XCTAssertEqual(newSandbox, Configuration.shared.isSandbox) Configuration.restoreDefaults() Configuration.plistName = "testInfo" Configuration.bundle = Bundle(for: type(of: self)) XCTAssertEqual(Configuration.shared.clientID, defaultClientID) XCTAssertEqual(defaultGeneralCallbackString, Configuration.shared.getCallbackURIString()) XCTAssertEqual(defaultDisplayName, Configuration.shared.appDisplayName) XCTAssertEqual(defaultServerToken, Configuration.shared.serverToken) XCTAssertEqual("", Configuration.shared.defaultKeychainAccessGroup) XCTAssertEqual(defaultAccessTokenIdentifier, Configuration.shared.defaultAccessTokenIdentifier) XCTAssertEqual(defaultSandbox, Configuration.shared.isSandbox) } //MARK: Client ID Tests func testClientID_getDefault() { XCTAssertEqual(defaultClientID, Configuration.shared.clientID) } func testClientID_overwriteDefault() { let clientID = "clientID" Configuration.shared.clientID = clientID XCTAssertEqual(clientID, Configuration.shared.clientID) } //MARK: Callback URI String Tests func testCallbackURIString_getDefault() { XCTAssertEqual(defaultGeneralCallbackString, Configuration.shared.getCallbackURIString()) } func testCallbackURIString_overwriteDefault() { let callbackURIString = "callback://test" Configuration.shared.setCallbackURIString(callbackURIString) XCTAssertEqual(callbackURIString, Configuration.shared.getCallbackURIString()) } func testCallbackURIString_getDefault_getTypes() { XCTAssertEqual(defaultGeneralCallbackString, Configuration.shared.getCallbackURIString(for: .general)) XCTAssertEqual(defaultAuthorizationCodeCallbackString, Configuration.shared.getCallbackURIString(for: .authorizationCode)) XCTAssertEqual(defaultImplicitCallbackString, Configuration.shared.getCallbackURIString(for: .implicit)) XCTAssertEqual(defaultNativeCallbackString, Configuration.shared.getCallbackURIString(for: .native)) } func testCallbackURIString_overwriteDefault_allTypes() { let generalCallbackString = "testURI://uberConnectGeneralNew" let authorizationCodeCallbackString = "testURI://uberConnectAuthorizationCodeNew" let implicitCallbackString = "testURI://uberConnectImplicitNew" let nativeCallbackString = "testURI://uberConnectNativeNew" Configuration.shared.setCallbackURIString(generalCallbackString, type: .general) Configuration.shared.setCallbackURIString(authorizationCodeCallbackString, type: .authorizationCode) Configuration.shared.setCallbackURIString(implicitCallbackString, type: .implicit) Configuration.shared.setCallbackURIString(nativeCallbackString, type: .native) XCTAssertEqual(generalCallbackString, Configuration.shared.getCallbackURIString(for: .general)) XCTAssertEqual(authorizationCodeCallbackString, Configuration.shared.getCallbackURIString(for: .authorizationCode)) XCTAssertEqual(implicitCallbackString, Configuration.shared.getCallbackURIString(for: .implicit)) XCTAssertEqual(nativeCallbackString, Configuration.shared.getCallbackURIString(for: .native)) } func testCallbackURIString_resetDefault_allTypes() { let generalCallbackString = "testURI://uberConnectGeneralNew" let authorizationCodeCallbackString = "testURI://uberConnectAuthorizationCodeNew" let implicitCallbackString = "testURI://uberConnectImplicitNew" let nativeCallbackString = "testURI://uberConnectNativeNew" Configuration.shared.setCallbackURIString(generalCallbackString, type: .general) Configuration.shared.setCallbackURIString(authorizationCodeCallbackString, type: .authorizationCode) Configuration.shared.setCallbackURIString(implicitCallbackString, type: .implicit) Configuration.shared.setCallbackURIString(nativeCallbackString, type: .native) Configuration.shared.setCallbackURIString(nil, type: .general) Configuration.shared.setCallbackURIString(nil, type: .authorizationCode) Configuration.shared.setCallbackURIString(nil, type: .implicit) Configuration.shared.setCallbackURIString(nil, type: .native) XCTAssertEqual(defaultGeneralCallbackString, Configuration.shared.getCallbackURIString(for: .general)) XCTAssertEqual(defaultAuthorizationCodeCallbackString, Configuration.shared.getCallbackURIString(for: .authorizationCode)) XCTAssertEqual(defaultImplicitCallbackString, Configuration.shared.getCallbackURIString(for: .implicit)) XCTAssertEqual(defaultNativeCallbackString, Configuration.shared.getCallbackURIString(for: .native)) } func testCallbackURIString_resetDefault_oneType() { let generalCallbackString = "testURI://uberConnectGeneralNew" let authorizationCodeCallbackString = "testURI://uberConnectAuthorizationCodeNew" let implicitCallbackString = "testURI://uberConnectImplicitNew" let nativeCallbackString = "testURI://uberConnectNativeNew" Configuration.shared.setCallbackURIString(generalCallbackString, type: .general) Configuration.shared.setCallbackURIString(authorizationCodeCallbackString, type: .authorizationCode) Configuration.shared.setCallbackURIString(implicitCallbackString, type: .implicit) Configuration.shared.setCallbackURIString(nativeCallbackString, type: .native) Configuration.shared.setCallbackURIString(nil, type: .native) XCTAssertEqual(generalCallbackString, Configuration.shared.getCallbackURIString(for: .general)) XCTAssertEqual(authorizationCodeCallbackString, Configuration.shared.getCallbackURIString(for: .authorizationCode)) XCTAssertEqual(implicitCallbackString, Configuration.shared.getCallbackURIString(for: .implicit)) XCTAssertEqual(defaultNativeCallbackString, Configuration.shared.getCallbackURIString(for: .native)) } func testCallbackURIStringFallback_whenCallbackURIsMissing() { Configuration.plistName = "testInfoMissingCallbacks" XCTAssertEqual(defaultCallbackString, Configuration.shared.getCallbackURIString(for: .general)) XCTAssertEqual(defaultCallbackString, Configuration.shared.getCallbackURIString(for: .authorizationCode)) XCTAssertEqual(defaultCallbackString, Configuration.shared.getCallbackURIString(for: .implicit)) XCTAssertEqual(defaultCallbackString, Configuration.shared.getCallbackURIString(for: .native)) } func testCallbackURIStringFallbackUsesGeneralOverride_whenCallbackURIsMissing() { Configuration.plistName = "testInfoMissingCallbacks" let override = "testURI://override" Configuration.shared.setCallbackURIString(override, type: .general) XCTAssertEqual(override, Configuration.shared.getCallbackURIString(for: .general)) XCTAssertEqual(override, Configuration.shared.getCallbackURIString(for: .authorizationCode)) XCTAssertEqual(override, Configuration.shared.getCallbackURIString(for: .implicit)) XCTAssertEqual(override, Configuration.shared.getCallbackURIString(for: .native)) } //MARK: App Display Name Tests func testAppDisplayName_getDefault() { XCTAssertEqual(defaultDisplayName, Configuration.shared.appDisplayName) } func testAppDisplayName_overwriteDefault() { let appDisplayName = "Test App" Configuration.shared.appDisplayName = appDisplayName XCTAssertEqual(appDisplayName, Configuration.shared.appDisplayName) } //MARK: Server Token Tests func testServerToken_getDefault() { XCTAssertEqual(defaultServerToken, Configuration.shared.serverToken) } func testServerToken_overwriteDefault() { let serverToken = "nonDefaultToken" Configuration.shared.serverToken = serverToken XCTAssertEqual(serverToken, Configuration.shared.serverToken) } //MARK: Keychain Access Group Tests func testDefaultKeychainAccessGroup_getDefault() { XCTAssertEqual("", Configuration.shared.defaultKeychainAccessGroup) } func testDefaultKeychainAccessGroup_overwriteDefault() { let defaultKeychainAccessGroup = "accessGroup" Configuration.shared.defaultKeychainAccessGroup = defaultKeychainAccessGroup XCTAssertEqual(defaultKeychainAccessGroup, Configuration.shared.defaultKeychainAccessGroup) } //MARK: Access token identifier tests func testDefaultAccessTokenIdentifier_getDefault() { XCTAssertEqual(defaultAccessTokenIdentifier, Configuration.shared.defaultAccessTokenIdentifier) } func testDefaultAccessTokenIdentifier_overwriteDefault() { let newIdentifier = "newIdentifier" Configuration.shared.defaultAccessTokenIdentifier = newIdentifier XCTAssertEqual(newIdentifier, Configuration.shared.defaultAccessTokenIdentifier) } //MARK: Sandbox Tests func testSandbox_getDefault() { XCTAssertEqual(defaultSandbox, Configuration.shared.isSandbox) } func testSandbox_overwriteDefault() { let newSandbox = true Configuration.shared.isSandbox = newSandbox XCTAssertEqual(newSandbox, Configuration.shared.isSandbox) } }
mit
dd9fbfdceb025ee5751b1bac5593330b
48.233083
130
0.748931
5.345306
false
true
false
false
SwifterLC/SinaWeibo
LCSinaWeibo/LCSinaWeibo/Classes/View/Main/MainViewController.swift
1
2445
// // MainViewController.swift // LCSinaWeibo // // Created by 刘成 on 2017/8/2. // Copyright © 2017年 刘成. All rights reserved. // import UIKit class MainViewController: UITabBarController { /// 编辑按钮点击事件 @objc fileprivate func composedBtClick(){ print("点击了编辑按钮") } //视图加载方法 override func viewDidLoad() { super.viewDidLoad() addChildViewControllers() setUpComposeButton() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //将编辑按钮至顶 tabBar.bringSubview(toFront: composedButton) } // MARK:- 懒加载 composedButton fileprivate lazy var composedButton :UIButton = UIButton( imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button") } //设置界面 extension MainViewController{ /// 添加并设置 composedButton fileprivate func setUpComposeButton(){ //添加按钮 tabBar.addSubview(composedButton) //为按钮添加点击事件 composedButton.addTarget(self, action: #selector(MainViewController.composedBtClick), for: .touchUpInside) //设置按钮布局 let count = childViewControllers.count let width = tabBar.bounds.width/CGFloat(count) - 1 composedButton.frame = tabBar.bounds.insetBy(dx: width * 2, dy: 0) } /// 添加所有的控制器 fileprivate func addChildViewControllers() { addChildViewController(vc: HomeViewController(), title: "首页", imageName: "tabbar_home") addChildViewController(vc: MessageViewController(), title: "消息", imageName: "tabbar_message_center") addChildViewController(UIViewController()) addChildViewController(vc: DiscoverViewController(), title: "发现", imageName: "tabbar_discover") addChildViewController(vc: ProfileViewController(), title: "我", imageName: "tabbar_profile") } private func addChildViewController(vc:UIViewController,title:String,imageName:String) { vc.title = title vc.tabBarItem.image = UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal) vc.tabBarItem.selectedImage = UIImage(named: "\(imageName)_highlighted")?.withRenderingMode(.alwaysOriginal) let nav = UINavigationController(rootViewController: vc) addChildViewController(nav) } }
mit
f60de085f8d23d6bdc13a3d7935d6271
34.71875
116
0.682852
4.792453
false
false
false
false
niekang/WeiBo
WeiBo/Class/Utils/NKRefresh/NKRefreshControl.swift
1
5297
// // NKRefreshControl.swift // NKRefresh // // Created by 聂康 on 2017/6/25. // Copyright © 2017年 聂康. All rights reserved. // import UIKit private let NKRefreshOffSet:CGFloat = 120 class NKRefreshControl: UIControl { private weak var scrollView:UIScrollView? lazy var refreshView:NKRefreshView = NKRefreshView.refreshView() init() { super.init(frame: CGRect()) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// 重载方法 KVO 监控contentOffset override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) guard let scr = newSuperview as? UIScrollView else { return } scrollView = scr scr.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil) } /// 移除KVO override func removeFromSuperview() { superview?.removeObserver(self, forKeyPath: "contentOffset") super.removeFromSuperview() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let scr = scrollView else { return } //计算NKRefreshControl高度 let height = -(scr.contentInset.top + scr.contentOffset.y) if height < 0 { return } self.frame = CGRect(x: 0, y: -height, width: scr.bounds.width, height: height) if refreshView.state != .refreshing { refreshView.parentViewHeight = height } if scr.isDragging { if height < NKRefreshOffSet && refreshView.state == .idle{ refreshView.state = .pulling }else if height < NKRefreshOffSet && refreshView.state == .willRefresh { refreshView.state = .pulling }else if height >= NKRefreshOffSet && refreshView.state == .pulling{ refreshView.state = .willRefresh } }else { if refreshView.state == .willRefresh { beginRefresh() sendActions(for: .valueChanged) } } } /// 刷新方法 func beginRefresh() { guard let scr = scrollView else{ return } //防止多次刷新 if refreshView.state == .refreshing { return } refreshView.parentViewHeight = NKRefreshOffSet refreshView.state = .refreshing var inset = scr.contentInset inset.top += NKRefreshOffSet scr.contentInset = inset } ///结束刷新 func endRefresh() { guard let scr = scrollView else{ return } //防止多次刷新 if refreshView.state != .refreshing { return } refreshView.state = .idle var inset = scr.contentInset inset.top -= NKRefreshOffSet scr.contentInset = inset } } extension NKRefreshControl { func setupUI() { // clipsToBounds = true refreshView.backgroundColor = superview?.backgroundColor addSubview(refreshView) refreshView.translatesAutoresizingMaskIntoConstraints = false //给刷新视图添加约束 addConstraint(NSLayoutConstraint(item: refreshView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: refreshView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: refreshView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.width)) addConstraint(NSLayoutConstraint(item: refreshView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.height)) } }
apache-2.0
c636ac5ccd686cd218e06141e88ece54
29.255814
151
0.473866
6.065268
false
false
false
false
e78l/swift-corelibs-foundation
Foundation/NSRegularExpression.swift
1
21644
// 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 // /* NSRegularExpression is a class used to represent and apply regular expressions. An instance of this class is an immutable representation of a compiled regular expression pattern and various option flags. */ import CoreFoundation extension NSRegularExpression { public struct Options : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let caseInsensitive = Options(rawValue: 1 << 0) /* Match letters in the pattern independent of case. */ public static let allowCommentsAndWhitespace = Options(rawValue: 1 << 1) /* Ignore whitespace and #-prefixed comments in the pattern. */ public static let ignoreMetacharacters = Options(rawValue: 1 << 2) /* Treat the entire pattern as a literal string. */ public static let dotMatchesLineSeparators = Options(rawValue: 1 << 3) /* Allow . to match any character, including line separators. */ public static let anchorsMatchLines = Options(rawValue: 1 << 4) /* Allow ^ and $ to match the start and end of lines. */ public static let useUnixLineSeparators = Options(rawValue: 1 << 5) /* Treat only \n as a line separator (otherwise, all standard line separators are used). */ public static let useUnicodeWordBoundaries = Options(rawValue: 1 << 6) /* Use Unicode TR#29 to specify word boundaries (otherwise, traditional regular expression word boundaries are used). */ } } open class NSRegularExpression: NSObject, NSCopying, NSSecureCoding { internal var _internal: _CFRegularExpression open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } aCoder.encode(self.pattern._nsObject, forKey: "NSPattern") aCoder.encode(Int64(self.options.rawValue), forKey: "NSOptions") } public required convenience init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } guard let pattern = aDecoder.decodeObject(of: NSString.self, forKey: "NSPattern") else { return nil } let options = aDecoder.decodeInt64(forKey: "NSOptions") do { try self.init(pattern: pattern._swiftObject, options: Options(rawValue: UInt(options))) } catch { return nil } } open class var supportsSecureCoding: Bool { return true } open override func isEqual(_ object: Any?) -> Bool { guard let other = object as? NSRegularExpression else { return false } return self === other || (self.pattern == other.pattern && self.options == other.options) } /* An instance of NSRegularExpression is created from a regular expression pattern and a set of options. If the pattern is invalid, nil will be returned and an NSError will be returned by reference. The pattern syntax currently supported is that specified by ICU. */ public init(pattern: String, options: Options = []) throws { var error: Unmanaged<CFError>? #if os(macOS) || os(iOS) let opt = _CFRegularExpressionOptions(rawValue: options.rawValue) #else let opt = _CFRegularExpressionOptions(options.rawValue) #endif if let regex = _CFRegularExpressionCreate(kCFAllocatorSystemDefault, pattern._cfObject, opt, &error) { _internal = regex } else { throw error!.takeRetainedValue() } } open var pattern: String { return _CFRegularExpressionGetPattern(_internal)._swiftObject } open var options: Options { #if os(macOS) || os(iOS) let opt = _CFRegularExpressionGetOptions(_internal).rawValue #else let opt = _CFRegularExpressionGetOptions(_internal) #endif return Options(rawValue: opt) } open var numberOfCaptureGroups: Int { return _CFRegularExpressionGetNumberOfCaptureGroups(_internal) } internal func _captureGroupNumber(withName name: String) -> Int { return _CFRegularExpressionGetCaptureGroupNumberWithName(_internal, name._cfObject) } /* This class method will produce a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as pattern metacharacters. */ open class func escapedPattern(for string: String) -> String { return _CFRegularExpressionCreateEscapedPattern(string._cfObject)._swiftObject } } extension NSRegularExpression { public struct MatchingOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let reportProgress = MatchingOptions(rawValue: 1 << 0) /* Call the block periodically during long-running match operations. */ public static let reportCompletion = MatchingOptions(rawValue: 1 << 1) /* Call the block once after the completion of any matching. */ public static let anchored = MatchingOptions(rawValue: 1 << 2) /* Limit matches to those at the start of the search range. */ public static let withTransparentBounds = MatchingOptions(rawValue: 1 << 3) /* Allow matching to look beyond the bounds of the search range. */ public static let withoutAnchoringBounds = MatchingOptions(rawValue: 1 << 4) /* Prevent ^ and $ from automatically matching the beginning and end of the search range. */ internal static let OmitResult = MatchingOptions(rawValue: 1 << 13) } public struct MatchingFlags : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let progress = MatchingFlags(rawValue: 1 << 0) /* Set when the block is called to report progress during a long-running match operation. */ public static let completed = MatchingFlags(rawValue: 1 << 1) /* Set when the block is called after completion of any matching. */ public static let hitEnd = MatchingFlags(rawValue: 1 << 2) /* Set when the current match operation reached the end of the search range. */ public static let requiredEnd = MatchingFlags(rawValue: 1 << 3) /* Set when the current match depended on the location of the end of the search range. */ public static let internalError = MatchingFlags(rawValue: 1 << 4) /* Set when matching failed due to an internal error. */ } } internal class _NSRegularExpressionMatcher { var regex: NSRegularExpression var block: (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void init(regex: NSRegularExpression, block: @escaping (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Void) { self.regex = regex self.block = block } } internal func _NSRegularExpressionMatch(_ context: UnsafeMutableRawPointer?, ranges: UnsafeMutablePointer<CFRange>?, count: CFIndex, flags: _CFRegularExpressionMatchingFlags, stop: UnsafeMutablePointer<_DarwinCompatibleBoolean>) -> Void { let matcher = unsafeBitCast(context, to: _NSRegularExpressionMatcher.self) #if os(macOS) || os(iOS) let flags = NSRegularExpression.MatchingFlags(rawValue: flags.rawValue) #else let flags = NSRegularExpression.MatchingFlags(rawValue: flags) #endif let result = ranges?.withMemoryRebound(to: NSRange.self, capacity: count) { rangePtr in NSTextCheckingResult.regularExpressionCheckingResult(ranges: rangePtr, count: count, regularExpression: matcher.regex) } stop.withMemoryRebound(to: ObjCBool.self, capacity: 1, { matcher.block(result, flags, $0) }) } extension NSRegularExpression { /* The fundamental matching method on NSRegularExpression is a block iterator. There are several additional convenience methods, for returning all matches at once, the number of matches, the first match, or the range of the first match. Each match is specified by an instance of NSTextCheckingResult (of type NSTextCheckingTypeRegularExpression) in which the overall match range is given by the range property (equivalent to range at:0) and any capture group ranges are given by range at: for indexes from 1 to numberOfCaptureGroups. {NSNotFound, 0} is used if a particular capture group does not participate in the match. */ public func enumerateMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange, using block: @escaping (NSTextCheckingResult?, NSRegularExpression.MatchingFlags, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { let matcher = _NSRegularExpressionMatcher(regex: self, block: block) withExtendedLifetime(matcher) { (m: _NSRegularExpressionMatcher) -> Void in #if os(macOS) || os(iOS) let opts = _CFRegularExpressionMatchingOptions(rawValue: options.rawValue) #else let opts = _CFRegularExpressionMatchingOptions(options.rawValue) #endif _CFRegularExpressionEnumerateMatchesInString(_internal, string._cfObject, opts, CFRange(range), unsafeBitCast(matcher, to: UnsafeMutableRawPointer.self), _NSRegularExpressionMatch) } } public func matches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> [NSTextCheckingResult] { var matches = [NSTextCheckingResult]() enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in if let match = result { matches.append(match) } } return matches } public func numberOfMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> Int { var count = 0 enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion).union(.OmitResult), range: range) {_,_,_ in count += 1 } return count } public func firstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> NSTextCheckingResult? { var first: NSTextCheckingResult? enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in first = result stop.pointee = true } return first } public func rangeOfFirstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> NSRange { var firstRange = NSRange(location: NSNotFound, length: 0) enumerateMatches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) { (result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) in if let match = result { firstRange = match.range } else { firstRange = NSRange(location: 0, length: 0) } stop.pointee = true } return firstRange } } /* By default, the block iterator method calls the block precisely once for each match, with a non-nil result and appropriate flags. The client may then stop the operation by setting the contents of stop to YES. If the NSMatchingReportProgress option is specified, the block will also be called periodically during long-running match operations, with nil result and NSMatchingProgress set in the flags, at which point the client may again stop the operation by setting the contents of stop to YES. If the NSMatchingReportCompletion option is specified, the block will be called once after matching is complete, with nil result and NSMatchingCompleted set in the flags, plus any additional relevant flags from among NSMatchingHitEnd, NSMatchingRequiredEnd, or NSMatchingInternalError. NSMatchingReportProgress and NSMatchingReportCompletion have no effect for methods other than the block iterator. NSMatchingHitEnd is set in the flags passed to the block if the current match operation reached the end of the search range. NSMatchingRequiredEnd is set in the flags passed to the block if the current match depended on the location of the end of the search range. NSMatchingInternalError is set in the flags passed to the block if matching failed due to an internal error (such as an expression requiring exponential memory allocations) without examining the entire search range. NSMatchingAnchored, NSMatchingWithTransparentBounds, and NSMatchingWithoutAnchoringBounds can apply to any match or replace method. If NSMatchingAnchored is specified, matches are limited to those at the start of the search range. If NSMatchingWithTransparentBounds is specified, matching may examine parts of the string beyond the bounds of the search range, for purposes such as word boundary detection, lookahead, etc. If NSMatchingWithoutAnchoringBounds is specified, ^ and $ will not automatically match the beginning and end of the search range (but will still match the beginning and end of the entire string). NSMatchingWithTransparentBounds and NSMatchingWithoutAnchoringBounds have no effect if the search range covers the entire string. NSRegularExpression is designed to be immutable and threadsafe, so that a single instance can be used in matching operations on multiple threads at once. However, the string on which it is operating should not be mutated during the course of a matching operation (whether from another thread or from within the block used in the iteration). */ extension NSRegularExpression { /* NSRegularExpression also provides find-and-replace methods for both immutable and mutable strings. The replacement is treated as a template, with $0 being replaced by the contents of the matched range, $1 by the contents of the first capture group, and so on. Additional digits beyond the maximum required to represent the number of capture groups will be treated as ordinary characters, as will a $ not followed by digits. Backslash will escape both $ and itself. */ public func stringByReplacingMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange, withTemplate templ: String) -> String { var str: String = "" let length = string.length var previousRange = NSRange(location: 0, length: 0) let results = matches(in: string, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) let start = string.utf16.startIndex for result in results { let currentRange = result.range let replacement = replacementString(for: result, in: string, offset: 0, template: templ) if currentRange.location > NSMaxRange(previousRange) { let min = string.utf16.index(start, offsetBy: NSMaxRange(previousRange)) let max = string.utf16.index(start, offsetBy: currentRange.location) str += String(string.utf16[min..<max])! } str += replacement previousRange = currentRange } if length > NSMaxRange(previousRange) { let min = string.utf16.index(start, offsetBy: NSMaxRange(previousRange)) let max = string.utf16.index(start, offsetBy: length) str += String(string.utf16[min..<max])! } return str } public func replaceMatches(in string: NSMutableString, options: NSRegularExpression.MatchingOptions = [], range: NSRange, withTemplate templ: String) -> Int { let results = matches(in: string._swiftObject, options: options.subtracting(.reportProgress).subtracting(.reportCompletion), range: range) var count = 0 var offset = 0 for result in results { var currentRange = result.range let replacement = replacementString(for: result, in: string._swiftObject, offset: offset, template: templ) currentRange.location += offset string.replaceCharacters(in: currentRange, with: replacement) offset += replacement.length - currentRange.length count += 1 } return count } /* For clients implementing their own replace functionality, this is a method to perform the template substitution for a single result, given the string from which the result was matched, an offset to be added to the location of the result in the string (for example, in case modifications to the string moved the result since it was matched), and a replacement template. */ public func replacementString(for result: NSTextCheckingResult, in string: String, offset: Int, template templ: String) -> String { // ??? need to consider what happens if offset takes range out of bounds due to replacement struct once { static let characterSet = CharacterSet(charactersIn: "\\$") } let template = templ._nsObject var range = template.rangeOfCharacter(from: once.characterSet) if range.length > 0 { var numberOfDigits = 1 var orderOfMagnitude = 10 let numberOfRanges = result.numberOfRanges let str = templ._nsObject.mutableCopy(with: nil) as! NSMutableString var length = str.length while (orderOfMagnitude < numberOfRanges && numberOfDigits < 20) { numberOfDigits += 1 orderOfMagnitude *= 10 } while range.length > 0 { var c = str.character(at: range.location) if c == unichar(unicodeScalarLiteral: "\\") { str.deleteCharacters(in: range) length -= range.length range.length = 1 } else if c == unichar(unicodeScalarLiteral: "$") { var groupNumber: Int = NSNotFound var idx = NSMaxRange(range) while idx < length && idx < NSMaxRange(range) + numberOfDigits { c = str.character(at: idx) if c < unichar(unicodeScalarLiteral: "0") || c > unichar(unicodeScalarLiteral: "9") { break } if groupNumber == NSNotFound { groupNumber = 0 } groupNumber *= 10 groupNumber += Int(c) - Int(unichar(unicodeScalarLiteral: "0")) idx += 1 } if groupNumber != NSNotFound { let rangeToReplace = NSRange(location: range.location, length: idx - range.location) var substringRange = NSRange(location: NSNotFound, length: 0) var substring = "" if groupNumber < numberOfRanges { substringRange = result.range(at: groupNumber) } if substringRange.location != NSNotFound { substringRange.location += offset } if substringRange.location != NSNotFound && substringRange.length > 0 { let start = string.utf16.startIndex let min = string.utf16.index(start, offsetBy: substringRange.location) let max = string.utf16.index(start, offsetBy: substringRange.location + substringRange.length) substring = String(string.utf16[min..<max])! } str.replaceCharacters(in: rangeToReplace, with: substring) length += substringRange.length - rangeToReplace.length range.length = substringRange.length } } if NSMaxRange(range) > length { break } range = str.rangeOfCharacter(from: once.characterSet, options: [], range: NSRange(location: NSMaxRange(range), length: length - NSMaxRange(range))) } return str._swiftObject } return templ } /* This class method will produce a string by adding backslash escapes as necessary to the given string, to escape any characters that would otherwise be treated as template metacharacters. */ open class func escapedTemplate(for string: String) -> String { return _CFRegularExpressionCreateEscapedPattern(string._cfObject)._swiftObject } }
apache-2.0
0f96e616727d0508c57c598e1f183cc1
57.655827
901
0.673351
5.345517
false
false
false
false
nebojsamihajlovic/SecondAssignment
GuessGame/GameViewController.swift
1
9993
// // GameViewController.swift // GuessGame // // Created by Nebojsa Mihajlovic on 2/16/17. // Copyright © 2017 course. All rights reserved. // import UIKit class GameViewController: UIViewController { // always has a value (at least default) var randomAnimal: Animals! var game = Game() @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var animalView: UIImageView! @IBOutlet weak var buttonNewGame: UIButton! @IBOutlet weak var viewProposedLetters: UIView! @IBOutlet weak var viewPlayerLetters: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. disableAllProposedLettersButtons() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onProposedLetterButtonsClicked(_ sender: UIButton) { print("Clicked on proposed letter button") let alertsInseadOfViewsOnEndGame = true if let text = sender.titleLabel?.text { print("Letter chosen: \(text)") let result = game.tryLetter(inAnimal: text) if result == -1 { print("Letter not found") // check if game is completed - fail if game.gameOver == true { print("Game Over - FAILED") showEndGameView(success: false, alerts: alertsInseadOfViewsOnEndGame) } } else { print("Letter found!") let letterButton = viewPlayerLetters.subviews[result] (letterButton as! UIButton).backgroundColor = .yellow (letterButton as! UIButton).setTitle(text, for: .normal) // check if game is completed - success if game.gameOver == true { print("Game Over - SUCESS") showEndGameView(success: true, alerts: alertsInseadOfViewsOnEndGame) } } } sender.isEnabled = false sender.backgroundColor = UIColor.gray } func showEndGameView(success: Bool, alerts: Bool) { // first disable all buttons disableAllProposedLettersButtons() if alerts == false { createEndView(success: success) } else { createLevelClearAlert(success: success) } } func createLevelClearAlert(success: Bool) { if success == true { let alert = UIAlertController(title: "Level Clear", message: "Do you want to replay level or to start new game?", preferredStyle: .alert) for i in ["Replay level", "Start new game"] { alert.addAction(UIAlertAction(title: i, style: .default, handler: replayOrStartNewLevel)) } self.present(alert, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Game Over", message: "Do you want start level from beggining?", preferredStyle: .alert) for i in ["Yes", "No"] { alert.addAction(UIAlertAction(title: i, style: .default, handler: startLevelFromBeginnig)) } self.present(alert, animated: true, completion: nil) } } func replayOrStartNewLevel(action: UIAlertAction) { let userAction = action.title ?? "Start new game" if userAction == "Replay level" { print("Replay level ...") restartLevel() } else { print("Starting new game ...") startNewGame() } } func startLevelFromBeginnig(action: UIAlertAction) { let userAction = action.title ?? "No" if userAction == "Yes" { print("Replay level ...") restartLevel() } else { print("Starting new game ...") startNewGame() } } func restartLevel() { clearPlayerLetterViewButtons() game.initialize(animal: randomAnimal.animal.rawValue) // begin new game for btn in viewProposedLetters.subviews { (btn as! UIButton).isEnabled = true (btn as! UIButton).backgroundColor = UIColor.blue } } func createEndView(success: Bool) { let viewEndGame = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 60)) viewEndGame.textAlignment = .center viewEndGame.font = UIFont.boldSystemFont(ofSize: 36.0) viewEndGame.translatesAutoresizingMaskIntoConstraints = false viewEndGame.tag = 999 // set tag value so we can remove it from superview if success == true { viewEndGame.backgroundColor = .green viewEndGame.text = "CORRECT!" } else { viewEndGame.backgroundColor = .red viewEndGame.text = "GAME OVER!" } self.animalView.addSubview(viewEndGame) let centerX = NSLayoutConstraint( item: viewEndGame, attribute: .centerX, relatedBy: .equal, toItem: animalView, attribute: .centerX, multiplier: 1, constant: 0) let centerY = NSLayoutConstraint( item: viewEndGame, attribute: .centerY, relatedBy: .equal, toItem: animalView, attribute: .centerY, multiplier: 1, constant: 0) let leading = NSLayoutConstraint( item: viewEndGame, attribute: .leading, relatedBy: .equal, toItem: animalView, attribute: .leading, multiplier: 1, constant: 16) let trailing = NSLayoutConstraint( item: viewEndGame, attribute: .trailing, relatedBy: .equal, toItem: animalView, attribute: .trailing, multiplier: 1, constant: -16) animalView.addConstraints([centerX, centerY, leading, trailing]) buttonNewGame.setTitle("NEW GAME", for: .normal) } func getRandomAnimalAndSetupImageView() { randomAnimal = Animals.random() imageView.image = randomAnimal.animalImage let randomizedAnimal = String.randomizeAnimalString(randomizeString: randomAnimal.animal.rawValue) print("Randomized animal string: \(randomizedAnimal)") // convert to array let characters = randomizedAnimal.characters.shuffled() print("Shuffled randomized animal string: \(characters)") // set randomized string characters as button labels var counter = 0 for btn in viewProposedLetters.subviews { (btn as! UIButton).setTitle(String(characters[counter]), for: .normal) counter += 1 } // initialize game game.initialize(animal: randomAnimal.animal.rawValue) } func clearPlayerLetterViewButtons() { let length = randomAnimal.animal.rawValue.characters.count var counter = 0 for btn in viewPlayerLetters.subviews { (btn as! UIButton).isEnabled = false (btn as! UIButton).setTitle(" ", for: .normal) counter += 1 if counter > length { (btn as! UIButton).backgroundColor = .lightGray } else { (btn as! UIButton).backgroundColor = .black } } } func restartLevel(action: UIAlertAction) { let userAction = action.title ?? "No" if userAction == "Yes" { print("Restarting level ...") restartLevel() } } @IBAction func btnNewGameClicked(_ sender: UIButton) { if sender.title(for: .normal) == "RESTART LEVEL" { let alert = UIAlertController(title: "Restart Level", message: "Do you really want to restart level?", preferredStyle: .alert) for i in ["Yes", "No"] { alert.addAction(UIAlertAction(title: i, style: .default, handler: restartLevel)) } self.present(alert, animated: true, completion: nil) return } startNewGame() } func startNewGame() { // begin new game for btn in viewProposedLetters.subviews { (btn as! UIButton).isEnabled = true (btn as! UIButton).setTitle(" ", for: .normal) (btn as! UIButton).backgroundColor = UIColor.blue } getRandomAnimalAndSetupImageView() clearPlayerLetterViewButtons() removeEndGameMessageFromSuperView() buttonNewGame.setTitle("RESTART LEVEL", for: .normal) } func removeEndGameMessageFromSuperView() { let subViews = self.animalView.subviews for subview in subViews { if subview.tag == 999 { subview.removeFromSuperview() } } } func disableAllProposedLettersButtons() { for btn in viewProposedLetters.subviews { (btn as! UIButton).isEnabled = false } } }
gpl-3.0
e6990c2c2544a571be23029869d90568
27.962319
149
0.530024
5.209593
false
false
false
false
emilstahl/swift
test/decl/var/properties.swift
9
28535
// RUN: %target-parse-verify-swift func markUsed<T>(t: T) {} struct X { } var _x: X class SomeClass {} func takeTrailingClosure(fn: () -> ()) -> Int {} func takeIntTrailingClosure(fn: () -> Int) -> Int {} //===--- // Stored properties //===--- var stored_prop_1: Int = 0 var stored_prop_2: Int = takeTrailingClosure {} //===--- // Computed properties -- basic parsing //===--- var a1: X { get { return _x } } var a2: X { get { return _x } set { _x = newValue } } var a3: X { get { return _x } set(newValue) { _x = newValue } } var a4: X { set { _x = newValue } get { return _x } } var a5: X { set(newValue) { _x = newValue } get { return _x } } // Reading/writing properties func accept_x(x: X) { } func accept_x_inout(inout x: X) { } func test_global_properties(x: X) { accept_x(a1) accept_x(a2) accept_x(a3) accept_x(a4) accept_x(a5) a1 = x // expected-error {{cannot assign to value: 'a1' is a get-only property}} a2 = x a3 = x a4 = x a5 = x accept_x_inout(&a1) // expected-error {{cannot pass immutable value as inout argument: 'a1' is a get-only property}} accept_x_inout(&a2) accept_x_inout(&a3) accept_x_inout(&a4) accept_x_inout(&a5) } //===--- Implicit 'get'. var implicitGet1: X { return _x } var implicitGet2: Int { var zzz = 0 // For the purpose of this test, any other function attribute work as well. @noreturn func foo() {} return 0 } var implicitGet3: Int { @noreturn func foo() {} return 0 } // Here we used apply weak to the getter itself, not to the variable. var x15: Int { // For the purpose of this test we need to use an attribute that can not be // applied to the getter. weak var foo: SomeClass? = SomeClass() // expected-warning {{variable 'foo' was written to, but never read}} return 0 } // Disambiguated as stored property with a trailing closure in the initializer. // // FIXME: QoI could be much better here. var disambiguateGetSet1a: Int = 0 { get {} // expected-error {{use of unresolved identifier 'get'}} } var disambiguateGetSet1b: Int = 0 { get { // expected-error {{use of unresolved identifier 'get'}} return 42 } } var disambiguateGetSet1c: Int = 0 { set {} // expected-error {{use of unresolved identifier 'set'}} } var disambiguateGetSet1d: Int = 0 { set(newValue) {} // expected-error {{use of unresolved identifier 'set'}} expected-error {{use of unresolved identifier 'newValue'}} } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet2() { func get(fn: () -> ()) {} var a: Int = takeTrailingClosure { get {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet2Attr() { func get(fn: () -> ()) {} var a: Int = takeTrailingClosure { @noreturn func foo() {} get {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet3() { func set(fn: () -> ()) {} var a: Int = takeTrailingClosure { set {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet3Attr() { func set(fn: () -> ()) {} var a: Int = takeTrailingClosure { @noreturn func foo() {} set {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet4() { func set(x: Int, fn: () -> ()) {} let newValue: Int = 0 var a: Int = takeTrailingClosure { set(newValue) {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet4Attr() { func set(x: Int, fn: () -> ()) {} var newValue: Int = 0 var a: Int = takeTrailingClosure { @noreturn func foo() {} set(newValue) {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. var disambiguateImplicitGet1: Int = 0 { // expected-error {{cannot call value of non-function type 'Int'}} return 42 } var disambiguateImplicitGet2: Int = takeIntTrailingClosure { return 42 } //===--- // Observed properties //===--- class C { var prop1 = 42 { didSet { } } var prop2 = false { willSet { } } var prop3: Int? = nil { didSet { } } var prop4: Bool? = nil { willSet { } } } protocol TrivialInitType { init() } class CT<T : TrivialInitType> { var prop1 = 42 { didSet { } } var prop2 = false { willSet { } } var prop3: Int? = nil { didSet { } } var prop4: Bool? = nil { willSet { } } var prop5: T? = nil { didSet { } } var prop6: T? = nil { willSet { } } var prop7 = T() { didSet { } } var prop8 = T() { willSet { } } } //===--- // Parsing problems //===--- var computed_prop_with_init_1: X { get {} } = X() // expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{2-2=;}} // FIXME: Redundant error below var x2 { // expected-error{{computed property must have an explicit type}} expected-error{{type annotation missing in pattern}} get { return _x } } var (x3): X { // expected-error{{getter/setter can only be defined for a single variable}} get { return _x } } var duplicateAccessors1: X { get { // expected-note {{previous definition of getter is here}} return _x } set { // expected-note {{previous definition of setter is here}} _x = value } get { // expected-error {{duplicate definition of getter}} return _x } set(v) { // expected-error {{duplicate definition of setter}} _x = v } } var duplicateAccessors2: Int = 0 { willSet { // expected-note {{previous definition of willSet is here}} } didSet { // expected-note {{previous definition of didSet is here}} } willSet { // expected-error {{duplicate definition of willSet}} } didSet { // expected-error {{duplicate definition of didSet}} } } var extraTokensInAccessorBlock1: X { get {} a // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} } var extraTokensInAccessorBlock2: X { get {} weak // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} a } var extraTokensInAccessorBlock3: X { get {} a = b // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} set {} get {} } var extraTokensInAccessorBlock4: X { get blah wibble // expected-error{{expected '{' to start getter definition}} } var extraTokensInAccessorBlock5: X { set blah wibble // expected-error{{expected '{' to start setter definition}} } var extraTokensInAccessorBlock6: X { willSet blah wibble // expected-error{{expected '{' to start willSet definition}} } var extraTokensInAccessorBlock7: X { didSet blah wibble // expected-error{{expected '{' to start didSet definition}} } var extraTokensInAccessorBlock8: X { foo // expected-error {{use of unresolved identifier 'foo'}} get {} // expected-error{{use of unresolved identifier 'get'}} set {} // expected-error{{use of unresolved identifier 'set'}} } var extraTokensInAccessorBlock9: Int { get // expected-error {{expected '{' to start getter definition}} var a = b } struct extraTokensInAccessorBlock10 { var x: Int { get // expected-error {{expected '{' to start getter definition}} var a = b } init() {} } var x9: X { get ( ) { // expected-error{{expected '{' to start getter definition}} } } var x10: X { set ( : ) { // expected-error{{expected setter parameter name}} } get {} } var x11 : X { set { // expected-error{{variable with a setter must also have a getter}} } } var x12: X { set(newValue %) { // expected-error {{expected ')' after setter parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start setter definition}} } } var x13: X {} // expected-error {{computed property must have accessors specified}} // Type checking problems struct Y { } var y: Y var x20: X { get { return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}} } set { y = newValue // expected-error{{cannot assign value of type 'X' to type 'Y'}} } } var x21: X { get { return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}} } set(v) { y = v // expected-error{{cannot assign value of type 'X' to type 'Y'}} } } var x23: Int, x24: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}} return 42 } var x25: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}} return 42 }, x26: Int // Properties of struct/enum/extensions struct S { var _backed_x: X, _backed_x2: X var x: X { get { return _backed_x } mutating set(v) { _backed_x = v } } } extension S { var x2: X { get { return self._backed_x2 } mutating set { _backed_x2 = newValue } } var x3: X { get { return self._backed_x2 } } } struct StructWithExtension1 { var foo: Int static var fooStatic = 4 } extension StructWithExtension1 { var fooExt: Int // expected-error {{extensions may not contain stored properties}} static var fooExtStatic = 4 } class ClassWithExtension1 { var foo: Int = 0 class var fooStatic = 4 // expected-error {{class stored properties not yet supported in classes; did you mean 'static'?}} } extension ClassWithExtension1 { var fooExt: Int // expected-error {{extensions may not contain stored properties}} class var fooExtStatic = 4 // expected-error {{class stored properties not yet supported in classes; did you mean 'static'?}} } enum EnumWithExtension1 { var foo: Int // expected-error {{enums may not contain stored properties}} static var fooStatic = 4 } extension EnumWithExtension1 { var fooExt: Int // expected-error {{extensions may not contain stored properties}} static var fooExtStatic = 4 } protocol ProtocolWithExtension1 { var foo: Int { get } static var fooStatic : Int { get } } extension ProtocolWithExtension1 { final var fooExt: Int // expected-error{{extensions may not contain stored properties}} final static var fooExtStatic = 4 // expected-error{{static stored properties not yet supported in generic types}} } func getS() -> S { let s: S return s } func test_extension_properties(inout s: S, inout x: X) { accept_x(s.x) accept_x(s.x2) accept_x(s.x3) accept_x(getS().x) accept_x(getS().x2) accept_x(getS().x3) s.x = x s.x2 = x s.x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}} getS().x = x // expected-error{{cannot assign to property: 'getS' returns immutable value}} getS().x2 = x // expected-error{{cannot assign to property: 'getS' returns immutable value}} getS().x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}} accept_x_inout(&getS().x) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}} accept_x_inout(&getS().x2) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}} accept_x_inout(&getS().x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}} x = getS().x x = getS().x2 x = getS().x3 accept_x_inout(&s.x) accept_x_inout(&s.x2) accept_x_inout(&s.x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}} } extension S { mutating func test(inout other_x: X) { x = other_x x2 = other_x x3 = other_x // expected-error{{cannot assign to property: 'x3' is a get-only property}} other_x = x other_x = x2 other_x = x3 } } // Accessor on non-settable type struct Aleph { var b: Beth { get { return Beth(c: 1) } } } struct Beth { var c: Int } func accept_int_inout(inout c: Int) { } func accept_int(c: Int) { } func test_settable_of_nonsettable(a: Aleph) { a.b.c = 1 // expected-error{{cannot assign}} let x:Int = a.b.c _ = x accept_int(a.b.c) accept_int_inout(&a.b.c) // expected-error {{cannot pass immutable value as inout argument: 'b' is a get-only property}} } // TODO: Static properties are only implemented for nongeneric structs yet. struct MonoStruct { static var foo: Int = 0 static var (bar, bas): (String, UnicodeScalar) = ("zero", "0") static var zim: UInt8 { return 0 } static var zang = UnicodeScalar() static var zung: UInt16 { get { return 0 } set {} } var a: Double var b: Double } struct MonoStructOneProperty { static var foo: Int = 22 } enum MonoEnum { static var foo: Int = 0 static var zim: UInt8 { return 0 } } struct GenStruct<T> { static var foo: Int = 0 // expected-error{{static stored properties not yet supported in generic types}} } class MonoClass { class var foo: Int = 0 // expected-error{{class stored properties not yet supported in classes; did you mean 'static'?}} } protocol Proto { static var foo: Int { get } } func staticPropRefs() -> (Int, Int, String, UnicodeScalar, UInt8) { return (MonoStruct.foo, MonoEnum.foo, MonoStruct.bar, MonoStruct.bas, MonoStruct.zim) } func staticPropRefThroughInstance(foo: MonoStruct) -> Int { return foo.foo //expected-error{{static member 'foo' cannot be used on instance of type 'MonoStruct'}} } func memberwiseInitOnlyTakesInstanceVars() -> MonoStruct { return MonoStruct(a: 1.2, b: 3.4) } func getSetStaticProperties() -> (UInt8, UInt16) { MonoStruct.zim = 12 // expected-error{{cannot assign}} MonoStruct.zung = 34 return (MonoStruct.zim, MonoStruct.zung) } var selfRefTopLevel: Int { return selfRefTopLevel // expected-warning {{attempting to access 'selfRefTopLevel' within its own getter}} } var selfRefTopLevelSetter: Int { get { return 42 } set { markUsed(selfRefTopLevelSetter) // no-warning selfRefTopLevelSetter = newValue // expected-warning {{attempting to modify 'selfRefTopLevelSetter' within its own setter}} } } var selfRefTopLevelSilenced: Int { get { return properties.selfRefTopLevelSilenced // no-warning } set { properties.selfRefTopLevelSilenced = newValue // no-warning } } class SelfRefProperties { var getter: Int { return getter // expected-warning {{attempting to access 'getter' within its own getter}} // expected-note@-1 {{access 'self' explicitly to silence this warning}} {{12-12=self.}} } var setter: Int { get { return 42 } set { markUsed(setter) // no-warning var unused = setter + setter // expected-warning {{initialization of variable 'unused' was never used; consider replacing with assignment to '_' or removing it}} {{7-17=_}} setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}} // expected-note@-1 {{access 'self' explicitly to silence this warning}} {{7-7=self.}} } } var silenced: Int { get { return self.silenced // no-warning } set { self.silenced = newValue // no-warning } } var someOtherInstance: SelfRefProperties = SelfRefProperties() var delegatingVar: Int { // This particular example causes infinite access, but it's easily possible // for the delegating instance to do something else. return someOtherInstance.delegatingVar // no-warning } } func selfRefLocal() { var getter: Int { return getter // expected-warning {{attempting to access 'getter' within its own getter}} } var setter: Int { get { return 42 } set { markUsed(setter) // no-warning setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}} } } } struct WillSetDidSetProperties { var a: Int { willSet { markUsed("almost") } didSet { markUsed("here") } } var b: Int { willSet { markUsed(b) markUsed(newValue) } } var c: Int { willSet(newC) { markUsed(c) markUsed(newC) } } var d: Int { didSet { markUsed("woot") } get { // expected-error {{didSet variable may not also have a get specifier}} return 4 } } var e: Int { willSet { markUsed("woot") } set { // expected-error {{willSet variable may not also have a set specifier}} return 4 } } var f: Int { willSet(5) {} // expected-error {{expected willSet parameter name}} didSet(^) {} // expected-error {{expected didSet parameter name}} } var g: Int { willSet(newValue 5) {} // expected-error {{expected ')' after willSet parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start willSet definition}} } var h: Int { didSet(oldValue ^) {} // expected-error {{expected ')' after didSet parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start didSet definition}} } // didSet/willSet with initializers. // Disambiguate trailing closures. var disambiguate1: Int = 42 { // simple initializer, simple label didSet { markUsed("eek") } } var disambiguate2: Int = 42 { // simple initializer, complex label willSet(v) { markUsed("eek") } } var disambiguate3: Int = takeTrailingClosure {} { // Trailing closure case. willSet(v) { markUsed("eek") } } var disambiguate4: Int = 42 { willSet {} } var disambiguate5: Int = 42 { didSet {} } var disambiguate6: Int = takeTrailingClosure { @noreturn func f() {} return () } var inferred1 = 42 { willSet { markUsed("almost") } didSet { markUsed("here") } } var inferred2 = 40 { willSet { markUsed(b) markUsed(newValue) } } var inferred3 = 50 { willSet(newC) { markUsed(c) markUsed(newC) } } } // Disambiguated as accessor. struct WillSetDidSetDisambiguate1 { var willSet: Int var x: (() -> ()) -> Int = takeTrailingClosure { willSet = 42 // expected-error {{expected '{' to start willSet definition}} } } struct WillSetDidSetDisambiguate1Attr { var willSet: Int var x: (() -> ()) -> Int = takeTrailingClosure { willSet = 42 // expected-error {{expected '{' to start willSet definition}} } } // Disambiguated as accessor. struct WillSetDidSetDisambiguate2 { func willSet(_: () -> Int) {} var x: (() -> ()) -> Int = takeTrailingClosure { willSet {} } } struct WillSetDidSetDisambiguate2Attr { func willSet(_: () -> Int) {} var x: (() -> ()) -> Int = takeTrailingClosure { willSet {} } } // No need to disambiguate -- this is clearly a function call. func willSet(_: () -> Int) {} struct WillSetDidSetDisambiguate3 { var x: Int = takeTrailingClosure({ willSet { 42 } }) } protocol ProtocolGetSet1 { var a: Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} } protocol ProtocolGetSet2 { var a: Int {} // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} } protocol ProtocolGetSet3 { var a: Int { get } } protocol ProtocolGetSet4 { var a: Int { set } // expected-error {{variable with a setter must also have a getter}} } protocol ProtocolGetSet5 { var a: Int { get set } } protocol ProtocolGetSet6 { var a: Int { set get } } protocol ProtocolWillSetDidSet1 { var a: Int { willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet2 { var a: Int { didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet3 { var a: Int { willSet didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet4 { var a: Int { didSet willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} expected-error {{expected get or set in a protocol property}} } var globalDidsetWillSet: Int { // expected-error {{non-member observing properties require an initializer}} didSet {} } var globalDidsetWillSet2 : Int = 42 { didSet {} } class Box { var num: Int init(num: Int) { self.num = num } } func double(inout val: Int) { val *= 2 } class ObservingPropertiesNotMutableInWillSet { var anotherObj : ObservingPropertiesNotMutableInWillSet init() {} var property: Int = 42 { willSet { // <rdar://problem/16826319> willSet immutability behavior is incorrect anotherObj.property = 19 // ok property = 19 // expected-warning {{attempting to store to property 'property' within its own willSet}} double(&property) // expected-warning {{attempting to store to property 'property' within its own willSet}} double(&self.property) // no-warning } } // <rdar://problem/21392221> - call to getter through BindOptionalExpr was not viewed as a load var _oldBox : Int weak var weakProperty: Box? { willSet { _oldBox = weakProperty?.num ?? -1 } } func localCase() { var localProperty: Int = 42 { willSet { localProperty = 19 // expected-warning {{attempting to store to property 'localProperty' within its own willSet}} } } } } func doLater(fn : () -> ()) {} // rdar://<rdar://problem/16264989> property not mutable in closure inside of its willSet class MutableInWillSetInClosureClass { var bounds: Int = 0 { willSet { let oldBounds = bounds doLater { self.bounds = oldBounds } } } } // <rdar://problem/16191398> add an 'oldValue' to didSet so you can implement "didChange" properties var didSetPropertyTakingOldValue : Int = 0 { didSet(oldValue) { markUsed(oldValue) markUsed(didSetPropertyTakingOldValue) } } // rdar://16280138 - synthesized getter is defined in terms of archetypes, not interface types protocol AbstractPropertyProtocol { typealias Index var a : Index { get } } struct AbstractPropertyStruct<T> : AbstractPropertyProtocol { typealias Index = T var a : T } // Allow _silgen_name accessors without bodies. var _silgen_nameGet1: Int { @_silgen_name("get1") get set { } } var _silgen_nameGet2: Int { set { } @_silgen_name("get2") get } var _silgen_nameGet3: Int { @_silgen_name("get3") get } var _silgen_nameGetSet: Int { @_silgen_name("get4") get @_silgen_name("set4") set } // <rdar://problem/16375910> reject observing properties overriding readonly properties class Base16375910 { var x : Int { // expected-note {{attempt to override property here}} return 42 } var y : Int { // expected-note {{attempt to override property here}} get { return 4 } set {} } } class Derived16375910 : Base16375910 { override init() {} override var x : Int { // expected-error {{cannot observe read-only property 'x'; it can't change}} willSet { markUsed(newValue) } } } // <rdar://problem/16382967> Observing properties have no storage, so shouldn't prevent initializer synth class Derived16382967 : Base16375910 { override var y : Int { willSet { markUsed(newValue) } } } // <rdar://problem/16659058> Read-write properties can be made read-only in a property override class Derived16659058 : Base16375910 { override var y : Int { // expected-error {{cannot override mutable property with read-only property 'y'}} get { return 42 } } } // <rdar://problem/16406886> Observing properties don't work with ownership types struct PropertiesWithOwnershipTypes { unowned var p1 : SomeClass { didSet { } } init(res: SomeClass) { p1 = res } } // <rdar://problem/16608609> Assert (and incorrect error message) when defining a constant stored property with observers class Test16608609 { let constantStored: Int = 0 { // expected-error {{'let' declarations cannot be observing properties}} willSet { } didSet { } } } // <rdar://problem/16941124> Overriding property observers warn about using the property value "within its own getter" class rdar16941124Base { var x = 0 } class rdar16941124Derived : rdar16941124Base { var y = 0 override var x: Int { didSet { y = x + 1 // no warning. } } } // Overrides of properties with custom ownership. class OwnershipBase { class var defaultObject: AnyObject { fatalError("") } var strongVar: AnyObject? // expected-note{{overridden declaration is here}} weak var weakVar: AnyObject? // FIXME: These should be optional to properly test overriding. unowned var unownedVar: AnyObject = defaultObject unowned(unsafe) var unownedUnsafeVar: AnyObject = defaultObject // expected-note{{overridden declaration is here}} } class OwnershipExplicitSub : OwnershipBase { override var strongVar: AnyObject? { didSet {} } override weak var weakVar: AnyObject? { didSet {} } override unowned var unownedVar: AnyObject { didSet {} } override unowned(unsafe) var unownedUnsafeVar: AnyObject { didSet {} } } class OwnershipImplicitSub : OwnershipBase { override var strongVar: AnyObject? { didSet {} } override weak var weakVar: AnyObject? { didSet {} } override unowned var unownedVar: AnyObject { didSet {} } override unowned(unsafe) var unownedUnsafeVar: AnyObject { didSet {} } } class OwnershipBadSub : OwnershipBase { override weak var strongVar: AnyObject? { // expected-error {{cannot override strong property with weak property}} didSet {} } override unowned var weakVar: AnyObject? { // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'AnyObject?'}} didSet {} } override weak var unownedVar: AnyObject { // expected-error {{'weak' variable should have optional type 'AnyObject?'}} didSet {} } override unowned var unownedUnsafeVar: AnyObject { // expected-error {{cannot override unowned(unsafe) property with unowned property}} didSet {} } } // <rdar://problem/17391625> Swift Compiler Crashes when Declaring a Variable and didSet in an Extension class rdar17391625 { var prop = 42 // expected-note {{overridden declaration is here}} } extension rdar17391625 { var someStoredVar: Int // expected-error {{extensions may not contain stored properties}} var someObservedVar: Int { // expected-error {{extensions may not contain stored properties}} didSet { } } } class rdar17391625derived : rdar17391625 { } extension rdar17391625derived { // Not a stored property, computed because it is an override. override var prop: Int { // expected-error {{declarations in extensions cannot override yet}} didSet { } } } // <rdar://problem/19874152> struct memberwise initializer violates new sanctity of previously set `let` property struct r19874152S1 { let number : Int = 42 } _ = r19874152S1(number:64) // expected-error {{extra argument 'number' in call}} _ = r19874152S1() // Ok struct r19874152S2 { var number : Int = 42 } _ = r19874152S2(number:64) // Ok, property is a var. _ = r19874152S2() // Ok struct r19874152S3 { let number : Int = 42 let flavour : Int } _ = r19874152S3(number:64) // expected-error {{incorrect argument label in call (have 'number:', expected 'flavour:')}} {{17-23=flavour}} _ = r19874152S3(number:64, flavour: 17) // expected-error {{extra argument 'number' in call}} _ = r19874152S3(flavour: 17) // ok _ = r19874152S3() // expected-error {{missing argument for parameter 'flavour' in call}} struct r19874152S4 { let number : Int? = nil } _ = r19874152S4(number:64) // expected-error {{extra argument 'number' in call}} _ = r19874152S4() // Ok struct r19874152S5 { } _ = r19874152S5() // ok struct r19874152S6 { let (a,b) = (1,2) // Cannot handle implicit synth of this yet. } _ = r19874152S5() // ok
apache-2.0
700ab7b3f859ef253973fe6b54f2a164
23.24384
188
0.654424
3.741804
false
false
false
false
RobinFalko/Ubergang
Examples/TweenApp/Pods/Ubergang/Ubergang/Extension/CGPath.swift
1
3152
// // CGPath.swift // Ubergang // // Created by Robin Frielingsdorf on 19/05/16. // Copyright © 2016 Robin Falko. All rights reserved. // import UIKit extension CGPath { func forEach(_ body: @convention(block) (CGPathElement) -> Void) { typealias Body = @convention(block) (CGPathElement) -> Void func callback(_ info: UnsafeMutableRawPointer, element: UnsafePointer<CGPathElement>) { let body = unsafeBitCast(info, to: Body.self) body(element.pointee) } let unsafeBody = unsafeBitCast(body, to: UnsafeMutableRawPointer.self) self.apply(info: unsafeBody, function: callback as! CGPathApplierFunction) } func getElements() -> [(type: CGPathElementType, points: [CGPoint])] { var result = [(type: CGPathElementType, points: [CGPoint])]() var elementType: CGPathElementType! var points: [CGPoint]! var firstPoint: CGPoint! var previousLastPoint: CGPoint! forEach { element in switch (element.type) { case CGPathElementType.moveToPoint: firstPoint = element.points[0] previousLastPoint = firstPoint case .addLineToPoint: points = [CGPoint]() elementType = element.type points.append(previousLastPoint) points.append(element.points[0]) result.append((elementType, points)) previousLastPoint = element.points[0] case .addQuadCurveToPoint: points = [CGPoint]() elementType = element.type points.append(previousLastPoint) points.append(element.points[0]) points.append(element.points[1]) result.append((elementType, points)) previousLastPoint = element.points[1] case .addCurveToPoint: points = [CGPoint]() elementType = element.type points.append(previousLastPoint) points.append(element.points[0]) points.append(element.points[1]) points.append(element.points[2]) result.append((elementType, points)) previousLastPoint = element.points[2] case .closeSubpath: points = [CGPoint]() elementType = element.type points.append(previousLastPoint) points.append(firstPoint) result.append((elementType, points)) } } return result } func getElement(_ index: Int) -> (type: CGPathElementType, points: [CGPoint])? { let elements = getElements() if index >= elements.count { return nil } return elements[index] } func elementCount() -> Int { var count = 0 self.forEach { element in if element.type != .moveToPoint && element.type != .closeSubpath { count += 1 } } return count } }
apache-2.0
53108cfbfa4d409b1b7cd7d7744e33b8
34.404494
95
0.548397
5.090468
false
false
false
false
jobrunner/FeedbackCards
FeedbackCards/CardPageViewDataSource.swift
1
2249
// Copyright (c) 2017 Jo Brunner // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class CardPageViewDataSource: NSObject, UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if let controller = StoryboardHelper.controller("CardViewController") as? CardViewController { let card = (viewController as! CardViewController).card controller.card = CardDeck.index(fromCard: card!).prev.card return controller } return nil } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if let controller = StoryboardHelper.controller("CardViewController") as? CardViewController { let card = (viewController as! CardViewController).card controller.card = CardDeck.index(fromCard: card!).next.card return controller } return nil } }
mit
d03a0b3ca7a092dca8d786aecb0617b3
40.648148
105
0.697199
5.594527
false
false
false
false
knehez/edx-app-ios
Source/BorderStyle.swift
2
1072
// // BorderStyle.swift // edX // // Created by Akiva Leffert on 6/4/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation public class BorderStyle { enum Width { case Hairline case Size(CGFloat) var value : CGFloat { switch self { case Hairline: return OEXStyles.dividerSize() case let Size(s): return s } } } let cornerRadius : CGFloat let width : Width let color : UIColor? init(cornerRadius : CGFloat = 0, width : Width = .Size(0), color : UIColor? = nil) { self.cornerRadius = cornerRadius self.width = width self.color = color } public func applyToView(view : UIView) { view.layer.cornerRadius = cornerRadius view.layer.borderWidth = width.value view.layer.borderColor = color?.CGColor if cornerRadius != 0 { view.clipsToBounds = true } } class func clearStyle() -> BorderStyle { return BorderStyle() } }
apache-2.0
460fb42e84aad1a151853c39888abbcd
22.326087
88
0.564366
4.523207
false
false
false
false
aschwaighofer/swift
test/Incremental/PrivateDependencies/private-function-return-type-fine.swift
2
1171
// REQUIRES: shell // Also uses awk: // XFAIL OS=windows // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main -experimental-private-intransitive-dependencies | %FileCheck %s -check-prefix=CHECK-OLD // RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main -experimental-private-intransitive-dependencies | %FileCheck %s -check-prefix=CHECK-NEW // RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh <%t.swiftdeps >%t-processed.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps private func testReturnType() -> InterestingType { fatalError() } // CHECK-OLD: sil_global @$s4main1x{{[^ ]+}} : $Int // CHECK-NEW: sil_global @$s4main1x{{[^ ]+}} : $Double public var x = testReturnType() + 0 // CHECK-DEPS: topLevel interface '' InterestingType false
apache-2.0
e81a650b9f1079bc9f6d214f62d70e5a
60.631579
251
0.732707
3.444118
false
true
false
false
justin999/gitap
gitap/SettingsTableViewDelegate.swift
1
2125
// // SettingsTableViewDelegate.swift // gitap // // Created by Koichi Sato on 12/25/16. // Copyright © 2016 Koichi Sato. All rights reserved. // import UIKit class SettingsTableViewDelegate: NSObject { let stateController: StateController init(tableView: UITableView, stateController: StateController) { self.stateController = stateController super.init() tableView.delegate = self } } extension SettingsTableViewDelegate: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if indexPath.section == 0 && indexPath.row == 2 { print("clearing oauth token") self.stateController.deleteGitHubAuthorization(completionHandler: { (result) in switch result { case .failure(_): DispatchQueue.main.async { self.stateController.presentAlert(title: "", message: "Failed to Logout from Gitap", style: .alert, actions: [UIAlertAction.okAlert()], completion: nil) } case .success(_): GitHubAPIManager.shared.clearOAuthToken() let okAlert = UIAlertAction(title: "OK", style: .cancel) { okAlert in DispatchQueue.main.async { self.stateController.viewController.performSegue(withIdentifier: String.segue.backToSetupSegue, sender: nil) } } DispatchQueue.main.async { self.stateController.presentAlert(title: "", message: "Successfully Logout from Gitap", style: .alert, actions: [okAlert], completion: nil) } } }) } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 20 } }
mit
ba8242cbca53914b61a961bc3ef372c0
35.62069
176
0.590866
5.390863
false
false
false
false
TeletronicsDotAe/FloatingActionButton
Example/LiquidFloatingActionButton/ViewController.swift
1
4587
// // ViewController.swift // FloatingActionButton // Adapted by Martin Jacon Rehder on 2016/04/17 // // Original by // // Created by Takuma Yoshida on 08/25/2015. // Copyright (c) 2015 Takuma Yoshida. All rights reserved. // import UIKit import SnapKit import LiquidFloatingActionButton public class CustomCell : FloatingCell { var name: String = "sample" init(icon: UIImage, name: String) { self.name = name super.init(icon: icon) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func setupView(view: UIView) { super.setupView(view) let label = UILabel() label.text = name label.textColor = UIColor.whiteColor() label.font = UIFont(name: "Helvetica-Neue", size: 12) addSubview(label) label.snp_makeConstraints { make in make.left.equalTo(self).offset(-80) make.width.equalTo(75) make.top.height.equalTo(self) } } } public class CustomDrawingActionButton: FloatingActionButton { override public func createPlusLayer(frame: CGRect) -> CAShapeLayer { let plusLayer = CAShapeLayer() plusLayer.lineCap = kCALineCapRound plusLayer.strokeColor = UIColor.whiteColor().CGColor plusLayer.lineWidth = 3.0 let w = frame.width let h = frame.height let points = [ (CGPoint(x: w * 0.25, y: h * 0.35), CGPoint(x: w * 0.75, y: h * 0.35)), (CGPoint(x: w * 0.25, y: h * 0.5), CGPoint(x: w * 0.75, y: h * 0.5)), (CGPoint(x: w * 0.25, y: h * 0.65), CGPoint(x: w * 0.75, y: h * 0.65)) ] let path = UIBezierPath() for (start, end) in points { path.moveToPoint(start) path.addLineToPoint(end) } plusLayer.path = path.CGPath return plusLayer } } class ViewController: UIViewController, FloatingActionButtonDataSource, FloatingActionButtonDelegate { var cells: [FloatingCell] = [] var floatingActionButton: FloatingActionButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let createButton: (CGRect, FloatingActionButtonAnimateStyle) -> FloatingActionButton = { (frame, style) in let floatingActionButton = CustomDrawingActionButton(frame: frame) floatingActionButton.animateStyle = style floatingActionButton.childControlsColor = UIColor.whiteColor(); floatingActionButton.childControlsTintColor = UIColor.darkGrayColor(); floatingActionButton.childControlsTintColor = UIColor.blackColor() floatingActionButton.dataSource = self floatingActionButton.delegate = self return floatingActionButton } let cellFactory: (String) -> FloatingCell = { (iconName) in let cell = FloatingCell(icon: UIImage(named: iconName)!) return cell } let customCellFactory: (String) -> FloatingCell = { (iconName) in let cell = CustomCell(icon: UIImage(named: iconName)!, name: iconName) return cell } cells.append(cellFactory("ic_cloud")) cells.append(customCellFactory("ic_system")) cells.append(cellFactory("ic_place")) let floatingFrame = CGRect(x: self.view.frame.width - 56 - 16, y: self.view.frame.height - 56 - 16, width: 56, height: 56) let bottomRightButton = createButton(floatingFrame, .Up) let image = UIImage(named: "ic_art") bottomRightButton.image = image let floatingFrame2 = CGRect(x: 16, y: 16, width: 56, height: 56) let topLeftButton = createButton(floatingFrame2, .Down) self.view.addSubview(bottomRightButton) self.view.addSubview(topLeftButton) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfCells(floatingActionButton: FloatingActionButton) -> Int { return cells.count } func cellForIndex(index: Int) -> FloatingCell { return cells[index] } func liquidFloatingActionButton(floatingActionButton: FloatingActionButton, didSelectItemAtIndex index: Int) { print("did Tapped! \(index)") floatingActionButton.close() } }
mit
0e61ad05e740f522aced1a3cf7d1ffd8
32.735294
130
0.623937
4.61005
false
false
false
false
WeltN24/Carlos
Tests/CarlosTests/StringConvertibleTests.swift
1
464
import Foundation import Nimble import Quick import Carlos final class StringConvertibleTests: QuickSpec { override func spec() { describe("String values") { let value = "this is the value" it("should return self") { expect(value.toString()) == value } } describe("NSString values") { let value = "this is the value" it("should return self") { expect(value.toString()) == value } } } }
mit
726c0e41979de0235201f75d45b6e099
16.846154
47
0.599138
4.218182
false
false
false
false
MadAppGang/SmartLog
iOS/SmartLog/Extensions/UIView+SyntacticSugar.swift
1
4160
// // UIView+SyntacticSugar.swift // SmartLog // // Created by Dmytro Lisitsyn on 6/16/16. // Copyright © 2016 MadAppGang. All rights reserved. // import UIKit extension UIView { static func loadFromNib() -> Self { return loadViewFromNib() } private static func loadViewFromNib<View: UIView>() -> View { let nibContent = Bundle.main.loadNibNamed(className(), owner: nil, options: nil) var viewToReturn: View! for objectFromNib in nibContent! { guard let objectFromNib = objectFromNib as? View else { continue } viewToReturn = objectFromNib break } return viewToReturn } } extension NSObject { static func className() -> String { let objectClass: AnyClass = self let objectClassName = NSStringFromClass(objectClass) let objectClassNameComponents = objectClassName.components(separatedBy: ".") return objectClassNameComponents.last! } } extension UIStoryboard { func createViewController<ViewController: UIViewController>(_ vc: ViewController.Type) -> ViewController { return instantiateViewController(withIdentifier: vc.storyboardID()) as! ViewController } } extension UIViewController { static func storyboardID() -> String { return className() } } extension UITableViewCell { static func cellID() -> String { return className() } } extension UITableViewHeaderFooterView { static func viewID() -> String { return className() } } extension UITableView { func register<View: UITableViewHeaderFooterView>(nibOfReusableView view: View.Type) { let nib = UINib(nibName: view.className(), bundle: nil) register(nib, forHeaderFooterViewReuseIdentifier: view.viewID()) } func register<Cell: UITableViewCell>(nibOfCell cell: Cell.Type) { let nib = UINib(nibName: cell.className(), bundle: nil) register(nib, forCellReuseIdentifier: cell.cellID()) } func register<Cell: UITableViewCell>(cell: Cell.Type) { register(cell, forCellReuseIdentifier: cell.cellID()) } func dequeueCell<Cell: UITableViewCell>(_ cell: Cell.Type = Cell.self) -> Cell { let cell = dequeueReusableCell(withIdentifier: cell.cellID()) as? Cell return cell! } func dequeueCell<Cell: UITableViewCell>(at indexPath: IndexPath, cell: Cell.Type = Cell.self) -> Cell { let cell = dequeueReusableCell(withIdentifier: cell.cellID(), for: indexPath) as? Cell return cell! } func dequeueView<View: UITableViewHeaderFooterView>(_ view: View.Type = View.self) -> View { return dequeueReusableHeaderFooterView(withIdentifier: view.viewID()) as! View } } extension UICollectionViewCell { static func cellID() -> String { return className() } } extension UICollectionReusableView { static func viewID() -> String { return className() } } extension UICollectionView { func register<Cell: UICollectionViewCell>(nibOfCell cell: Cell.Type) { let nib = UINib(nibName: cell.className(), bundle: nil) register(nib, forCellWithReuseIdentifier: cell.cellID()) } func register<View: UICollectionReusableView>(nibOfHeader header: View.Type) { let nib = UINib(nibName: header.className(), bundle: nil) register(nib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: header.viewID()) } func dequeueCell<Cell: UICollectionViewCell>(at indexPath: IndexPath, cell: Cell.Type = Cell.self) -> Cell { let cell = dequeueReusableCell(withReuseIdentifier: cell.cellID(), for: indexPath) as? Cell return cell! } func dequeueView<View: UICollectionReusableView>(at indexPath: IndexPath, of kind: String = UICollectionElementKindSectionHeader, view: View.Type = View.self) -> View { let cell = dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: view.viewID(), for: indexPath) as? View return cell! } }
mit
39b449a1a50a0a635d62f88cb0e5d067
29.807407
172
0.667949
4.97488
false
false
false
false
manavgabhawala/CAEN-Lecture-Scraper
CAEN Lecture Scraper/DownloadVideosController.swift
1
5092
// // DownloadVideosController.swift // CAEN Lecture Scraper // // Created by Manav Gabhawala on 6/3/15. // Copyright (c) 2015 Manav Gabhawala. All rights reserved. // import Cocoa let downloadsAllowed = dispatch_semaphore_create(3) let finishedAcquiringLinksNotification = "FinishedAcquiringLinksNotification" class DownloadVideosController: NSViewController { @IBOutlet var tableView : NSTableView! @IBOutlet var downloadButton: NSButton! @IBOutlet var removeRowButton : NSButton! @IBOutlet var addRowButton: NSButton! @IBOutlet var clearDeleted: NSButton! var beginDownloading = false var videos = [VideoData]() { didSet { remakeCells() tableView.reloadData() } } var progressCells = [ProgressCellView]() var fileNameCells = [NSTableCellView]() var statusCells = [NSTableCellView]() override func viewDidLoad() { super.viewDidLoad() // Do view setup here. remakeCells() NSNotificationCenter.defaultCenter().addObserver(self, selector: "finishedAcquiringLinks", name: finishedAcquiringLinksNotification, object: nil) } override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder: NSCoder) { super.init(coder: coder) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func finishedAcquiringLinks() { downloadButton.enabled = true } func remakeCells() { fileNameCells.removeAll(keepCapacity: true) progressCells.removeAll(keepCapacity: true) statusCells.removeAll(keepCapacity: true) for video in videos { if let progressCell = tableView.makeViewWithIdentifier("progress", owner: self) as? ProgressCellView { progressCell.setup(video) progressCells.append(progressCell) if let cell = tableView.makeViewWithIdentifier("status", owner: self) as? NSTableCellView { progressCell.statusCell = cell // Give it a weak reference to status so it can update it when necessary. Not the best way to do this but works. cell.textField!.stringValue = "Waiting to Queue" statusCells.append(cell) } } if let cell = tableView.makeViewWithIdentifier("file", owner: self) as? NSTableCellView { cell.textField!.stringValue = video.filePath.lastPathComponent! fileNameCells.append(cell) } } } @IBAction func beginDownloads(sender: NSButton) { beginDownloading = true for cell in progressCells { cell.beginDownload() } } @IBAction func removeRow(sender: NSButton) { for selectedRow in tableView.selectedRowIndexes { let rowToDelete = selectedRow if rowToDelete >= 0 && rowToDelete < progressCells.count { progressCells[rowToDelete].delete() clearDeleted.enabled = true } else { removeRowButton.enabled = false } } removeRowButton.enabled = false tableView.selectRowIndexes(NSIndexSet(index: -1), byExtendingSelection: false) } @IBAction func clearDeletedRows(sender: NSButton) { var rowsToDelete = [Int]() for (i, row) in statusCells.enumerate() { if row.textField!.stringValue == "Deleted" { rowsToDelete.append(i) } } for rowToDelete in rowsToDelete.reverse() { statusCells.removeAtIndex(rowToDelete) progressCells.removeAtIndex(rowToDelete) fileNameCells.removeAtIndex(rowToDelete) videos.removeAtIndex(rowToDelete) tableView.removeRowsAtIndexes(NSIndexSet(index: rowToDelete), withAnimation: .SlideLeft) } clearDeleted.enabled = false } @IBAction func addRowBack(sender: NSButton) { for selectedRow in tableView.selectedRowIndexes { let rowToAdd = selectedRow if rowToAdd >= 0 && rowToAdd < progressCells.count && statusCells[rowToAdd].textField!.stringValue == "Deleted" { statusCells[rowToAdd].textField!.stringValue = "Waiting to Queue" if beginDownloading { progressCells[rowToAdd].beginDownload() } } } tableView.selectRowIndexes(NSIndexSet(index: -1), byExtendingSelection: false) addRowButton.enabled = false } } //MARK: - TableViewStuff extension DownloadVideosController : NSTableViewDelegate, NSTableViewDataSource { func numberOfRowsInTableView(tableView: NSTableView) -> Int { return progressCells.count } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { if tableColumn?.identifier == "progressColumn" { return progressCells[row] } else if tableColumn?.identifier == "fileColumn" { return fileNameCells[row] } else if tableColumn?.identifier == "statusColumn" { return statusCells[row] } return nil } func tableViewSelectionDidChange(notification: NSNotification) { var setDeleteTo = false var setAddTo = false for selectedRow in tableView.selectedRowIndexes { if selectedRow >= 0 && selectedRow < progressCells.count { if statusCells[selectedRow].textField!.stringValue == "Deleted" { setAddTo = true } else { setDeleteTo = true } } } removeRowButton.enabled = setDeleteTo addRowButton.enabled = setAddTo } }
mit
68ddd98de61a9b0cad84ead193bab029
25.805263
148
0.729772
3.797166
false
false
false
false
jmhooper/BRECBathroomFinder
BRECBathroomFinder/BBFLocationManager.swift
1
4815
// // BBFLocationManager.swift // BRECBathroomFinder // // Created by Jonathan Hooper on 3/18/15. // Copyright (c) 2015 JonathanHooper. All rights reserved. // import Foundation import CoreLocation class BBFLocationRequest: NSObject { var success: ((location: CLLocation) -> Void)! var failure: ((error: NSError) -> Void)! } var sharedBBFLocationManager: BBFLocationManager! class BBFLocationManager : CLLocationManager, CLLocationManagerDelegate { var locationRequests: Array<BBFLocationRequest> = Array<BBFLocationRequest>() var isLoadingLocation: Bool = false class func sharedManager() -> BBFLocationManager { if sharedBBFLocationManager == nil { sharedBBFLocationManager = BBFLocationManager() sharedBBFLocationManager.desiredAccuracy = CLLocationAccuracy(100.0) sharedBBFLocationManager.delegate = sharedBBFLocationManager } return sharedBBFLocationManager } func requestLocation(#success: (location: CLLocation) -> Void, failure: (error: NSError) -> Void) { // Create and store a Location Request var locationRequest = BBFLocationRequest() locationRequest.success = success locationRequest.failure = failure self.locationRequests.append(locationRequest) // Don't start updating locations if they have already started being updated if self.isLoadingLocation { return } else { self.isLoadingLocation = true } // Respond based on authorization status if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse { self.startUpdatingLocation() } else if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined { self.requestWhenInUseAuthorization() } else { failure(error: NSError(domain: "BBFLocationManager", code: 6578, userInfo: [NSLocalizedDescriptionKey: "Location services are not authorized"])) } } // LocationManagerDelegate func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { // Stop updates to process the requests self.stopUpdatingLocation() // Return errors to all the requests let copiedRequests = self.locationRequests for locationRequest: BBFLocationRequest in copiedRequests { // Forward the error locationRequest.failure(error: error) // Remove the request self.removeLocationRequest(locationRequest) } // Restart updates if the requests array has not reached 0 if self.locationRequests.count != 0 { self.startUpdatingLocation() } } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: Array<AnyObject>) { // Stop updates to process the requests self.stopUpdatingLocation() // Return success to all requests let copiedRequests = self.locationRequests for locationRequest: BBFLocationRequest in copiedRequests { // Forward the error locationRequest.success(location: self.location) // Remove the request self.removeLocationRequest(locationRequest) } // Restart updates if the requests array has not reached 0 if self.locationRequests.count != 0 { self.startUpdatingLocation() } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.AuthorizedWhenInUse { self.startUpdatingLocation() } else { // Return errors to all the requests let copiedRequests = self.locationRequests for locationRequest: BBFLocationRequest in copiedRequests { // Forward the error locationRequest.failure(error: NSError(domain: "BBFLocationManager", code: 4954, userInfo: [NSLocalizedDescriptionKey: "Location services are not authorized"])) // Remove the request self.removeLocationRequest(locationRequest) } } } private func removeLocationRequest(locationRequest: BBFLocationRequest) { // Remove the element from the location request array if let index = find(self.locationRequests, locationRequest) { self.locationRequests.removeAtIndex(index) } // If the requests array has reached 0, stop updating if self.locationRequests.count == 0 { self.stopUpdatingLocation() self.isLoadingLocation = false } } }
mit
c0a7bc6d82f6471c9ec9c58ed7426b79
37.528
176
0.657113
5.598837
false
false
false
false
robotwholearned/GettingStarted
Meal.swift
1
1730
// // Meal.swift // FoodTracker // // Created by Sandquist, Cassandra - Cassandra on 3/12/16. // Copyright © 2016 robotwholearned. All rights reserved. // import UIKit class Meal: NSObject, NSCoding { // MARK: Properties var name: String var photo: UIImage? var rating: Int // MARK: Archiving Paths static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("meals") // MARK: Types struct PropertyKey { static let nameKey = "name" static let photoKey = "photo" static let ratingKey = "rating" } // MARK: Initialization init?(name: String, photo: UIImage?, rating: Int) { // Initialize stored properties. self.name = name self.photo = photo self.rating = rating super.init() // Initialization should fail if there is no name or if the rating is negative. if name.isEmpty || rating < 0 { return nil } } // MARK: NSCoding func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: PropertyKey.nameKey) aCoder.encodeObject(photo, forKey: PropertyKey.photoKey) aCoder.encodeInteger(rating, forKey: PropertyKey.ratingKey) } required convenience init?(coder aDecoder: NSCoder) { let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String let photo = aDecoder.decodeObjectForKey(PropertyKey.photoKey) as? UIImage let rating = aDecoder.decodeIntegerForKey(PropertyKey.ratingKey) self.init(name: name, photo: photo, rating: rating) } }
mit
80afc6fb983d90c03f0608914b0474fb
28.305085
123
0.662811
4.622995
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressShareExtension/ShareData.swift
1
3254
import Foundation import WordPressKit enum PostStatus: String { case draft = "draft" case publish = "publish" } enum PostType: String, CaseIterable { case post = "post" case page = "page" var title: String { switch self { case .post: return AppLocalizedString("Post", comment: "Title shown when selecting a post type of Post from the Share Extension.") case .page: return AppLocalizedString("Page", comment: "Title shown when selecting a post type of Page from the Share Extension.") } } } /// ShareData is a state container for the share extension screens. /// @objc class ShareData: NSObject { /// Selected Site's ID /// var selectedSiteID: Int? /// Selected Site's Name /// var selectedSiteName: String? /// Post's Title /// var title = "" /// Post's Content /// var contentBody = "" /// Post's status, set to publish by default /// var postStatus: PostStatus = .publish /// Post's type, set to post by default /// var postType: PostType = .post /// Dictionary of URLs mapped to attachment ID's /// var sharedImageDict = [URL: String]() /// Comma-delimited list of tags for post /// var tags: String? /// Default category ID for selected site /// var defaultCategoryID: NSNumber? /// Default category name for selected site /// var defaultCategoryName: String? /// Selected post categories (IDs and Names) /// var userSelectedCategories: [RemotePostCategory]? /// All categories for the selected site /// var allCategoriesForSelectedSite: [RemotePostCategory]? // MARK: - Computed Vars /// Total number of categories for selected site /// var categoryCountForSelectedSite: Int { return allCategoriesForSelectedSite?.count ?? 0 } /// Computed (read-only) var that returns a comma-delimited string of selected category names. If /// selected categories is empty then return the default category name. Otherwise return "". /// var selectedCategoriesNameString: String { guard let selectedCategories = userSelectedCategories, !selectedCategories.isEmpty else { return defaultCategoryName ?? "" } return selectedCategories.map({ $0.name }).joined(separator: ", ") } /// Computed (read-only) var that returns a comma-delimited string of selected category IDs /// var selectedCategoriesIDString: String? { guard let selectedCategories = userSelectedCategories, !selectedCategories.isEmpty else { return nil } return selectedCategories.map({ $0.categoryID.stringValue }).joined(separator: ", ") } // MARK: - Helper Functions /// Helper function to set both the default category. /// func setDefaultCategory(categoryID: NSNumber, categoryName: String) { defaultCategoryID = categoryID defaultCategoryName = categoryName } /// Clears out all category information /// func clearCategoryInfo() { defaultCategoryID = nil defaultCategoryName = nil allCategoriesForSelectedSite = nil userSelectedCategories = nil } }
gpl-2.0
4e6de41cd150435c2fe7ac0383f02538
26.116667
138
0.64874
4.960366
false
false
false
false
BLVudu/SkyFloatingLabelTextField
SkyFloatingLabelTextField/SkyFloatingLabelTextFieldExample/Example3/SubclassingViewController.swift
1
1973
// Copyright 2016 Skyscanner Ltd // // 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 UIKit class SubclassingViewController: UIViewController { @IBOutlet var textField:ThemedTextField? override func viewDidLoad() { super.viewDidLoad() // SkyFloatingLabelTextField will inherit it's superview's `tintColor`. self.view.tintColor = UIColor(red: 0.0, green: 221.0/256.0, blue: 238.0/256.0, alpha: 1.0) self.textField?.placeholder = NSLocalizedString("Placeholder", tableName: "SkyFloatingLabelTextField", comment: "") } @IBOutlet var addErrorButton:UIButton? @IBAction func addError() { if(self.addErrorButton?.titleForState(.Normal) == NSLocalizedString("Add error", tableName: "SkyFloatingLabelTextField", comment: "add error button title")) { self.textField?.errorMessage = NSLocalizedString("error message", tableName: "SkyFloatingLabelTextField", comment: "") self.addErrorButton?.setTitle(NSLocalizedString("Clear error", tableName: "SkyFloatingLabelTextField", comment: "clear errors button title"), forState: .Normal) } else { self.textField?.errorMessage = "" self.addErrorButton?.setTitle(NSLocalizedString("Add error", tableName: "SkyFloatingLabelTextField", comment: "add error button title"), forState: .Normal) } } @IBAction func resignTextField() { self.textField?.resignFirstResponder() } }
apache-2.0
50457192fec1011a201ef6f02c5c16f7
50.921053
309
0.710086
4.731415
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Post/PostListFilterSettings.swift
1
6295
import Foundation import WordPressShared /// `PostListFilterSettings` manages settings for filtering posts (by author or status) /// - Note: previously found within `AbstractPostListViewController` class PostListFilterSettings: NSObject { fileprivate static let currentPostAuthorFilterKey = "CurrentPostAuthorFilterKey" fileprivate static let currentPageListStatusFilterKey = "CurrentPageListStatusFilterKey" fileprivate static let currentPostListStatusFilterKey = "CurrentPostListStatusFilterKey" @objc let blog: Blog @objc let postType: PostServiceType fileprivate var allPostListFilters: [PostListFilter]? enum AuthorFilter: UInt { case mine = 0 case everyone = 1 var stringValue: String { switch self { case .mine: return NSLocalizedString("Me", comment: "Label for the post author filter. This filter shows posts only authored by the current user.") case .everyone: return NSLocalizedString("Everyone", comment: "Label for the post author filter. This filter shows posts for all users on the blog.") } } } /// Initializes a new PostListFilterSettings instance /// - Parameter blog: the blog which owns the list of posts /// - Parameter postType: the type of post being listed @objc init(blog: Blog, postType: PostServiceType) { self.blog = blog self.postType = postType } @objc func availablePostListFilters() -> [PostListFilter] { if allPostListFilters == nil { allPostListFilters = PostListFilter.postListFilters() } return allPostListFilters! } func filterThatDisplaysPostsWithStatus(_ postStatus: BasePost.Status) -> PostListFilter { let index = indexOfFilterThatDisplaysPostsWithStatus(postStatus) return availablePostListFilters()[index] } func indexOfFilterThatDisplaysPostsWithStatus(_ postStatus: BasePost.Status) -> Int { var index = 0 var found = false for (idx, filter) in availablePostListFilters().enumerated() { if filter.statuses.contains(postStatus) { found = true index = idx break } } if !found { // The draft filter is the catch all by convention. index = indexForFilterWithType(.draft) } return index } func indexForFilterWithType(_ filterType: PostListFilter.Status) -> Int { if let index = availablePostListFilters().firstIndex(where: { (filter: PostListFilter) -> Bool in return filter.filterType == filterType }) { return index } else { return NSNotFound } } func setFilterWithPostStatus(_ status: BasePost.Status) { let index = indexOfFilterThatDisplaysPostsWithStatus(status) self.setCurrentFilterIndex(index) } // MARK: - Current filter /// - returns: the last active PostListFilter @objc func currentPostListFilter() -> PostListFilter { return availablePostListFilters()[currentFilterIndex()] } @objc func keyForCurrentListStatusFilter() -> String { switch postType { case .page: return type(of: self).currentPageListStatusFilterKey case .post: return type(of: self).currentPageListStatusFilterKey default: return "" } } /// currentPostListFilter: returns the index of the last active PostListFilter @objc func currentFilterIndex() -> Int { let userDefaults = UserPersistentStoreFactory.instance() if let filter = userDefaults.object(forKey: keyForCurrentListStatusFilter()) as? Int, filter < availablePostListFilters().count { return filter } else { return 0 // first item is the default } } /// setCurrentFilterIndex: stores the index of the last active PostListFilter @objc func setCurrentFilterIndex(_ newIndex: Int) { let index = self.currentFilterIndex() guard newIndex != index else { return } UserPersistentStoreFactory.instance().set(newIndex, forKey: self.keyForCurrentListStatusFilter()) UserDefaults.resetStandardUserDefaults() } // MARK: - Author-related methods @objc func canFilterByAuthor() -> Bool { if postType == .post { return blog.isMultiAuthor && blog.userID != nil } return false } @objc func authorIDFilter() -> NSNumber? { return currentPostAuthorFilter() == .mine ? blog.userID : nil } @objc func shouldShowOnlyMyPosts() -> Bool { let filter = currentPostAuthorFilter() return filter == .mine } /// currentPostListFilter: returns the last active AuthorFilter func currentPostAuthorFilter() -> AuthorFilter { if !canFilterByAuthor() { return .everyone } if let filter = UserPersistentStoreFactory.instance().object(forKey: type(of: self).currentPostAuthorFilterKey) { if (filter as AnyObject).uintValue == AuthorFilter.everyone.rawValue { return .everyone } } return .mine } /// currentPostListFilter: stores the last active AuthorFilter /// - Note: _Also tracks a .PostListAuthorFilterChanged analytics event_ func setCurrentPostAuthorFilter(_ filter: AuthorFilter) { guard filter != currentPostAuthorFilter() else { return } WPAnalytics.track(.postListAuthorFilterChanged, withProperties: propertiesForAnalytics()) UserPersistentStoreFactory.instance().set(filter.rawValue, forKey: type(of: self).currentPostAuthorFilterKey) UserDefaults.resetStandardUserDefaults() } // MARK: - Analytics @objc func propertiesForAnalytics() -> [String: AnyObject] { var properties = [String: AnyObject]() properties["type"] = postType.rawValue as AnyObject? properties["filter"] = currentPostListFilter().title as AnyObject? if let dotComID = blog.dotComID { properties[WPAppAnalyticsKeyBlogID] = dotComID } return properties } }
gpl-2.0
9b3e9c06e16491e7cc8352a7d3ba3d92
32.306878
151
0.648133
5.088925
false
false
false
false
kickstarter/ios-oss
Library/String+SimpleHTMLTests.swift
1
4139
@testable import Library import XCTest final class StringSimpleHTMLTests: XCTestCase { func testHtmlParsing() { let font = UIFont.systemFont(ofSize: 12.0) let html = "<b>Hello</b> <i>Brandon</i>, how are you?" let stripped = "Hello Brandon, how are you?" guard let string = html.simpleHtmlAttributedString(font: font) else { XCTAssert(false, "Couldn't parse HTML string.") return } XCTAssertEqual(string.string, stripped) } func testHtmlWithAllFontsSpecified() { let font = UIFont.systemFont(ofSize: 12.0) let bold = UIFont.boldSystemFont(ofSize: 14.0) let italic = UIFont.italicSystemFont(ofSize: 16.0) let html = "<b>Hello</b> <i>Brandon</i>, how are you?" guard let string = html.simpleHtmlAttributedString(font: font, bold: bold, italic: italic) else { XCTAssert(false, "Couldn't parse HTML string") return } let extractedBold = string.attribute(NSAttributedString.Key.font, at: 1, effectiveRange: nil) as? UIFont if let testBold = extractedBold { XCTAssertEqual(testBold.pointSize, bold.pointSize) XCTAssert(testBold.fontDescriptor.symbolicTraits.contains(.traitBold)) } else { XCTAssertTrue(false, "Couldn't find font in attributed string") } let extractedItalic = string.attribute(NSAttributedString.Key.font, at: 7, effectiveRange: nil) as? UIFont if let testItalic = extractedItalic { XCTAssertEqual(testItalic.pointSize, italic.pointSize) XCTAssert(testItalic.fontDescriptor.symbolicTraits.contains(.traitItalic)) } else { XCTAssertTrue(false, "Couldn't find font in attributed string") } let extractedBase = string.attribute(NSAttributedString.Key.font, at: 16, effectiveRange: nil) as? UIFont if let testBase = extractedBase { XCTAssertEqual(testBase.pointSize, font.pointSize) XCTAssertFalse(testBase.fontDescriptor.symbolicTraits.contains(.traitBold)) XCTAssertFalse(testBase.fontDescriptor.symbolicTraits.contains(.traitItalic)) } else { XCTAssertTrue(false, "Couldn't find font in attributed string") } } func testHtmlWithFallbackFonts() { let font = UIFont.systemFont(ofSize: 12.0) let html = "<b>Hello</b> <i>Brandon</i>, how are you?" let string = html.simpleHtmlAttributedString(font: font) if string == nil { XCTAssert(false, "Couldn't parse HTML string") } let extractedBold = string?.attribute(NSAttributedString.Key.font, at: 1, effectiveRange: nil) as? UIFont if let testBold = extractedBold { XCTAssertEqual(testBold.pointSize, font.pointSize) XCTAssert(testBold.fontDescriptor.symbolicTraits.contains(.traitBold)) } else { XCTAssert(false, "Couldn't find font in attributed string") } let extractedItalic = string?.attribute( NSAttributedString.Key.font, at: 7, effectiveRange: nil ) as? UIFont if let testItalic = extractedItalic { XCTAssertEqual(testItalic.pointSize, font.pointSize) XCTAssert(testItalic.fontDescriptor.symbolicTraits.contains(.traitItalic)) } else { XCTAssertTrue(false, "Couldn't find font in attributed string") } let extractedBase = string?.attribute( NSAttributedString.Key.font, at: 16, effectiveRange: nil ) as? UIFont if let testBase = extractedBase { XCTAssertEqual(testBase.pointSize, font.pointSize) XCTAssertFalse(testBase.fontDescriptor.symbolicTraits.contains(.traitBold)) XCTAssertFalse(testBase.fontDescriptor.symbolicTraits.contains(.traitItalic)) } else { XCTAssertTrue(false, "Couldn't find font in attributed string") } } func test_htmlStripped_WithSimpleHtml() { let html = "<b>Hello</b> <i>Brandon</i>, how are you?" XCTAssertEqual("Hello Brandon, how are you?", html.htmlStripped()) } func test_htmlStripped_WithParagraphTags() { let html = "<b>Hello</b> <i>Brandon</i>,<p>how are you?</p>" XCTAssertEqual("Hello Brandon,\nhow are you?", html.htmlStripped()) XCTAssertEqual("Hello Brandon,\nhow are you?\n", html.htmlStripped(trimWhitespace: false)) } }
apache-2.0
3786d89c4d467aa6d4600685f5edf765
36.288288
110
0.702827
4.253854
false
true
false
false
Chaosspeeder/YourGoals
YourGoals/UI/Views/Actionable Table Cells/ActionableSwipeButtonCreator.swift
1
4087
// // ActionableBehaviorButton.swift // YourGoals // // Created by André Claaßen on 10.11.17. // Copyright © 2017 André Claaßen. All rights reserved. // import Foundation import MGSwipeTableCell extension MGSwipeButton { convenience init(properties:(title: String, titleColor: UIColor?, backgroundColor: UIColor)) { self.init(title: properties.title, backgroundColor: properties.backgroundColor) if let titleColor = properties.titleColor { self.setTitleColor(titleColor, for: .normal) } } } /// this class helps to create swipe buttons with the correct colors and titles depending on the state of the wanted behavior class ActionableSwipeButtonCreator { /// create a swipe buttion, if the data source provides a behavior for the swipe button /// /// - Parameters: /// - date: for this date /// - actionable: for this actionable (a task or a habit) /// - behavior: a behaviour, like commitment, active or progressing /// - dataSource: a actionable data source ( list of ordered tasks or habits) /// - Returns: a swipe button or nil, if the data source is not providing an behaviour func create(date: Date, item: ActionableItem, behavior:ActionableBehavior, dataSource: ActionableDataSource) -> MGSwipeButton? { guard let switchProtocol = dataSource.switchProtocol(forBehavior: behavior) else { return nil } let properties = buttonProperties(behaviorIsActive: switchProtocol.isBehaviorActive(forItem: item, atDate: date), behavior: behavior) let button = MGSwipeButton(properties: properties) return button } /// create swipe buttons for the given behaviors, if the data source provide a behavior for the switch button /// /// - Parameters: /// - date: for this date /// - actionable: for this actionable (a task or a habit) /// - behaviors: an array of behaviors /// - dataSource: a actionable data source ( list of ordered tasks or habits) /// - Returns: an arra of swipe buttons func createSwipeButtons(forDate date: Date, item: ActionableItem, forBehaviors behaviors:[ActionableBehavior], dataSource: ActionableDataSource?) -> [MGSwipeButton] { guard let dataSource = dataSource else { NSLog("no datasource configured") return [] } var buttons = [MGSwipeButton]() for behavior in behaviors { if let button = create(date: date, item: item, behavior: behavior, dataSource: dataSource ) { buttons.append(button) } } return buttons } /// creates a tuple with properties for coloring and give the button a tile /// /// - Parameters: /// - behaviorIsActive: true, if the buttion is active for the wanted behavior (progressing committed or active state) /// - behavior: the behavior /// - Returns: a tuple with properties to create a MGSwipeButton func buttonProperties(behaviorIsActive:Bool, behavior: ActionableBehavior) -> (title: String, titleColor: UIColor?, backgroundColor: UIColor) { switch behavior { case .commitment: if behaviorIsActive { return ("Someday", UIColor.black, UIColor.gray) } else { return ("Today", UIColor.black, UIColor.yellow) } case .progress: if behaviorIsActive { return ("Stop", nil, UIColor.red) } else { return ("Start", nil, UIColor.green) } case .state: if behaviorIsActive { return ("Done", nil, UIColor.blue) } else { return ("Open", nil, UIColor.blue) } case .tomorrow: if behaviorIsActive { return (" ", UIColor.black, UIColor.white) } else { return ("Tomorrow", UIColor.black, UIColor.blue) } } } }
lgpl-3.0
dd7ad502932a48562db2a5febdc385cf
37.866667
170
0.61578
4.934704
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Views/AARecordAudioController.swift
2
11607
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit import AVFoundation class AARecordAudioController: UIViewController,UIViewControllerTransitioningDelegate { //////////////////////////////// var buttonClose : UIButton! var recorderView : UIView! var timerLabel : UILabel! var chatController : ConversationViewController! var startRecButton : UIButton! var stopRecButton : UIButton! var playRecButton : UIButton! var sendRecord : UIButton! var cleanRecord : UIButton! // var filePath : String! var fileDuration : NSTimeInterval! var recorded : Bool! = false private let audioRecorder: AAAudioRecorder! = AAAudioRecorder() private var audioPlayer: AAModernConversationAudioPlayer! var meterTimer:NSTimer! var soundFileURL:NSURL? //////////////////////////////// required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.commonInit() } override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.commonInit() } func commonInit() { self.modalPresentationStyle = .Custom self.transitioningDelegate = self } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } // ---- UIViewControllerTransitioningDelegate methods func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { if presented == self { return AACustomPresentationController(presentedViewController: presented, presentingViewController: presenting) } return nil } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { if presented == self { return AACustomPresentationAnimationController(isPresenting: true) } else { return nil } } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { if dismissed == self { return AACustomPresentationAnimationController(isPresenting: false) } else { return nil } } override func loadView() { super.loadView() self.recorderView = UIView() self.recorderView.frame = CGRectMake(self.view.frame.width/2 - 120, self.view.frame.height/2 - 80, 240, 160) self.recorderView.backgroundColor = UIColor.whiteColor() self.recorderView.layer.cornerRadius = 10 self.recorderView.layer.masksToBounds = true self.view.addSubview(self.recorderView) self.buttonClose = UIButton(type: UIButtonType.System) self.buttonClose.addTarget(self, action: #selector(AARecordAudioController.closeController), forControlEvents: UIControlEvents.TouchUpInside) self.buttonClose.tintColor = UIColor.whiteColor() self.buttonClose.setImage(UIImage.bundled("aa_closerecordbutton"), forState: UIControlState.Normal) self.buttonClose.frame = CGRectMake(205, 5, 25, 25) self.recorderView.addSubview(self.buttonClose) let separatorView = UIView() separatorView.frame = CGRectMake(0, 80, 240, 0.5) separatorView.backgroundColor = UIColor.grayColor() self.recorderView.addSubview(separatorView) self.timerLabel = UILabel() self.timerLabel.text = "00:00" self.timerLabel.font = UIFont(name: "HelveticaNeue-Medium", size: 17)! self.timerLabel.textColor = ActorSDK.sharedActor().style.vcHintColor self.timerLabel.frame = CGRectMake(70, 5, 100, 40) self.timerLabel.textAlignment = .Center self.timerLabel.backgroundColor = UIColor.clearColor() self.recorderView.addSubview(self.timerLabel) self.startRecButton = UIButton(type: UIButtonType.System) self.startRecButton.tintColor = UIColor.redColor() self.startRecButton.setImage(UIImage.bundled("aa_startrecordbutton"), forState: UIControlState.Normal) self.startRecButton.addTarget(self, action: #selector(AARecordAudioController.startRec), forControlEvents: UIControlEvents.TouchUpInside) self.startRecButton.frame = CGRectMake(100, 110, 40, 40) self.recorderView.addSubview(self.startRecButton) self.stopRecButton = UIButton(type: UIButtonType.System) self.stopRecButton.tintColor = UIColor.redColor() self.stopRecButton.setImage(UIImage.bundled("aa_pauserecordbutton"), forState: UIControlState.Normal) self.stopRecButton.addTarget(self, action: #selector(AARecordAudioController.stopRec), forControlEvents: UIControlEvents.TouchUpInside) self.stopRecButton.frame = CGRectMake(100, 110, 40, 40) self.recorderView.addSubview(self.stopRecButton) self.stopRecButton.hidden = true self.playRecButton = UIButton(type: UIButtonType.System) self.playRecButton.tintColor = UIColor.greenColor() self.playRecButton.setImage(UIImage.bundled("aa_playrecordbutton"), forState: UIControlState.Normal) self.playRecButton.addTarget(self, action: #selector(AARecordAudioController.play), forControlEvents: UIControlEvents.TouchUpInside) self.playRecButton.frame = CGRectMake(100, 110, 40, 40) self.recorderView.addSubview(self.playRecButton) self.playRecButton.hidden = true self.sendRecord = UIButton(type: UIButtonType.System) self.sendRecord.tintColor = UIColor.greenColor() self.sendRecord.setImage(UIImage.bundled("aa_sendrecord"), forState: UIControlState.Normal) self.sendRecord.addTarget(self, action: #selector(AARecordAudioController.sendRecordMessage), forControlEvents: UIControlEvents.TouchUpInside) self.sendRecord.frame = CGRectMake(190, 115, 40, 40) self.sendRecord.enabled = false self.recorderView.addSubview(self.sendRecord) self.cleanRecord = UIButton(type: UIButtonType.System) self.cleanRecord.tintColor = UIColor.redColor() self.cleanRecord.setImage(UIImage.bundled("aa_deleterecord"), forState: UIControlState.Normal) self.cleanRecord.addTarget(self, action: #selector(AARecordAudioController.sendRecordMessage), forControlEvents: UIControlEvents.TouchUpInside) self.cleanRecord.frame = CGRectMake(10, 120, 30, 30) self.cleanRecord.enabled = false self.recorderView.addSubview(self.cleanRecord) //cx_deleterecord } override func viewDidLoad() { super.viewDidLoad() } // actions func closeController() { self.audioRecorder.cancel() self.dismissViewControllerAnimated(true, completion: nil) } func startRec() { //log.debug("recording. recorder nil") playRecButton.hidden = true stopRecButton.hidden = false startRecButton.hidden = true startTimer() recordWithPermission() } func stopRec() { //log.debug("stop") meterTimer.invalidate() playRecButton.hidden = false startRecButton.hidden = true stopRecButton.hidden = true audioRecorder.finish({ (path: String!, duration: NSTimeInterval) -> Void in if (nil == path) { print("onAudioRecordingFinished: empty path") return } self.filePath = path self.fileDuration = duration dispatch_async(dispatch_get_main_queue(), { () -> Void in self.sendRecord.enabled = true self.cleanRecord.enabled = true }) }) } func stopAudioRecording() { if (audioRecorder != nil) { audioRecorder.delegate = nil audioRecorder.cancel() } } func play() { self.audioPlayer = AAModernConversationAudioPlayer(filePath:self.filePath) self.audioPlayer.play(0) playRecButton.hidden = true startRecButton.hidden = true stopRecButton.hidden = false } // setup record func recordWithPermission() { let session:AVAudioSession = AVAudioSession.sharedInstance() // ios 8 and later if (session.respondsToSelector(#selector(AVAudioSession.requestRecordPermission(_:)))) { AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in if granted { print("Permission to record granted") self.setSessionPlayAndRecord() self.meterTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target:self, selector:#selector(AARecordAudioController.updateAudioMeter(_:)), userInfo:nil, repeats:true) } else { print("Permission to record not granted") } }) } else { print("requestRecordPermission unrecognized") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func startTimer() { self.meterTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target:self, selector:#selector(AARecordAudioController.updateAudioMeter(_:)), userInfo:nil, repeats:true) } func updateAudioMeter(timer:NSTimer) { if (self.audioRecorder != nil) { let dur = self.audioRecorder.currentDuration() let min = Int(dur / 60) let sec = Int(dur % 60) let s = String(format: "%02d:%02d", min, sec) self.timerLabel.text = s } } func setSessionPlayback() { let session:AVAudioSession = AVAudioSession.sharedInstance() do { try! session.setCategory(AVAudioSessionCategoryPlayback) } do { try! session.setActive(true) } } func setSessionPlayAndRecord() { let session:AVAudioSession = AVAudioSession.sharedInstance() do { try! session.setCategory(AVAudioSessionCategoryPlayAndRecord) } do { try! session.setActive(true) } self.audioRecorder.start() } func sendRecordMessage() { self.dismissViewControllerAnimated(true, completion: nil) //self.chatController.sendVoiceMessage(self.filePath, duration: self.fileDuration) } }
agpl-3.0
0e5511873c68386491e69a0a8160c467
32.741279
219
0.615921
5.358726
false
false
false
false
vakoc/particle-swift-cli
Sources/Commands.swift
1
4807
// This source file is part of the vakoc.com open source project(s) // // Copyright © 2016, 2017 Mark Vakoc. All rights reserved. // Licensed under Apache License v2.0 // // See http://www.vakoc.com/LICENSE.txt for license information import Foundation enum CommandName: String { case help, createToken, showTokens, devices, deviceDetail, variables, claimDevice, transferDevice, createClaimCode, callFunction, unclaimDevice, showWebhooks, getWebhook, createWebhook, deleteWebhook, events, products, productTeamMembers, productInviteTeamMember, productRemoveTeamMember } enum ArgumentName: String { case verbose, username, password, oauthclient, oauthsecret, deviceid, deviceids, markdown, variables, detail, accessToken, imei, iccid, json, functionName, param, productId, webhookId, event, url, requestType, jsonFile, expires } struct ArgumentOptions: OptionSet { let rawValue: Int static let required = ArgumentOptions(rawValue: 1 << 0) static let hasValue = ArgumentOptions(rawValue: 1 << 1) } struct Argument { let name: ArgumentName let helpText: String let options: ArgumentOptions } extension Argument: Equatable {} func ==(lhs: Argument, rhs: Argument) -> Bool { return lhs.name == rhs.name && lhs.options == rhs.options } extension Argument: Hashable { var hashValue: Int { return self.name.hashValue + self.options.rawValue } } typealias RunnableFunction = (_ arguments: [Argument : String], _ extras: [String], _ callback: @escaping (CommandResult) -> Void ) -> Void protocol Runnable { var name: CommandName { get } var summary: String { get } var subHelp: String? { get } func helpText(_ markdown: Bool) -> String var arguments: [Argument] { get } var run: RunnableFunction { get } } extension Runnable { func helpText(_ markdown: Bool) -> String { var message = "" if !markdown { message += "\(self.name): \(self.summary)\n" if !self.arguments.isEmpty{ message += "\nArguments: \n" for arg in arguments { message += "\t--\(arg.name)" if arg.options.contains(.hasValue) { message += " <value>" } message += " : \(arg.helpText)" if arg.options.contains(.required) { message += " (required)" } message += "\n" } } message += "\nGlobal Arguments: \n" for argument in globalArguments { message += "\t--\(argument.name.rawValue)" if argument.options.contains([.hasValue]) { message += " <value>" } message += " : \(argument.helpText)\n" } if let subHelp = self.subHelp { message += "\n\(subHelp)\n" } } else { message += "### \(self.name)\n" message += "\(self.summary)\n" if !arguments.isEmpty { message += "\n##### Arguments\n" message += "Name | Description | Uses Value | Required\n" message += "------------- | ----------- | ---------- | --------\n" for arg in arguments { message += "\(arg.name) | \(arg.helpText) | \(arg.options.contains(.hasValue)) | \(arg.options.contains(.required))\n" } message += "\n\n" message += "\n##### Global Arguments\n" message += "Name | Description | Uses Value | Required\n" message += "------------- | ----------- | ---------- | --------\n" for arg in globalArguments { message += "\(arg.name) | \(arg.helpText) | \(arg.options.contains(.hasValue)) | \(arg.options.contains(.required))\n" } message += "\n\n" } if let subHelp = self.subHelp { message += subHelp + "\n\n" } message += "----\n\n" } return message } } enum CommandResult { case success(string: String, json: Any), failure(Error) } /// Representation of a command that can be run from the shell struct Command: Runnable { var name: CommandName var summary: String var arguments: [Argument] var subHelp: String? = nil var run: RunnableFunction }
apache-2.0
b60357f399023fecd13271dbcec3f7c6
24.700535
140
0.509363
4.577143
false
false
false
false
J-Mendes/Weather
Weather/Weather/Core Layer/Data Model/Wind.swift
1
803
// // Wind.swift // Weather // // Created by Jorge Mendes on 04/07/17. // Copyright © 2017 Jorge Mendes. All rights reserved. // import Foundation struct Wind { internal var chill: String! internal var direction: String! internal var speed: String! init() { self.chill = "" self.direction = "" self.speed = "" } init(dictionary: [String: Any]) { self.init() if let chill: String = dictionary["chill"] as? String { self.chill = chill } if let direction: String = dictionary["direction"] as? String { self.direction = direction } if let speed: String = dictionary["speed"] as? String { self.speed = speed } } }
gpl-3.0
eb290b699aa6ad06593d9a4c32f58bc0
19.564103
71
0.526185
4.28877
false
false
false
false
kwizzad/kwizzad-ios
Source/OpenTransaction.swift
1
2391
// // OpenTransaction.swift // KwizzadSDK // // Created by Sandro Manke on 20.10.16. // Copyright © 2016 Kwizzad. All rights reserved. // import Foundation /// Holds information about a reward that the user can earn, has earned, or has not earned /// because there was an issue. /// /// On requesting an ad and on ad dismissal, you get an information about if/how the user got /// pending transactions for rewards. You can then display this information to your user—either /// summarized or with a dialog for each single pending reward. As soon as your app confirms a /// transaction, its reward will be paid out. /// /// Transactions work like an inbox, so you might transactions again (asynchronously) until your /// app confirms them. @objc(KwizzadOpenTransaction) open class OpenTransaction: NSObject, FromDict { public let adId : String? public let transactionId : String? public let conversionTimestamp : String? public let reward : Reward? public var state : State = .ACTIVE public enum State { /// The reward will be payed out on confirmation. case ACTIVE /// The transaction is being confirmed by the client. case SENDING /// The transaction has been confirmed. case SENT /// There was an error confirming the transaction. case ERROR } public required init(_ map: [String : Any]) { adId = map["adId"] as? String if let tid = map["transactionId"] as? NSNumber { transactionId = tid.stringValue } else { transactionId = nil } conversionTimestamp = map["conversionTimestamp"] as? String if let rewardMap = map["reward"] as? [String:Any] { reward = Reward(rewardMap) } else { reward = nil } } override open var hash: Int { return (transactionId!+adId!).hashValue } open override var description: String { guard let tid = transactionId, let aid = adId else { return "OpenTransaction" } return "OpenTransaction \(tid) for ad \(aid)" } @nonobjc public static func ==(lhs: OpenTransaction, rhs: OpenTransaction) -> Bool { return lhs.adId == rhs.adId && lhs.transactionId == rhs.transactionId } }
mit
525dcc5e2323f2a6841c1fb73cb6c46f
29.227848
96
0.619765
4.574713
false
false
false
false
caodong1991/SwiftStudyNote
Swift.playground/Pages/20 - Extensions.xcplaygroundpage/Contents.swift
1
5265
import Foundation // 扩展 /* 扩展可以给一个现有的类、结构体、枚举,还有协议添加新的功能。 它还拥有不需要访问被扩展类型源代码就能完成扩展的能力,即逆向建模。 swift扩展没有名字,它可以: * 添加计算型实例和计算型类属性 * 定义实例方法和类方法 * 提供新的构造器 * 定义下标 * 定义和使用新的嵌套类型 * 使已经存在的类型遵循一个协议 扩展可以给一个类型添加新的功能,但是不能重写已经存在的功能。 */ // 扩展的语法 /* 使用extension关键字声明扩展 extension SomeType { // 在这里给SomeType添加新的功能 } 扩展可以扩充一个现有的类型,给它添加一个或多个协议。协议名称的写法和类或者结构体一样。 extension SomeType: SomeProtocol, AnotherProtocol { // 协议所需要的实现写在这里 } 扩展可以使用在现有的泛型类型上。 还可以使用扩展给泛型类型有条件的添加功能。 对一个现有的类型,如果定义了一个扩展来添加新的功能,那么这个类型的所有实例都可以使用这个新功能,包括那些在扩展定义之前就存在的实例。 */ // 计算属性 /* 扩展可以给现有的类型添加计算型属性和计算型类属性。 扩展不能添加存储属性,或向现有的属性添加属性观察者。 */ extension Double { var km: Double { return self * 1_000.0 } var m: Double { return self } var cm: Double { return self / 100.0 } var mm: Double { return self / 1_000.0} var ft: Double { return self / 3.28084} } let oneInch = 25.4.mm print("One inch is \(oneInch) meters") let threeFeet = 3.ft print("Three feet is \(threeFeet) meters") let aMarathon = 42.km + 195.m print("A marathon is \(aMarathon) meters long") // 构造器 /* 扩展可以给现有的类型添加新的构造器。 使你可以把自定义类型作为参数来供其他类型的构造器使用,或者在类型的原始实现上添加额外的构造选项。 如果使用扩展给一个值类型添加构造器只是用于给所有的存储属性提供一个默认值,并且没有定义任何自定义构造器,那么可以在该值类型扩展的构造器中使用默认构造器和成员构造器。 如果把构造器写到了值类型的原始实现中,那么就不属于在扩展中添加构造器。 如果使用扩展给另一个模块中定义的结构体添加构造器,那么新的构造器直接定义模块中使用一个构造器之前,不能访问self。 */ struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } struct Rect { var origin = Point() var size = Size() } let defaultRect = Rect() let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0)) /* 如果通过扩展提供一个新的构造器,就要确保每个通过该构造器创建的实例都是初始化完整的。 */ extension Rect { init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) // 方法 /* 扩展可以给现有类型添加新的实例方法和类方法 */ extension Int { func repetitions(task:() -> Void) { for _ in 0..<self { task() } } } 3.repetitions { print("Hello!") } // 可变实例方法 /* 通过扩展添加的实例方法同样也可以修改(或 mutating)实例本身。 结构体和枚举的方法,若是可以修改self或者它自己的属性,则必须将这个实例方法标记mutating,就像是改变了方法的原始实现。 */ extension Int { mutating func square() { self = self * self } } var someInt = 3 someInt.square() // 下标 /* 扩展可以给现有的类型添加新的下标。 */ extension Int { subscript(digitIndex: Int) -> Int { var decimalBase = 1 for _ in 0..<digitIndex { decimalBase += 10 } return (self / decimalBase) % 10 } } 746381295[0] 746381295[1] 746381295[2] 746381295[8] // 嵌套类型 /* 扩展可以给现有的类、结构体还有枚举添加新的嵌套类型。 */ extension Int { enum Kind { case negative, zero, positive } var kind: Kind { switch self { case 0: return .zero case let x where x > 0: return .positive default: return .negative } } } /* 注意 number.kind 已经被认为是 Int.Kind 类型。所以,在 switch 语句中所有的 Int.Kind case 分支可以被缩写,就像使用 .negative 替代 Int.Kind.negative. */ func printIntegerKinds(_ numbers: [Int]) { for number in numbers { switch number.kind { case .negative: print("- ", terminator: "") case .zero: print("0 ", terminator: "") case .positive: print("+ ", terminator: "") } } } printIntegerKinds([3, 19, -27, 0, -6, 0, 7])
mit
356f5927e83158db75272cf67b841116
18.516667
112
0.632792
2.710648
false
false
false
false
mgadda/zig
Sources/MessagePackEncoder/MessagePackUnkeyedDecodingContainer.swift
1
7011
// // MessagePackUnkeyedDecodingContainer.swift // MessagePackEncoder // // Created by Matt Gadda on 10/9/17. // import Foundation import MessagePack class MessagePackUnkeyedDecodingContainer : UnkeyedDecodingContainer { var codingPath: [CodingKey] var currentIndex: Int var container: [MessagePackValue] var count: Int? { return container.count } var isAtEnd: Bool { return self.currentIndex >= self.count! } private var decoder: _MessagePackDecoder init(decoder: _MessagePackDecoder, container: [MessagePackValue]) { self.decoder = decoder self.container = container self.codingPath = decoder.codingPath self.currentIndex = 0 } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey { guard !self.isAtEnd else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Nested keyed container is unavailable because isAtEnd was unexpectedly true.")) } guard case let .map(mapContainer) = self.container[self.currentIndex] else { throw DecodingError.typeMismatch([MessagePackValue : MessagePackValue].self, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Container value at \(self.currentIndex) is not a MessagePackValue.map")) } self.currentIndex += 1 let decodingContainer = MessagePackKeyedDecodingContainer<NestedKey>(decoder: self.decoder, container: mapContainer) return KeyedDecodingContainer(decodingContainer) } func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer { guard !self.isAtEnd else { throw DecodingError.valueNotFound(UnkeyedDecodingContainer.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "Nested unkeyed container unavailable because isAtEnd was unexpectedly true.")) } guard case let .array(arrayContainer) = self.container[self.currentIndex] else { throw DecodingError.typeMismatch([MessagePackValue].self, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Container value at \(self.currentIndex) is not a MessagePackValue.array")) } self.currentIndex += 1 return MessagePackUnkeyedDecodingContainer(decoder: self.decoder, container: arrayContainer) } func superDecoder() throws -> Decoder { self.decoder.codingPath.append(MessagePackKey(index: self.currentIndex)) defer { self.decoder.codingPath.removeLast() } guard !self.isAtEnd else { throw DecodingError.valueNotFound(Decoder.self, DecodingError.Context(codingPath: self.codingPath, debugDescription: "superDecoder unavailable because container isAtEnd.")) } let value = self.container[self.currentIndex] self.currentIndex += 1 return _MessagePackDecoder(container: value, at: self.decoder.codingPath) } /// Decode non-standard types (i.e. your own types) func decode<T>(_ type: T.Type) throws -> T where T : Decodable { try expectNotAtEnd(type) guard let value = try decoder.unbox(self.container[self.currentIndex], type: type) else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath, debugDescription: "Expected \(type) but found nil")) } self.currentIndex += 1 return value } func decodeNil() throws -> Bool { guard !self.isAtEnd else { throw DecodingError.valueNotFound(Any?.self, DecodingError.Context(codingPath: self.decoder.codingPath + [MessagePackKey(index: self.currentIndex)], debugDescription: "Cannot decode Nil. Unkeyed container isAtEnd.")) } self.currentIndex += 1 return self.container[self.currentIndex].isNil } func expectNotAtEnd(_ type: Any.Type) throws { guard !self.isAtEnd else { throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: self.decoder.codingPath + [MessagePackKey(index: self.currentIndex)], debugDescription: "Expected to not be at end of unkeyed container.")) } } func decode(_ type: Bool.Type) throws -> Bool { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: Int.Type) throws -> Int { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: Int8.Type) throws -> Int8 { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: Int16.Type) throws -> Int16 { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: Int32.Type) throws -> Int32 { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: Int64.Type) throws -> Int64 { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: UInt.Type) throws -> UInt { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: UInt8.Type) throws -> UInt8 { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: UInt16.Type) throws -> UInt16 { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: UInt32.Type) throws -> UInt32 { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: UInt64.Type) throws -> UInt64 { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: Float.Type) throws -> Float { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: Double.Type) throws -> Double { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } func decode(_ type: String.Type) throws -> String { try expectNotAtEnd(type) let value = try decoder.unbox(self.container[self.currentIndex], type: type) self.currentIndex += 1 return value } }
mit
793d8d92bab28e5e66be4a1a5a5409f6
36.095238
233
0.723435
4.376404
false
false
false
false
apple/swift-syntax
Sources/_SwiftSyntaxTestSupport/SyntaxProtocol+Initializer.swift
1
6530
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 SwiftBasicFormat @_spi(RawSyntax) import SwiftSyntax import SwiftSyntaxBuilder private class InitializerExprFormat: BasicFormat { override var indentation: TriviaPiece { return .spaces(indentationLevel * 2) } private func formatChildrenSeparatedByNewline<SyntaxType: SyntaxProtocol>(children: SyntaxChildren, elementType: SyntaxType.Type) -> [SyntaxType] { indentationLevel += 1 var formattedChildren = children.map { self.visit($0).as(SyntaxType.self)! } formattedChildren = formattedChildren.map { if $0.leadingTrivia?.first?.isNewline == true { return $0 } else { return $0.withLeadingTrivia(indentedNewline + ($0.leadingTrivia ?? [])) } } indentationLevel -= 1 if !formattedChildren.isEmpty { formattedChildren[formattedChildren.count - 1] = formattedChildren[formattedChildren.count - 1].withTrailingTrivia(indentedNewline) } return formattedChildren } override func visit(_ node: TupleExprElementListSyntax) -> TupleExprElementListSyntax { let children = node.children(viewMode: .all) // If the function only takes a single argument, display it on the same line if children.count > 1 { return TupleExprElementListSyntax(formatChildrenSeparatedByNewline(children: children, elementType: TupleExprElementSyntax.self)) } else { return super.visit(node) } } override func visit(_ node: ArrayElementListSyntax) -> ArrayElementListSyntax { let children = node.children(viewMode: .all) // Short array literals are presented on one line, list each element on a different line. if node.description.count > 30 { return ArrayElementListSyntax(formatChildrenSeparatedByNewline(children: children, elementType: ArrayElementSyntax.self)) } else { return super.visit(node) } } } private extension TriviaPiece { var initializerExpr: ExprSyntaxProtocol { let (label, value) = Mirror(reflecting: self).children.first! switch value { case let value as String: return FunctionCallExpr(callee: ".\(label!)") { TupleExprElement(expression: StringLiteralExpr(content: value)) } case let value as Int: return FunctionCallExpr(callee: ".\(label!)") { TupleExprElement(expression: IntegerLiteralExpr(value)) } default: fatalError("Unknown associated value type") } } } private extension Trivia { var initializerExpr: ExprSyntaxProtocol { if pieces.count == 1 { switch pieces.first { case .spaces(1): return MemberAccessExpr(name: "space") case .newlines(1): return MemberAccessExpr(name: "newline") default: break } } return ArrayExpr() { for piece in pieces { ArrayElement(expression: piece.initializerExpr) } } } } extension SyntaxProtocol { /// Returns a Swift expression that, when parsed, constructs this syntax node /// (or at least an expression that's very close to constructing this node, the addition of a few manual upcast by hand is still needed). /// The intended use case for this is to print a syntax tree and create a substructure assertion from the generated expression. public var debugInitCall: String { return self.debugInitCallExpr.formatted(using: InitializerExprFormat()).description } private var debugInitCallExpr: ExprSyntaxProtocol { let mirror = Mirror(reflecting: self) if self.isCollection { return FunctionCallExpr(callee: "\(type(of: self))") { TupleExprElement( expression: ArrayExpr() { for child in mirror.children { let value = child.value as! SyntaxProtocol? ArrayElement(expression: value?.debugInitCallExpr ?? NilLiteralExpr()) } } ) } } else if let token = Syntax(self).as(TokenSyntax.self) { let tokenKind = token.tokenKind let tokenInitializerName: String let requiresExplicitText: Bool if tokenKind.isKeyword || tokenKind == .eof { tokenInitializerName = String(describing: tokenKind) requiresExplicitText = false } else if tokenKind.decomposeToRaw().rawKind.defaultText != nil { tokenInitializerName = "\(String(describing: tokenKind))Token" requiresExplicitText = false } else { let tokenKindStr = String(describing: tokenKind) tokenInitializerName = String(tokenKindStr[..<tokenKindStr.firstIndex(of: "(")!]) requiresExplicitText = true } return FunctionCallExpr(callee: ".\(tokenInitializerName)") { if requiresExplicitText { TupleExprElement( expression: StringLiteralExpr(content: token.text) ) } if !token.leadingTrivia.isEmpty { TupleExprElement( label: .identifier("leadingTrivia"), colon: .colon, expression: token.leadingTrivia.initializerExpr ) } if !token.trailingTrivia.isEmpty { TupleExprElement( label: .identifier("trailingTrivia"), colon: .colon, expression: token.trailingTrivia.initializerExpr ) } if token.presence != .present { TupleExprElement( label: .identifier("presence"), colon: .colon, expression: MemberAccessExpr(name: "missing") ) } } } else { return FunctionCallExpr(callee: "\(type(of: self))") { for child in mirror.children { let label = child.label! let value = child.value as! SyntaxProtocol? let isUnexpected = label.hasPrefix("unexpected") if !isUnexpected || value != nil { TupleExprElement( label: isUnexpected ? nil : .identifier(label), colon: isUnexpected ? nil : .colon, expression: value?.debugInitCallExpr ?? NilLiteralExpr() ) } } } } } }
apache-2.0
614bbef4d3e1bb299bc3b03f333381b7
35.480447
149
0.640429
4.819188
false
false
false
false
groue/GRDB.swift
GRDB/Core/DatabaseRegion.swift
1
14846
/// An observable region of the database. /// /// A `DatabaseRegion` is the union of any number of "table regions", which can /// cover a full table, or the combination of columns and rows identified by /// their rowids: /// /// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 | /// |-------| |-------| |-------| |-------| |-------| /// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | | /// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | | /// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | | /// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | | /// /// It is dedicated to help ``TransactionObserver`` types detect impactful /// database changes. /// /// You get `DatabaseRegion` instances from a ``DatabaseRegionConvertible`` /// value, a prepared ``Statement``, or from the initializers described below. /// /// ## Topics /// /// ### Creating Regions /// /// - ``fullDatabase-3ir3p`` /// - ``init()`` /// /// ### Instance Properties /// /// - ``isEmpty`` /// - ``isFullDatabase`` /// /// ### Combining Regions /// /// - ``formUnion(_:)`` /// - ``union(_:)`` /// /// ### Detecting Database Changes /// /// Use those methods from ``TransactionObserver`` methods. /// /// - ``isModified(byEventsOfKind:)`` /// - ``isModified(by:)`` public struct DatabaseRegion { private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]? private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) { self.tableRegions = tableRegions } /// Returns whether the region is empty. public var isEmpty: Bool { guard let tableRegions else { // full database return false } return tableRegions.isEmpty } /// Returns whether the region covers the full database. public var isFullDatabase: Bool { tableRegions == nil } /// The region that covers the full database. public static let fullDatabase = DatabaseRegion(tableRegions: nil) /// The empty database region. public init() { self.init(tableRegions: [:]) } /// Creates a region that spans all rows and columns of a database table. /// /// - parameter table: A table name. init(table: String) { let table = CaseInsensitiveIdentifier(rawValue: table) self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)]) } /// Full columns in a table: (some columns in a table) × (all rows) init(table: String, columns: Set<String>) { let table = CaseInsensitiveIdentifier(rawValue: table) let columns = Set(columns.map(CaseInsensitiveIdentifier.init)) self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)]) } /// Full rows in a table: (all columns in a table) × (some rows) init(table: String, rowIds: Set<Int64>) { let table = CaseInsensitiveIdentifier(rawValue: table) self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)]) } /// Returns the intersection of this region and the given one. /// /// This method is not public because there is no known public use case for /// this intersection. It is currently only used as support for /// the isModified(byEventsOfKind:) method. func intersection(_ other: DatabaseRegion) -> DatabaseRegion { guard let tableRegions else { return other } guard let otherTableRegions = other.tableRegions else { return self } var tableRegionsIntersection: [CaseInsensitiveIdentifier: TableRegion] = [:] for (table, tableRegion) in tableRegions { guard let otherTableRegion = otherTableRegions .first(where: { (otherTable, _) in otherTable == table })? .value else { continue } let tableRegionIntersection = tableRegion.intersection(otherTableRegion) guard !tableRegionIntersection.isEmpty else { continue } tableRegionsIntersection[table] = tableRegionIntersection } return DatabaseRegion(tableRegions: tableRegionsIntersection) } /// Only keeps those rowIds in the given table func tableIntersection(_ table: String, rowIds: Set<Int64>) -> DatabaseRegion { guard var tableRegions else { return DatabaseRegion(table: table, rowIds: rowIds) } let table = CaseInsensitiveIdentifier(rawValue: table) guard let tableRegion = tableRegions[table] else { return self } let intersection = tableRegion.intersection(TableRegion(columns: nil, rowIds: rowIds)) if intersection.isEmpty { tableRegions.removeValue(forKey: table) } else { tableRegions[table] = intersection } return DatabaseRegion(tableRegions: tableRegions) } /// Returns the union of this region and the given one. public func union(_ other: DatabaseRegion) -> DatabaseRegion { guard let tableRegions else { return .fullDatabase } guard let otherTableRegions = other.tableRegions else { return .fullDatabase } var tableRegionsUnion: [CaseInsensitiveIdentifier: TableRegion] = [:] let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys)) for table in tableNames { let tableRegion = tableRegions[table] let otherTableRegion = otherTableRegions[table] let tableRegionUnion: TableRegion switch (tableRegion, otherTableRegion) { case (nil, nil): preconditionFailure() case let (nil, tableRegion?), let (tableRegion?, nil): tableRegionUnion = tableRegion case let (tableRegion?, otherTableRegion?): tableRegionUnion = tableRegion.union(otherTableRegion) } tableRegionsUnion[table] = tableRegionUnion } return DatabaseRegion(tableRegions: tableRegionsUnion) } /// Inserts the given region into this region public mutating func formUnion(_ other: DatabaseRegion) { self = union(other) } /// Returns a region suitable for database observation func observableRegion(_ db: Database) throws -> DatabaseRegion { // SQLite does not expose schema changes to the // TransactionObserver protocol. By removing internal SQLite tables from // the observed region, we optimize database observation. // // And by canonicalizing table names, we remove views, and help the // `isModified` methods. try ignoringInternalSQLiteTables().canonicalTables(db) } /// Returns a region only made of actual tables with their canonical names. /// Canonical names help the `isModified` methods. /// /// This method removes views (assuming no table exists with the same name /// as a view). private func canonicalTables(_ db: Database) throws -> DatabaseRegion { guard let tableRegions else { return .fullDatabase } var region = DatabaseRegion() for (table, tableRegion) in tableRegions { if let canonicalTableName = try db.canonicalTableName(table.rawValue) { let table = CaseInsensitiveIdentifier(rawValue: canonicalTableName) region.formUnion(DatabaseRegion(tableRegions: [table: tableRegion])) } } return region } /// Returns a region which doesn't contain any SQLite internal table. private func ignoringInternalSQLiteTables() -> DatabaseRegion { guard let tableRegions else { return .fullDatabase } let filteredRegions = tableRegions.filter { !Database.isSQLiteInternalTable($0.key.rawValue) } return DatabaseRegion(tableRegions: filteredRegions) } } extension DatabaseRegion { // MARK: - Database Events /// Returns whether the content in the region would be impacted if the /// database were modified by an event of this kind. public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool { intersection(eventKind.modifiedRegion).isEmpty == false } /// Returns whether the content in the region is impacted by this event. /// /// - precondition: event has been filtered by the same region /// in the TransactionObserver.observes(eventsOfKind:) method, by calling /// region.isModified(byEventsOfKind:) public func isModified(by event: DatabaseEvent) -> Bool { guard let tableRegions else { // Full database: all changes are impactful return true } guard let tableRegion = tableRegions[CaseInsensitiveIdentifier(rawValue: event.tableName)] else { // FTS4 (and maybe other virtual tables) perform unadvertised // changes. For example, an "INSERT INTO document ..." statement // advertises an insertion in the `document` table, but the // actual change events happen in the `document_content` shadow // table. When such a non-advertised event happens, assume that // the region is modified. // See https://github.com/groue/GRDB.swift/issues/620 return true } return tableRegion.contains(rowID: event.rowID) } } extension DatabaseRegion: Equatable { public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool { switch (lhs.tableRegions, rhs.tableRegions) { case (nil, nil): return true case let (ltableRegions?, rtableRegions?): let ltableNames = Set(ltableRegions.keys) let rtableNames = Set(rtableRegions.keys) guard ltableNames == rtableNames else { return false } for tableName in ltableNames where ltableRegions[tableName]! != rtableRegions[tableName]! { return false } return true default: return false } } } extension DatabaseRegion: CustomStringConvertible { public var description: String { guard let tableRegions else { return "full database" } if tableRegions.isEmpty { return "empty" } return tableRegions .sorted(by: { (l, r) in l.key.rawValue < r.key.rawValue }) .map { (table, tableRegion) in var desc = table.rawValue if let columns = tableRegion.columns { desc += "(" + columns.map(\.rawValue).sorted().joined(separator: ",") + ")" } else { desc += "(*)" } if let rowIds = tableRegion.rowIds { desc += "[" + rowIds.sorted().map { "\($0)" }.joined(separator: ",") + "]" } return desc } .joined(separator: ",") } } private struct TableRegion: Equatable { var columns: Set<CaseInsensitiveIdentifier>? // nil means "all columns" var rowIds: Set<Int64>? // nil means "all rowids" var isEmpty: Bool { if let columns = columns, columns.isEmpty { return true } if let rowIds = rowIds, rowIds.isEmpty { return true } return false } func intersection(_ other: TableRegion) -> TableRegion { let columnsIntersection: Set<CaseInsensitiveIdentifier>? switch (self.columns, other.columns) { case let (nil, columns), let (columns, nil): columnsIntersection = columns case let (columns?, other?): columnsIntersection = columns.intersection(other) } let rowIdsIntersection: Set<Int64>? switch (self.rowIds, other.rowIds) { case let (nil, rowIds), let (rowIds, nil): rowIdsIntersection = rowIds case let (rowIds?, other?): rowIdsIntersection = rowIds.intersection(other) } return TableRegion(columns: columnsIntersection, rowIds: rowIdsIntersection) } func union(_ other: TableRegion) -> TableRegion { let columnsUnion: Set<CaseInsensitiveIdentifier>? switch (self.columns, other.columns) { case (nil, _), (_, nil): columnsUnion = nil case let (columns?, other?): columnsUnion = columns.union(other) } let rowIdsUnion: Set<Int64>? switch (self.rowIds, other.rowIds) { case (nil, _), (_, nil): rowIdsUnion = nil case let (rowIds?, other?): rowIdsUnion = rowIds.union(other) } return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion) } func contains(rowID: Int64) -> Bool { guard let rowIds else { return true } return rowIds.contains(rowID) } } // MARK: - DatabaseRegionConvertible /// A type that operates on a specific ``DatabaseRegion``. /// /// ## Topics /// /// ### Supporting Types /// /// - ``AnyDatabaseRegionConvertible`` public protocol DatabaseRegionConvertible { /// Returns a database region. /// /// - parameter db: A database connection. func databaseRegion(_ db: Database) throws -> DatabaseRegion } extension DatabaseRegionConvertible where Self == DatabaseRegion { /// The region that covers the full database: all columns and all rows /// from all tables. public static var fullDatabase: Self { DatabaseRegion.fullDatabase } } extension DatabaseRegion: DatabaseRegionConvertible { public func databaseRegion(_ db: Database) throws -> DatabaseRegion { self } } /// A type-erased DatabaseRegionConvertible public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { let _region: (Database) throws -> DatabaseRegion public init(_ region: @escaping (Database) throws -> DatabaseRegion) { _region = region } public init(_ region: some DatabaseRegionConvertible) { _region = region.databaseRegion } public func databaseRegion(_ db: Database) throws -> DatabaseRegion { try _region(db) } } // MARK: - Utils extension DatabaseRegion { static func union(_ regions: DatabaseRegion...) -> DatabaseRegion { regions.reduce(into: DatabaseRegion()) { union, region in union.formUnion(region) } } static func union(_ regions: [any DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { return { db in try regions.reduce(into: DatabaseRegion()) { union, region in try union.formUnion(region.databaseRegion(db)) } } } }
mit
cdaf70b3be7708b5102f4b1eab581971
35.742574
106
0.608596
4.647464
false
false
false
false
tad-iizuka/swift-sdk
Source/PersonalityInsightsV2/Models/Profile.swift
3
2027
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** A personality profile generated by the Personality Insights service. */ public struct Profile: JSONDecodable { /// Detailed results for a specific characteristic of the input text. public let tree: TraitTreeNode /// The unique identifier for which these characteristics were computed, /// from the "userid" field of the input ContentItems. public let id: String /// The source for which these characteristics were computed, /// from the "sourceid" field of the input ContentItems. public let source: String /// The number of words found in the input. public let wordCount: Int /// A message indicating the number of words found and where the value falls /// in the range of required or suggested number of words when guidance is /// available. public let wordCountMessage: String? /// The language model that was used to process the input. public let processedLanguage: String /// Used internally to initialize a `Profile` model from JSON. public init(json: JSON) throws { tree = try json.decode(at: "tree") id = try json.getString(at: "id") source = try json.getString(at: "source") wordCount = try json.getInt(at: "word_count") wordCountMessage = try? json.getString(at: "word_count_message") processedLanguage = try json.getString(at: "processed_lang") } }
apache-2.0
21ae93d71015952c37372503ae4b0994
36.537037
80
0.707943
4.494457
false
false
false
false
piscoTech/GymTracker
Gym Tracker iOS/CompletedWorkoutsTVC.swift
1
5435
// // CompletedWorkoutsTableViewController.swift // Gym Tracker // // Created by Marco Boschi on 10/04/2017. // Copyright © 2017 Marco Boschi. All rights reserved. // import UIKit import HealthKit import MBLibrary import GymTrackerCore class CompletedWorkoutsTableViewController: UITableViewController { private let batchSize = 40 private var moreToBeLoaded = false private var isLoadingMore = true private weak var loadMoreCell: LoadMoreCell? private var workouts = [(name: String?, start: Date, duration: TimeInterval)]() private var ignoreWorkoutsWhenLoadingMore: [HKWorkout] = [] override func viewDidLoad() { super.viewDidLoad() appDelegate.completedWorkouts = self refresh(self) if #available(iOS 13, *) {} else { self.navigationController?.navigationBar.barStyle = .black tableView.backgroundColor = .black } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source @IBAction func refresh(_ sender: AnyObject) { workouts = [] ignoreWorkoutsWhenLoadingMore = [] moreToBeLoaded = false loadData() } private func loadData() { isLoadingMore = true loadMoreCell?.isEnabled = false let filter = HKQuery.predicateForObjects(from: HKSource.default()) let limit: Int let predicate: NSPredicate if let lastStart = ignoreWorkoutsWhenLoadingMore.first?.startDate { predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [ filter, NSPredicate(format: "%K <= %@", HKPredicateKeyPathStartDate, lastStart as NSDate) ]) limit = ignoreWorkoutsWhenLoadingMore.count + batchSize } else { predicate = filter limit = batchSize } let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false) let type = HKObjectType.workoutType() let workoutQuery = HKSampleQuery(sampleType: type, predicate: predicate, limit: limit, sortDescriptors: [sortDescriptor]) { (_, r, err) in if let res = r as? [HKWorkout] { DispatchQueue.main.async { self.moreToBeLoaded = res.count >= limit let newWorkout = res.subtract(self.ignoreWorkoutsWhenLoadingMore) let addLineCount = self.workouts.isEmpty ? nil : newWorkout.count self.workouts += newWorkout.map { w in let name = w.metadata?[ExecuteWorkoutController.workoutNameMetadataKey] as? String let start = w.startDate let dur = w.duration return (name?.count ?? 0 > 0 ? name : nil, start, dur) } if let lastLoaded = newWorkout.last, let index = newWorkout.firstIndex(where: { $0.startDate == lastLoaded.startDate }) { self.ignoreWorkoutsWhenLoadingMore = Array(newWorkout.suffix(from: index)) } self.tableView.beginUpdates() self.isLoadingMore = false if let added = addLineCount { let oldCount = self.tableView.numberOfRows(inSection: 0) self.tableView.insertRows(at: (oldCount ..< (oldCount + added)).map { IndexPath(row: $0, section: 0) }, with: .automatic) self.loadMoreCell?.isEnabled = true } else { self.tableView.reloadSections([0], with: .automatic) } if self.moreToBeLoaded && self.tableView.numberOfSections == 1 { self.tableView.insertSections([1], with: .automatic) } else if !self.moreToBeLoaded && self.tableView.numberOfSections > 1 { self.tableView.deleteSections([1], with: .automatic) } self.tableView.endUpdates() } } } healthStore.execute(workoutQuery) } override func numberOfSections(in tableView: UITableView) -> Int { return moreToBeLoaded ? 2 : 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return max(1, workouts.count) case 1: return 1 default: return 0 } } private var normalFont: UIFont! private var italicFont: UIFont! override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard workouts.count > 0 else { return tableView.dequeueReusableCell(withIdentifier: "noWorkout", for: indexPath) } if indexPath.section == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "loadMore", for: indexPath) as! LoadMoreCell loadMoreCell = cell cell.isEnabled = !isLoadingMore return cell } let w = workouts[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "workout", for: indexPath) if normalFont == nil { normalFont = cell.textLabel?.font if let font = normalFont?.fontDescriptor, let descr = font.withSymbolicTraits(.traitItalic) { italicFont = UIFont(descriptor: descr, size: 0) } } if let n = w.name { cell.textLabel?.text = n cell.textLabel?.font = normalFont } else { cell.textLabel?.text = GTLocalizedString("WORKOUT", comment: "Workout") cell.textLabel?.font = italicFont } cell.detailTextLabel?.text = [w.start.formattedDateTime, w.duration.formattedDuration].joined(separator: " – ") return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 1, loadMoreCell?.isEnabled ?? false { loadMoreCell?.isEnabled = false loadData() } tableView.deselectRow(at: indexPath, animated: true) } }
mit
2b1e8a23469428d0faa0e9f2f1ba0284
29.346369
140
0.697165
4.068914
false
false
false
false
necrowman/CRLAlamofireFuture
Examples/SimpleTvOSCarthage/Carthage/Checkouts/Future/Future/Future.swift
111
5584
//===--- Future.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //===----------------------------------------------------------------------===// import Foundation import Result import Boilerplate import ExecutionContext public protocol FutureType : ExecutionContextTenantProtocol { associatedtype Value init(value:Value) init(error:ErrorProtocol) init<E : ErrorProtocol>(result:Result<Value, E>) func onComplete<E: ErrorProtocol>(callback: Result<Value, E> -> Void) -> Self var isCompleted:Bool {get} } public class Future<V> : FutureType { public typealias Value = V private var _chain:TaskChain? private var _resolver:ExecutionContextType? internal var result:Result<Value, AnyError>? = nil { didSet { if result != nil { self.isCompleted = true /// some performance optimization is done here, so don't touch the ifs. ExecutionContext.current is not the fastest func let context = selectContext() _chain!.append { next in return { context in admin.execute { self._resolver = context self._chain = nil context.execute { next.content?(context) } } } } _chain!.perform(context) } } } public let context: ExecutionContextType //make it atomic later private (set) public var isCompleted:Bool = false internal init(context:ExecutionContextType) { self._chain = TaskChain() self.context = context } public required convenience init(value:Value) { self.init(result: Result<Value, AnyError>(value: value)) } public required convenience init(error:ErrorProtocol) { self.init(result: Result(error: AnyError(error))) } public required convenience init<E : ErrorProtocol>(result:Result<Value, E>) { self.init(context: immediate) self.result = result.asAnyError() self.isCompleted = true self._resolver = selectContext() self._chain = nil } private func selectContext() -> ExecutionContextType { return self.context.isEqualTo(immediate) ? ExecutionContext.current : self.context } public func onComplete<E: ErrorProtocol>(callback: Result<Value, E> -> Void) -> Self { return self.onCompleteInternal(callback) } //to avoid endless recursion internal func onCompleteInternal<E: ErrorProtocol>(callback: Result<Value, E> -> Void) -> Self { admin.execute { if let resolver = self._resolver { let mapped:Result<Value, E>? = self.result!.tryAsError() if let result = mapped { resolver.execute { callback(result) } } } else { self._chain!.append { next in return { context in let mapped:Result<Value, E>? = self.result!.tryAsError() if let result = mapped { callback(result) next.content?(context) } else { next.content?(context) } } } } } return self } } extension Future : MovableExecutionContextTenantProtocol { public typealias SettledTenant = Future<Value> public func settle(in context: ExecutionContextType) -> SettledTenant { let future = MutableFuture<Value>(context: context) future.completeWith(self) return future } } public func future<T>(context:ExecutionContextType = contextSelector(), task:() throws ->T) -> Future<T> { let future = MutableFuture<T>(context: context) context.execute { do { let value = try task() try! future.success(value) } catch let e { try! future.fail(e) } } return future } public func future<T, E : ErrorProtocol>(context:ExecutionContextType = contextSelector(), task:() -> Result<T, E>) -> Future<T> { let future = MutableFuture<T>(context: context) context.execute { let result = task() try! future.complete(result) } return future } public func future<T, F : FutureType where F.Value == T>(context:ExecutionContextType = contextSelector(), task:() -> F) -> Future<T> { let future = MutableFuture<T>(context: context) context.execute { future.completeWith(task()) } return future }
mit
266eda27948511962a12291dab1c1fc3
31.277457
136
0.549606
5.141805
false
false
false
false
huonw/swift
benchmark/single-source/OpenClose.swift
13
1100
//===--- OpenClose.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils import Foundation // A micro benchmark for checking the speed of string-based enums. public let OpenClose = BenchmarkInfo( name: "OpenClose", runFunction: run_OpenClose, tags: [.validation, .api, .String]) enum MyState : String { case Closed = "Closed" case Opened = "Opened" } @inline(never) func check_state(_ state : MyState) -> Int { return state == .Opened ? 1 : 0 } @inline(never) public func run_OpenClose(_ N: Int) { var c = 0 for _ in 1...N*10000 { c += check_state(identity(MyState.Closed)) } CheckResults(c == 0) }
apache-2.0
b412f128c4679695f76265a9ddecf455
25.829268
80
0.601818
4.150943
false
false
false
false
frajaona/LiFXSwiftKit
Sources/LiFXSocksSocket.swift
1
1899
/* * Copyright (C) 2016 Fred Rajaona * * 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 class LiFXSocksSocket: LiFXSocket { var messageHandler: ((LiFXMessage, String) -> ())? var udpSocket: Socket? { return rawSocket } fileprivate var rawSocket: UdpSocksSocket? func openConnection() { let socket = UdpSocksSocket(destPort: LiFXSocksSocket.UdpPort, socketDelegate: self) rawSocket = socket if !socket.openConnection() { closeConnection() } else { } } func closeConnection() { rawSocket?.closeConnection() rawSocket = nil } func isConnected() -> Bool { return udpSocket != nil && udpSocket!.isConnected() } } extension LiFXSocksSocket: UdpSocksSocketDelegate { func onConnected(to socket: UdpSocksSocket) { Log.debug("socked did connect") } func onReceive(data: NSData, from address: String, by socket: UdpSocksSocket) { Log.debug("\nReceive data from address: \(address)") //Log.debug(data.description) let message = LiFXMessage(fromData: data as Data) messageHandler?(message, address) } func onSent(at address: String, by socket: UdpSocksSocket) { Log.debug("socked did send data") } }
apache-2.0
1ffc8ac20d14cb2e6d73026d953ecb12
26.926471
92
0.640864
4.229399
false
false
false
false
skyPeat/DoYuLiveStreaming
DoYuLiveStreaming/DoYuLiveStreaming/Classes/Main/View/SP_CommonTitleView.swift
1
3603
// // SP_CommonTitleView.swift // DoYuLiveStreaming // // Created by tianfeng pan on 17/3/23. // Copyright © 2017年 tianfeng pan. All rights reserved. // import UIKit //MARK:- 定义协议 protocol SP_CommonTitleViewDelegate : class { func sp_CommonTitleView(_ titleView : SP_CommonTitleView, index : Int) } class SP_CommonTitleView: UIView { //MARK:- 定义属性 fileprivate var titles : [String] var previouButton = UIButton() var buttonArray = [UIButton]() //MARK:- 懒加载属性 fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() lazy var titleButton = [UIButton]() fileprivate lazy var slideLine : UIView = { let slideLine = UIView() slideLine.backgroundColor = UIColor.orange return slideLine }() // 设置代理属性 weak var delegate : SP_CommonTitleViewDelegate? //MARK:- 自定义构造函数 init(frame : CGRect,titles : [String]) { self.titles = titles super.init(frame: frame) // 设置UI界面 setUpUIView() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK:- 设置UI界面 extension SP_CommonTitleView{ fileprivate func setUpUIView(){ // 添加scrollView addSubview(scrollView) scrollView.frame = bounds // 添加titleButton let titleY : CGFloat = 0 let titleW : CGFloat = frame.width / CGFloat(titles.count) let titleH : CGFloat = frame.height for (index,title) in titles.enumerated() { let titleX = titleW * CGFloat(index) let titleButton = UIButton() titleButton.tag = index titleButton.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH) titleButton.setTitleColor(UIColor.black, for: .normal) titleButton.setTitleColor(UIColor.orange, for: .selected) titleButton.setTitle(title, for: .normal) titleButton.addTarget(self, action: #selector(titleButtonClick(button:)), for: .touchUpInside) buttonArray.append(titleButton) scrollView.addSubview(titleButton) // 添加slideLine if index == 0 { titleButtonClick(button: titleButton) let lineX : CGFloat = 0 let lineH : CGFloat = 1 let lineY : CGFloat = frame.height - lineH let lineW : CGFloat = titleW * 0.8 slideLine.frame = CGRect(x: lineX, y: lineY, width: lineW, height: lineH) slideLine.center.x = titleButton.center.x slideLine.backgroundColor = UIColor.orange addSubview(slideLine) } } } //MARK:- 监听按钮点击 func titleButtonClick(button : UIButton){ previouButton.isSelected = false button.isSelected = !button.isSelected previouButton = button //点击按钮时,下划线跟着滑动 UIView.animate(withDuration: 0.2) {self.slideLine.center.x = button.center.x} // 回调代理方法 delegate?.sp_CommonTitleView(self,index: button.tag) } } //MARK:- 对外暴露方法 extension SP_CommonTitleView{ func setCurrentIndex(_ currentIndex : Int){ titleButtonClick(button: buttonArray[currentIndex]) } }
mit
df1c9e2f899460de90f54332de1b48c8
32.572816
106
0.614228
4.580132
false
false
false
false
RoniLeshes/RLRoundedProgressBar
RLRoundedProgressBarExample/RLRoundedProgressBarExample/ViewController.swift
1
1784
// // ViewController.swift // RoundedProgressBar // // Created by Roni Leshes on 04/07/2017. // Copyright © 2017 Roni Leshes. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate{ @IBOutlet weak var progressView: RLRoundedProgressView! @IBOutlet weak var progressTextField: UITextField! @IBOutlet weak var animatedSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() // 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 setProgressPressed(_ sender: Any) { let percent = CGFloat(Double(self.progressTextField.text ?? "")!) if self.animatedSwitch.isOn{ UIView.animate(withDuration: 0.8, delay: 0.0, options: .curveEaseInOut, animations: { self.progressView.setProgress(percent:percent) }, completion: nil) }else{ self.progressView.setProgress(percent:percent) } } //==================================== //MARK: Textfield delegate //==================================== func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let fullString = "\(self.progressTextField.text ?? "")\(string)" let doubleValue = Double(fullString) if doubleValue! > 100.0 || doubleValue! < 0.0{ //Make sure text field will have a valid percent value return false } return true } }
apache-2.0
ac26c2eb39001464b304322aab4f3609
28.229508
129
0.595625
5.244118
false
false
false
false
johnno1962d/swift
stdlib/public/core/Index.swift
1
13163
//===--- Index.swift - A position in a Collection -------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // ForwardIndex, BidirectionalIndex, and RandomAccessIndex // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// //===--- ForwardIndex -----------------------------------------------------===// /// This protocol is an implementation detail of `ForwardIndex`; do /// not use it directly. /// /// Its requirements are inherited by `ForwardIndex` and thus must /// be satisfied by types conforming to that protocol. @_show_in_interface public protocol _Incrementable : Equatable { /// Returns the next consecutive value in a discrete sequence of /// `Self` values. /// /// - Precondition: `self` has a well-defined successor. @warn_unused_result func successor() -> Self mutating func _successorInPlace() } extension _Incrementable { @inline(__always) public mutating func _successorInPlace() { self = self.successor() } } //===----------------------------------------------------------------------===// // A dummy type that we can use when we /don't/ want to create an // ambiguity indexing Range<T> outside a generic context. See the // implementation of Range for details. public struct _DisabledRangeIndex_ { init() { _sanityCheckFailure("Nobody should ever create one.") } } //===----------------------------------------------------------------------===// /// Replace `i` with its `successor()` and return the updated value of /// `i`. @_transparent @available(*, unavailable, message: "it has been removed in Swift 3") public prefix func ++ <T : _Incrementable> (i: inout T) -> T { i._successorInPlace() return i } /// Replace `i` with its `successor()` and return the original /// value of `i`. @_transparent @available(*, unavailable, message: "it has been removed in Swift 3") public postfix func ++ <T : _Incrementable> (i: inout T) -> T { let ret = i i._successorInPlace() return ret } /// Represents a discrete value in a series, where a value's /// successor, if any, is reachable by applying the value's /// `successor()` method. public protocol ForwardIndex : _Incrementable { /// A type that can represent the number of steps between pairs of /// `Self` values where one value is reachable from the other. /// /// Reachability is defined by the ability to produce one value from /// the other via zero or more applications of `successor`. associatedtype Distance : _SignedInteger = Int // See the implementation of Range for an explanation of this // associated type associatedtype _DisabledRangeIndex = _DisabledRangeIndex_ /// Performs a range check in O(1), or a no-op when a range check is not /// implementable in O(1). /// /// The range check, if performed, is equivalent to: /// /// precondition(bounds.contains(index)) /// /// Use this function to perform a cheap range check for QoI purposes when /// memory safety is not a concern. Do not rely on this range check for /// memory safety. /// /// The default implementation for forward and bidirectional indices is a /// no-op. The default implementation for random access indices performs a /// range check. /// /// - Complexity: O(1). static func _failEarlyRangeCheck(_ index: Self, bounds: Range<Self>) /// Performs a range check in O(1), or a no-op when a range check is not /// implementable in O(1). /// /// The range check, if performed, is equivalent to: /// /// precondition( /// bounds.contains(range.startIndex) || /// range.startIndex == bounds.endIndex) /// precondition( /// bounds.contains(range.endIndex) || /// range.endIndex == bounds.endIndex) /// /// Use this function to perform a cheap range check for QoI purposes when /// memory safety is not a concern. Do not rely on this range check for /// memory safety. /// /// The default implementation for forward and bidirectional indices is a /// no-op. The default implementation for random access indices performs a /// range check. /// /// - Complexity: O(1). static func _failEarlyRangeCheck2( rangeStart: Self, rangeEnd: Self, boundsStart: Self, boundsEnd: Self) // FIXME: the suffix `2` in the name, and passing `startIndex` and `endIndex` // separately (rather than as a range) are workarounds for a compiler defect. // <rdar://problem/21855350> Rejects-valid: rejects code that has two Self // types in non-direct-argument-type position /// Returns the result of advancing `self` by `n` positions. /// /// - Returns: /// - If `n > 0`, the result of applying `successor` to `self` `n` times. /// - If `n < 0`, the result of applying `predecessor` to `self` `-n` times. /// - Otherwise, `self`. /// /// - Precondition: `n >= 0` if only conforming to `ForwardIndex` /// - Complexity: /// - O(1) if conforming to `RandomAccessIndex` /// - O(`abs(n)`) otherwise @warn_unused_result func advanced(by n: Distance) -> Self /// Returns the result of advancing `self` by `n` positions, or until it /// equals `limit`. /// /// - Returns: /// - If `n > 0`, the result of applying `successor` to `self` `n` times /// but not past `limit`. /// - If `n < 0`, the result of applying `predecessor` to `self` `-n` times /// but not past `limit`. /// - Otherwise, `self`. /// /// - Precondition: `n >= 0` if only conforming to `ForwardIndex`. /// /// - Complexity: /// - O(1) if conforming to `RandomAccessIndex` /// - O(`abs(n)`) otherwise @warn_unused_result func advanced(by n: Distance, limit: Self) -> Self /// Measure the distance between `self` and `end`. /// /// - Precondition: /// - `start` and `end` are part of the same sequence when conforming to /// `RandomAccessIndex`. /// - `end` is reachable from `self` by incrementation otherwise. /// /// - Complexity: /// - O(1) if conforming to `RandomAccessIndex` /// - O(`n`) otherwise, where `n` is the function's result. @warn_unused_result func distance(to end: Self) -> Distance } // advance and distance implementations extension ForwardIndex { public static func _failEarlyRangeCheck(_ index: Self, bounds: Range<Self>) { // Can't perform range checks in O(1) on forward indices. } public static func _failEarlyRangeCheck2( rangeStart: Self, rangeEnd: Self, boundsStart: Self, boundsEnd: Self ) { // Can't perform range checks in O(1) on forward indices. } /// Do not use this method directly; call advanced(by: n) instead. @_transparent @warn_unused_result internal func _advanceForward(_ n: Distance) -> Self { _precondition(n >= 0, "Only BidirectionalIndex can be advanced by a negative amount") var p = self var i : Distance = 0 while i != n { p._successorInPlace() i += 1 } return p } /// Do not use this method directly; call advanced(by: n, limit) instead. @_transparent @warn_unused_result internal func _advanceForward(_ n: Distance, _ limit: Self) -> Self { _precondition(n >= 0, "Only BidirectionalIndex can be advanced by a negative amount") var p = self var i : Distance = 0 while i != n { if p == limit { break } p._successorInPlace() i += 1 } return p } @warn_unused_result public func advanced(by n: Distance) -> Self { return self._advanceForward(n) } @warn_unused_result public func advanced(by n: Distance, limit: Self) -> Self { return self._advanceForward(n, limit) } @warn_unused_result public func distance(to end: Self) -> Distance { var p = self var count: Distance = 0 while p != end { count += 1 p._successorInPlace() } return count } } //===----------------------------------------------------------------------===// //===--- BidirectionalIndex -----------------------------------------------===// /// An index that can step backwards via application of its /// `predecessor()` method. public protocol BidirectionalIndex : ForwardIndex { /// Returns the previous consecutive value in a discrete sequence. /// /// If `self` has a well-defined successor, /// `self.successor().predecessor() == self`. If `self` has a /// well-defined predecessor, `self.predecessor().successor() == /// self`. /// /// - Precondition: `self` has a well-defined predecessor. @warn_unused_result func predecessor() -> Self mutating func _predecessorInPlace() } extension BidirectionalIndex { @inline(__always) public mutating func _predecessorInPlace() { self = self.predecessor() } @warn_unused_result public func advanced(by n: Distance) -> Self { if n >= 0 { return _advanceForward(n) } var p = self var i: Distance = n while i != 0 { p._predecessorInPlace() i._successorInPlace() } return p } @warn_unused_result public func advanced(by n: Distance, limit: Self) -> Self { if n >= 0 { return _advanceForward(n, limit) } var p = self var i: Distance = n while i != 0 && p != limit { p._predecessorInPlace() i._successorInPlace() } return p } } /// Replace `i` with its `predecessor()` and return the updated value /// of `i`. @_transparent @available(*, unavailable, message: "it has been removed in Swift 3") public prefix func -- <T : BidirectionalIndex> (i: inout T) -> T { i._predecessorInPlace() return i } /// Replace `i` with its `predecessor()` and return the original /// value of `i`. @_transparent @available(*, unavailable, message: "it has been removed in Swift 3") public postfix func -- <T : BidirectionalIndex> (i: inout T) -> T { let ret = i i._predecessorInPlace() return ret } //===----------------------------------------------------------------------===// //===--- RandomAccessIndex ------------------------------------------------===// /// Used to force conformers of RandomAccessIndex to implement /// `advanced(by:)` methods and `distance(to:)`. @_show_in_interface public protocol _RandomAccessAmbiguity { associatedtype Distance : _SignedInteger = Int } extension _RandomAccessAmbiguity { @warn_unused_result public func advanced(by n: Distance) -> Self { fatalError("advanced(by:) not implemented") } } /// An index that can be offset by an arbitrary number of positions, /// and can measure the distance to any reachable value, in O(1). public protocol RandomAccessIndex : BidirectionalIndex, Strideable, _RandomAccessAmbiguity { @warn_unused_result func distance(to other: Self) -> Distance @warn_unused_result func advanced(by n: Distance) -> Self @warn_unused_result func advanced(by n: Distance, limit: Self) -> Self } extension RandomAccessIndex { public static func _failEarlyRangeCheck(_ index: Self, bounds: Range<Self>) { _precondition( bounds.startIndex <= index, "index is out of bounds: index designates a position before bounds.startIndex") _precondition( index < bounds.endIndex, "index is out of bounds: index designates the bounds.endIndex position or a position after it") } public static func _failEarlyRangeCheck2( rangeStart: Self, rangeEnd: Self, boundsStart: Self, boundsEnd: Self ) { let range = rangeStart..<rangeEnd let bounds = boundsStart..<boundsEnd _precondition( bounds.startIndex <= range.startIndex, "range.startIndex is out of bounds: index designates a position before bounds.startIndex") _precondition( bounds.startIndex <= range.endIndex, "range.endIndex is out of bounds: index designates a position before bounds.startIndex") _precondition( range.startIndex <= bounds.endIndex, "range.startIndex is out of bounds: index designates a position after bounds.endIndex") _precondition( range.endIndex <= bounds.endIndex, "range.startIndex is out of bounds: index designates a position after bounds.endIndex") } @_transparent @warn_unused_result public func advanced(by n: Distance, limit: Self) -> Self { let d = self.distance(to: limit) if d == 0 || (d > 0 ? d <= n : d >= n) { return limit } return self.advanced(by: n) } } @available(*, unavailable, renamed: "ForwardIndex") public typealias ForwardIndexType = ForwardIndex @available(*, unavailable, renamed: "BidirectionalIndex") public typealias BidirectionalIndexType = BidirectionalIndex @available(*, unavailable, renamed: "RandomAccessIndex") public typealias RandomAccessIndexType = RandomAccessIndex
apache-2.0
c615cfb39aee7cf819ded7ece7cf2093
31.026764
101
0.625237
4.26125
false
false
false
false
korrolion/smartrate
Example/SmartRate/AppDelegate.swift
1
3740
// // AppDelegate.swift // SmartRate // // Created by korrolion on 07/17/2017. // Copyright (c) 2017 korrolion. All rights reserved. // import UIKit import SmartRate import StoreKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //Configure SmartRate SMBlocker.shared.minTimeAfterInstalled = 60 //Will not fire 60 seconds after first launch SMBlocker.shared.minTimeAfterLaunch = 10 //Will not fire 10 seconds after launch SMBlocker.shared.minTimeAfterFire = 60 //Will not fire 60 seconds after fire 😀 SMBlocker.shared.showRatingForEveryVersion = true //Will reset block if the app version will change //Create triggers for SmartRate let countTrigger = SMTriggerCounterType(notificationName: ViewController.duplicateActionNotificationName, repeatTimes: 4, uniqName: "press4TimesTrigger") //For every trigger you can provide custom fire function, or use default countTrigger.customFireCompletion = { if #available(iOS 10.3, *) { SKStoreReviewController.requestReview() } } //Will fire on 4-th button press SMTriggersStore.shared.addTrigger(countTrigger) let chainTrigger = SMTriggerChainType(notificationNames: [ ViewController.step1NotificationName, //provide sequence of steps ViewController.step2NotificationName, ViewController.step3NotificationName, ], breakNotificationName: ViewController.breakNotificationName, //You can break chain on any other action, or set nil uniqName: "pressButtons123Trigger" ) //Will fire after correct sequence of 3 steps. Will not fire if sequence will be broken SMTriggersStore.shared.addTrigger(chainTrigger) 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:. } }
mit
e28b9ab447f1890e723eeda0ae9c1238
48.171053
285
0.721969
5.361549
false
false
false
false
SECH-Tag-EEXCESS-Browser/iOSX-App
Team UI/Browser/Browser/WebViewDelegate.swift
1
3103
// // WebViewDelegate.swift // Browser // // Created by Andreas Ziemer on 16.10.15. // Copyright © 2015 SECH-Tag-EEXCESS-Browser. All rights reserved. // import UIKit import WebKit class WebViewDelegate: NSObject, WKNavigationDelegate { let regex = RegexForSech() let sechManager = SechManager() var mURL : String = "" var viewCtrl: ViewController! var htmlHead : String = "" var htmlBody : String = "" func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { mURL = (webView.URL?.absoluteString)! viewCtrl.addressBarTxt.text = mURL // Ineinander verschachtelt, weil completionHandler wartet bis ausgeführt wurde webView.evaluateJavaScript("document.head.innerHTML", completionHandler: { (object, error) -> Void in if error == nil && object != nil{ self.htmlHead = (object as? String)! webView .evaluateJavaScript("document.body.innerHTML", completionHandler: { (object, error) -> Void in if error == nil && object != nil{ self.htmlBody = (object as? String)! let sech = self.sechManager.getSechObjects(self.htmlHead, htmlBody: self.htmlBody) print("Sechlinks found: \(sech.count)") print("SechlinkIDs:") self.viewCtrl.countSechsLabel.hidden = false self.viewCtrl.countSechsLabel.text = "\(sech.count)" for item in sech{ print(item.id) } //-> ! // Put call for Request of EEXCESS here! let setRecommendations = ({(msg:String,data:[EEXCESSAllResponses]?) -> () in print(msg) // TODO: To be redesigned! 6 let ds = self.viewCtrl.tableViewDataSource ds.makeLabels(sech) if(data != nil){ self.viewCtrl.eexcessAllResponses = data }else{ self.viewCtrl.eexcessAllResponses = [] } dispatch_async(dispatch_get_main_queue(), { () -> Void in // TODO: To be redesigned! 8 self.viewCtrl.rankThatShit(self.viewCtrl.eexcessAllResponses) self.viewCtrl.tableView.reloadData() }) }) let task = TaskCtrl() task.getRecommendations(sech, setRecommendations: setRecommendations) } }) } } ) } func webView(webView: WKWebView, didFailLoadWithError error: NSError?) { } }
mit
d6cf2336cb125b4b2b438cb8ba942a3e
30.979381
114
0.475975
5.108731
false
false
false
false
dmsl1805/Spider
Example/Spider/GlobalConst.swift
1
476
// // GlobalConst.swift // Weather // // Created by Dmitriy Shulzhenko on 1/11/17. // Copyright © 2017 Dmitriy Shulzhenko. All rights reserved. // import Foundation let openweatherForecastApiDomain = "http://api.openweathermap.org/data/2.5/forecast"//?id=524901&APPID=7cda97320c711c46bb42956c1a23c729 // full req example api.openweathermap.org/data/2.5/forecast?id=524901&APPID=7cda97320c711c46bb42956c1a23c729 let openweatherAPPID = "7cda97320c711c46bb42956c1a23c729"
mit
d638d0dbe61808e88f8bf13d422c61d9
35.538462
135
0.793684
2.745665
false
false
false
false
ello/ello-ios
Sources/Model/Regions/ImageRegion.swift
1
2311
//// /// ImageRegion.swift // import SwiftyJSON let ImageRegionVersion = 1 @objc(ImageRegion) final class ImageRegion: Model, Regionable { let url: URL? let buyButtonURL: URL? var isRepost: Bool = false let kind: RegionKind = .image var asset: Asset? { return getLinkObject("assets") } var fullScreenURL: URL? { guard let asset = asset else { return url } let assetURL: URL? if asset.isGif { assetURL = asset.optimized?.url } else { assetURL = asset.oneColumnAttachment?.url } return assetURL ?? url } init(url: URL?, buyButtonURL: URL?) { self.url = url self.buyButtonURL = buyButtonURL super.init(version: ImageRegionVersion) } required init(coder: NSCoder) { let decoder = Coder(coder) self.isRepost = decoder.decodeKey("isRepost") self.url = decoder.decodeOptionalKey("url") self.buyButtonURL = decoder.decodeOptionalKey("buyButtonURL") super.init(coder: coder) } override func encode(with encoder: NSCoder) { let coder = Coder(encoder) coder.encodeObject(isRepost, forKey: "isRepost") coder.encodeObject(url, forKey: "url") coder.encodeObject(buyButtonURL, forKey: "buyButtonURL") super.encode(with: coder.coder) } class func fromJSON(_ data: [String: Any]) -> ImageRegion { let json = JSON(data) var url: URL? if var urlStr = json["data"]["url"].string { if urlStr.hasPrefix("//") { urlStr = "https:\(urlStr)" } url = URL(string: urlStr) } let buyButtonURL = json["link_url"].url let imageRegion = ImageRegion(url: url, buyButtonURL: buyButtonURL) imageRegion.mergeLinks(data["links"] as? [String: Any]) return imageRegion } func coding() -> NSCoding { return self } func toJSON() -> [String: Any] { var json: [String: Any] = [ "kind": kind.rawValue, ] if let url = url?.absoluteString { json["data"] = [ "url": url ] } if let buyButtonURL = buyButtonURL { json["link_url"] = buyButtonURL.absoluteString } return json } }
mit
766dc52ccc41819a04dd591c728ee267
25.261364
75
0.574643
4.240367
false
false
false
false
FredericJacobs/AsyncMessagesViewController
Example/ViewController.swift
1
3405
// // ViewController.swift // AsyncMessagesViewController // // Created by Huy Nguyen on 17/02/15. // Copyright (c) 2015 Huy Nguyen. All rights reserved. // import UIKit class ViewController: AsyncMessagesViewController, ASCollectionViewDelegate { private let users: [User] private var currentUser: User? { return users.filter({$0.ID == self.dataSource.currentUserID()}).first } init() { let avatarImageSize = CGSizeMake(kAMMessageCellNodeAvatarImageSize, kAMMessageCellNodeAvatarImageSize) users = (0..<5).map() { let avatarURL = LoremIpsum.URLForPlaceholderImageFromService(.LoremPixel, withSize: avatarImageSize) return User(ID: "user-\($0)", name: LoremIpsum.name(), avatarURL: avatarURL) } let dataSource = DefaultAsyncMessagesCollectionViewDataSource(currentUserID: users[0].ID) super.init(dataSource: dataSource) collectionView.asyncDelegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Change user", style: .Plain, target: self, action: "changeCurrentUser") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) generateMessages() } override func didPressRightButton(sender: AnyObject!) { if let user = currentUser { let message = Message( contentType: kAMMessageDataContentTypeText, content: textView.text, date: NSDate(), sender: user) dataSource.collectionView(collectionView, insertMessages: [message]) {completed in self.scrollCollectionViewToBottom() } } super.didPressRightButton(sender) } private func generateMessages() { var messages = [Message]() for i in 0..<200 { let isTextMessage = arc4random_uniform(4) <= 2 // 75% let contentType = isTextMessage ? kAMMessageDataContentTypeText : kAMMessageDataContentTypeNetworkImage let content = isTextMessage ? LoremIpsum.wordsWithNumber((random() % 100) + 1) : LoremIpsum.URLForPlaceholderImageFromService(.LoremPixel, withSize: CGSizeMake(200, 200)).absoluteString let sender = users[random() % users.count] let previousMessage: Message? = i > 0 ? messages[i - 1] : nil let hasSameSender = (sender.ID == previousMessage?.senderID()) ?? false let date = hasSameSender ? previousMessage!.date().dateByAddingTimeInterval(5) : LoremIpsum.date() let message = Message( contentType: contentType, content: content, date: date, sender: sender) messages.append(message) } dataSource.collectionView(collectionView, insertMessages: messages, completion: nil) } func changeCurrentUser() { let otherUsers = users.filter({$0.ID != self.dataSource.currentUserID()}) let newUser = otherUsers[random() % otherUsers.count] dataSource.collectionView(collectionView, updateCurrentUserID: newUser.ID) } }
mit
104713e65b95c4e5438a3888f972bb5b
36.417582
139
0.630837
5.036982
false
false
false
false
yq616775291/DiliDili-Fun
DiliDili/Classes/Home/ViewController/HomeViewController.swift
1
1666
// // ViewController.swift // DiliDili // // Created by yq on 16/3/2. // Copyright © 2016年 yq. All rights reserved. // import UIKit import SnapKit class HomeViewController: UIViewController { var container:DAPagesContainer? override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = true // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = UIColor.whiteColor() self.createContainer() } func createContainer() { self.container = DAPagesContainer.init() let zb = ZBViewController() let re = RecommendViewController() let fj = FJViewController() let fq = FQViewController() zb.pagesTitle = "直播" re.pagesTitle = "推荐" fj.pagesTitle = "番剧" fq.pagesTitle = "分区" self.container?.view.frame = CGRectMake(0, 20, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height-20-49) self.container?.topBarHeight = 44 self.container?.topBarItemLabelsFont = UIFont.systemFontOfSize(14) self.container?.pageItemsTitleColor = UIColor.darkGrayColor() self.container?.topBarBackgroundColor = UIColor.whiteColor() self.container?.selectedPageItemTitleColor = UIColor.dilidiliThemeColor() self.view.addSubview((self.container?.view)!) self.container?.viewControllers = [zb,re,fj,fq] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
587bc889a9b521fa584ad3f758e15790
32.612245
143
0.666667
4.487738
false
false
false
false
MaartenBrijker/project
project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Flat Frequency Response Reverb.xcplaygroundpage/Contents.swift
2
1556
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Flat Frequency Response Reverb //: import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("drumloop", ofType: "wav") var player = AKAudioPlayer(file!) player.looping = true var reverb = AKFlatFrequencyResponseReverb(player, loopDuration: 0.1) //: Set the parameters of the delay here reverb.reverbDuration = 1 AudioKit.output = reverb AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { var durationLabel: Label? override func setup() { addTitle("Flat Frequency Response Reverb") addLabel("Audio Playback") addButton("Start", action: #selector(start)) addButton("Stop", action: #selector(stop)) durationLabel = addLabel("Duration: \(reverb.reverbDuration)") addSlider(#selector(setDuration), value: reverb.reverbDuration, minimum: 0, maximum: 5) } func start() { player.play() } func stop() { player.stop() } func setDuration(slider: Slider) { reverb.reverbDuration = Double(slider.value) durationLabel!.text = "Duration: \(String(format: "%0.3f", reverb.reverbDuration))" } } let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 300)) XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = view //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
apache-2.0
5aa3915376397e7bad3265cd33277c5b
25.827586
95
0.678021
4.149333
false
false
false
false
luizlopezm/ios-Luis-Trucking
Luis Trucking/ViewControllerExpense.swift
1
1923
// // ViewControllerExpense.swift // Luis Trucking // // Created by Luiz Lopez on 5/2/16. // Copyright © 2016 Luis Trucking. All rights reserved. // import UIKit class ViewControllerExpense: UIViewController { @IBOutlet weak var bt: UIButton! @IBOutlet weak var Nt: UILabel! override func viewWillAppear(animated: Bool) { super.viewDidLoad() Nt.hidden = true if(!isConnectedToNetwork()) { bt.hidden = true Nt.hidden = false } else { bt.hidden = false Nt.hidden = true } // Do any additional setup after loading the view. } @IBAction func log_t(sender: UIBarButtonItem) { self.performSegueWithIdentifier("logoff", sender: sender) } @IBAction func SubExpense(sender: UIButton) { let expense = ExpenseModel() expense.expensedate = Date2 expense.truckid = TruckID2 expense.expensetype = ExpenseT expense.drivername = Name expense.vendorname = Vendor expense.details = Descript expense.amount = Amount2 if(SubmitExpense(expense)) { self.performSegueWithIdentifier("subeg", sender: sender) } else { self.performSegueWithIdentifier("subef", sender: sender) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
c46e188c0e36adb9bee4b91fa45aaf40
24.972973
106
0.609261
4.829146
false
false
false
false
nickswalker/ASCIIfy
Pod/Classes/Extensions/Image+ASCIIfy.swift
1
2648
// // Copyright for portions of ASCIIfy are held by Barış Koç, 2014 as part of // project BKAsciiImage and Amy Dyer, 2012 as part of project Ascii. All other copyright // for ASCIIfy are held by Nick Walker, 2016. // // 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 #if os(iOS) import UIKit #endif public extension Image { func fy_asciiString() -> String { let converter = ASCIIConverter() return converter.convertToString(self) } func fy_asciiStringWith(_ handler: @escaping StringHandler) { let converter = ASCIIConverter() converter.convertToString(self) { handler($0) } } func fy_asciiImage(_ font: Font = ASCIIConverter.defaultFont) -> Image { let converter = ASCIIConverter() converter.font = font return converter.convertImage(self) } func fy_asciiImage(_ font: Font = ASCIIConverter.defaultFont, completionHandler handler: @escaping ImageHandler) { let converter = ASCIIConverter() converter.font = font converter.convertImage(self) { handler($0)} } func fy_asciiImageWith(_ font: Font = ASCIIConverter.defaultFont, bgColor: Color = .black, columns: Int? = nil, invertLuminance: Bool = true, colorMode: ASCIIConverter.ColorMode = .color, completionHandler handler: @escaping ImageHandler) { let converter = ASCIIConverter() converter.font = font converter.backgroundColor = bgColor converter.columns = columns converter.colorMode = colorMode converter.convertImage(self) { handler($0) } } }
mit
f0bbdf5818a98fef4a1d4ff8f9342abb
40.984127
244
0.711153
4.393688
false
false
false
false
brentdax/swift
benchmark/single-source/MonteCarloE.swift
9
1553
//===--- MonteCarloE.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 // //===----------------------------------------------------------------------===// // This test measures performance of Monte Carlo estimation of the e constant. // // We use 'dart' method: we split an interval into N pieces and drop N darts // to this interval. // After that we count number of empty intervals. The probability of being // empty is (1 - 1/N)^N which estimates to e^-1 for large N. // Thus, e = N / Nempty. import TestsUtils public let MonteCarloE = BenchmarkInfo( name: "MonteCarloE", runFunction: run_MonteCarloE, tags: [.validation, .algorithm]) public func run_MonteCarloE(scale: Int) { let N = 200000*scale var intervals = [Bool](repeating: false, count: N) for _ in 1...N { let pos = Int(UInt(truncatingIfNeeded: Random())%UInt(N)) intervals[pos] = true } let numEmptyIntervals = intervals.filter{!$0}.count // If there are no empty intervals, then obviously the random generator is // not 'random' enough. CheckResults(numEmptyIntervals != N) let e_estimate = Double(N)/Double(numEmptyIntervals) let e = 2.71828 CheckResults(abs(e_estimate - e) < 0.1) }
apache-2.0
adbde6fd24e6bca5f4c6ba4cc700d686
36.878049
80
0.649066
4.002577
false
false
false
false
prasanth223344/celapp
Cgrams/ATSketchKit/ATUnistrokeTemplate.swift
1
2322
// // ATUnistrokeTemplate.swift // ATSketchKit // // Created by Arnaud Thiercelin on 12/31/15. // Copyright © 2015 Arnaud Thiercelin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial // portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit class ATUnistrokeTemplate: NSObject { var name = "Unnamed" var points = [CGPoint]() var recognizedPathWithRect: ((_ rect: CGRect) -> UIBezierPath)! convenience init(json filePath: String) { self.init() let fileURL = URL(fileURLWithPath: filePath) do { let fileData = try Data(contentsOf: fileURL) let jsonObject = try JSONSerialization.jsonObject(with: fileData, options: .mutableContainers) as! Dictionary <String, AnyObject> self.name = jsonObject["name"] as! String let jsonPoints = jsonObject["points"] as! [Dictionary <String, Double>] for point in jsonPoints { let x = point["x"]! let y = point["y"]! self.points.append(CGPoint(x: x, y: y)) } } catch { // Error handling here if necessary } } override var description: String { get { return self.debugDescription } } override var debugDescription: String{ get { return "ATUnistrokeTemplate \n" + "Name: \(self.name)\n" + "Point: \(self.points)\n" + "Clean Path Making Closure: \(self.recognizedPathWithRect)\n" } } }
mit
ec9b5f581f822cd76be92bcb4622bb9e
33.132353
132
0.715209
3.881271
false
false
false
false
victorchee/Live
Live/RTMP/RTMPChunk.swift
1
8180
// // RTMPChunk.swift // RTMP // // Created by VictorChee on 2016/12/21. // Copyright © 2016年 VictorChee. All rights reserved. // import Foundation /// 消息分块、接受消息 final class RTMPChunk { /// RTMP 分成的Chunk有4中类型,可以通过 chunk basic header的 高两位指定,一般在拆包的时候会把一个RTMP消息拆成以 Type_0 类型开始的chunk,之后的包拆成 Type_3 类型的chunk enum ChunkType: UInt8 { /// Message Header占用11个字节,其他三种能表示的数据它都能表示,但在chunk stream的开始的第一个chunk和头信息中的时间戳后退(即值与上一个chunk相比减小,通常在回退播放的时候会出现这种情况)的时候必须采用这种格式 case zero = 0 /// Message Header占用7个字节,省去了表示msg stream id的4个字节,表示此chunk和上一次发的chunk所在的流相同,如果在发送端只和对端有一个流链接的时候可以尽量去采取这种格式。timestamp delta:占用3个字节,注意这里和type=0时不同,存储的是和上一个chunk的时间差。类似上面提到的timestamp,当它的值超过3个字节所能表示的最大值时,三个字节都置为1,实际的时间戳差值就会转存到Extended Timestamp字段中,接受端在判断timestamp delta字段24个位都为1时就会去Extended timestamp中解析时机的与上次时间戳的差值。 case one /// Message Header占用3个字节,相对于type=1格式又省去了表示消息长度的3个字节和表示消息类型的1个字节,表示此chunk和上一次发送的chunk所在的流、消息的长度和消息的类型都相同。余下的这三个字节表示timestamp delta,使用同type=1 case two /// 0字节,它表示这个chunk的Message Header和上一个是完全相同的,自然就不用再传输一遍了。当它跟在Type=0的chunk后面时,表示和前一个chunk的时间戳都是相同的。什么时候连时间戳都相同呢?就是一个Message拆分成了多个chunk,这个chunk和上一个chunk同属于一个Message。而当它跟在Type=1或者Type=2的chunk后面时,表示和前一个chunk的时间戳的差是相同的。比如第一个chunk的Type=0,timestamp=100,第二个chunk的Type=2,timestamp delta=20,表示时间戳为100+20=120,第三个chunk的Type=3,表示timestamp delta=20,时间戳为120+20=140 case three /** chunkStreamID 2~63 +-+-+-+-+-+-+-+-+ |fmt| stream id | +-+-+-+-+-+-+-+-+ 64~319 +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ |fmt| 0 | stream id | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ 64~65599 +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ |fmt| 1 | stream id | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ */ func createBasicHeader(_ streamID: UInt16) -> [UInt8] { if streamID <= 63 { return [rawValue << 6 | UInt8(streamID)] } else if streamID <= 319 { return [rawValue << 6 | 0b00000000, UInt8(streamID - 64)] } else { return [rawValue << 6 | 0b00111111] + (streamID - 64).bigEndian.bytes } } } static let ControlChannel: UInt16 = 0x02 static let CommandChannel: UInt16 = 0x03 static let AudioChannel: UInt16 = 0x05 static let VideoChannel: UInt16 = 0x06 static var inWindowAckSize: UInt32! /// Window Acknowledgement Size 是设置接收端消息窗口大小,一般是2500000字节,即告诉客户端你在收到我设置的窗口大小的这么多数据之后给我返回一个ACK消息,告诉我你收到了这么多消息。在实际做推流的时候推流端要接收很少的服务器数据,远远到达不了窗口大小,所以基本不用考虑这点。而对于服务器返回的ACK消息一般也不做处理,我们默认服务器都已经收到了这么多消息。 之后要等待服务器对于connect的回应的,一般是把服务器返回的chunk都读完组成完整的RTMP消息,没有错误就可以进行下一步了 static var outWindowAckChunkSize: UInt32 = 2500 * 1000 /// Chunk basic header(1~3B) /// chunkType决定了消息头的编码格式(2b) var chunkType = ChunkType.zero // chunk type -> fmt /// RTMP 的Chunk Steam ID是用来区分某一个chunk是属于哪一个message的 ,0和1是保留的。每次在发送一个不同类型的RTMP消息时都要有不用的chunk stream ID, 如上一个Message 是command类型的,之后要发送视频类型的消息,视频消息的chunk stream ID 要保证和上面 command类型的消息不同。每一种消息类型的起始chunk 的类型必须是 zero 类型的,表明这是一个新的消息的起始 var chunkStreamID: UInt16 = 0 /// Chunk message header var timestamp: UInt32! // 4B Timestamp var messageStreamID: UInt32! // 4B Stream ID var messageType: MessageType! // 1B message Type /// Split message into chunks class func splitMessage(_ message: RTMPMessage, chunkSize: Int, chunkType: ChunkType, chunkStreamID: UInt16) -> [UInt8]? { var buffer = [UInt8]() // Basic header buffer += chunkType.createBasicHeader(chunkStreamID) // Message header(下面只处理了zero和one两种情况,two和three未处理) /* zero +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-| | timestamp | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-| | message length | |-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-| |message type id| |-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ | message stream id | |-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ one +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-| | timestamp delta | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-| | message length | |-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-| |message type id| |-+-+-+-+-+-+-+-+ two +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ | timestamp delta | +-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-+ three empty message header */ buffer += (message.timestamp >= 0xffffff ? [0xff, 0xff, 0xff] : message.timestamp.bigEndian.bytes[1...3]) // 3B timestamp buffer += UInt32(message.payloadLength).bigEndian.bytes[1...3] // 3B payload length buffer.append(message.messageType.rawValue) // 1B message type if chunkType == .zero { // Only type 0 has the message stream id buffer += message.messageStreamID.littleEndian.bytes // 4B message stream id } // 4B extended timestamp if message.timestamp >= 0xffffff { buffer += message.timestamp.bigEndian.bytes } // Chunk data if message.payloadLength < chunkSize { buffer += message.payload } else { var remainingCount = message.payloadLength var position = 0 while remainingCount > chunkSize { buffer += message.payload[position..<(position+chunkSize)] remainingCount -= chunkSize position += chunkSize // 第一个chunk为zero,以后的chunk都为three buffer += ChunkType.three.createBasicHeader(chunkStreamID) } buffer += message.payload[position..<(position+remainingCount)] } return buffer } }
mit
f154931986af7f6e906e1a2146ff5bcf
44.804348
356
0.530612
3.233248
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0165.xcplaygroundpage/Contents.swift
1
24660
/*: # Dictionary & Set Enhancements - Proposal: [SE-0165](0165-dict.md) - Author: [Nate Cook](https://github.com/natecook1000) - Review Manager: [Ben Cohen](https://github.com/airspeedswift) - Status: **Implemented (Swift 4)** - Decision Notes: [Rationale][rationale] ## Introduction This proposal comprises a variety of commonly (and less commonly) suggested improvements to the standard library's `Dictionary` type, from merging initializers to dictionary-specific `filter` and `mapValues` methods. The proposed additions to `Dictionary`, and the corresponding changes to `Set`, are detailed in the sections below. - Suggested Improvements: - [Merging initializers and methods](#1-merging-initializers-and-methods) - [Key-based subscript with default value](#2-key-based-subscript-with-default-value) - [Dictionary-specific map and filter](#3-dictionary-specific-map-and-filter) - [Visible `Dictionary` capacity](#4-visible-dictionary-capacity) - [Grouping sequence elements](#5-grouping-sequence-elements) - [Relevant changes to `Set`](#6-apply-relevant-changes-to-set) - [Detailed Design](#detailed-design) - [Sandbox with Prototype][sandbox] - [Source Compatibility](#source-compatibility) --- ## 1. Merging initializers and methods The `Dictionary` type should allow initialization from a sequence of `(Key, Value)` tuples and offer methods that merge a sequence of `(Key, Value)` tuples into a new or existing dictionary, using a closure to combine values for duplicate keys. - [First message of discussion thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160104/006124.html) - [Initial proposal draft](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160111/006665.html) - [Prior standalone proposal (SE-100)](https://github.com/apple/swift-evolution/blob/master/proposals/0100-add-sequence-based-init-and-merge-to-dictionary.md) `Array` and `Set` both have initializers that create a new instance from a sequence of elements. The `Array` initializer is useful for converting other sequences and collections to the "standard" collection type, while the `Set` initializer is essential for recovering set operations after performing any functional operations on a set. For example, filtering a set produces a collection without any set operations available. ```swift let numberSet = Set(1 ... 100) let fivesOnly = numberSet.lazy.filter { $0 % 5 == 0 } ``` `fivesOnly` is a `LazyFilterCollection<Set<Int>>` instead of a `Set`—sending that back through the `Set` sequence initializer restores the expected methods. ```swift let fivesOnlySet = Set(numberSet.lazy.filter { $0 % 5 == 0 }) fivesOnlySet.isSubsetOf(numberSet) // true ``` `Dictionary`, on the other hand, has no such initializer, so a similar operation leaves no room to recover dictionary functionality without building a mutable `Dictionary` via iteration or functional methods. These techniques also don't support type inference from the source sequence, increasing verbosity. ```swift let numberDictionary = ["one": 1, "two": 2, "three": 3, "four": 4] let evenOnly = numberDictionary.lazy.filter { (_, value) in value % 2 == 0 } var viaIteration: [String: Int] = [:] for (key, value) in evenOnly { viaIteration[key] = value } let viaReduce: [String: Int] = evenOnly.reduce([:]) { (cumulative, kv) in var dict = cumulative dict[kv.key] = kv.value return dict } ``` Beyond initialization, `Array` and `Set` both also provide a method to add a new block of elements to an existing collection. `Array` provides this via `append(contentsOf:)` for the common appending case or `replaceSubrange(_:with:)` for general inserting or replacing, while the unordered `Set` type lets you pass any sequence to `unionInPlace(_:)` to add elements to an existing set. Once again, `Dictionary` has no corresponding API -- looping and adding elements one at a time as shown above is the only way to merge new elements into an existing dictionary. ### Proposed solution This proposal puts forward two new ways to convert `(Key, Value)` sequences to dictionary form: an initializer and a set of merging APIs that handle input data with duplicate keys. #### Sequence-based initializer The proposed solution would add a new initializer to `Dictionary` that accepts any sequence of `(Key, Value)` tuple pairs. ```swift init<S: Sequence where S.Iterator.Element == (key: Key, value: Value)>( uniqueKeysWithValues: S) ``` With the proposed initializer, creating a `Dictionary` instance from a sequence of key/value pairs is as easy as creating an `Array` or `Set`: ```swift let viaProposed = Dictionary(uniqueKeysWithValues: evenOnly) ``` Like `Array.init(_:)` and `Set.init(_:)`, this is a full-width initializer. To ensure this, the initializer has a precondition that each key in the supplied sequence is unique, and traps whenever that condition isn't met. When duplicate keys are possible in the input, the merging initializer described in the next section must be used instead. The new initializer allows for some convenient uses that aren't currently possible. - Initializing from a `DictionaryLiteral` (the type, not an actual literal) ```swift let literal: DictionaryLiteral = ["a": 1, "b": 2, "c": 3, "d": 4] let dictFromDL = Dictionary(uniqueKeysWithValues: literal) ``` - Converting an array to an indexed dictionary (popular on the thread) ```swift let names = ["Cagney", "Lacey", "Bensen"] let dict = Dictionary(uniqueKeysWithValues: names.enumerated().map { (i, val) in (i + 1, val) }) // [2: "Lacey", 3: "Bensen", 1: "Cagney"] ``` - Initializing from a pair of zipped sequences (examples abound) ```swift let letters = "abcdef".characters.lazy.map(String.init) let dictFromZip = Dictionary(uniqueKeysWithValues: zip(letters, 1...10)) // ["b": 2, "e": 5, "a": 1, "f": 6, "d": 4, "c": 3] ``` > This particular use is currently blocked by [SR-922](https://bugs.swift.org/browse/SR-922). As a workaround, add `.map {(key: $0, value: $1)}`. #### Merging initializer and methods Creating a `Dictionary` from a dictional literal checks the keys for uniqueness, trapping on a duplicate. The sequence-based initializer shown above has the same requirement. ```swift let duplicates: DictionaryLiteral = ["a": 1, "b": 2, "a": 3, "b": 4] let letterDict = Dictionary(uniqueKeysWithValues: duplicates) // error: Duplicate key found: "a" ``` Because some use cases can be forgiving of duplicate keys, this proposal includes a second new initializer. This initializer allows the caller to supply, along with the sequence, a combining closure that's called with the old and new values for any duplicate keys. ```swift init<S: Sequence>( _ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows where S.Iterator.Element == (key: Key, value: Value) ``` This example shows how one could keep the first value of all those supplied for a duplicate key. ```swift let letterDict2 = Dictionary(duplicates, uniquingKeysWith: { (first, _) in first }) // ["b": 2, "a": 1] ``` Or the largest value for any duplicate keys. ```swift let letterDict3 = Dictionary(duplicates, uniquingKeysWith: max) // ["b": 4, "a": 3] ``` At other times the merging initializer could be used to combine values for duplicate keys. Donnacha Oisín Kidney wrote a neat `frequencies()` method for sequences as an example of such a use in the thread. ```swift extension Sequence where Iterator.Element: Hashable { func frequencies() -> [Iterator.Element: Int] { return Dictionary(self.lazy.map { v in (v, 1) }, uniquingKeysWith: +) } } [1, 2, 2, 3, 1, 2, 4, 5, 3, 2, 3, 1].frequencies() // [2: 4, 4: 1, 5: 1, 3: 3, 1: 3] ``` This proposal also includes new mutating and non-mutating methods for `Dictionary` that merge the contents of a sequence of `(Key, Value)` tuples into an existing dictionary, `merge(_:uniquingKeysWith:)` and `merging(_:uniquingKeysWith:)`. ```swift mutating func merge<S: Sequence>( _ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows where S.Iterator.Element == (key: Key, value: Value) func merging<S: Sequence>( _ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows -> [Key: Value] where S.Iterator.Element == (key: Key, value: Value) ``` As above, there are a wide variety of uses for the merge. ```swift // Adding default values let defaults: [String: Bool] = ["foo": false, "bar": false, "baz": false] var options: [String: Bool] = ["foo": true, "bar": false] options.merge(defaults) { (old, _) in old } // options is now ["foo": true, "bar": false, "baz": false] // Summing counts repeatedly var bugCounts: [String: Int] = ["bees": 9, "ants": 112, ...] while bugCountingSource.hasMoreData() { bugCounts.merge(bugCountingSource.countMoreBugs(), uniquingKeysWith: +) } ``` --- ## 2. Key-based subscript with default value Another common challenge with dictionaries is iteratively making changes to key/value pairs that may or may not already be present. For example, to iteratively add count the frequencies of letters in a string, one might write something like the following: ```swift let source = "how now brown cow" var frequencies: [Character: Int] = [:] for c in source.characters { if frequencies[c] == nil { frequencies[c] = 1 } else { frequencies[c]! += 1 } } ``` Testing for `nil` and assigning through the force unwrapping operator are awkward at best for such a common operation. Furthermore, the `Optional<Value>` return type of the current keyed subscript complicates efficiencies that could be gained for this type of `modify` action under a future ownership model. ### Proposed solution A keyed subscript with a default value neatly simplifies this usage. Instead of checking for `nil`, one can pass the default value along with the key as a `default` subscript parameter. ```swift let source = "how now brown cow" var frequencies: [Character: Int] = [:] for c in source.characters { frequencies[c, default: 0] += 1 } ``` The return type of this subscript is a non-optional `Value`. Note that accessing the subscript as a getter does not store the default value in the dictionary—the following two lines are equivalent: ```swift let x = frequencies["a", default: 0] let y = frequencies["a"] ?? 0 ``` --- ## 3. Dictionary-specific map and filter The standard `map` and `filter` methods, while always useful and beloved, aren't ideal when applied to dictionaries. In both cases, the desired end-result is frequently another dictionary instead of an array of key-value pairs—even with the sequence-based initializer proposed above this is an inefficient way of doing things. Additionally, the standard `map` method doesn't gracefully support passing a function when transforming only the *values* of a dictionary. The transform function must accept and return key/value pairs, necessitating a custom closure in nearly every case. Assuming the addition of a sequence-based initializer, the current `filter` and `map` look like the following: ```swift let numbers = ["one": 1, "two": 2, "three": 3, "four": 4] let evens = Dictionary(numbers.lazy.filter { $0.value % 2 == 0 })! // ["four": 4, "two": 2] let strings = Dictionary(numbers.lazy.map { (k, v) in (k, String(v)) })! // ["three": "3", "four": "4", "one": "1", "two": "2"] ``` ### Proposed solution This proposal adds two new methods for `Dictionary`: 1. A `mapValues` method that keeps a dictionary's keys intact while transforming the values. Mapping a dictionary's key/value pairs can't always produce a new dictionary, due to the possibility of key collisions, but mapping only the values can produce a new dictionary with the same underlying layout as the original. ```swift let strings = numbers.mapValues(String.init) // ["three": "3", "four": "4", "one": "1", "two": "2"] ``` 2. A `Dictionary`-returning `filter` method. While transforming the keys and values of a dictionary can result in key collisions, filtering the elements of a dictionary can at worst replicate the entire dictionary. ```swift let evens = numbers.filter { $0.value % 2 == 0 } // ["four": 4, "two": 2] ``` Both of these can be made significantly more efficient than their `Sequence`-sourced counterparts. For example, the `mapValues` method can simply copy the portion of the storage that holds the keys to the new dictionary before transforming the values. --- ## 4. Visible dictionary capacity As you add elements to a dictionary, it automatically grows its backing storage as necessary. This reallocation is a significant operation—unlike arrays, where the existing elements can be copied to a new block of storage en masse, every key/value pair must be moved over individually, recalculating the hash value for the key to find its position in the larger backing buffer. While dictionaries uses an exponential growth strategy to make this as efficient as possible, beyond the `init(minimumCapacity:)` initializer they do not expose a way to reserve a specific capacity. In addition, adding a key/value pair to a dictionary is guaranteed not to invalidate existing indices as long as the capacity doesn't change, yet we don't provide any way of seeing a dictionary's current or post-addition capacity. ### Proposed solution `Dictionary` should add a `capacity` property and a `reserveCapacity(_:)` method, like those used in range-replaceable collections. The `capacity` of a dictionary is the number of elements it can hold without reallocating a larger backing storage, while calling `reserveCapacity(_:)` allocates a large enough buffer to hold the requested number of elements without reallocating. ```swift var numbers = ["one": 1, "two": 2, "three": 3, "four": 4] numbers.capacity // 6 numbers.reserveCapacity(20) numbers.capacity // 24 ``` Because hashed collections use extra storage capacity to reduce the likelihood and cost of collisions, the value of the `capacity` property won't be equal to the actual size of the backing storage. Likewise, the capacity after calling `reserveCapacity(_:)` will be at least as large as the argument, but usually larger. (In its current implementation, `Dictionary` always has a power of 2-sized backing storage.) --- ## 5. Grouping sequence elements As a final `Dictionary`-related issue, grouping elements in a sequence by some computed key is a commonly requested addition that we can add as part of this omnibus proposal. Call a new `Dictionary(grouping:by:)` initializer with a closure that converts each value in a sequence to a hashable type `T`; the result is a dictionary with keys of type `T` and values of type `[Iterator.Element]`. ```swift let names = ["Patti", "Aretha", "Anita", "Gladys"] // By first letter Dictionary(grouping: names, by: { $0.characters.first! }) // ["P": ["Patti"], "G": ["Gladys"], "A": ["Aretha", "Anita"]] // By name length Dictionary(grouping: names) { $0.utf16.count } // [5: ["Patti", "Anita"], 6: ["Aretha", "Gladys"]] ``` --- ## 6. Apply relevant changes to `Set` As the `Set` and `Dictionary` types are similar enough to share large chunks of their implementations, it makes sense to look at which of these `Dictionary` enhancements can also be applied to `Set`. Of the symbols proposed above, the following additions would also be useful and appropriate for the `Set` type: - Add a `Set`-specific `filter` method that returns a new set—this would function essentially as a predicate-based `intersection` method. - Add a `capacity` property and `reserveCapacity()` method, for the reasons listed above. ## Detailed design With the exception of the proposed capacity property and method, the proposed additions to `Dictionary`, `Set`, and `Sequence` are available in [this Swift Sandbox][sandbox]. Note that this prototype is not a proposed implementation; rather a way to try out the behavior of the proposed changes. Collected in one place, these are the new APIs for `Dictionary`, `Set`, and `Sequence`: ```swift struct Dictionary<Key: Hashable, Value> { typealias Element = (key: Key, value: Value) // existing declarations /// Creates a new dictionary using the key/value pairs in the given sequence. /// If the given sequence has any duplicate keys, the result is `nil`. init<S: Sequence>(uniqueKeysWithValues: S) where S.Iterator.Element == Element /// Creates a new dictionary using the key/value pairs in the given sequence, /// using a combining closure to determine the value for any duplicate keys. init<S: Sequence>( _ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows where S.Iterator.Element == Element /// Creates a new dictionary where the keys are the groupings returned by /// the given closure and the values are arrays of the elements that /// returned each specific key. init<S: Sequence>( grouping values: S, by keyForValue: (S.Iterator.Element) throws -> Key ) rethrows where Value == [S.Iterator.Element] /// Merges the key/value pairs in the given sequence into the dictionary, /// using a combining closure to determine the value for any duplicate keys. mutating func merge<S: Sequence>( _ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows where S.Iterator.Element == Element /// Returns a new dictionary created by merging the key/value pairs in the /// given sequence into the dictionary, using a combining closure to determine /// the value for any duplicate keys. func merging<S: Sequence>( _ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows -> [Key: Value] where S.Iterator.Element == Element /// Accesses the element with the given key, or the specified default value, /// if the dictionary doesn't contain the given key. subscript(key: Key, default defaultValue: Value) -> Value { get set } /// Returns a new dictionary containing the key/value pairs that satisfy /// the given predicate. func filter(_ isIncluded: (Key, Value) throws -> Bool) rethrows -> [Key: Value] /// Returns a new dictionary containing the existing keys and the results of /// mapping the given closure over the dictionary's values. func mapValues<T>(_ transform: (Value) throws -> T) rethrows -> [Key: T] /// The number of key/value pairs that can be stored by the dictionary without /// reallocating storage. var capacity: Int { get } /// Ensures that the dictionary has enough storage for `capacity` key/value /// pairs. var reserveCapacity(_ capacity: Int) } struct Set<Element: Hashable> { // existing declarations /// Returns a new set containing the elements that satisfy the given predicate. func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Set /// The number of elements that can be stored by the set without /// reallocating storage. var capacity: Int { get } /// Ensures that the set has enough storage for `capacity` elements. var reserveCapacity(_ capacity: Int) } ``` ## Alternatives Considered - An earlier version of this proposal declared the first merging initializer as failable, returning `nil` when a sequence with duplicate keys was passed. That initializer is really only appropriate when working with known unique keys, however, as there isn't a feasible recovery path when there can be duplicate keys. That leaves two possibilities: 1. The source input can *never* have duplicate keys, and the programmer has to write `!` or unwrap in some other way, or 2. The source input *can* have duplicate keys, in which case the programmer should be using `init(merging:mergingValues:)` instead. - An earlier version of this proposal included the addition of two new top-level functions to the standard library: `first(_:_:)` and `last(_:_:)`, which return their first and last arguments, respectively. These new functions would be passed instead of a custom closure to a merging method or initializer: ```swift let firstWins = Dictionary(merging: duplicates, mergingValues: first) // ["b": 2, "a": 1] let lastWins = Dictionary(merging: duplicates, mergingValues: last) // ["b": 4, "a": 3] ``` As an alternative to the `first(_:_:)` and `last(_:_:)` functions, at the cost of three additional overloads for the merging initializer and methods, we could allow users to specify the `useFirst` and `useLast` cases of a `MergeCollisionStrategy` enumeration. ```swift extension Dictionary { /// The strategy to use when merging a sequence of key-value pairs into a dictionary. enum MergeCollisionStrategy { /// If there is more than one instance of a key in the sequence to merge, use /// only the first value for the dictionary. case useFirst /// If there is more than one instance of a key in the sequence to merge, use /// only the last value for the dictionary. case useLast } init<S: Sequence>( merging keysAndValues: S, mergingValues strategy: MergeCollisionStrategy ) // other merging overloads } ``` In use, this overload would look similar to the functional version, but may aid in discoverability: ```swift let firstWins = Dictionary(merging: duplicates, mergingValues: .useFirst) // ["b": 2, "a": 1] let lastWins = Dictionary(merging: duplicates, mergingValues: .useLast) // ["b": 4, "a": 3] ``` - An earlier version of this proposal included a change to both collections' `remove(at:)` method, such that it would return both the removed element and the next valid index in the iteration sequence. This change lets a programmer write code that would remove elements of a dictionary or a set in place, which can't currently be done with as much efficiency due to index invalidation: ```swift var i = dict.startIndex while i != dict.endIndex { if shouldRemove(dict[i]) { (_, i) = dict.remove(at: i) } else { dict.formIndex(after: &i) } } ``` This change to `remove(at:)` has been deferred to a later proposal that can better deal with the impact on existing code. - The reviewed version of this proposal had different spelling of the merging initializers and methods: ```swift init<S: Sequence where S.Iterator.Element == (key: Key, value: Value)>( _ keysAndValues: S) init<S: Sequence>( merging keysAndValues: S, mergingValues combine: (Value, Value) throws -> Value ) rethrows where S.Iterator.Element == (key: Key, value: Value) mutating func merge<S: Sequence>( _ other: S, mergingValues combine: (Value, Value) throws -> Value ) rethrows where S.Iterator.Element == (key: Key, value: Value) func merged<S: Sequence>( with other: S, mergingValues combine: (Value, Value) throws -> Value ) rethrows -> [Key: Value] where S.Iterator.Element == (key: Key, value: Value) ``` In addition, the `Dictionary(grouping:by:)` initializer was proposed as a `grouped(by:)` method on the `Sequence` protocol. The [rationale][] for accepting the proposal explains the reasons for these changes. ## Source compatibility All the proposed additions are purely additive and should impose only a minimal source compatibility burden. The addition of same-type returning `filter(_:)` methods to `Dictionary` and `Set` could cause problems if code is relying on the previous behavior of returning an array. For example, the following code would break after this change: ```swift let digits = Set(0..<10) let evens = digits.filter { $0 % 2 == 0 } functionThatTakesAnArray(evens) ``` To mitigate the impact of this on code compiled in Swift 3 mode, `Dictionary` and `Set` will have an additional overload of the `Array`-returning `filter(_:)` that is marked as obsoleted in Swift 4. This will allow Swift 3 code to continue to compile and work as expected: ```swift extension Set { @available(swift, obsoleted: 4) func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element] @available(swift, introduced: 4) func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Set<Element> } ``` [sandbox]: http://swift.sandbox.bluemix.net/#/repl/58f8e3aee785f75678f428a8 [rationale]: https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170417/035955.html ---------- [Previous](@previous) | [Next](@next) */
mit
0fb9496557b410299399a2d5d6d39c3f
46.130019
429
0.719137
4.109537
false
false
false
false
edx/edx-app-ios
Source/Core/Test/Code/Array+FunctionalTests.swift
5
2092
// // Array+FunctionalTests.swift // edX // // Created by Akiva Leffert on 5/4/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit import XCTest import edXCore class Array_FunctionalTests: XCTestCase { func testMapOrNilSuccess() { let list = [1, 2, 3] let result = list.mapOrFailIfNil { return $0 + 1 } XCTAssertEqual([2, 3, 4], result!) } func testMapOrNilFailure() { let list = [1, 2, 3] let result = list.mapOrFailIfNil { i -> Int? in if i == 1 { return nil } else { return i + 1 } } XCTAssertNil(result) } func testMapSkippingNil() { let list = [1, 2, 3] let result = list.mapSkippingNils {i -> Int? in if i == 2 { return nil } else { return i + 1 } } XCTAssertEqual(result, [2, 4]) } func testFirstIndexMatchingSuccess() { let list = [1, 2, 3, 2, 4] let i = list.firstIndexMatching({$0 == 2}) XCTAssertEqual(1, i!) } func testFirstIndexMatchingFailure() { let list = [1, 2, 3, 2, 4] let i = list.firstIndexMatching({$0 == 10}) XCTAssertNil(i) } func testWithItemIndexes() { let list = ["a", "b", "c"] let result = list.withItemIndexes() XCTAssertEqual(result.count, list.count) for i in 0 ..< list.count { XCTAssertEqual(list[i], result[i].value) XCTAssertEqual(i, result[i].index) } } func testInterposeExpected() { let list = [1, 2, 3] let result = list.interpose({ 10 }) XCTAssertEqual(result, [1, 10, 2, 10, 3]) } func testInterposeNewItem() { let list = [1, 2, 3] var counter = 10 let result = list.interpose { counter = counter + 1 return counter } XCTAssertEqual(result, [1, 11, 2, 12, 3]) } }
apache-2.0
f3c517d425e3cc36aff2f2615eed88a2
23.325581
55
0.490918
4
false
true
false
false
PFei-He/PFSwift
PFSwift/PFString.swift
1
5658
// // PFString.swift // PFSwift // // Created by PFei_He on 15/11/17. // Copyright © 2015年 PF-Lib. All rights reserved. // // https://github.com/PFei-He/PFSwift // // 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. // // ***** String扩展 ***** // import Foundation extension String { /** 判断是否QQ号码 - Note: 无 - Parameter 无 - Returns: 判断结果 */ public func isQQ() -> Bool { let regex = "(^[0-9]*$)" let predicate = NSPredicate(format: "SELF MATCHES %@", regex) return predicate.evaluateWithObject(self) } /** 判断是否邮箱地址 - Note: 无 - Parameter 无 - Returns: 判断结果 */ public func isEmail() -> Bool { let regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" let predicate = NSPredicate(format: "SELF MATCHES %@", regex) return predicate.evaluateWithObject(self) } /** 判断是否URL - Note: 无 - Parameter 无 - Returns: 判断结果 */ public func isURL() -> Bool { let regex = "(http[s]{0,1}|ftp):\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?" let predicate = NSPredicate(format: "SELF MATCHES %@", regex) return predicate.evaluateWithObject(self) } /** 判断是否手机号码 - Note: 无 - Parameter 无 - Returns: 判断结果 */ public func isMobilePhoneNumber() -> Bool { let regexMobile = "^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$" let regexCM = "^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$" let regexCU = "^1(3[0-2]|5[256]|8[56])\\d{8}$" let regexCT = "^1((33|53|8[09])[0-9]|349)\\d{7}$" let regexPHS = "^0(10|2[0-5789]|\\d{3})\\d{7,8}$" let predicateMobile = NSPredicate(format: "SELF MATCHES %@", regexMobile) let predicateCM = NSPredicate(format: "SELF MATCHES %@", regexCM) let predicateCU = NSPredicate(format: "SELF MATCHES %@", regexCU) let predicateCT = NSPredicate(format: "SELF MATCHES %@", regexCT) let predicatePHS = NSPredicate(format: "SELF MATCHES %@", regexPHS) return predicateMobile.evaluateWithObject(self) || predicateCM.evaluateWithObject(self) || predicateCU.evaluateWithObject(self) || predicateCT.evaluateWithObject(self) || predicatePHS.evaluateWithObject(self) } /** 匹配邮箱地址 - Note: 无 - Parameter string: 需要匹配的字符串 - Returns: 寻找出的邮箱地址 */ public func matchesEmail(string: String) -> String { let regulaStr = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" let regex = try? NSRegularExpression(pattern: regulaStr, options: NSRegularExpressionOptions.CaseInsensitive) let arrayOfAllMatches = regex?.matchesInString(string, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, string.characters.count)) var matchesStr: String? for match in arrayOfAllMatches! { matchesStr = (string as NSString).substringWithRange(match.range) } return matchesStr! } /** 匹配URL - Note: 无 - Parameter string: 需要匹配的字符串 - Returns: 寻找出的URL */ public func matchesURL(string: String) -> String { let regulaStr = "(http[s]{0,1}|ftp):\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?" let regex = try? NSRegularExpression(pattern: regulaStr, options: NSRegularExpressionOptions.CaseInsensitive) let arrayOfAllMatches = regex?.matchesInString(string, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, string.characters.count)) var matchesStr: String? for match in arrayOfAllMatches! { matchesStr = (string as NSString).substringWithRange(match.range) } return matchesStr! } } extension String { /** 本地化 - Note: 无 - Parameter 无 - Returns: 当前语言环境对应的值 */ public var localized: String { return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "") } /** 本地化带注释 - Note: 无 - Parameter comment: 本地化文件中的注释 - Returns: 当前语言环境对应的值 */ public func localizedWithComment(comment: String) -> String { return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: comment) } }
mit
4c3fc7297b89171f1bb2d5da9a879f19
33.793548
153
0.61005
3.948023
false
false
false
false
Babylonpartners/ReactiveFeedback
Example/SingleStoreExample/Movies/MoviesView.swift
1
3259
import UIKit import ReactiveFeedback final class MoviesViewController: ContainerViewController<MoviesView> { private let store: Store<Movies.State, Movies.Event> init(store: Store<Movies.State, Movies.Event>) { self.store = store super.init() } override func viewDidLoad() { super.viewDidLoad() store.state.producer.startWithValues(contentView.render) contentView.didSelectItem.action = { [unowned self] movie in let nc = self.navigationController! let vc = ColorPickerViewController( store: self.store.view( value: \.colorPicker, event: Movies.Event.picker ) ) nc.pushViewController(vc, animated: true) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } final class MoviesView: UICollectionView, NibLoadable, UICollectionViewDelegateFlowLayout { public let didSelectItem = CommandWith<Movie>() private let adapter = ArrayCollectionViewDataSource<Movie>() private let loadNext = Command() private var isReloadInProgress = false override func awakeFromNib() { super.awakeFromNib() self.dataSource = adapter register(MovieCell.nib, forCellWithReuseIdentifier: "\(MovieCell.self)") adapter.cellFactory = { (collectionView, indexPath, item) -> UICollectionViewCell in let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "\(MovieCell.self)", for: indexPath ) as! MovieCell cell.configure(with: item) return cell } self.delegate = self } func render(context: Context<Movies.State, Movies.Event>) { adapter.update(with: context.movies) backgroundColor = context.backgroundColor loadNext.action = { context.send(event: .startLoadingNextPage) } reloadData() } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let movie = adapter.items[indexPath.row] didSelectItem.action(movie) } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if indexPath.row == adapter.items.count - 1 { // Because feedbacks are now synchronous // Dispatching some events may cause a dead lock // because collection view calls it again during reload data DispatchQueue.main.async { self.loadNext.action() } } } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize { let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout let spacing = flowLayout.minimumInteritemSpacing let width = (collectionView.bounds.width - 3 * spacing) / 3 return CGSize( width: width, height: width * 1.5 ) } }
mit
2128df262e8cc07d1458ae43c2b8ca0e
34.043011
133
0.623197
5.580479
false
false
false
false
taxfix/native-navigation
lib/ios/native-navigation/ReactNavigationImplementation.swift
1
22025
// // ReactNavigationImplementation.swift // NativeNavigation // // Created by Leland Richardson on 2/14/17. // // import Foundation import UIKit import React @objc public protocol ReactNavigationImplementation: class { func makeNavigationController(rootViewController: UIViewController) -> UINavigationController func reconcileScreenConfig( viewController: ReactViewController, navigationController: UINavigationController?, prev: [String: AnyObject], next: [String: AnyObject] ) func reconcileTabConfig( tabBarItem: UITabBarItem, prev: [String: AnyObject], next: [String: AnyObject] ) func reconcileTabBarConfig( tabBar: UITabBar, prev: [String: AnyObject], next: [String: AnyObject] ) func getBarHeight(viewController: ReactViewController, navigationController: UINavigationController?, config: [String: AnyObject]) -> CGFloat; } // this is a convenience class to allow us to easily assign lambdas as press handlers class BlockBarButtonItem: UIBarButtonItem { var actionHandler: (() -> Void)? convenience init(title: String?, style: UIBarButtonItemStyle) { self.init(title: title, style: style, target: nil, action: #selector(barButtonItemPressed)) self.target = self } convenience init(image: UIImage?, style: UIBarButtonItemStyle) { self.init(image: image, style: style, target: nil, action: #selector(barButtonItemPressed)) self.target = self } convenience init(barButtonSystemItem: UIBarButtonSystemItem) { self.init(barButtonSystemItem: barButtonSystemItem, target: nil, action: #selector(barButtonItemPressed)) self.target = self } convenience init( title: String?, image: UIImage?, barButtonSystemItem: UIBarButtonSystemItem?, style: UIBarButtonItemStyle, enabled: Bool?, tintColor: UIColor?, titleTextAttributes: [NSAttributedStringKey: Any]? ) { if let barButtonSystemItem = barButtonSystemItem { self.init(barButtonSystemItem: barButtonSystemItem) } else if let title = title { self.init(title: title, style: style) } else { self.init(image: image, style: style) } if let enabled = enabled { isEnabled = enabled } if let tintColor = tintColor { self.tintColor = tintColor } if let titleTextAttributes = titleTextAttributes { // TODO(lmr): what about other control states? do we care? setTitleTextAttributes(titleTextAttributes, for: .normal) } } @objc func barButtonItemPressed(sender: UIBarButtonItem) { actionHandler?() } } func stringHasChanged(_ key: String, _ prev: [String: AnyObject], _ next: [String: AnyObject]) -> Bool { let a = stringForKey(key, prev) let b = stringForKey(key, next) if let a = a, let b = b { return a != b } else if let _ = a { return true } else if let _ = b { return true } return false } func boolHasChanged(_ key: String, _ prev: [String: AnyObject], _ next: [String: AnyObject]) -> Bool { let a = boolForKey(key, prev) let b = boolForKey(key, next) if let a = a, let b = b { return a != b } else if let _ = a { return true } else if let _ = b { return true } return false } func numberHasChanged(_ key: String, _ prev: [String: AnyObject], _ next: [String: AnyObject]) -> Bool { if let before = prev[key] as? NSNumber { if let after = next[key] as? NSNumber { return before != after } else { return true } } else if let _ = next[key] as? NSNumber { return true } return false } func mapHasChanged(_ key: String, _ prev: [String: AnyObject], _ next: [String: AnyObject]) -> Bool { if let _ = prev[key] { if let _ = next[key] { return true // TODO: could do more here... } else { return true } } else if let _ = next[key] { return true } return false } func colorForKey(_ key: String, _ props: [String: AnyObject]) -> UIColor? { guard let val = props[key] as? NSNumber else { return nil } let argb: UInt = val.uintValue; let a = CGFloat((argb >> 24) & 0xFF) / 255.0; let r = CGFloat((argb >> 16) & 0xFF) / 255.0; let g = CGFloat((argb >> 8) & 0xFF) / 255.0; let b = CGFloat(argb & 0xFF) / 255.0; return UIColor(red: r, green: g, blue: b, alpha: a) } func stringForKey(_ key: String, _ props: [String: AnyObject]) -> String? { if let val = props[key] as? String?, (val != nil) { return val } return nil } func intForKey(_ key: String, _ props: [String: AnyObject]) -> Int? { if let val = props[key] as? Int { return val } return nil } func floatForKey(_ key: String, _ props: [String: AnyObject]) -> CGFloat? { if let val = props[key] as? CGFloat { return val } return nil } func doubleForKey(_ key: String, _ props: [String: AnyObject]) -> Double? { if let val = props[key] as? Double { return val } return nil } func boolForKey(_ key: String, _ props: [String: AnyObject]) -> Bool? { if let val = props[key] as? Bool { return val } return nil } func imageForKey(_ key: String, _ props: [String: AnyObject]) -> UIImage? { if let json = props[key] as? NSDictionary { return RCTConvert.uiImage(json) } return nil } func barButtonStyleFromString(_ string: String?) -> UIBarButtonItemStyle { switch(string) { case .some("done"): return .done default: return .plain } } func barButtonSystemItemFromString(_ string: String?) -> UIBarButtonSystemItem? { switch string { case .some("done"): return .done case .some("cancel"): return .cancel case .some("edit"): return .edit case .some("save"): return .save case .some("add"): return .add case .some("flexibleSpace"): return .flexibleSpace // case .some("fixedSpace"): return .fixedSpace case .some("compose"): return .compose case .some("reply"): return .reply case .some("action"): return .action case .some("organize"): return .organize case .some("bookmarks"): return .bookmarks case .some("search"): return .search case .some("refresh"): return .refresh case .some("stop"): return .stop case .some("camera"): return .camera case .some("trash"): return .trash case .some("play"): return .play case .some("pause"): return .pause case .some("rewind"): return .rewind case .some("fastForward"): return .fastForward case .some("undo"): return .undo case .some("redo"): return .redo case .some("pageCurl"): return .pageCurl default: return nil } } func statusBarStyleFromString(_ string: String?) -> UIStatusBarStyle { switch(string) { case .some("light"): return .lightContent default: return .default } } func statusBarAnimationFromString(_ string: String?) -> UIStatusBarAnimation { switch(string) { case .some("slide"): return .slide case .some("none"): return .none default: return UIStatusBarAnimation.fade } } func textAttributesFromPrefix( _ prefix: String, _ props: [String: AnyObject] ) -> [NSAttributedStringKey: Any]? { var attributes: [NSAttributedStringKey: Any] = [:] if let color = colorForKey("\(prefix)Color", props) { attributes[NSAttributedStringKey.foregroundColor] = color } else if let color = colorForKey("foregroundColor", props) { attributes[NSAttributedStringKey.foregroundColor] = color } let fontName = stringForKey("\(prefix)FontName", props) let fontSize = floatForKey("\(prefix)FontSize", props) // TODO(lmr): use system font if no fontname is given if let name = fontName, let size = fontSize { if let font = UIFont(name: name, size: size) { attributes[NSAttributedStringKey.font] = font } } return attributes.count == 0 ? nil : attributes } func lower(_ key: String) -> String { let i = key.index(key.startIndex, offsetBy: 1) return key.substring(to: i).lowercased() + key.substring(from: i) } func configureBarButtonItemFromPrefix( _ prefix: String, _ props: [String: AnyObject], _ passedItem: UIBarButtonItem? ) -> BlockBarButtonItem? { // TODO: // * customView // * setBackButtonBackgroundImage(nil, for: .focused, barMetrics: .default) // * width let title = stringForKey(lower("\(prefix)Title"), props) let image = imageForKey(lower("\(prefix)Image"), props) let systemItem = stringForKey(lower("\(prefix)SystemItem"), props) let barButtonSystemItem = barButtonSystemItemFromString(systemItem) let enabled = boolForKey(lower("\(prefix)Enabled"), props) let tintColor = colorForKey(lower("\(prefix)TintColor"), props) let style = stringForKey(lower("\(prefix)Style"), props) let titleTextAttributes = textAttributesFromPrefix(lower("\(prefix)Title"), props) let accessibilityLabel = stringForKey(lower("\(prefix)AccessibilityLabel"), props) let testID = stringForKey(lower("\(prefix)TestID"), props) if let prev = passedItem { if ( title != prev.title || enabled != prev.isEnabled || tintColor != prev.tintColor ) { let barButton = BlockBarButtonItem( title: title ?? prev.title, image: image ?? prev.image, barButtonSystemItem: barButtonSystemItem, style: barButtonStyleFromString(style), enabled: enabled, tintColor: tintColor, titleTextAttributes: titleTextAttributes ) barButton.accessibilityLabel = accessibilityLabel barButton.accessibilityIdentifier = testID return barButton } else { return nil } } else { if (title != nil || image != nil || barButtonSystemItem != nil) { let barButton = BlockBarButtonItem( title: title, image: image, barButtonSystemItem: barButtonSystemItem, style: barButtonStyleFromString(style), enabled: enabled, tintColor: tintColor, titleTextAttributes: titleTextAttributes ) barButton.accessibilityLabel = accessibilityLabel barButton.accessibilityIdentifier = testID return barButton } else { return nil } } } func configureBarButtonArrayForKey(_ key: String, _ props: [String: AnyObject]) -> [BlockBarButtonItem]? { if let buttons = props[key] as? [AnyObject] { var result = [BlockBarButtonItem]() for item in buttons { if let buttonProps = item as? [String: AnyObject] { if let button = configureBarButtonItemFromPrefix("", buttonProps, nil) { result.append(button) } } } return result } return nil } open class DefaultReactNavigationImplementation: ReactNavigationImplementation { public func getBarHeight( viewController: ReactViewController, navigationController: UINavigationController?, config: [String: AnyObject] ) -> CGFloat { guard viewController.isViewLoaded else { return 0 } return viewController.topLayoutGuide.length } public func makeNavigationController(rootViewController: UIViewController) -> UINavigationController { // TODO(lmr): pass initialConfig // TODO(lmr): do we want to provide a way to customize the NavigationBar class? return UINavigationController(rootViewController: rootViewController) } public func reconcileTabConfig( tabBarItem: UITabBarItem, prev: [String: AnyObject], next: [String: AnyObject] ){ // Image if mapHasChanged("image", prev, next) { tabBarItem.image = imageForKey("image", next) } if mapHasChanged("selectedImage", prev, next) { tabBarItem.selectedImage = imageForKey("selectedImage", next) } // TODO: imageInsets // Title if stringHasChanged("title", prev, next) { tabBarItem.title = stringForKey("title", next) } // TODO: titleTextAttributes (for various states), titlePositionAdjustment // Badge if stringHasChanged("badgeValue", prev, next) { tabBarItem.badgeValue = stringForKey("badgeValue", next) } if #available(iOS 10.0, *), numberHasChanged("badgeColor", prev, next) { if let badgeColor = colorForKey("badgeColor", next) { tabBarItem.badgeColor = badgeColor } } // TODO: badgeTextAttributes (for various states) } public func reconcileTabBarConfig( tabBar: UITabBar, prev: [String: AnyObject], next: [String: AnyObject] ) { if boolHasChanged("translucent", prev, next) { if let translucent = boolForKey("translucent", next) { tabBar.isTranslucent = translucent } else { tabBar.isTranslucent = false } } if numberHasChanged("tintColor", prev, next) { if let tintColor = colorForKey("tintColor", next) { tabBar.tintColor = tintColor } else { // Default perhaps? } } if #available(iOS 10.0, *), numberHasChanged("unselectedItemTintColor", prev, next) { tabBar.unselectedItemTintColor = colorForKey("unselectedItemTintColor", next) } if numberHasChanged("barTintColor", prev, next) { if let barTintColor = colorForKey("barTintColor", next) { tabBar.barTintColor = barTintColor } else { } } if mapHasChanged("backgroundImage", prev, next) { tabBar.backgroundImage = imageForKey("backgroundImage", next) } if mapHasChanged("shadowImage", prev, next) { tabBar.shadowImage = imageForKey("shadowImage", next) } if mapHasChanged("selectionIndicatorImage", prev, next) { tabBar.selectionIndicatorImage = imageForKey("selectionIndicatorImage", next) } // tabBar.alpha // tabBar.backgroundColor // itemPositioning // barStyle // itemSpacing float // itemWidth: float } public func reconcileScreenConfig( viewController: ReactViewController, navigationController: UINavigationController?, prev: [String: AnyObject], next: [String: AnyObject] ) { // status bar if let statusBarHidden = boolForKey("statusBarHidden", next) { viewController.setStatusBarHidden(statusBarHidden) } else { viewController.setStatusBarHidden(false) } if stringHasChanged("statusBarStyle", prev, next) { if let statusBarStyle = stringForKey("statusBarStyle", next) { viewController.setStatusBarStyle(statusBarStyleFromString(statusBarStyle)) } else { viewController.setStatusBarStyle(.default) } } if let statusBarAnimation = stringForKey("statusBarAnimation", next) { viewController.setStatusBarAnimation(statusBarAnimationFromString(statusBarAnimation)) } else { viewController.setStatusBarAnimation(.fade) } viewController.updateStatusBarIfNeeded() let navItem = viewController.navigationItem if let titleView = titleAndSubtitleViewFromProps(next) { if let title = stringForKey("title", next) { // set the title anyway, for accessibility viewController.title = title } navItem.titleView = titleView } else if let title = stringForKey("title", next) { navItem.titleView = nil viewController.title = title } if #available(iOS 11.0, *) { let prefersLargeTitles = boolForKey("prefersLargeTitles", next) ?? false viewController.navigationController?.navigationBar.prefersLargeTitles = prefersLargeTitles viewController.navigationItem.largeTitleDisplayMode = .automatic } if let screenColor = colorForKey("screenColor", next) { viewController.view.backgroundColor = screenColor } if let prompt = stringForKey("prompt", next) { navItem.prompt = prompt } else if navItem.prompt != nil { navItem.prompt = nil } if let rightBarButtonItems = configureBarButtonArrayForKey("rightButtons", next) { for (i, item) in rightBarButtonItems.enumerated() { item.actionHandler = { [weak viewController] in viewController?.emitEvent("onRightPress", body: i as AnyObject?) } } navItem.setRightBarButtonItems(rightBarButtonItems, animated: true) } else if let rightBarButtonItem = configureBarButtonItemFromPrefix("right", next, navItem.rightBarButtonItem) { rightBarButtonItem.actionHandler = { [weak viewController] in viewController?.emitEvent("onRightPress", body: nil) } navItem.setRightBarButton(rightBarButtonItem, animated: true) } // TODO(lmr): we have to figure out how to reset this back to the default "back" behavior... if let leftBarButtonItems = configureBarButtonArrayForKey("leftButtons", next) { for (i, item) in leftBarButtonItems.enumerated() { item.actionHandler = { [weak viewController] in viewController?.emitEvent("onLeftPress", body: i as AnyObject?) } } navItem.setLeftBarButtonItems(leftBarButtonItems, animated: true) } else if let leftBarButtonItem = configureBarButtonItemFromPrefix("left", next, navItem.leftBarButtonItem) { leftBarButtonItem.actionHandler = { [weak viewController] in // TODO(lmr): we want to dismiss here... viewController?.emitEvent("onLeftPress", body: nil) } navItem.setLeftBarButton(leftBarButtonItem, animated: true) } if let hidesBackButton = boolForKey("hidesBackButton", next) { navItem.setHidesBackButton(hidesBackButton, animated: true) } if let navController = navigationController { if let hidesBarsOnTap = boolForKey("hidesBarsOnTap", next) { navController.hidesBarsOnTap = hidesBarsOnTap } if let hidesBarsOnSwipe = boolForKey("hidesBarsOnSwipe", next) { navController.hidesBarsOnSwipe = hidesBarsOnSwipe } if let hidesBarsWhenKeyboardAppears = boolForKey("hidesBarsWhenKeyboardAppears", next) { navController.hidesBarsWhenKeyboardAppears = hidesBarsWhenKeyboardAppears } if let hidden = boolForKey("hidden", next) { navController.setNavigationBarHidden(hidden, animated: true) } if let isToolbarHidden = boolForKey("isToolbarHidden", next) { navController.setToolbarHidden(isToolbarHidden, animated: true) } let navBar = navController.navigationBar if let titleAttributes = textAttributesFromPrefix("title", next) { var combined = titleAttributes if let appearance = UINavigationBar.appearance().titleTextAttributes { combined = appearance.combineWith(values: titleAttributes) } navBar.titleTextAttributes = combined } if let backIndicatorImage = imageForKey("backIndicatorImage", next) { navBar.backIndicatorImage = backIndicatorImage } if let backIndicatorTransitionMaskImage = imageForKey("backIndicatorTransitionMaskImage", next) { navBar.backIndicatorTransitionMaskImage = backIndicatorTransitionMaskImage } if let backgroundColor = colorForKey("backgroundColor", next) { navBar.barTintColor = backgroundColor } if let foregroundColor = colorForKey("foregroundColor", next) { navBar.tintColor = foregroundColor } if let alpha = floatForKey("alpha", next) { navBar.alpha = alpha } if let translucent = boolForKey("translucent", next) { navBar.isTranslucent = translucent } // navigationController?.navigationBar.barStyle = .blackTranslucent // navigationController?.navigationBar.shadowImage = nil } // viewController.navigationItem.titleView = nil } } func getFont(_ name: String, _ size: CGFloat) -> UIFont { guard let font = UIFont(name: name, size: size) else { return UIFont.systemFont(ofSize: size) } return font } func buildFontFromProps(nameKey: String, sizeKey: String, defaultSize: CGFloat, props: [String: AnyObject]) -> UIFont { let name = stringForKey(nameKey, props) let size = floatForKey(sizeKey, props) if let name = name, let size = size { return getFont(name, size) } else if let name = name { return getFont(name, defaultSize) } else if let size = size { return UIFont.systemFont(ofSize: size) } else { return UIFont.systemFont(ofSize: defaultSize) } } func titleAndSubtitleViewFromProps(_ props: [String: AnyObject]) -> UIView? { guard let title = stringForKey("title", props) else { return nil } guard let subtitle = stringForKey("subtitle", props) else { return nil } let titleHeight = 18 let subtitleHeight = 12 let foregroundColor = colorForKey("foregroundColor", props) let titleLabel = UILabel(frame: CGRect(x:0, y:-5, width:0, height:0)) titleLabel.backgroundColor = UIColor.clear if let titleColor = colorForKey("titleColor", props) { titleLabel.textColor = titleColor } else if let titleColor = foregroundColor { titleLabel.textColor = titleColor } else { titleLabel.textColor = UIColor.gray } titleLabel.font = buildFontFromProps(nameKey: "titleFontName", sizeKey: "titleFontSize", defaultSize: 17, props: props) titleLabel.text = title titleLabel.sizeToFit() let subtitleLabel = UILabel(frame: CGRect(x:0, y:titleHeight, width:0, height:0)) subtitleLabel.backgroundColor = UIColor.clear if let subtitleColor = colorForKey("subtitleColor", props) { subtitleLabel.textColor = subtitleColor } else if let titleColor = foregroundColor { subtitleLabel.textColor = titleColor } else { subtitleLabel.textColor = UIColor.black } subtitleLabel.font = buildFontFromProps(nameKey: "subtitleFontName", sizeKey: "subtitleFontSize", defaultSize: 12, props: props) subtitleLabel.text = subtitle subtitleLabel.sizeToFit() let titleView = UIView( frame: CGRect( x: 0, y:0, width: max(Int(titleLabel.frame.size.width), Int(subtitleLabel.frame.size.width)), height: titleHeight + subtitleHeight ) ) titleView.addSubview(titleLabel) titleView.addSubview(subtitleLabel) let widthDiff = subtitleLabel.frame.size.width - titleLabel.frame.size.width if widthDiff > 0 { var frame = titleLabel.frame frame.origin.x = widthDiff / 2 titleLabel.frame = frame } else { var frame = subtitleLabel.frame frame.origin.x = abs(widthDiff) / 2 subtitleLabel.frame = frame } return titleView }
mit
ff9c3b35a032c1e65a163da8c6b44c78
30.152758
144
0.681271
4.518876
false
false
false
false
hooman/swift
stdlib/public/core/StringUTF8View.swift
3
17918
//===--- StringUTF8.swift - A UTF8 view of String -------------------------===// // // 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 // //===----------------------------------------------------------------------===// // FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of UTF-8 code units. /// /// You can access a string's view of UTF-8 code units by using its `utf8` /// property. A string's UTF-8 view encodes the string's Unicode scalar /// values as 8-bit integers. /// /// let flowers = "Flowers 💐" /// for v in flowers.utf8 { /// print(v) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 240 /// // 159 /// // 146 /// // 144 /// /// A string's Unicode scalar values can be up to 21 bits in length. To /// represent those scalar values using 8-bit integers, more than one UTF-8 /// code unit is often required. /// /// let flowermoji = "💐" /// for v in flowermoji.unicodeScalars { /// print(v, v.value) /// } /// // 💐 128144 /// /// for v in flowermoji.utf8 { /// print(v) /// } /// // 240 /// // 159 /// // 146 /// // 144 /// /// In the encoded representation of a Unicode scalar value, each UTF-8 code /// unit after the first is called a *continuation byte*. /// /// UTF8View Elements Match Encoded C Strings /// ========================================= /// /// Swift streamlines interoperation with C string APIs by letting you pass a /// `String` instance to a function as an `Int8` or `UInt8` pointer. When you /// call a C function using a `String`, Swift automatically creates a buffer /// of UTF-8 code units and passes a pointer to that buffer. The code units /// of that buffer match the code units in the string's `utf8` view. /// /// The following example uses the C `strncmp` function to compare the /// beginning of two Swift strings. The `strncmp` function takes two /// `const char*` pointers and an integer specifying the number of characters /// to compare. Because the strings are identical up to the 14th character, /// comparing only those characters results in a return value of `0`. /// /// let s1 = "They call me 'Bell'" /// let s2 = "They call me 'Stacey'" /// /// print(strncmp(s1, s2, 14)) /// // Prints "0" /// print(String(s1.utf8.prefix(14))!) /// // Prints "They call me '" /// /// Extending the compared character count to 15 includes the differing /// characters, so a nonzero result is returned. /// /// print(strncmp(s1, s2, 15)) /// // Prints "-17" /// print(String(s1.utf8.prefix(15))!) /// // Prints "They call me 'B" @frozen public struct UTF8View: Sendable { @usableFromInline internal var _guts: _StringGuts @inlinable @inline(__always) internal init(_ guts: _StringGuts) { self._guts = guts _invariantCheck() } } } extension String.UTF8View { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { // TODO: Ensure index alignment } #endif // INTERNAL_CHECKS_ENABLED } extension String.UTF8View: BidirectionalCollection { public typealias Index = String.Index public typealias Element = UTF8.CodeUnit /// The position of the first code unit if the UTF-8 view is /// nonempty. /// /// If the UTF-8 view is empty, `startIndex` is equal to `endIndex`. @inlinable @inline(__always) public var startIndex: Index { return _guts.startIndex } /// The "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// In an empty UTF-8 view, `endIndex` is equal to `startIndex`. @inlinable @inline(__always) public var endIndex: Index { return _guts.endIndex } /// Returns the next consecutive position after `i`. /// /// - Precondition: The next position is representable. @inlinable @inline(__always) public func index(after i: Index) -> Index { if _fastPath(_guts.isFastUTF8) { return i.strippingTranscoding.nextEncoded } return _foreignIndex(after: i) } @inlinable @inline(__always) public func index(before i: Index) -> Index { precondition(!i.isZeroPosition) if _fastPath(_guts.isFastUTF8) { return i.strippingTranscoding.priorEncoded } return _foreignIndex(before: i) } @inlinable @inline(__always) public func index(_ i: Index, offsetBy n: Int) -> Index { if _fastPath(_guts.isFastUTF8) { _precondition(n + i._encodedOffset <= _guts.count) return i.strippingTranscoding.encoded(offsetBy: n) } return _foreignIndex(i, offsetBy: n) } @inlinable @inline(__always) public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { if _fastPath(_guts.isFastUTF8) { // Check the limit: ignore limit if it precedes `i` (in the correct // direction), otherwise must not be beyond limit (in the correct // direction). let iOffset = i._encodedOffset let result = iOffset + n let limitOffset = limit._encodedOffset if n >= 0 { guard limitOffset < iOffset || result <= limitOffset else { return nil } } else { guard limitOffset > iOffset || result >= limitOffset else { return nil } } return Index(_encodedOffset: result) } return _foreignIndex(i, offsetBy: n, limitedBy: limit) } @inlinable @inline(__always) public func distance(from i: Index, to j: Index) -> Int { if _fastPath(_guts.isFastUTF8) { return j._encodedOffset &- i._encodedOffset } return _foreignDistance(from: i, to: j) } /// Accesses the code unit at the given position. /// /// The following example uses the subscript to print the value of a /// string's first UTF-8 code unit. /// /// let greeting = "Hello, friend!" /// let i = greeting.utf8.startIndex /// print("First character's UTF-8 code unit: \(greeting.utf8[i])") /// // Prints "First character's UTF-8 code unit: 72" /// /// - Parameter position: A valid index of the view. `position` /// must be less than the view's end index. @inlinable @inline(__always) public subscript(i: Index) -> UTF8.CodeUnit { String(_guts)._boundsCheck(i) if _fastPath(_guts.isFastUTF8) { return _guts.withFastUTF8 { utf8 in utf8[_unchecked: i._encodedOffset] } } return _foreignSubscript(position: i) } } extension String.UTF8View: CustomStringConvertible { @inlinable @inline(__always) public var description: String { return String(_guts) } } extension String.UTF8View: CustomDebugStringConvertible { public var debugDescription: String { return "UTF8View(\(self.description.debugDescription))" } } extension String { /// A UTF-8 encoding of `self`. @inlinable public var utf8: UTF8View { @inline(__always) get { return UTF8View(self._guts) } set { self = String(newValue._guts) } } /// A contiguously stored null-terminated UTF-8 representation of the string. /// /// To access the underlying memory, invoke `withUnsafeBufferPointer` on the /// array. /// /// let s = "Hello!" /// let bytes = s.utf8CString /// print(bytes) /// // Prints "[72, 101, 108, 108, 111, 33, 0]" /// /// bytes.withUnsafeBufferPointer { ptr in /// print(strlen(ptr.baseAddress!)) /// } /// // Prints "6" public var utf8CString: ContiguousArray<CChar> { @_effects(readonly) @_semantics("string.getUTF8CString") get { if _fastPath(_guts.isFastUTF8) { var result = _guts.withFastCChar { ContiguousArray($0) } result.append(0) return result } return _slowUTF8CString() } } @usableFromInline @inline(never) // slow-path internal func _slowUTF8CString() -> ContiguousArray<CChar> { var result = ContiguousArray<CChar>() result.reserveCapacity(self._guts.count + 1) for c in self.utf8 { result.append(CChar(bitPattern: c)) } result.append(0) return result } /// Creates a string corresponding to the given sequence of UTF-8 code units. @available(swift, introduced: 4.0, message: "Please use failable String.init?(_:UTF8View) when in Swift 3.2 mode") @inlinable @inline(__always) public init(_ utf8: UTF8View) { self = String(utf8._guts) } } extension String.UTF8View { @inlinable @inline(__always) public var count: Int { if _fastPath(_guts.isFastUTF8) { return _guts.count } return _foreignCount() } } // Index conversions extension String.UTF8View.Index { /// Creates an index in the given UTF-8 view that corresponds exactly to the /// specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the string's /// `utf8` view. /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.firstIndex(of: 32)! /// let utf8Index = String.UTF8View.Index(utf16Index, within: cafe.utf8)! /// /// print(Array(cafe.utf8[..<utf8Index])) /// // Prints "[67, 97, 102, 195, 169]" /// /// If the position passed in `utf16Index` doesn't have an exact /// corresponding position in `utf8`, the result of the initializer is /// `nil`. For example, because UTF-8 and UTF-16 represent high Unicode code /// points differently, an attempt to convert the position of the trailing /// surrogate of a UTF-16 surrogate pair fails. /// /// The next example attempts to convert the indices of the two UTF-16 code /// points that represent the teacup emoji (`"🍵"`). The index of the lead /// surrogate is successfully converted to a position in `utf8`, but the /// index of the trailing surrogate is not. /// /// let emojiHigh = cafe.utf16.index(after: utf16Index) /// print(String.UTF8View.Index(emojiHigh, within: cafe.utf8)) /// // Prints "Optional(String.Index(...))" /// /// let emojiLow = cafe.utf16.index(after: emojiHigh) /// print(String.UTF8View.Index(emojiLow, within: cafe.utf8)) /// // Prints "nil" /// /// - Parameters: /// - sourcePosition: A position in a `String` or one of its views. /// - target: The `UTF8View` in which to find the new position. @inlinable public init?(_ idx: String.Index, within target: String.UTF8View) { if _slowPath(target._guts.isForeign) { guard idx._foreignIsWithin(target) else { return nil } } else { // All indices, except sub-scalar UTF-16 indices pointing at trailing // surrogates, are valid. guard idx.transcodedOffset == 0 else { return nil } } self = idx } } // Reflection extension String.UTF8View: CustomReflectable { /// Returns a mirror that reflects the UTF-8 view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } //===--- Slicing Support --------------------------------------------------===// /// In Swift 3.2, in the absence of type context, /// /// someString.utf8[someString.utf8.startIndex..<someString.utf8.endIndex] /// /// was deduced to be of type `String.UTF8View`. Provide a more-specific /// Swift-3-only `subscript` overload that continues to produce /// `String.UTF8View`. extension String.UTF8View { public typealias SubSequence = Substring.UTF8View @inlinable @available(swift, introduced: 4) public subscript(r: Range<Index>) -> String.UTF8View.SubSequence { return Substring.UTF8View(self, _bounds: r) } } extension String.UTF8View { /// Copies `self` into the supplied buffer. /// /// - Precondition: The memory in `self` is uninitialized. The buffer must /// contain sufficient uninitialized memory to accommodate /// `source.underestimatedCount`. /// /// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` /// are initialized. @inlinable @inline(__always) public func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Iterator.Element> ) -> (Iterator, UnsafeMutableBufferPointer<Iterator.Element>.Index) { guard buffer.baseAddress != nil else { _preconditionFailure( "Attempt to copy string contents into nil buffer pointer") } guard let written = _guts.copyUTF8(into: buffer) else { _preconditionFailure( "Insufficient space allocated to copy string contents") } let it = String().utf8.makeIterator() return (it, buffer.index(buffer.startIndex, offsetBy: written)) } } // Foreign string support extension String.UTF8View { // Align a foreign UTF-16 index to a valid UTF-8 position. If there is a // transcoded offset already, this is already a valid UTF-8 position // (referring to a continuation byte) and returns `idx`. Otherwise, this will // scalar-align the index. This is needed because we may be passed a // non-scalar-aligned foreign index from the UTF16View. @inline(__always) internal func _utf8AlignForeignIndex(_ idx: String.Index) -> String.Index { _internalInvariant(_guts.isForeign) guard idx.transcodedOffset == 0 else { return idx } return _guts.scalarAlign(idx) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(after idx: Index) -> Index { _internalInvariant(_guts.isForeign) let idx = _utf8AlignForeignIndex(idx) let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar( startingAt: idx.strippingTranscoding) let utf8Len = UTF8.width(scalar) if utf8Len == 1 { _internalInvariant(idx.transcodedOffset == 0) return idx.nextEncoded._scalarAligned } // Check if we're still transcoding sub-scalar if idx.transcodedOffset < utf8Len - 1 { return idx.nextTranscoded } // Skip to the next scalar _internalInvariant(idx.transcodedOffset == utf8Len - 1) return idx.encoded(offsetBy: scalarLen)._scalarAligned } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(before idx: Index) -> Index { _internalInvariant(_guts.isForeign) let idx = _utf8AlignForeignIndex(idx) if idx.transcodedOffset != 0 { _internalInvariant((1...3) ~= idx.transcodedOffset) return idx.priorTranscoded } let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar( endingAt: idx.strippingTranscoding) let utf8Len = UTF8.width(scalar) return idx.encoded( offsetBy: -scalarLen ).transcoded(withOffset: utf8Len &- 1) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignSubscript(position idx: Index) -> UTF8.CodeUnit { _internalInvariant(_guts.isForeign) let idx = _utf8AlignForeignIndex(idx) let scalar = _guts.foreignErrorCorrectedScalar( startingAt: idx.strippingTranscoding).0 let encoded = Unicode.UTF8.encode(scalar)._unsafelyUnwrappedUnchecked _internalInvariant(idx.transcodedOffset < 1+encoded.count) return encoded[ encoded.index(encoded.startIndex, offsetBy: idx.transcodedOffset)] } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(_ i: Index, offsetBy n: Int) -> Index { _internalInvariant(_guts.isForeign) return _index(i, offsetBy: n) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { _internalInvariant(_guts.isForeign) return _index(i, offsetBy: n, limitedBy: limit) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignDistance(from i: Index, to j: Index) -> Int { _internalInvariant(_guts.isForeign) let i = _utf8AlignForeignIndex(i) let j = _utf8AlignForeignIndex(j) #if _runtime(_ObjC) // Currently, foreign means NSString if let count = _cocoaStringUTF8Count( _guts._object.cocoaObject, range: i._encodedOffset ..< j._encodedOffset ) { // _cocoaStringUTF8Count gave us the scalar aligned count, but we still // need to compensate for sub-scalar indexing, e.g. if `i` is in the // middle of a two-byte UTF8 scalar. let refinedCount = (count - i.transcodedOffset) + j.transcodedOffset _internalInvariant(refinedCount == _distance(from: i, to: j)) return refinedCount } #endif return _distance(from: i, to: j) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignCount() -> Int { _internalInvariant(_guts.isForeign) return _foreignDistance(from: startIndex, to: endIndex) } } extension String.Index { @usableFromInline @inline(never) // opaque slow-path @_effects(releasenone) internal func _foreignIsWithin(_ target: String.UTF8View) -> Bool { _internalInvariant(target._guts.isForeign) return self == target._utf8AlignForeignIndex(self) } } extension String.UTF8View { @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { guard _guts.isFastUTF8 else { return nil } return try _guts.withFastUTF8(body) } }
apache-2.0
11c021b0c08c2bbd56c3bcba7b2352c4
31.787546
80
0.649927
4.016603
false
false
false
false
jianghuihon/DYZB
DYZB/Classes/Main/Model/AnthorModel.swift
1
627
// // AnthorModel.swift // DYZB // // Created by Enjoy on 2017/3/25. // Copyright © 2017年 SZCE. All rights reserved. // import UIKit class AnthorModel: NSObject { var vertical_src : String = "" var nickname : String = "" var online : Int = 0 var isVertical : Int = 0 var room_id : Int = 0 var room_name : String = "" var anchor_city : String = "" init(dict: [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
mit
c9b482b51af9a18e4d18233a095880dc
6.090909
73
0.524038
3.924528
false
false
false
false
apple/swift-nio
Sources/NIOCore/ChannelPipeline.swift
1
81476
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// /// A list of `ChannelHandler`s that handle or intercept inbound events and outbound operations of a /// `Channel`. `ChannelPipeline` implements an advanced form of the Intercepting Filter pattern /// to give a user full control over how an event is handled and how the `ChannelHandler`s in a pipeline /// interact with each other. /// /// # Creation of a pipeline /// /// Each `Channel` has its own `ChannelPipeline` and it is created automatically when a new `Channel` is created. /// /// # How an event flows in a pipeline /// /// The following diagram describes how I/O events are typically processed by `ChannelHandler`s in a `ChannelPipeline`. /// An I/O event is handled by either a `ChannelInboundHandler` or a `ChannelOutboundHandler` /// and is forwarded to the next handler in the `ChannelPipeline` by calling the event propagation methods defined in /// `ChannelHandlerContext`, such as `ChannelHandlerContext.fireChannelRead` and /// `ChannelHandlerContext.write`. /// /// ``` /// I/O Request /// via `Channel` or /// `ChannelHandlerContext` /// | /// +---------------------------------------------------+---------------+ /// | ChannelPipeline | | /// | TAIL \|/ | /// | +---------------------+ +-----------+----------+ | /// | | Inbound Handler N | | Outbound Handler 1 | | /// | +----------+----------+ +-----------+----------+ | /// | /|\ | | /// | | \|/ | /// | +----------+----------+ +-----------+----------+ | /// | | Inbound Handler N-1 | | Outbound Handler 2 | | /// | +----------+----------+ +-----------+----------+ | /// | /|\ . | /// | . . | /// | ChannelHandlerContext.fireIN_EVT() ChannelHandlerContext.OUT_EVT()| /// | [ method call] [method call] | /// | . . | /// | . \|/ | /// | +----------+----------+ +-----------+----------+ | /// | | Inbound Handler 2 | | Outbound Handler M-1 | | /// | +----------+----------+ +-----------+----------+ | /// | /|\ | | /// | | \|/ | /// | +----------+----------+ +-----------+----------+ | /// | | Inbound Handler 1 | | Outbound Handler M | | /// | +----------+----------+ +-----------+----------+ | /// | /|\ HEAD | | /// +---------------+-----------------------------------+---------------+ /// | \|/ /// +---------------+-----------------------------------+---------------+ /// | | | | /// | [ Socket.read ] [ Socket.write ] | /// | | /// | SwiftNIO Internal I/O Threads (Transport Implementation) | /// +-------------------------------------------------------------------+ /// ``` /// /// An inbound event is handled by the inbound handlers in the head-to-tail direction as shown on the left side of the /// diagram. An inbound handler usually handles the inbound data generated by the I/O thread on the bottom of the /// diagram. The inbound data is often read from a remote peer via the actual input operation such as /// `Socket.read`. If an inbound event goes beyond the tail inbound handler, it is discarded /// silently, or logged if it needs your attention. /// /// An outbound event is handled by the outbound handlers in the tail-to-head direction as shown on the right side of the /// diagram. An outbound handler usually generates or transforms the outbound traffic such as write requests. /// If an outbound event goes beyond the head outbound handler, it is handled by an I/O thread associated with the /// `Channel`. The I/O thread often performs the actual output operation such as `Socket.write`. /// /// /// For example, let us assume that we created the following pipeline: /// /// ``` /// ChannelPipeline p = ... /// let future = p.add(name: "1", handler: InboundHandlerA()).flatMap { /// p.add(name: "2", handler: InboundHandlerB()) /// }.flatMap { /// p.add(name: "3", handler: OutboundHandlerA()) /// }.flatMap { /// p.add(name: "4", handler: OutboundHandlerB()) /// }.flatMap { /// p.add(name: "5", handler: InboundOutboundHandlerX()) /// } /// // Handle the future as well .... /// ``` /// /// In the example above, a class whose name starts with `Inbound` is an inbound handler. /// A class whose name starts with `Outbound` is an outbound handler. /// /// In the given example configuration, the handler evaluation order is 1, 2, 3, 4, 5 when an event goes inbound. /// When an event goes outbound, the order is 5, 4, 3, 2, 1. On top of this principle, `ChannelPipeline` skips /// the evaluation of certain handlers to shorten the stack depth: /// /// - 3 and 4 don't implement `ChannelInboundHandler`, and therefore the actual evaluation order of an inbound event will be: 1, 2, and 5. /// - 1 and 2 don't implement `ChannelOutboundHandler`, and therefore the actual evaluation order of a outbound event will be: 5, 4, and 3. /// - If 5 implements both `ChannelInboundHandler` and `ChannelOutboundHandler`, the evaluation order of an inbound and a outbound event could be 125 and 543 respectively. /// /// Note: Handlers may choose not to propagate messages down the pipeline immediately. For example a handler may need to wait /// for additional data before sending a protocol event to the next handler in the pipeline. Due to this you can't assume that later handlers /// in the pipeline will receive the same number of events as were sent, or that events of different types will arrive in the same order. /// For example - a user event could overtake a data event if a handler is aggregating data events before propagating but immediately /// propagating user events. /// /// # Forwarding an event to the next handler /// /// As you might noticed in the diagram above, a handler has to invoke the event propagation methods in /// `ChannelHandlerContext` to forward an event to its next handler. /// Those methods include: /// /// - Inbound event propagation methods defined in `ChannelInboundInvoker` /// - Outbound event propagation methods defined in `ChannelOutboundInvoker`. /// /// # Building a pipeline /// /// A user is supposed to have one or more `ChannelHandler`s in a `ChannelPipeline` to receive I/O events (e.g. read) and /// to request I/O operations (e.g. write and close). For example, a typical server will have the following handlers /// in each channel's pipeline, but your mileage may vary depending on the complexity and characteristics of the /// protocol and business logic: /// /// - Protocol Decoder - translates binary data (e.g. `ByteBuffer`) into a struct / class /// - Protocol Encoder - translates a struct / class into binary data (e.g. `ByteBuffer`) /// - Business Logic Handler - performs the actual business logic (e.g. database access) /// /// # Thread safety /// /// A `ChannelHandler` can be added or removed at any time because a `ChannelPipeline` is thread safe. public final class ChannelPipeline: ChannelInvoker { private var head: Optional<ChannelHandlerContext> private var tail: Optional<ChannelHandlerContext> private var idx: Int = 0 internal private(set) var destroyed: Bool = false /// The `EventLoop` that is used by the underlying `Channel`. public let eventLoop: EventLoop /// The `Channel` that this `ChannelPipeline` belongs to. /// /// - note: This will be nil after the channel has closed private var _channel: Optional<Channel> /// The `Channel` that this `ChannelPipeline` belongs to. internal var channel: Channel { self.eventLoop.assertInEventLoop() assert(self._channel != nil || self.destroyed) return self._channel ?? DeadChannel(pipeline: self) } /// Add a `ChannelHandler` to the `ChannelPipeline`. /// /// - parameters: /// - name: the name to use for the `ChannelHandler` when it's added. If none is specified it will generate a name. /// - handler: the `ChannelHandler` to add /// - position: The position in the `ChannelPipeline` to add `handler`. Defaults to `.last`. /// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was added. public func addHandler(_ handler: ChannelHandler, name: String? = nil, position: ChannelPipeline.Position = .last) -> EventLoopFuture<Void> { let future: EventLoopFuture<Void> if self.eventLoop.inEventLoop { future = self.eventLoop.makeCompletedFuture(self.addHandlerSync(handler, name: name, position: position)) } else { future = self.eventLoop.submit { try self.addHandlerSync(handler, name: name, position: position).get() } } return future } /// Synchronously add a `ChannelHandler` to the `ChannelPipeline`. /// /// May only be called from on the event loop. /// /// - parameters: /// - handler: the `ChannelHandler` to add /// - name: the name to use for the `ChannelHandler` when it's added. If none is specified a name will be generated. /// - position: The position in the `ChannelPipeline` to add `handler`. Defaults to `.last`. /// - returns: the result of adding this handler - either success or failure with an error code if this could not be completed. fileprivate func addHandlerSync(_ handler: ChannelHandler, name: String? = nil, position: ChannelPipeline.Position = .last) -> Result<Void, Error> { self.eventLoop.assertInEventLoop() if self.destroyed { return .failure(ChannelError.ioOnClosedChannel) } switch position { case .first: return self.add0(name: name, handler: handler, relativeContext: head!, operation: self.add0(context:after:)) case .last: return self.add0(name: name, handler: handler, relativeContext: tail!, operation: self.add0(context:before:)) case .before(let beforeHandler): return self.add0(name: name, handler: handler, relativeHandler: beforeHandler, operation: self.add0(context:before:)) case .after(let afterHandler): return self.add0(name: name, handler: handler, relativeHandler: afterHandler, operation: self.add0(context:after:)) } } /// Synchronously add a `ChannelHandler` to the pipeline, relative to another `ChannelHandler`, /// where the insertion is done by a specific operation. /// /// May only be called from on the event loop. /// /// This will search the pipeline for `relativeHandler` and, if it cannot find it, will fail /// `promise` with `ChannelPipelineError.notFound`. /// /// - parameters: /// - name: The name to use for the `ChannelHandler` when its added. If none is specified, a name will be /// automatically generated. /// - handler: The `ChannelHandler` to add. /// - relativeHandler: The `ChannelHandler` already in the `ChannelPipeline` that `handler` will be /// inserted relative to. /// - operation: A callback that will insert `handler` relative to `relativeHandler`. /// - returns: the result of adding this handler - either success or failure with an error code if this could not be completed. private func add0(name: String?, handler: ChannelHandler, relativeHandler: ChannelHandler, operation: (ChannelHandlerContext, ChannelHandlerContext) -> Void) -> Result<Void, Error> { self.eventLoop.assertInEventLoop() if self.destroyed { return .failure(ChannelError.ioOnClosedChannel) } guard let context = self.contextForPredicate0({ $0.handler === relativeHandler }) else { return .failure(ChannelPipelineError.notFound) } return self.add0(name: name, handler: handler, relativeContext: context, operation: operation) } /// Synchronously add a `ChannelHandler` to the pipeline, relative to a `ChannelHandlerContext`, /// where the insertion is done by a specific operation. /// /// May only be called from on the event loop. /// /// This method is more efficient than the one that takes a `relativeHandler` as it does not need to /// search the pipeline for the insertion point. It should be used whenever possible. /// /// - parameters: /// - name: The name to use for the `ChannelHandler` when its added. If none is specified, a name will be /// automatically generated. /// - handler: The `ChannelHandler` to add. /// - relativeContext: The `ChannelHandlerContext` already in the `ChannelPipeline` that `handler` will be /// inserted relative to. /// - operation: A callback that will insert `handler` relative to `relativeHandler`. /// - returns: the result of adding this handler - either success or failure with an error code if this could not be completed. private func add0(name: String?, handler: ChannelHandler, relativeContext: ChannelHandlerContext, operation: (ChannelHandlerContext, ChannelHandlerContext) -> Void) -> Result<Void, Error> { self.eventLoop.assertInEventLoop() if self.destroyed { return .failure(ChannelError.ioOnClosedChannel) } let context = ChannelHandlerContext(name: name ?? nextName(), handler: handler, pipeline: self) operation(context, relativeContext) context.invokeHandlerAdded() return .success(()) } /// Synchronously add a single new `ChannelHandlerContext` after one that currently exists in the /// pipeline. /// /// Must be called from within the event loop thread, as it synchronously manipulates the /// `ChannelHandlerContext`s on the `ChannelPipeline`. /// /// - parameters: /// - new: The `ChannelHandlerContext` to add to the pipeline. /// - existing: The `ChannelHandlerContext` that `new` will be added after. private func add0(context new: ChannelHandlerContext, after existing: ChannelHandlerContext) { self.eventLoop.assertInEventLoop() let next = existing.next new.prev = existing new.next = next existing.next = new next?.prev = new } /// Synchronously add a single new `ChannelHandlerContext` before one that currently exists in the /// pipeline. /// /// Must be called from within the event loop thread, as it synchronously manipulates the /// `ChannelHandlerContext`s on the `ChannelPipeline`. /// /// - parameters: /// - new: The `ChannelHandlerContext` to add to the pipeline. /// - existing: The `ChannelHandlerContext` that `new` will be added before. private func add0(context new: ChannelHandlerContext, before existing: ChannelHandlerContext) { self.eventLoop.assertInEventLoop() let prev = existing.prev new.prev = prev new.next = existing existing.prev = new prev?.next = new } /// Remove a `ChannelHandler` from the `ChannelPipeline`. /// /// - parameters: /// - handler: the `ChannelHandler` to remove. /// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was removed. public func removeHandler(_ handler: RemovableChannelHandler) -> EventLoopFuture<Void> { let promise = self.eventLoop.makePromise(of: Void.self) self.removeHandler(handler, promise: promise) return promise.futureResult } /// Remove a `ChannelHandler` from the `ChannelPipeline`. /// /// - parameters: /// - name: the name that was used to add the `ChannelHandler` to the `ChannelPipeline` before. /// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was removed. public func removeHandler(name: String) -> EventLoopFuture<Void> { let promise = self.eventLoop.makePromise(of: Void.self) self.removeHandler(name: name, promise: promise) return promise.futureResult } /// Remove a `ChannelHandler` from the `ChannelPipeline`. /// /// - parameters: /// - context: the `ChannelHandlerContext` that belongs to `ChannelHandler` that should be removed. /// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was removed. public func removeHandler(context: ChannelHandlerContext) -> EventLoopFuture<Void> { let promise = self.eventLoop.makePromise(of: Void.self) self.removeHandler(context: context, promise: promise) return promise.futureResult } /// Remove a `ChannelHandler` from the `ChannelPipeline`. /// /// - parameters: /// - handler: the `ChannelHandler` to remove. /// - promise: An `EventLoopPromise` that will complete when the `ChannelHandler` is removed. public func removeHandler(_ handler: RemovableChannelHandler, promise: EventLoopPromise<Void>?) { func removeHandler0() { switch self.contextSync(handler: handler) { case .success(let context): self.removeHandler(context: context, promise: promise) case .failure(let error): promise?.fail(error) } } if self.eventLoop.inEventLoop { removeHandler0() } else { self.eventLoop.execute { removeHandler0() } } } /// Remove a `ChannelHandler` from the `ChannelPipeline`. /// /// - parameters: /// - name: the name that was used to add the `ChannelHandler` to the `ChannelPipeline` before. /// - promise: An `EventLoopPromise` that will complete when the `ChannelHandler` is removed. public func removeHandler(name: String, promise: EventLoopPromise<Void>?) { func removeHandler0() { switch self.contextSync(name: name) { case .success(let context): self.removeHandler(context: context, promise: promise) case .failure(let error): promise?.fail(error) } } if self.eventLoop.inEventLoop { removeHandler0() } else { self.eventLoop.execute { removeHandler0() } } } /// Remove a `ChannelHandler` from the `ChannelPipeline`. /// /// - parameters: /// - context: the `ChannelHandlerContext` that belongs to `ChannelHandler` that should be removed. /// - promise: An `EventLoopPromise` that will complete when the `ChannelHandler` is removed. public func removeHandler(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) { guard context.handler is RemovableChannelHandler else { promise?.fail(ChannelError.unremovableHandler) return } func removeHandler0() { context.startUserTriggeredRemoval(promise: promise) } if self.eventLoop.inEventLoop { removeHandler0() } else { self.eventLoop.execute { removeHandler0() } } } /// Returns the `ChannelHandlerContext` that belongs to a `ChannelHandler`. /// /// - parameters: /// - handler: the `ChannelHandler` for which the `ChannelHandlerContext` should be returned /// - returns: the `EventLoopFuture` which will be notified once the the operation completes. public func context(handler: ChannelHandler) -> EventLoopFuture<ChannelHandlerContext> { let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self) if self.eventLoop.inEventLoop { promise.completeWith(self.contextSync(handler: handler)) } else { self.eventLoop.execute { promise.completeWith(self.contextSync(handler: handler)) } } return promise.futureResult } /// Synchronously returns the `ChannelHandlerContext` that belongs to a `ChannelHandler`. /// /// - Important: This must be called on the `EventLoop`. /// - parameters: /// - handler: the `ChannelHandler` for which the `ChannelHandlerContext` should be returned /// - returns: the `ChannelHandlerContext` that belongs to the `ChannelHandler`, if one exists. fileprivate func contextSync(handler: ChannelHandler) -> Result<ChannelHandlerContext, Error> { return self._contextSync({ $0.handler === handler }) } /// Returns the `ChannelHandlerContext` that belongs to a `ChannelHandler`. /// /// - parameters: /// - name: the name that was used to add the `ChannelHandler` to the `ChannelPipeline` before. /// - returns: the `EventLoopFuture` which will be notified once the the operation completes. public func context(name: String) -> EventLoopFuture<ChannelHandlerContext> { let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self) if self.eventLoop.inEventLoop { promise.completeWith(self.contextSync(name: name)) } else { self.eventLoop.execute { promise.completeWith(self.contextSync(name: name)) } } return promise.futureResult } /// Synchronously finds and returns the `ChannelHandlerContext` that belongs to the /// `ChannelHandler` with the given name. /// /// - Important: This must be called on the `EventLoop`. /// - Parameter name: The name of the `ChannelHandler` to find. /// - Returns: the `ChannelHandlerContext` that belongs to the `ChannelHandler`, if one exists. fileprivate func contextSync(name: String) -> Result<ChannelHandlerContext, Error> { return self._contextSync({ $0.name == name }) } /// Returns the `ChannelHandlerContext` that belongs to a `ChannelHandler` of the given type. /// /// If multiple channel handlers of the same type are present in the pipeline, returns the context /// belonging to the first such handler. /// /// - parameters: /// - handlerType: The type of the handler to search for. /// - returns: the `EventLoopFuture` which will be notified once the the operation completes. @inlinable public func context<Handler: ChannelHandler>(handlerType: Handler.Type) -> EventLoopFuture<ChannelHandlerContext> { let promise = self.eventLoop.makePromise(of: ChannelHandlerContext.self) if self.eventLoop.inEventLoop { promise.completeWith(self._contextSync(handlerType: handlerType)) } else { self.eventLoop.execute { promise.completeWith(self._contextSync(handlerType: handlerType)) } } return promise.futureResult } /// Synchronously finds and returns the `ChannelHandlerContext` that belongs to the first /// `ChannelHandler` of the given type. /// /// - Important: This must be called on the `EventLoop`. /// - Parameter handlerType: The type of handler to search for. /// - Returns: the `ChannelHandlerContext` that belongs to the `ChannelHandler`, if one exists. @inlinable // should be fileprivate internal func _contextSync<Handler: ChannelHandler>(handlerType: Handler.Type) -> Result<ChannelHandlerContext, Error> { return self._contextSync({ $0.handler is Handler }) } /// Synchronously finds a `ChannelHandlerContext` in the `ChannelPipeline`. /// - Important: This must be called on the `EventLoop`. @usableFromInline // should be fileprivate internal func _contextSync(_ body: (ChannelHandlerContext) -> Bool) -> Result<ChannelHandlerContext, Error> { self.eventLoop.assertInEventLoop() if let context = self.contextForPredicate0(body) { return .success(context) } else { return .failure(ChannelPipelineError.notFound) } } /// Returns a `ChannelHandlerContext` which matches. /// /// This skips head and tail (as these are internal and should not be accessible by the user). /// /// - parameters: /// - body: The predicate to execute per `ChannelHandlerContext` in the `ChannelPipeline`. /// - returns: The first `ChannelHandlerContext` that matches or `nil` if none did. private func contextForPredicate0(_ body: (ChannelHandlerContext) -> Bool) -> ChannelHandlerContext? { var curCtx: ChannelHandlerContext? = self.head?.next while let context = curCtx, context !== self.tail { if body(context) { return context } curCtx = context.next } return nil } /// Remove a `ChannelHandlerContext` from the `ChannelPipeline` directly without going through the /// `RemovableChannelHandler` API. This must only be used to clear the pipeline on `Channel` tear down and /// as a result of the `leavePipeline` call in the `RemovableChannelHandler` API. internal func removeHandlerFromPipeline(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() let nextCtx = context.next let prevCtx = context.prev if let prevCtx = prevCtx { prevCtx.next = nextCtx } if let nextCtx = nextCtx { nextCtx.prev = prevCtx } context.invokeHandlerRemoved() promise?.succeed(()) // We need to keep the current node alive until after the callout in case the user uses the context. context.next = nil context.prev = nil } /// Returns the next name to use for a `ChannelHandler`. private func nextName() -> String { self.eventLoop.assertInEventLoop() let name = "handler\(idx)" idx += 1 return name } /// Remove all the `ChannelHandler`s from the `ChannelPipeline` and destroy these. /// /// This method must only be called from within the `EventLoop`. It should only be called from a `ChannelCore` /// implementation. Once called, the `ChannelPipeline` is no longer active and cannot be used again. func removeHandlers() { self.eventLoop.assertInEventLoop() if let head = self.head { while let context = head.next { removeHandlerFromPipeline(context: context, promise: nil) } removeHandlerFromPipeline(context: self.head!, promise: nil) } self.head = nil self.tail = nil self.destroyed = true self._channel = nil } // Just delegate to the head and tail context public func fireChannelRegistered() { if eventLoop.inEventLoop { fireChannelRegistered0() } else { eventLoop.execute { self.fireChannelRegistered0() } } } public func fireChannelUnregistered() { if eventLoop.inEventLoop { fireChannelUnregistered0() } else { eventLoop.execute { self.fireChannelUnregistered0() } } } public func fireChannelInactive() { if eventLoop.inEventLoop { fireChannelInactive0() } else { eventLoop.execute { self.fireChannelInactive0() } } } public func fireChannelActive() { if eventLoop.inEventLoop { fireChannelActive0() } else { eventLoop.execute { self.fireChannelActive0() } } } public func fireChannelRead(_ data: NIOAny) { if eventLoop.inEventLoop { fireChannelRead0(data) } else { eventLoop.execute { self.fireChannelRead0(data) } } } public func fireChannelReadComplete() { if eventLoop.inEventLoop { fireChannelReadComplete0() } else { eventLoop.execute { self.fireChannelReadComplete0() } } } public func fireChannelWritabilityChanged() { if eventLoop.inEventLoop { fireChannelWritabilityChanged0() } else { eventLoop.execute { self.fireChannelWritabilityChanged0() } } } public func fireUserInboundEventTriggered(_ event: Any) { if eventLoop.inEventLoop { fireUserInboundEventTriggered0(event) } else { eventLoop.execute { self.fireUserInboundEventTriggered0(event) } } } public func fireErrorCaught(_ error: Error) { if eventLoop.inEventLoop { fireErrorCaught0(error: error) } else { eventLoop.execute { self.fireErrorCaught0(error: error) } } } public func close(mode: CloseMode = .all, promise: EventLoopPromise<Void>?) { if eventLoop.inEventLoop { close0(mode: mode, promise: promise) } else { eventLoop.execute { self.close0(mode: mode, promise: promise) } } } public func flush() { if eventLoop.inEventLoop { flush0() } else { eventLoop.execute { self.flush0() } } } public func read() { if eventLoop.inEventLoop { read0() } else { eventLoop.execute { self.read0() } } } public func write(_ data: NIOAny, promise: EventLoopPromise<Void>?) { if eventLoop.inEventLoop { write0(data, promise: promise) } else { eventLoop.execute { self.write0(data, promise: promise) } } } public func writeAndFlush(_ data: NIOAny, promise: EventLoopPromise<Void>?) { if eventLoop.inEventLoop { writeAndFlush0(data, promise: promise) } else { eventLoop.execute { self.writeAndFlush0(data, promise: promise) } } } public func bind(to address: SocketAddress, promise: EventLoopPromise<Void>?) { if eventLoop.inEventLoop { bind0(to: address, promise: promise) } else { eventLoop.execute { self.bind0(to: address, promise: promise) } } } public func connect(to address: SocketAddress, promise: EventLoopPromise<Void>?) { if eventLoop.inEventLoop { connect0(to: address, promise: promise) } else { eventLoop.execute { self.connect0(to: address, promise: promise) } } } public func register(promise: EventLoopPromise<Void>?) { if eventLoop.inEventLoop { register0(promise: promise) } else { eventLoop.execute { self.register0(promise: promise) } } } public func triggerUserOutboundEvent(_ event: Any, promise: EventLoopPromise<Void>?) { if eventLoop.inEventLoop { triggerUserOutboundEvent0(event, promise: promise) } else { eventLoop.execute { self.triggerUserOutboundEvent0(event, promise: promise) } } } // These methods are expected to only be called from within the EventLoop private var firstOutboundCtx: ChannelHandlerContext? { return self.tail?.prev } private var firstInboundCtx: ChannelHandlerContext? { return self.head?.next } private func close0(mode: CloseMode, promise: EventLoopPromise<Void>?) { if let firstOutboundCtx = firstOutboundCtx { firstOutboundCtx.invokeClose(mode: mode, promise: promise) } else { promise?.fail(ChannelError.alreadyClosed) } } private func flush0() { if let firstOutboundCtx = firstOutboundCtx { firstOutboundCtx.invokeFlush() } } private func read0() { if let firstOutboundCtx = firstOutboundCtx { firstOutboundCtx.invokeRead() } } private func write0(_ data: NIOAny, promise: EventLoopPromise<Void>?) { if let firstOutboundCtx = firstOutboundCtx { firstOutboundCtx.invokeWrite(data, promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } private func writeAndFlush0(_ data: NIOAny, promise: EventLoopPromise<Void>?) { if let firstOutboundCtx = firstOutboundCtx { firstOutboundCtx.invokeWriteAndFlush(data, promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } private func bind0(to address: SocketAddress, promise: EventLoopPromise<Void>?) { if let firstOutboundCtx = firstOutboundCtx { firstOutboundCtx.invokeBind(to: address, promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } private func connect0(to address: SocketAddress, promise: EventLoopPromise<Void>?) { if let firstOutboundCtx = firstOutboundCtx { firstOutboundCtx.invokeConnect(to: address, promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } private func register0(promise: EventLoopPromise<Void>?) { if let firstOutboundCtx = firstOutboundCtx { firstOutboundCtx.invokeRegister(promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } private func triggerUserOutboundEvent0(_ event: Any, promise: EventLoopPromise<Void>?) { if let firstOutboundCtx = firstOutboundCtx { firstOutboundCtx.invokeTriggerUserOutboundEvent(event, promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } private func fireChannelRegistered0() { if let firstInboundCtx = firstInboundCtx { firstInboundCtx.invokeChannelRegistered() } } private func fireChannelUnregistered0() { if let firstInboundCtx = firstInboundCtx { firstInboundCtx.invokeChannelUnregistered() } } private func fireChannelInactive0() { if let firstInboundCtx = firstInboundCtx { firstInboundCtx.invokeChannelInactive() } } private func fireChannelActive0() { if let firstInboundCtx = firstInboundCtx { firstInboundCtx.invokeChannelActive() } } private func fireChannelRead0(_ data: NIOAny) { if let firstInboundCtx = firstInboundCtx { firstInboundCtx.invokeChannelRead(data) } } private func fireChannelReadComplete0() { if let firstInboundCtx = firstInboundCtx { firstInboundCtx.invokeChannelReadComplete() } } private func fireChannelWritabilityChanged0() { if let firstInboundCtx = firstInboundCtx { firstInboundCtx.invokeChannelWritabilityChanged() } } private func fireUserInboundEventTriggered0(_ event: Any) { if let firstInboundCtx = firstInboundCtx { firstInboundCtx.invokeUserInboundEventTriggered(event) } } private func fireErrorCaught0(error: Error) { assert((error as? ChannelError).map { $0 != .eof } ?? true) if let firstInboundCtx = firstInboundCtx { firstInboundCtx.invokeErrorCaught(error) } } private var inEventLoop: Bool { return eventLoop.inEventLoop } /// Create `ChannelPipeline` for a given `Channel`. This method should never be called by the end-user /// directly: it is only intended for use with custom `Channel` implementations. Users should always use /// `channel.pipeline` to access the `ChannelPipeline` for a `Channel`. /// /// - parameters: /// - channel: The `Channel` this `ChannelPipeline` is created for. public init(channel: Channel) { self._channel = channel self.eventLoop = channel.eventLoop self.head = nil // we need to initialise these to `nil` so we can use `self` in the lines below self.tail = nil // we need to initialise these to `nil` so we can use `self` in the lines below self.head = ChannelHandlerContext(name: HeadChannelHandler.name, handler: HeadChannelHandler.sharedInstance, pipeline: self) self.tail = ChannelHandlerContext(name: TailChannelHandler.name, handler: TailChannelHandler.sharedInstance, pipeline: self) self.head?.next = self.tail self.tail?.prev = self.head } } #if swift(>=5.7) extension ChannelPipeline: @unchecked Sendable {} #endif extension ChannelPipeline { /// Adds the provided channel handlers to the pipeline in the order given, taking account /// of the behaviour of `ChannelHandler.add(first:)`. /// /// - parameters: /// - handlers: The array of `ChannelHandler`s to be added. /// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`. /// /// - returns: A future that will be completed when all of the supplied `ChannelHandler`s were added. public func addHandlers(_ handlers: [ChannelHandler], position: ChannelPipeline.Position = .last) -> EventLoopFuture<Void> { let future: EventLoopFuture<Void> if self.eventLoop.inEventLoop { future = self.eventLoop.makeCompletedFuture(self.addHandlersSync(handlers, position: position)) } else { future = self.eventLoop.submit { try self.addHandlersSync(handlers, position: position).get() } } return future } /// Adds the provided channel handlers to the pipeline in the order given, taking account /// of the behaviour of `ChannelHandler.add(first:)`. /// /// - parameters: /// - handlers: One or more `ChannelHandler`s to be added. /// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`. /// /// - returns: A future that will be completed when all of the supplied `ChannelHandler`s were added. public func addHandlers(_ handlers: ChannelHandler..., position: ChannelPipeline.Position = .last) -> EventLoopFuture<Void> { return self.addHandlers(handlers, position: position) } /// Synchronously adds the provided `ChannelHandler`s to the pipeline in the order given, taking /// account of the behaviour of `ChannelHandler.add(first:)`. /// /// - Important: Must be called on the `EventLoop`. /// - Parameters: /// - handlers: The array of `ChannelHandler`s to add. /// - position: The position in the `ChannelPipeline` to add the handlers. /// - Returns: A result representing whether the handlers were added or not. fileprivate func addHandlersSync(_ handlers: [ChannelHandler], position: ChannelPipeline.Position) -> Result<Void, Error> { switch position { case .first, .after: return self._addHandlersSync(handlers.reversed(), position: position) case .last, .before: return self._addHandlersSync(handlers, position: position) } } /// Synchronously adds a sequence of `ChannelHandlers` to the pipeline at the given position. /// /// - Important: Must be called on the `EventLoop`. /// - Parameters: /// - handlers: A sequence of handlers to add. /// - position: The position in the `ChannelPipeline` to add the handlers. /// - Returns: A result representing whether the handlers were added or not. private func _addHandlersSync<Handlers: Sequence>(_ handlers: Handlers, position: ChannelPipeline.Position) -> Result<Void, Error> where Handlers.Element == ChannelHandler { self.eventLoop.assertInEventLoop() for handler in handlers { let result = self.addHandlerSync(handler, position: position) switch result { case .success: () case .failure: return result } } return .success(()) } } // MARK: - Synchronous View extension ChannelPipeline { /// A view of a `ChannelPipeline` which may be used to invoke synchronous operations. /// /// All functions **must** be called from the pipeline's event loop. public struct SynchronousOperations { @usableFromInline internal let _pipeline: ChannelPipeline fileprivate init(pipeline: ChannelPipeline) { self._pipeline = pipeline } /// The `EventLoop` of the `Channel` this synchronous operations view corresponds to. public var eventLoop: EventLoop { return self._pipeline.eventLoop } /// Add a handler to the pipeline. /// /// - Important: This *must* be called on the event loop. /// - Parameters: /// - handler: The handler to add. /// - name: The name to use for the `ChannelHandler` when it's added. If no name is specified the one will be generated. /// - position: The position in the `ChannelPipeline` to add `handler`. Defaults to `.last`. public func addHandler(_ handler: ChannelHandler, name: String? = nil, position: ChannelPipeline.Position = .last) throws { try self._pipeline.addHandlerSync(handler, name: name, position: position).get() } /// Add an array of handlers to the pipeline. /// /// - Important: This *must* be called on the event loop. /// - Parameters: /// - handlers: The handlers to add. /// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`. public func addHandlers(_ handlers: [ChannelHandler], position: ChannelPipeline.Position = .last) throws { try self._pipeline.addHandlersSync(handlers, position: position).get() } /// Add one or more handlers to the pipeline. /// /// - Important: This *must* be called on the event loop. /// - Parameters: /// - handlers: The handlers to add. /// - position: The position in the `ChannelPipeline` to add `handlers`. Defaults to `.last`. public func addHandlers(_ handlers: ChannelHandler..., position: ChannelPipeline.Position = .last) throws { try self._pipeline.addHandlersSync(handlers, position: position).get() } /// Returns the `ChannelHandlerContext` for the given handler instance if it is in /// the `ChannelPipeline`, if it exists. /// /// - Important: This *must* be called on the event loop. /// - Parameter handler: The handler belonging to the context to fetch. /// - Returns: The `ChannelHandlerContext` associated with the handler. public func context(handler: ChannelHandler) throws -> ChannelHandlerContext { return try self._pipeline._contextSync({ $0.handler === handler }).get() } /// Returns the `ChannelHandlerContext` for the handler with the given name, if one exists. /// /// - Important: This *must* be called on the event loop. /// - Parameter name: The name of the handler whose context is being fetched. /// - Returns: The `ChannelHandlerContext` associated with the handler. public func context(name: String) throws -> ChannelHandlerContext { return try self._pipeline.contextSync(name: name).get() } /// Returns the `ChannelHandlerContext` for the handler of given type, if one exists. /// /// - Important: This *must* be called on the event loop. /// - Parameter name: The name of the handler whose context is being fetched. /// - Returns: The `ChannelHandlerContext` associated with the handler. @inlinable public func context<Handler: ChannelHandler>(handlerType: Handler.Type) throws -> ChannelHandlerContext { return try self._pipeline._contextSync(handlerType: handlerType).get() } /// Returns the `ChannelHandler` of the given type from the `ChannelPipeline`, if it exists. /// /// - Important: This *must* be called on the event loop. /// - Returns: A `ChannelHandler` of the given type if one exists in the `ChannelPipeline`. @inlinable public func handler<Handler: ChannelHandler>(type _: Handler.Type) throws -> Handler { return try self._pipeline._handlerSync(type: Handler.self).get() } /// Fires `channelRegistered` from the head to the tail. /// /// This method should typically only be called by `Channel` implementations directly. public func fireChannelRegistered() { self.eventLoop.assertInEventLoop() self._pipeline.fireChannelRegistered0() } /// Fires `channelUnregistered` from the head to the tail. /// /// This method should typically only be called by `Channel` implementations directly. public func fireChannelUnregistered() { self.eventLoop.assertInEventLoop() self._pipeline.fireChannelUnregistered0() } /// Fires `channelInactive` from the head to the tail. /// /// This method should typically only be called by `Channel` implementations directly. public func fireChannelInactive() { self.eventLoop.assertInEventLoop() self._pipeline.fireChannelInactive0() } /// Fires `channelActive` from the head to the tail. /// /// This method should typically only be called by `Channel` implementations directly. public func fireChannelActive() { self.eventLoop.assertInEventLoop() self._pipeline.fireChannelActive0() } /// Fires `channelRead` from the head to the tail. /// /// This method should typically only be called by `Channel` implementations directly. public func fireChannelRead(_ data: NIOAny) { self.eventLoop.assertInEventLoop() self._pipeline.fireChannelRead0(data) } /// Fires `channelReadComplete` from the head to the tail. /// /// This method should typically only be called by `Channel` implementations directly. public func fireChannelReadComplete() { self.eventLoop.assertInEventLoop() self._pipeline.fireChannelReadComplete0() } /// Fires `channelWritabilityChanged` from the head to the tail. /// /// This method should typically only be called by `Channel` implementations directly. public func fireChannelWritabilityChanged() { self.eventLoop.assertInEventLoop() self._pipeline.fireChannelWritabilityChanged0() } /// Fires `userInboundEventTriggered` from the head to the tail. /// /// This method should typically only be called by `Channel` implementations directly. public func fireUserInboundEventTriggered(_ event: Any) { self.eventLoop.assertInEventLoop() self._pipeline.fireUserInboundEventTriggered0(event) } /// Fires `errorCaught` from the head to the tail. /// /// This method should typically only be called by `Channel` implementations directly. public func fireErrorCaught(_ error: Error) { self.eventLoop.assertInEventLoop() self._pipeline.fireErrorCaught0(error: error) } /// Fires `close` from the tail to the head. /// /// This method should typically only be called by `Channel` implementations directly. public func close(mode: CloseMode = .all, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() self._pipeline.close0(mode: mode, promise: promise) } /// Fires `flush` from the tail to the head. /// /// This method should typically only be called by `Channel` implementations directly. public func flush() { self.eventLoop.assertInEventLoop() self._pipeline.flush0() } /// Fires `read` from the tail to the head. /// /// This method should typically only be called by `Channel` implementations directly. public func read() { self.eventLoop.assertInEventLoop() self._pipeline.read0() } /// Fires `write` from the tail to the head. /// /// This method should typically only be called by `Channel` implementations directly. public func write(_ data: NIOAny, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() self._pipeline.write0(data, promise: promise) } /// Fires `writeAndFlush` from the tail to the head. /// /// This method should typically only be called by `Channel` implementations directly. public func writeAndFlush(_ data: NIOAny, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() self._pipeline.writeAndFlush0(data, promise: promise) } /// Fires `bind` from the tail to the head. /// /// This method should typically only be called by `Channel` implementations directly. public func bind(to address: SocketAddress, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() self._pipeline.bind0(to: address, promise: promise) } /// Fires `connect` from the tail to the head. /// /// This method should typically only be called by `Channel` implementations directly. public func connect(to address: SocketAddress, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() self._pipeline.connect0(to: address, promise: promise) } /// Fires `register` from the tail to the head. /// /// This method should typically only be called by `Channel` implementations directly. public func register(promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() self._pipeline.register0(promise: promise) } /// Fires `triggerUserOutboundEvent` from the tail to the head. /// /// This method should typically only be called by `Channel` implementations directly. public func triggerUserOutboundEvent(_ event: Any, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() self._pipeline.triggerUserOutboundEvent0(event, promise: promise) } } /// Returns a view of operations which can be performed synchronously on this pipeline. All /// operations **must** be called on the event loop. public var syncOperations: SynchronousOperations { return SynchronousOperations(pipeline: self) } } #if swift(>=5.7) @available(*, unavailable) extension ChannelPipeline.SynchronousOperations: Sendable {} #endif extension ChannelPipeline { /// A `Position` within the `ChannelPipeline` used to insert handlers into the `ChannelPipeline`. public enum Position { /// The first `ChannelHandler` -- the front of the `ChannelPipeline`. case first /// The last `ChannelHandler` -- the back of the `ChannelPipeline`. case last /// Before the given `ChannelHandler`. case before(ChannelHandler) /// After the given `ChannelHandler`. case after(ChannelHandler) } } #if swift(>=5.7) @available(*, unavailable) extension ChannelPipeline.Position: Sendable {} #endif /// Special `ChannelHandler` that forwards all events to the `Channel.Unsafe` implementation. /* private but tests */ final class HeadChannelHandler: _ChannelOutboundHandler { static let name = "head" static let sharedInstance = HeadChannelHandler() private init() { } func register(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) { context.channel._channelCore.register0(promise: promise) } func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) { context.channel._channelCore.bind0(to: address, promise: promise) } func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) { context.channel._channelCore.connect0(to: address, promise: promise) } func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { context.channel._channelCore.write0(data, promise: promise) } func flush(context: ChannelHandlerContext) { context.channel._channelCore.flush0() } func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) { context.channel._channelCore.close0(error: mode.error, mode: mode, promise: promise) } func read(context: ChannelHandlerContext) { context.channel._channelCore.read0() } func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise<Void>?) { context.channel._channelCore.triggerUserOutboundEvent0(event, promise: promise) } } private extension CloseMode { /// Returns the error to fail outstanding operations writes with. var error: ChannelError { switch self { case .all: return .ioOnClosedChannel case .output: return .outputClosed case .input: return .inputClosed } } } /// Special `ChannelInboundHandler` which will consume all inbound events. /* private but tests */ final class TailChannelHandler: _ChannelInboundHandler { static let name = "tail" static let sharedInstance = TailChannelHandler() private init() { } func channelRegistered(context: ChannelHandlerContext) { // Discard } func channelUnregistered(context: ChannelHandlerContext) { // Discard } func channelActive(context: ChannelHandlerContext) { // Discard } func channelInactive(context: ChannelHandlerContext) { // Discard } func channelReadComplete(context: ChannelHandlerContext) { // Discard } func channelWritabilityChanged(context: ChannelHandlerContext) { // Discard } func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { // Discard } func errorCaught(context: ChannelHandlerContext, error: Error) { context.channel._channelCore.errorCaught0(error: error) } func channelRead(context: ChannelHandlerContext, data: NIOAny) { context.channel._channelCore.channelRead0(data) } } /// `Error` that is used by the `ChannelPipeline` to inform the user of an error. public enum ChannelPipelineError: Error { /// `ChannelHandler` was already removed. case alreadyRemoved /// `ChannelHandler` was not found. case notFound } /// Every `ChannelHandler` has -- when added to a `ChannelPipeline` -- a corresponding `ChannelHandlerContext` which is /// the way `ChannelHandler`s can interact with other `ChannelHandler`s in the pipeline. /// /// Most `ChannelHandler`s need to send events through the `ChannelPipeline` which they do by calling the respective /// method on their `ChannelHandlerContext`. In fact all the `ChannelHandler` default implementations just forward /// the event using the `ChannelHandlerContext`. /// /// Many events are instrumental for a `ChannelHandler`'s life-cycle and it is therefore very important to send them /// at the right point in time. Often, the right behaviour is to react to an event and then forward it to the next /// `ChannelHandler`. public final class ChannelHandlerContext: ChannelInvoker { // visible for ChannelPipeline to modify fileprivate var next: Optional<ChannelHandlerContext> fileprivate var prev: Optional<ChannelHandlerContext> public let pipeline: ChannelPipeline public var channel: Channel { return self.pipeline.channel } public var handler: ChannelHandler { return self.inboundHandler ?? self.outboundHandler! } public var remoteAddress: SocketAddress? { do { // Fast-path access to the remoteAddress. return try self.channel._channelCore.remoteAddress0() } catch ChannelError.ioOnClosedChannel { // Channel was closed already but we may still have the address cached so try to access it via the Channel // so we are able to use it in channelInactive(...) / handlerRemoved(...) methods. return self.channel.remoteAddress } catch { return nil } } public var localAddress: SocketAddress? { do { // Fast-path access to the localAddress. return try self.channel._channelCore.localAddress0() } catch ChannelError.ioOnClosedChannel { // Channel was closed already but we may still have the address cached so try to access it via the Channel // so we are able to use it in channelInactive(...) / handlerRemoved(...) methods. return self.channel.localAddress } catch { return nil } } public var eventLoop: EventLoop { return self.pipeline.eventLoop } public let name: String private let inboundHandler: _ChannelInboundHandler? private let outboundHandler: _ChannelOutboundHandler? private var removeHandlerInvoked = false private var userTriggeredRemovalStarted = false // Only created from within ChannelPipeline fileprivate init(name: String, handler: ChannelHandler, pipeline: ChannelPipeline) { self.name = name self.pipeline = pipeline self.inboundHandler = handler as? _ChannelInboundHandler self.outboundHandler = handler as? _ChannelOutboundHandler self.next = nil self.prev = nil precondition(self.inboundHandler != nil || self.outboundHandler != nil, "ChannelHandlers need to either be inbound or outbound") } /// Send a `channelRegistered` event to the next (inbound) `ChannelHandler` in the `ChannelPipeline`. /// /// - note: For correct operation it is very important to forward any `channelRegistered` event using this method at the right point in time, that is usually when received. public func fireChannelRegistered() { self.next?.invokeChannelRegistered() } /// Send a `channelUnregistered` event to the next (inbound) `ChannelHandler` in the `ChannelPipeline`. /// /// - note: For correct operation it is very important to forward any `channelUnregistered` event using this method at the right point in time, that is usually when received. public func fireChannelUnregistered() { self.next?.invokeChannelUnregistered() } /// Send a `channelActive` event to the next (inbound) `ChannelHandler` in the `ChannelPipeline`. /// /// - note: For correct operation it is very important to forward any `channelActive` event using this method at the right point in time, that is often when received. public func fireChannelActive() { self.next?.invokeChannelActive() } /// Send a `channelInactive` event to the next (inbound) `ChannelHandler` in the `ChannelPipeline`. /// /// - note: For correct operation it is very important to forward any `channelInactive` event using this method at the right point in time, that is often when received. public func fireChannelInactive() { self.next?.invokeChannelInactive() } /// Send data to the next inbound `ChannelHandler`. The data should be of type `ChannelInboundHandler.InboundOut`. public func fireChannelRead(_ data: NIOAny) { self.next?.invokeChannelRead(data) } /// Signal to the next `ChannelHandler` that a read burst has finished. public func fireChannelReadComplete() { self.next?.invokeChannelReadComplete() } /// Send a `writabilityChanged` event to the next (inbound) `ChannelHandler` in the `ChannelPipeline`. /// /// - note: For correct operation it is very important to forward any `writabilityChanged` event using this method at the right point in time, that is usually when received. public func fireChannelWritabilityChanged() { self.next?.invokeChannelWritabilityChanged() } /// Send an error to the next inbound `ChannelHandler`. public func fireErrorCaught(_ error: Error) { self.next?.invokeErrorCaught(error) } /// Send a user event to the next inbound `ChannelHandler`. public func fireUserInboundEventTriggered(_ event: Any) { self.next?.invokeUserInboundEventTriggered(event) } /// Send a `register` event to the next (outbound) `ChannelHandler` in the `ChannelPipeline`. /// /// - note: For correct operation it is very important to forward any `register` event using this method at the right point in time, that is usually when received. public func register(promise: EventLoopPromise<Void>?) { if let outboundNext = self.prev { outboundNext.invokeRegister(promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } /// Send a `bind` event to the next outbound `ChannelHandler` in the `ChannelPipeline`. /// When the `bind` event reaches the `HeadChannelHandler` a `ServerSocketChannel` will be bound. /// /// - parameters: /// - address: The address to bind to. /// - promise: The promise fulfilled when the socket is bound or failed if it cannot be bound. public func bind(to address: SocketAddress, promise: EventLoopPromise<Void>?) { if let outboundNext = self.prev { outboundNext.invokeBind(to: address, promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } /// Send a `connect` event to the next outbound `ChannelHandler` in the `ChannelPipeline`. /// When the `connect` event reaches the `HeadChannelHandler` a `SocketChannel` will be connected. /// /// - parameters: /// - address: The address to connect to. /// - promise: The promise fulfilled when the socket is connected or failed if it cannot be connected. public func connect(to address: SocketAddress, promise: EventLoopPromise<Void>?) { if let outboundNext = self.prev { outboundNext.invokeConnect(to: address, promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } /// Send a `write` event to the next outbound `ChannelHandler` in the `ChannelPipeline`. /// When the `write` event reaches the `HeadChannelHandler` the data will be enqueued to be written on the next /// `flush` event. /// /// - parameters: /// - data: The data to write, should be of type `ChannelOutboundHandler.OutboundOut`. /// - promise: The promise fulfilled when the data has been written or failed if it cannot be written. public func write(_ data: NIOAny, promise: EventLoopPromise<Void>?) { if let outboundNext = self.prev { outboundNext.invokeWrite(data, promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } /// Send a `flush` event to the next outbound `ChannelHandler` in the `ChannelPipeline`. /// When the `flush` event reaches the `HeadChannelHandler` the data previously enqueued will be attempted to be /// written to the socket. /// /// - parameters: /// - promise: The promise fulfilled when the previously written data been flushed or failed if it cannot be flushed. public func flush() { if let outboundNext = self.prev { outboundNext.invokeFlush() } } /// Send a `write` event followed by a `flush` event to the next outbound `ChannelHandler` in the `ChannelPipeline`. /// When the `write` event reaches the `HeadChannelHandler` the data will be enqueued to be written when the `flush` /// also reaches the `HeadChannelHandler`. /// /// - parameters: /// - data: The data to write, should be of type `ChannelOutboundHandler.OutboundOut`. /// - promise: The promise fulfilled when the previously written data been written and flushed or if that failed. public func writeAndFlush(_ data: NIOAny, promise: EventLoopPromise<Void>?) { if let outboundNext = self.prev { outboundNext.invokeWriteAndFlush(data, promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } /// Send a `read` event to the next outbound `ChannelHandler` in the `ChannelPipeline`. /// When the `read` event reaches the `HeadChannelHandler` the interest to read data will be signalled to the /// `Selector`. This will subsequently -- when data becomes readable -- cause `channelRead` events containing the /// data being sent through the `ChannelPipeline`. public func read() { if let outboundNext = self.prev { outboundNext.invokeRead() } } /// Send a `close` event to the next outbound `ChannelHandler` in the `ChannelPipeline`. /// When the `close` event reaches the `HeadChannelHandler` the socket will be closed. /// /// - parameters: /// - mode: The `CloseMode` to use. /// - promise: The promise fulfilled when the `Channel` has been closed or failed if it the closing failed. public func close(mode: CloseMode = .all, promise: EventLoopPromise<Void>?) { if let outboundNext = self.prev { outboundNext.invokeClose(mode: mode, promise: promise) } else { promise?.fail(ChannelError.alreadyClosed) } } /// Send a user event to the next outbound `ChannelHandler` in the `ChannelPipeline`. /// /// - parameters: /// - event: The user event to send. /// - promise: The promise fulfilled when the user event has been sent or failed if it couldn't be sent. public func triggerUserOutboundEvent(_ event: Any, promise: EventLoopPromise<Void>?) { if let outboundNext = self.prev { outboundNext.invokeTriggerUserOutboundEvent(event, promise: promise) } else { promise?.fail(ChannelError.ioOnClosedChannel) } } fileprivate func invokeChannelRegistered() { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { inboundHandler.channelRegistered(context: self) } else { self.next?.invokeChannelRegistered() } } fileprivate func invokeChannelUnregistered() { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { inboundHandler.channelUnregistered(context: self) } else { self.next?.invokeChannelUnregistered() } } fileprivate func invokeChannelActive() { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { inboundHandler.channelActive(context: self) } else { self.next?.invokeChannelActive() } } fileprivate func invokeChannelInactive() { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { inboundHandler.channelInactive(context: self) } else { self.next?.invokeChannelInactive() } } fileprivate func invokeChannelRead(_ data: NIOAny) { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { inboundHandler.channelRead(context: self, data: data) } else { self.next?.invokeChannelRead(data) } } fileprivate func invokeChannelReadComplete() { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { inboundHandler.channelReadComplete(context: self) } else { self.next?.invokeChannelReadComplete() } } fileprivate func invokeChannelWritabilityChanged() { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { inboundHandler.channelWritabilityChanged(context: self) } else { self.next?.invokeChannelWritabilityChanged() } } fileprivate func invokeErrorCaught(_ error: Error) { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { inboundHandler.errorCaught(context: self, error: error) } else { self.next?.invokeErrorCaught(error) } } fileprivate func invokeUserInboundEventTriggered(_ event: Any) { self.eventLoop.assertInEventLoop() if let inboundHandler = self.inboundHandler { inboundHandler.userInboundEventTriggered(context: self, event: event) } else { self.next?.invokeUserInboundEventTriggered(event) } } fileprivate func invokeRegister(promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { outboundHandler.register(context: self, promise: promise) } else { self.prev?.invokeRegister(promise: promise) } } fileprivate func invokeBind(to address: SocketAddress, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { outboundHandler.bind(context: self, to: address, promise: promise) } else { self.prev?.invokeBind(to: address, promise: promise) } } fileprivate func invokeConnect(to address: SocketAddress, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { outboundHandler.connect(context: self, to: address, promise: promise) } else { self.prev?.invokeConnect(to: address, promise: promise) } } fileprivate func invokeWrite(_ data: NIOAny, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { outboundHandler.write(context: self, data: data, promise: promise) } else { self.prev?.invokeWrite(data, promise: promise) } } fileprivate func invokeFlush() { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { outboundHandler.flush(context: self) } else { self.prev?.invokeFlush() } } fileprivate func invokeWriteAndFlush(_ data: NIOAny, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { outboundHandler.write(context: self, data: data, promise: promise) outboundHandler.flush(context: self) } else { self.prev?.invokeWriteAndFlush(data, promise: promise) } } fileprivate func invokeRead() { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { outboundHandler.read(context: self) } else { self.prev?.invokeRead() } } fileprivate func invokeClose(mode: CloseMode, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { outboundHandler.close(context: self, mode: mode, promise: promise) } else { self.prev?.invokeClose(mode: mode, promise: promise) } } fileprivate func invokeTriggerUserOutboundEvent(_ event: Any, promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() if let outboundHandler = self.outboundHandler { outboundHandler.triggerUserOutboundEvent(context: self, event: event, promise: promise) } else { self.prev?.invokeTriggerUserOutboundEvent(event, promise: promise) } } fileprivate func invokeHandlerAdded() { self.eventLoop.assertInEventLoop() handler.handlerAdded(context: self) } fileprivate func invokeHandlerRemoved() { self.eventLoop.assertInEventLoop() guard !self.removeHandlerInvoked else { return } self.removeHandlerInvoked = true handler.handlerRemoved(context: self) } } #if swift(>=5.7) @available(*, unavailable) extension ChannelHandlerContext: Sendable {} #endif extension ChannelHandlerContext { /// A `RemovalToken` is handed to a `RemovableChannelHandler` when its `removeHandler` function is invoked. A /// `RemovableChannelHandler` is then required to remove itself from the `ChannelPipeline`. The removal process /// is finalized by handing the `RemovalToken` to the `ChannelHandlerContext.leavePipeline` function. public struct RemovalToken: Sendable { internal let promise: EventLoopPromise<Void>? } /// Synchronously remove the `ChannelHandler` with the given `ChannelHandlerContext`. /// /// - note: This function must only be used from a `RemovableChannelHandler` to remove itself. Calling this method /// on any other `ChannelHandlerContext` leads to undefined behaviour. /// /// - parameters: /// - removalToken: The removal token received from `RemovableChannelHandler.removeHandler` public func leavePipeline(removalToken: RemovalToken) { self.eventLoop.preconditionInEventLoop() self.pipeline.removeHandlerFromPipeline(context: self, promise: removalToken.promise) } internal func startUserTriggeredRemoval(promise: EventLoopPromise<Void>?) { self.eventLoop.assertInEventLoop() guard !self.userTriggeredRemovalStarted else { promise?.fail(NIOAttemptedToRemoveHandlerMultipleTimesError()) return } self.userTriggeredRemovalStarted = true (self.handler as! RemovableChannelHandler).removeHandler(context: self, removalToken: .init(promise: promise)) } } extension ChannelPipeline: CustomDebugStringConvertible { public var debugDescription: String { // This method forms output in the following format: // // ChannelPipeline[0x0000000000000000]: // [I] ↓↑ [O] // <incoming handler type> ↓↑ [<name>] // ↓↑ <outgoing handler type> [<name>] // <duplex handler type> ↓↑ <duplex handler type> [<name>] // var desc = ["ChannelPipeline[\(ObjectIdentifier(self))]:"] let debugInfos = self.collectHandlerDebugInfos() let maxIncomingTypeNameCount = debugInfos.filter { $0.isIncoming } .map { $0.typeName.count } .max() ?? 0 let maxOutgoingTypeNameCount = debugInfos.filter { $0.isOutgoing } .map { $0.typeName.count } .max() ?? 0 func whitespace(count: Int) -> String { return String(repeating: " ", count: count) } if debugInfos.isEmpty { desc.append(" <no handlers>") } else { desc.append(whitespace(count: maxIncomingTypeNameCount - 2) + "[I] ↓↑ [O]") for debugInfo in debugInfos { var line = [String]() line.append(" ") if debugInfo.isIncoming { line.append(whitespace(count: maxIncomingTypeNameCount - debugInfo.typeName.count)) line.append(debugInfo.typeName) } else { line.append(whitespace(count: maxIncomingTypeNameCount)) } line.append(" ↓↑ ") if debugInfo.isOutgoing { line.append(debugInfo.typeName) line.append(whitespace(count: maxOutgoingTypeNameCount - debugInfo.typeName.count)) } else { line.append(whitespace(count: maxOutgoingTypeNameCount)) } line.append(" ") line.append("[\(debugInfo.name)]") desc.append(line.joined()) } } return desc.joined(separator: "\n") } /// Returns the first `ChannelHandler` of the given type. /// /// - parameters: /// - type: the type of `ChannelHandler` to return. @inlinable public func handler<Handler: ChannelHandler>(type _: Handler.Type) -> EventLoopFuture<Handler> { return self.context(handlerType: Handler.self).map { context in guard let typedContext = context.handler as? Handler else { preconditionFailure("Expected channel handler of type \(Handler.self), got \(type(of: context.handler)) instead.") } return typedContext } } /// Synchronously finds and returns the first `ChannelHandler` of the given type. /// /// - Important: This must be called on the `EventLoop`. /// - Parameters: /// - type: the type of `ChannelHandler` to return. @inlinable // should be fileprivate internal func _handlerSync<Handler: ChannelHandler>(type _: Handler.Type) -> Result<Handler, Error> { return self._contextSync(handlerType: Handler.self).map { context in guard let typedContext = context.handler as? Handler else { preconditionFailure("Expected channel handler of type \(Handler.self), got \(type(of: context.handler)) instead.") } return typedContext } } private struct ChannelHandlerDebugInfo { let handler: ChannelHandler let name: String var isIncoming: Bool { return self.handler is _ChannelInboundHandler } var isOutgoing: Bool { return self.handler is _ChannelOutboundHandler } var typeName: String { return "\(type(of: self.handler))" } } private func collectHandlerDebugInfos() -> [ChannelHandlerDebugInfo] { var handlers = [ChannelHandlerDebugInfo]() var node = self.head?.next while let context = node, context !== self.tail { handlers.append(.init(handler: context.handler, name: context.name)) node = context.next } return handlers } }
apache-2.0
4d7966ed7bd48641318bc93528a0d864
39.766767
178
0.618597
4.83366
false
false
false
false