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
wxxsw/GSPhotos
GSPhotos/PHPhotoLibraryGSHelper.swift
1
4418
// // PHPhotoLibraryGSHelper.swift // GSPhotosExample // // Created by Gesen on 15/10/21. // Copyright (c) 2015年 Gesen. All rights reserved. // import Foundation import Photos let PHPhotoLibraryErrorDomain = "PHPhotoLibraryErrorDomain" @available(iOS 8.0, *) class PHPhotoLibraryGSHelper { /// 共享api实例 let library = PHPhotoLibrary.sharedPhotoLibrary() // MARK: - For GSPhotoLibrary /** 获取全部资源集合 */ func fetchAllAssets(mediaType: GSAssetMediaType, handler: AssetsCompletionHandler) { PHPhotoLibraryGSHelper.requestAuthorization { status, error in guard error == nil else { handler(nil, error) ; return } let mediaType = PHAssetMediaType(rawValue: mediaType.rawValue)! let options = PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let fetchAssets = PHAsset.fetchAssetsWithMediaType(mediaType, options: options) handler(fetchAssets.convertToGSAssets(), nil) } } /** 获取指定相册中的资源 */ func fetchAssetsInAlbum(album: GSAlbum, mediaType: GSAssetMediaType, handler: AssetsCompletionHandler) { PHPhotoLibraryGSHelper.requestAuthorization { status, error in guard error == nil else { handler(nil, error) ; return } let assetCollection = album.originalAssetCollection as! PHAssetCollection let options = PHFetchOptions() options.predicate = NSPredicate(format: "mediaType = %d", mediaType.rawValue) options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let fetchAssets = PHAsset.fetchAssetsInAssetCollection(assetCollection, options: options) handler(fetchAssets.convertToGSAssets(), nil) } } /** 获取相册集合 */ func fetchAlbums(handler: AlbumsCompletionHandler) { PHPhotoLibraryGSHelper.requestAuthorization { status, error in guard error == nil else { handler(nil, error) ; return } let options = PHFetchOptions() options.predicate = NSPredicate(format: "estimatedAssetCount > 0") let fetchSmartAlbums = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumUserLibrary, options: nil) let fetchAlbums = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: options) handler(fetchSmartAlbums.convertToGSAlbums() + fetchAlbums.convertToGSAlbums(), nil) } } } // MARK: - Class Method @available(iOS 8.0, *) extension PHPhotoLibraryGSHelper { /** 请求访问权限 - parameter handler: 完成回调 */ class func requestAuthorization(handler: (GSPhotoAuthorizationStatus, error: NSError?) -> Void) { PHPhotoLibrary.requestAuthorization { (status) -> Void in let status = GSPhotoAuthorizationStatus(rawValue: status.rawValue)! var error: NSError? if status != .Authorized { error = NSError(domain: PHPhotoLibraryErrorDomain, code: 403, userInfo: nil) } handler(status, error: error) } } /** 获取当前访问权限 - returns: 权限状态 */ class func authorizationStatus() -> GSPhotoAuthorizationStatus { return GSPhotoAuthorizationStatus(rawValue: PHPhotoLibrary.authorizationStatus().rawValue)! } } // MARK: - Convert Extension @available(iOS 8.0, *) extension PHFetchResult { private func convertToGSAssets() -> [GSAsset] { var assets = [GSAsset]() enumerateObjectsUsingBlock { (phAsset, index, stop) in if let phAsset = phAsset as? PHAsset { assets.append(GSAsset(phAsset: phAsset)) } } return assets } private func convertToGSAlbums() -> [GSAlbum] { var albums = [GSAlbum]() enumerateObjectsUsingBlock { (phAssetCollection, index, stop) in if let phAssetCollection = phAssetCollection as? PHAssetCollection { albums.append(GSAlbum(phAssetCollection: phAssetCollection)) } } return albums } }
mit
dbf8d5ea7678eae90b82f52d1204fa85
32.992126
142
0.631372
5.1875
false
false
false
false
huonw/swift
test/TypeCoercion/overload_noncall.swift
12
1910
// RUN: %target-typecheck-verify-swift struct X { } struct Y { } struct Z { } func f0(_ x1: X, x2: X) -> X {} // expected-note{{found this candidate}} func f0(_ y1: Y, y2: Y) -> Y {} // expected-note{{found this candidate}} var f0 : X // expected-note {{found this candidate}} expected-note {{'f0' previously declared here}} func f0_init(_ x: X, y: Y) -> X {} var f0 : (_ x : X, _ y : Y) -> X = f0_init // expected-error{{invalid redeclaration}} func f1(_ x: X) -> X {} func f2(_ g: (_ x: X) -> X) -> ((_ y: Y) -> Y) { } func test_conv() { var _ : (_ x1 : X, _ x2 : X) -> X = f0 var _ : (X, X) -> X = f0 var _ : (Y, X) -> X = f0 // expected-error{{ambiguous reference to member 'f0(_:x2:)'}} var _ : (X) -> X = f1 var a7 : (X) -> (X) = f1 var a8 : (_ x2 : X) -> (X) = f1 var a9 : (_ x2 : X) -> ((X)) = f1 a7 = a8 a8 = a9 a9 = a7 var _ : ((X) -> X) -> ((Y) -> Y) = f2 var _ : ((_ x2 : X) -> (X)) -> (((_ y2 : Y) -> (Y))) = f2 typealias fp = ((X) -> X) -> ((Y) -> Y) var _ = f2 } var xy : X // expected-note {{previously declared here}} var xy : Y // expected-error {{invalid redeclaration of 'xy'}} func accept_X(_ x: inout X) { } func accept_XY(_ x: inout X) -> X { } func accept_XY(_ y: inout Y) -> Y { } func accept_Z(_ z: inout Z) -> Z { } func test_inout() { var x : X accept_X(&x); accept_X(xy); // expected-error{{passing value of type 'X' to an inout parameter requires explicit '&'}} {{12-12=&}} accept_X(&xy); _ = accept_XY(&x); x = accept_XY(&xy); x = xy x = &xy; // expected-error {{use of extraneous '&'}} accept_Z(&xy); // expected-error{{cannot convert value of type 'X' to expected argument type 'Z'}} } func lvalue_or_rvalue(_ x: inout X) -> X { } func lvalue_or_rvalue(_ x: X) -> Y { } func test_lvalue_or_rvalue() { var x : X var y : Y let x1 = lvalue_or_rvalue(&x) x = x1 let y1 = lvalue_or_rvalue(x) y = y1 _ = y }
apache-2.0
536ad238f8a911186efeab7c851414f6
26.285714
118
0.519895
2.595109
false
false
false
false
ludoded/ReceiptBot
Pods/Material/Sources/iOS/Material+CALayer.swift
2
8170
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit fileprivate struct MaterialLayer { /// A reference to the CALayer. fileprivate weak var layer: CALayer? /// A property that sets the height of the layer's frame. fileprivate var heightPreset = HeightPreset.default { didSet { layer?.height = CGFloat(heightPreset.rawValue) } } /// A property that sets the cornerRadius of the backing layer. fileprivate var cornerRadiusPreset = CornerRadiusPreset.none { didSet { layer?.cornerRadius = CornerRadiusPresetToValue(preset: cornerRadiusPreset) } } /// A preset property to set the borderWidth. fileprivate var borderWidthPreset = BorderWidthPreset.none { didSet { layer?.borderWidth = BorderWidthPresetToValue(preset: borderWidthPreset) } } /// A preset property to set the shape. fileprivate var shapePreset = ShapePreset.none /// A preset value for Depth. fileprivate var depthPreset: DepthPreset { get { return depth.preset } set(value) { depth.preset = value } } /// Grid reference. fileprivate var depth = Depth.zero { didSet { guard let v = layer else { return } v.shadowOffset = depth.offset.asSize v.shadowOpacity = depth.opacity v.shadowRadius = depth.radius v.layoutShadowPath() } } /// Enables automatic shadowPath sizing. fileprivate var isShadowPathAutoSizing = false /** Initializer that takes in a CALayer. - Parameter view: A CALayer reference. */ fileprivate init(layer: CALayer?) { self.layer = layer } } fileprivate var MaterialLayerKey: UInt8 = 0 extension CALayer { /// MaterialLayer Reference. fileprivate var materialLayer: MaterialLayer { get { return AssociatedObject(base: self, key: &MaterialLayerKey) { return MaterialLayer(layer: self) } } set(value) { AssociateObject(base: self, key: &MaterialLayerKey, value: value) } } /// A property that accesses the frame.origin.x property. @IBInspectable open var x: CGFloat { get { return frame.origin.x } set(value) { frame.origin.x = value layoutShadowPath() } } /// A property that accesses the frame.origin.y property. @IBInspectable open var y: CGFloat { get { return frame.origin.y } set(value) { frame.origin.y = value layoutShadowPath() } } /// A property that accesses the frame.size.width property. @IBInspectable open var width: CGFloat { get { return frame.size.width } set(value) { frame.size.width = value if .none != shapePreset { frame.size.height = value layoutShape() } layoutShadowPath() } } /// A property that accesses the frame.size.height property. @IBInspectable open var height: CGFloat { get { return frame.size.height } set(value) { frame.size.height = value if .none != shapePreset { frame.size.width = value layoutShape() } layoutShadowPath() } } /// HeightPreset value. open var heightPreset: HeightPreset { get { return materialLayer.heightPreset } set(value) { materialLayer.heightPreset = value } } /** A property that manages the overall shape for the object. If either the width or height property is set, the other will be automatically adjusted to maintain the shape of the object. */ open var shapePreset: ShapePreset { get { return materialLayer.shapePreset } set(value) { materialLayer.shapePreset = value } } /// A preset value for Depth. open var depthPreset: DepthPreset { get { return depth.preset } set(value) { depth.preset = value } } /// Grid reference. open var depth: Depth { get { return materialLayer.depth } set(value) { materialLayer.depth = value } } /// Enables automatic shadowPath sizing. @IBInspectable open var isShadowPathAutoSizing: Bool { get { return materialLayer.isShadowPathAutoSizing } set(value) { materialLayer.isShadowPathAutoSizing = value } } /// A property that sets the cornerRadius of the backing layer. open var cornerRadiusPreset: CornerRadiusPreset { get { return materialLayer.cornerRadiusPreset } set(value) { materialLayer.cornerRadiusPreset = value } } /// A preset property to set the borderWidth. open var borderWidthPreset: BorderWidthPreset { get { return materialLayer.borderWidthPreset } set(value) { materialLayer.borderWidthPreset = value } } } extension CALayer { /// Manages the layout for the shape of the view instance. open func layoutShape() { guard .none != shapePreset else { return } if 0 == frame.width { frame.size.width = frame.height } if 0 == frame.height { frame.size.height = frame.width } guard .circle == shapePreset else { return } cornerRadius = bounds.size.width / 2 } /// Sets the shadow path. open func layoutShadowPath() { guard isShadowPathAutoSizing else { return } if .none == depthPreset { shadowPath = nil } else if nil == shadowPath { shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath } else { motion(.shadowPath(UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath)) } } }
lgpl-3.0
03217f18d739c8977278e0077ce59062
27.566434
101
0.585435
5.068238
false
false
false
false
rporzuc/FindFriends
FindFriends/FindFriends/Extensions/UITextField+extension.swift
1
431
import UIKit extension UITextField { func setBottomBorderWithoutPlaceholder(viewColor : UIColor, borderColor : UIColor, borderSize: CGFloat) { self.borderStyle = UITextBorderStyle.none self.layer.backgroundColor = viewColor.cgColor self.layer.masksToBounds = false self.layer.shadowColor = borderColor.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: borderSize) } }
gpl-3.0
8221b99f9c0f2d667cd004ec14ecbb7d
34.916667
107
0.719258
4.842697
false
false
false
false
twobitlabs/TBLCategories
Swift Extensions/UIViewController+TBL.swift
1
1403
import UIKit typealias SimpleBlock = () -> Void @objc extension UIViewController { public func dismissAlertIfNecessary() { if presentedViewController is UIAlertController { dismiss(animated: false, completion: nil) } } public func showAlert(title: String, message: String? = nil, actions: [UIAlertAction]? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) if actions == nil || actions!.isEmpty { alert.addAction(UIAlertAction(title: String.localized("OK"), style: UIAlertAction.Style.default, handler: nil)) } else { for action in actions! { alert.addAction(action) } } present(alert, animated: true, completion: nil) } func showRetryAlert(title: String, message: String? = nil, cancel: SimpleBlock?, retry: SimpleBlock?) { var actions = [ UIAlertAction(title: .localized("Cancel"), style: .default, handler: { (alert: UIAlertAction) in cancel?() }) ] if let retry = retry { actions.append(UIAlertAction(title: .localized("Retry"), style: .default, handler: { (alert: UIAlertAction) in retry() })) } showAlert(title: title, message: message, actions: actions) } }
mit
4e366dd21a78b0f34f39065f8729e5cb
34.974359
123
0.601568
4.739865
false
false
false
false
luanlzsn/pos
pos/Classes/Ant/AntNavController.swift
2
3055
// // LeomanNavController.swift // MoFan // // Created by luan on 2016/12/8. // Copyright © 2016年 luan. All rights reserved. // import UIKit class AntNavController: UINavigationController,UINavigationControllerDelegate,UIGestureRecognizerDelegate { var navBackground : UIView? var lineImageView : UIImageView? override func viewDidLoad() { super.viewDidLoad() navigationBar.isTranslucent = false checkNavBackground() if responds(to: #selector(getter: interactivePopGestureRecognizer)) { interactivePopGestureRecognizer?.delegate = self delegate = self } // Do any additional setup after loading the view. } func checkNavBackground() { for view : UIView in self.navigationBar.subviews { if #available(iOS 10, *) { if NSStringFromClass(view.classForCoder) == "_UIBarBackground" { navBackground = view } } else { if NSStringFromClass(view.classForCoder) == "_UINavigationBarBackground" { navBackground = view } } } } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if self.responds(to: #selector(getter: interactivePopGestureRecognizer)) { interactivePopGestureRecognizer?.isEnabled = false } super.pushViewController(viewController, animated: animated) if viewControllers.count > 1 { checkItem(viewController) } } func checkItem(_ viewController: UIViewController) { viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named :"nav_back")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), style: UIBarButtonItemStyle.plain, target: self, action: #selector(backSuperiorController)) } func backSuperiorController() { popViewController(animated: true) } //MARK: - UINavigationControllerDelegate func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { if responds(to: #selector(getter: interactivePopGestureRecognizer)) { interactivePopGestureRecognizer?.isEnabled = true } } //MARK: - UIGestureRecognizerDelegate func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
d729b2b62b1b6799d359ea07d1df5663
34.08046
256
0.66055
5.813333
false
false
false
false
vanshg/MacAssistant
Pods/SwiftProtobuf/Sources/SwiftProtobuf/NameMap.swift
2
10771
// Sources/SwiftProtobuf/NameMap.swift - Bidirectional number/name mapping // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// TODO: Right now, only the NameMap and the NameDescription enum /// (which are directly used by the generated code) are public. /// This means that code outside the library has no way to actually /// use this data. We should develop and publicize a suitable API /// for that purpose. (Which might be the same as the internal API.) /// This must be exactly the same as the corresponding code in the /// protoc-gen-swift code generator. Changing it will break /// compatibility of the library with older generated code. /// /// It does not necessarily need to match protoc's JSON field naming /// logic, however. private func toJsonFieldName(_ s: String) -> String { var result = String() var capitalizeNext = false #if swift(>=3.2) let chars = s #else let chars = s.characters #endif for c in chars { if c == "_" { capitalizeNext = true } else if capitalizeNext { result.append(String(c).uppercased()) capitalizeNext = false } else { result.append(String(c)) } } return result } /// Allocate static memory buffers to intern UTF-8 /// string data. Track the buffers and release all of those buffers /// in case we ever get deallocated. fileprivate class InternPool { private var interned = [UnsafeBufferPointer<UInt8>]() func intern(utf8: String.UTF8View) -> UnsafeBufferPointer<UInt8> { let bytePointer = UnsafeMutablePointer<UInt8>.allocate(capacity: utf8.count) let mutable = UnsafeMutableBufferPointer<UInt8>(start: bytePointer, count: utf8.count) _ = mutable.initialize(from: utf8) let immutable = UnsafeBufferPointer<UInt8>(start: bytePointer, count: utf8.count) interned.append(immutable) return immutable } deinit { for buff in interned { #if swift(>=4.1) buff.deallocate() #else let p = UnsafeMutableRawPointer(mutating: buff.baseAddress)! p.deallocate(bytes: buff.count, alignedTo: 1) #endif } } } #if !swift(>=4.2) // Constants for FNV hash http://tools.ietf.org/html/draft-eastlake-fnv-03 private let i_2166136261 = Int(bitPattern: 2166136261) private let i_16777619 = Int(16777619) #endif /// An immutable bidirectional mapping between field/enum-case names /// and numbers, used to record field names for text-based /// serialization (JSON and text). These maps are lazily instantiated /// for each message as needed, so there is no run-time overhead for /// users who do not use text-based serialization formats. public struct _NameMap: ExpressibleByDictionaryLiteral { /// An immutable interned string container. The `utf8Start` pointer /// is guaranteed valid for the lifetime of the `NameMap` that you /// fetched it from. Since `NameMap`s are only instantiated as /// immutable static values, that should be the lifetime of the /// program. /// /// Internally, this uses `StaticString` (which refers to a fixed /// block of UTF-8 data) where possible. In cases where the string /// has to be computed, it caches the UTF-8 bytes in an /// unmovable and immutable heap area. internal struct Name: Hashable, CustomStringConvertible { // This is safe to use elsewhere in this library internal init(staticString: StaticString) { self.nameString = .staticString(staticString) self.utf8Buffer = UnsafeBufferPointer<UInt8>(start: staticString.utf8Start, count: staticString.utf8CodeUnitCount) } // This should not be used outside of this file, as it requires // coordinating the lifecycle with the lifecycle of the pool // where the raw UTF8 gets interned. fileprivate init(string: String, pool: InternPool) { let utf8 = string.utf8 self.utf8Buffer = pool.intern(utf8: utf8) self.nameString = .string(string) } // This is for building a transient `Name` object sufficient for lookup purposes. // It MUST NOT be exposed outside of this file. fileprivate init(transientUtf8Buffer: UnsafeBufferPointer<UInt8>) { self.nameString = .staticString("") self.utf8Buffer = transientUtf8Buffer } private(set) var utf8Buffer: UnsafeBufferPointer<UInt8> private enum NameString { case string(String) case staticString(StaticString) } private var nameString: NameString public var description: String { switch nameString { case .string(let s): return s case .staticString(let s): return s.description } } #if swift(>=4.2) public func hash(into hasher: inout Hasher) { for byte in utf8Buffer { hasher.combine(byte) } } #else // swift(>=4.2) public var hashValue: Int { var h = i_2166136261 for byte in utf8Buffer { h = (h ^ Int(byte)) &* i_16777619 } return h } #endif // swift(>=4.2) public static func ==(lhs: Name, rhs: Name) -> Bool { if lhs.utf8Buffer.count != rhs.utf8Buffer.count { return false } return lhs.utf8Buffer.elementsEqual(rhs.utf8Buffer) } } /// The JSON and proto names for a particular field, enum case, or extension. internal struct Names { private(set) var json: Name? private(set) var proto: Name } /// A description of the names for a particular field or enum case. /// The different forms here let us minimize the amount of string /// data that we store in the binary. /// /// These are only used in the generated code to initialize a NameMap. public enum NameDescription { /// The proto (text format) name and the JSON name are the same string. case same(proto: StaticString) /// The JSON name can be computed from the proto string case standard(proto: StaticString) /// The JSON and text format names are just different. case unique(proto: StaticString, json: StaticString) /// Used for enum cases only to represent a value's primary proto name (the /// first defined case) and its aliases. The JSON and text format names for /// enums are always the same. case aliased(proto: StaticString, aliases: [StaticString]) } private var internPool = InternPool() /// The mapping from field/enum-case numbers to names. private var numberToNameMap: [Int: Names] = [:] /// The mapping from proto/text names to field/enum-case numbers. private var protoToNumberMap: [Name: Int] = [:] /// The mapping from JSON names to field/enum-case numbers. /// Note that this also contains all of the proto/text names, /// as required by Google's spec for protobuf JSON. private var jsonToNumberMap: [Name: Int] = [:] /// Creates a new empty field/enum-case name/number mapping. public init() {} /// Build the bidirectional maps between numbers and proto/JSON names. public init(dictionaryLiteral elements: (Int, NameDescription)...) { for (number, description) in elements { switch description { case .same(proto: let p): let protoName = Name(staticString: p) let names = Names(json: protoName, proto: protoName) numberToNameMap[number] = names protoToNumberMap[protoName] = number jsonToNumberMap[protoName] = number case .standard(proto: let p): let protoName = Name(staticString: p) let jsonString = toJsonFieldName(protoName.description) let jsonName = Name(string: jsonString, pool: internPool) let names = Names(json: jsonName, proto: protoName) numberToNameMap[number] = names protoToNumberMap[protoName] = number jsonToNumberMap[protoName] = number jsonToNumberMap[jsonName] = number case .unique(proto: let p, json: let j): let jsonName = Name(staticString: j) let protoName = Name(staticString: p) let names = Names(json: jsonName, proto: protoName) numberToNameMap[number] = names protoToNumberMap[protoName] = number jsonToNumberMap[protoName] = number jsonToNumberMap[jsonName] = number case .aliased(proto: let p, aliases: let aliases): let protoName = Name(staticString: p) let names = Names(json: protoName, proto: protoName) numberToNameMap[number] = names protoToNumberMap[protoName] = number jsonToNumberMap[protoName] = number for alias in aliases { let protoName = Name(staticString: alias) protoToNumberMap[protoName] = number jsonToNumberMap[protoName] = number } } } } /// Returns the name bundle for the field/enum-case with the given number, or /// `nil` if there is no match. internal func names(for number: Int) -> Names? { return numberToNameMap[number] } /// Returns the field/enum-case number that has the given JSON name, /// or `nil` if there is no match. /// /// This is used by the Text format parser to look up field or enum /// names using a direct reference to the un-decoded UTF8 bytes. internal func number(forProtoName raw: UnsafeBufferPointer<UInt8>) -> Int? { let n = Name(transientUtf8Buffer: raw) return protoToNumberMap[n] } /// Returns the field/enum-case number that has the given JSON name, /// or `nil` if there is no match. /// /// This accepts a regular `String` and is used in JSON parsing /// only when a field name or enum name was decoded from a string /// containing backslash escapes. /// /// JSON parsing must interpret *both* the JSON name of the /// field/enum-case provided by the descriptor *as well as* its /// original proto/text name. internal func number(forJSONName name: String) -> Int? { let utf8 = Array(name.utf8) return utf8.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) in let n = Name(transientUtf8Buffer: buffer) return jsonToNumberMap[n] } } /// Returns the field/enum-case number that has the given JSON name, /// or `nil` if there is no match. /// /// This is used by the JSON parser when a field name or enum name /// required no special processing. As a result, we can avoid /// copying the name and look up the number using a direct reference /// to the un-decoded UTF8 bytes. internal func number(forJSONName raw: UnsafeBufferPointer<UInt8>) -> Int? { let n = Name(transientUtf8Buffer: raw) return jsonToNumberMap[n] } }
mit
ba0041324df84e3db5e50e57e2078ee1
36.013746
122
0.675239
4.157082
false
false
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Showcase/SciChartShowcase/SciChartShowcaseDemo/DataManager/DataManager.swift
1
14597
// // DataManager.swift // SciChartShowcaseDemo // // Created by Mykola Hrybeniuk on 2/23/17. // Copyright © 2017 SciChart Ltd. All rights reserved. // import Foundation import SciChart enum StockIndex : String, EnumCollection, CustomStringConvertible { case NASDAQ = ".IXIC" case SP500 = ".INX" case DowJones = ".DJI" case Google = "GOOG" case Apple = "AAPL" var description: String { switch self { case .NASDAQ: return "NASDAQ" case .SP500: return "SP500" case .DowJones: return "Dow Jones" case .Google: return "Google" case .Apple: return "Apple" } } } enum TimePeriod : String, EnumCollection, CustomStringConvertible { case hour = "60m" case day = "1d" case week = "7d" case year = "1Y" var description: String { switch self { case .hour: return "1 hour" case .day: return "1 day" case .week: return "7 days" case .year: return "1 year" } } } enum TimeScale : Int, EnumCollection, CustomStringConvertible { case oneMin = 60 case fiveMin = 300 case fifteenMin = 900 case hour = 3600 case day = 86400 var description: String { switch self { case .oneMin: return "1 min" case .fiveMin: return "5 min" case .fifteenMin: return "15 min" case .hour: return "1 hour" case .day: return "1 day" } } } protocol EnumCollection: Hashable { static var allValues: [Self] { get } } extension EnumCollection { static func cases() -> AnySequence<Self> { typealias S = Self return AnySequence { () -> AnyIterator<S> in var raw = 0 return AnyIterator { let current : Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: S.self, capacity: 1) { $0.pointee } } guard current.hashValue == raw else { return nil } raw += 1 return current } } } static var allValues: [Self] { return Array(self.cases()) } } struct ResourcesFileName { static let bloodOxygenation = "BloodOxygenation" static let bloodPressure = "BloodPressure" static let bloodVolume = "BloodVolume" static let heartRate = "HeartRate" } typealias DataHanlder<T> = (_ dataSeries: T, _ errorMessage: ErrorMessage?) -> Void private typealias ReadFileHandler = (_ content: [String]) -> Void class DataManager { static func getHeartRateData(with handler: @escaping DataHanlder<SCIXyDataSeries>) { readText(fromFile: ResourcesFileName.heartRate) { (content: [String]) in handler(getXyDataSeries(xColumnNumber: 0, yColumnNumber: 1, content: content), nil) } } static func getBloodPressureData(with handler:@escaping DataHanlder<SCIXyDataSeries>) { readText(fromFile: ResourcesFileName.bloodPressure) { (content: [String]) in handler(getXyDataSeries(xColumnNumber: 0, yColumnNumber: 1, content: content), nil) } } static func getBloodVolumeData(with handler:@escaping DataHanlder<SCIXyDataSeries>) { readText(fromFile: ResourcesFileName.bloodVolume) { (content: [String]) in handler(getXyDataSeries(xColumnNumber: 0, yColumnNumber: 1, content: content), nil) } } static func getBloodOxygenationData(with handler:@escaping DataHanlder<SCIXyDataSeries>) { readText(fromFile: ResourcesFileName.bloodOxygenation) { (content: [String]) in handler(getXyDataSeries(xColumnNumber: 0, yColumnNumber: 1, content: content), nil) } } private static func readText(fromFile name: String, handler: @escaping ReadFileHandler) { DispatchQueue.global(qos: .userInitiated).async { var items = [""] if let resourcePath = Bundle.main.resourcePath { let filePath = resourcePath+"/"+name+".txt" do { var contentFile = try String(contentsOfFile: filePath) contentFile = contentFile.replacingOccurrences(of: "\r", with: "", options: NSString.CompareOptions.literal, range:nil) items = contentFile.components(separatedBy: "\n") items.removeLast() } catch let error { print("Reading File Error - "+error.localizedDescription) } } else { print("Resource Path doesn't exist") } DispatchQueue.main.async { handler(items) } } } private static func getXyDataSeries(xColumnNumber: Int, yColumnNumber: Int, content: [String]) -> SCIXyDataSeries { let dataSeries = SCIXyDataSeries(xType: .float, yType: .float) for item in content { let subItems : [String] = item.components(separatedBy: ";") let y : Float = Float(subItems[yColumnNumber])! let x : Float = Float(subItems[xColumnNumber])! dataSeries.appendX(SCIGeneric(x), y: SCIGeneric(y)) } return dataSeries } // MARK: Trader methods static func getPrices(with timeScale: TimeScale = .day, _ timePeriod: TimePeriod = .week, _ stockIndex: StockIndex = .NASDAQ, handler: @escaping DataHanlder<TraderViewModel>) { guard let reachability = Network.reachability else { let dataSeries = getTraderCachedDataSeries() let viewModel = TraderViewModel(stockIndex, timeScale, timePeriod, dataSeries: dataSeries) handler(viewModel, NetworkDomainErrors.noInternetConnection) return } let cachedDataHandler = { (_ errorMessage: (title: String, description: String?)?) in DispatchQueue.global().async { let dataSeries = getTraderCachedDataSeries() let viewModel = TraderViewModel(stockIndex, timeScale, timePeriod, dataSeries: dataSeries) DispatchQueue.main.async { handler(viewModel, errorMessage) } } } if reachability.status == .wifi || (!reachability.isRunningOnDevice && reachability.isConnectedToNetwork) { ServiceManager().getPrices(with: stockIndex, timeScale: timeScale, period: timePeriod, handler: { (succes, data, errorMessage) in if let isData = data, succes { let dataSeries = getTraderDataSeries(from: isData) let viewModel = TraderViewModel(stockIndex, timeScale, timePeriod, dataSeries: dataSeries) handler(viewModel, nil) } else { cachedDataHandler(errorMessage) } }) } else { cachedDataHandler(NetworkDomainErrors.noInternetConnection) } } typealias TraderDataSeries = (ohlc: SCIOhlcDataSeries, volume: SCIXyDataSeries, averageLow: SCIXyDataSeries, averageHigh: SCIXyDataSeries, rsi: SCIXyDataSeries, mcad: SCIXyyDataSeries, histogram: SCIXyDataSeries) private static func getTraderCachedDataSeries() -> TraderDataSeries { let count = 3000 let filePath = Bundle.main.path(forResource: "TraderData", ofType: "txt")! let data = try! String(contentsOfFile: filePath, encoding: String.Encoding.utf8) var items = data.components(separatedBy: "\n") var subItems = [String]() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY-MM-dd" let ohlcDataSeries = SCIOhlcDataSeries(xType: .dateTime, yType: .double) let volumeDataSeries = SCIXyDataSeries(xType: .dateTime, yType: .double) let lowDataSeries = SCIXyDataSeries(xType: .dateTime, yType: .double) let highDataSeries = SCIXyDataSeries(xType: .dateTime, yType: .double) let rsi = SCIXyDataSeries(xType: .dateTime, yType: .double) let mcad = SCIXyyDataSeries(xType: .dateTime, yType: .double) let histogram = SCIXyDataSeries(xType: .dateTime, yType: .double) let averageLow = MovingAverage(length: 50) let averageHigh = MovingAverage(length: 200) let averageGainRsi = MovingAverage(length: 14) let averageLossRsi = MovingAverage(length: 14) let averageSLow = MovingAverage(length: 12) let averageFast = MovingAverage(length: 26) let averageSignal = MovingAverage(length: 9) var previousClose = Double.nan for i in 0..<count { subItems = items[i].components(separatedBy: ",") let dateTime = dateFormatter.date(from: subItems[0])! let open = Double(subItems[1])! let high = Double(subItems[2])! let low = Double(subItems[3])! let close = Double(subItems[4])! let volume = Double(subItems[5])! ohlcDataSeries.appendX(SCIGeneric(dateTime), open: SCIGeneric(open), high: SCIGeneric(high), low: SCIGeneric(low), close: SCIGeneric(close)) volumeDataSeries.appendX(SCIGeneric(dateTime), y: SCIGeneric(volume)) lowDataSeries.appendX(SCIGeneric(dateTime), y: SCIGeneric(averageLow.push(close).current)) highDataSeries.appendX(SCIGeneric(dateTime), y: SCIGeneric(averageHigh.push(close).current)) // Rsi calculations and fill data series let rsiValue = rsiForAverageGain(averageGainRsi, andAveLoss: averageLossRsi, previousClose, close) rsi.appendX(SCIGeneric(dateTime), y: SCIGeneric(rsiValue)) // Mcad calculations and fill data series var mcadPoint = mcadPointForSlow(averageSLow, forFast: averageFast, forSignal: averageSignal, andCloseValue: close) if mcadPoint.divergence.isNaN { mcadPoint.divergence = 0.00000000000000; } mcad.appendX(SCIGeneric(dateTime), y1: SCIGeneric(mcadPoint.mcad), y2: SCIGeneric(mcadPoint.signal)) histogram.appendX(SCIGeneric(dateTime), y: SCIGeneric(mcadPoint.divergence)) previousClose = close } return (ohlcDataSeries, volumeDataSeries, lowDataSeries, highDataSeries, rsi, mcad, histogram) } private static func getTraderDataSeries(from stockPrices: StockPrices) -> TraderDataSeries { let ohlc = SCIOhlcDataSeries(xType: .dateTime, yType: .double) let volume = SCIXyDataSeries(xType: .dateTime, yType: .double) let low = SCIXyDataSeries(xType: .dateTime, yType: .double) let high = SCIXyDataSeries(xType: .dateTime, yType: .double) let rsi = SCIXyDataSeries(xType: .dateTime, yType: .double) let mcad = SCIXyyDataSeries(xType: .dateTime, yType: .double) let histogram = SCIXyDataSeries(xType: .dateTime, yType: .double) let averageLow = MovingAverage(length: 50) let averageHigh = MovingAverage(length: 200) let averageGainRsi = MovingAverage(length: 14) let averageLossRsi = MovingAverage(length: 14) let averageSLow = MovingAverage(length: 12) let averageFast = MovingAverage(length: 26) let averageSignal = MovingAverage(length: 9) var previousClose = Double.nan for item in stockPrices.items { ohlc.appendX(SCIGeneric(item.dateTime), open: SCIGeneric(item.open), high: SCIGeneric(item.high), low: SCIGeneric(item.low), close: SCIGeneric(item.close)) volume.appendX(SCIGeneric(item.dateTime), y: SCIGeneric(item.volume)) low.appendX(SCIGeneric(item.dateTime), y: SCIGeneric(averageLow.push(item.close).current)) high.appendX(SCIGeneric(item.dateTime), y: SCIGeneric(averageHigh.push(item.close).current)) // Rsi calculations and fill data series let rsiValue = rsiForAverageGain(averageGainRsi, andAveLoss: averageLossRsi, previousClose, item.close) rsi.appendX(SCIGeneric(item.dateTime), y: SCIGeneric(rsiValue)) // Mcad calculations and fill data series var mcadPoint = mcadPointForSlow(averageSLow, forFast: averageFast, forSignal: averageSignal, andCloseValue: item.close) if mcadPoint.divergence.isNaN { mcadPoint.divergence = 0.00000000000000; } mcad.appendX(SCIGeneric(item.dateTime), y1: SCIGeneric(mcadPoint.mcad), y2: SCIGeneric(mcadPoint.signal)) histogram.appendX(SCIGeneric(item.dateTime), y: SCIGeneric(mcadPoint.divergence)) previousClose = item.close } return (ohlc, volume, low, high, rsi, mcad, histogram) } private static func rsiForAverageGain(_ averageGain: MovingAverage, andAveLoss averageLoss: MovingAverage, _ previousClose: Double, _ currentClose: Double) -> Double { let gain = currentClose > previousClose ? currentClose - previousClose : 0.0 let loss = previousClose > currentClose ? previousClose - currentClose : 0.0 _ = averageGain.push(gain) _ = averageLoss.push(loss) let relativeStrength = averageGain.current.isNaN || averageLoss.current.isNaN ? Double.nan : averageGain.current / averageLoss.current return relativeStrength.isNaN ? Double.nan : 100.0 - (100.0 / (1.0 + relativeStrength)) } private static func mcadPointForSlow(_ slow: MovingAverage, forFast fast: MovingAverage, forSignal signal: MovingAverage, andCloseValue close: Double) -> (mcad: Double, signal: Double, divergence: Double) { _ = slow.push(close) _ = fast.push(close) let macd = slow.current - fast.current let signalLine = macd.isNaN ? Double.nan : signal.push(macd).current let divergence = macd.isNaN || signalLine.isNaN ? Double.nan : macd - signalLine return (macd, signalLine, divergence) } }
mit
b45e21b0e1ab2b1c06cebf5b79198dfa
39.432133
216
0.607358
4.488315
false
false
false
false
francisceioseph/Swift-Files-App
Swift-Files/SFPlainTextDetailViewController.swift
1
1027
// // SFPlainTextDetailViewController.swift // Swift-Files // // Created by Francisco José A. C. Souza on 26/12/15. // Copyright © 2015 Francisco José A. C. Souza. All rights reserved. // import UIKit class SFPlainTextDetailViewController: UIViewController { var bodyText:String? var editMode:Bool? @IBOutlet weak var fileContentTextView: UITextView! @IBOutlet weak var saveBarButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() self.fileContentTextView.text = self.bodyText if let editMode = self.editMode where editMode == true { self.fileContentTextView.editable = true self.saveBarButton.enabled = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onSaveTap(sender: UIBarButtonItem) { FileHelper.sharedInstance.savePlainTextFileWithName("plain_text", fileContent: self.fileContentTextView.text) } }
mit
41b6bbc581b1580be9399d0addd59939
27.444444
117
0.682617
4.807512
false
false
false
false
ECP-CANDLE/Supervisor
workflows/async-search/swift/workflow.swift
1
3679
/* * WORKFLOW.SWIFT * for CANDLE Benchmarks - mlrMBO */ import io; import sys; import files; import location; import string; import unix; import EQPy; import R; import assert; import python; string emews_root = getenv("EMEWS_PROJECT_ROOT"); string turbine_output = getenv("TURBINE_OUTPUT"); string resident_work_ranks = getenv("RESIDENT_WORK_RANKS"); string r_ranks[] = split(resident_work_ranks,","); int init_size = toint(argv("init_size", "4")); int max_evals = toint(argv("max_evals", "20")); int num_buffer = toint(argv("num_buffer", "2")); int num_regular_workers = turbine_workers()-1; int random_seed = toint(argv("seed", "0")); int max_threshold = toint(argv("max_threshold", "1")); int n_jobs = toint(argv("n_jobs", "1")); string model_name = argv("model_name"); string exp_id = argv("exp_id"); int benchmark_timeout = toint(argv("benchmark_timeout", "-1")); string restart_file = argv("restart_file", "DISABLED"); string py_package = argv("py_package", "async-search"); printf("TURBINE_OUTPUT: " + turbine_output); string restart_number = argv("restart_number", "1"); string site = argv("site"); if (restart_file != "DISABLED") { assert(restart_number != "1", "If you are restarting, you must increment restart_number!"); } string FRAMEWORK = "keras"; (void v) loop(location ME, int ME_rank) { for (boolean b = true, int i = 1; b; b=c, i = i + 1) { string params = EQPy_get(ME); boolean c; if (params == "DONE") { string finals = EQPy_get(ME); // TODO if appropriate // split finals string and join with "\\n" // e.g. finals is a ";" separated string and we want each // element on its own line: // multi_line_finals = join(split(finals, ";"), "\\n"); //string fname = "%s/final_res.Rds" % (turbine_output); //printf("See results in %s", fname) => string fname = "%s/final_result_%i" % (turbine_output, ME_rank); file results_file <fname> = write(finals) => printf("Writing final result to %s", fname) => //printf("Results: %s", finals) => v = propagate(finals) => c = false; } else if (params == "EQPY_ABORT") { printf("EQPy aborted: see output for Python error") => string why = EQPy_get(ME); printf("%s", why) => // v = propagate(why) => c = false; } else { string param_array[] = split(params, ";") => c = true; foreach param, j in param_array { obj(param,"%00i_%000i_%0000i" % (restart_number,i,j), ME_rank); } } } } (void o) start(int ME_rank) { location ME = locationFromRank(ME_rank); // algo_params is the string of parameters used to initialize the // Python algorithm. We pass these as Python code: a comma separated string // of variable=value assignments. string algo_params = "%d,%d,%d,%d,%d,%d,%d" % (init_size, max_evals, num_regular_workers, num_buffer, random_seed, max_threshold, n_jobs); string algorithm = py_package; EQPy_init_package(ME, algorithm) => EQPy_get(ME) => EQPy_put(ME, algo_params) => loop(ME, ME_rank) => { EQPy_stop(ME); o = propagate(); } } main() { assert(strlen(emews_root) > 0, "Set EMEWS_PROJECT_ROOT!"); int ME_ranks[]; foreach r_rank, i in r_ranks{ ME_ranks[i] = toint(r_rank); } /* int num_r_ranks = size(r_ranks); int num_servers = adlb_servers(); printf("num_r_ranks: " + num_r_ranks); printf("num_servers: " + num_servers); */ foreach ME_rank, i in ME_ranks { start(ME_rank) => printf("End rank: %d", ME_rank); } } // Local Variables: // c-basic-offset: 4 // End:
mit
06bd6c8cda7b32667b6930ccf8437ced
26.251852
118
0.600707
3.152528
false
false
false
false
Dan2552/Luncheon
Pod/Classes/Remote.swift
1
9407
// // File.swift // Pods // // Created by Daniel Green on 20/06/2015. // // import Foundation import Placemat import Alamofire public enum RESTAction { case index case show case create case update case destroy } func request<T: Lunch>(_ method: Alamofire.HTTPMethod, url: String, parameters: Alamofire.Parameters? = nil, allowEmptyForStatusCodes: [Int] = [], handler: @escaping (_ object: T?, _ collection: [T]?)->()) { let headers = Options.headers if Options.verbose { print("LUNCHEON: calling \(method) \(url) with params: \(parameters)") } let responseHandler: (DataResponse<Any>)->() = { response in var handleError = true if let statusCode = response.response?.statusCode { handleError = !allowEmptyForStatusCodes.contains(statusCode) } let value = response.result.value if handleError { if Options.errorHandler(response.result.error, response.response?.statusCode, value) { return } } // Single object if let attributes = value as? [String: AnyObject] { let model = T() model.remote.assignAttributes(attributes) handler(model, nil) // Collection } else if let collection = value as? [[String : AnyObject]] { let models: [T] = collection.map { attributes in let model = T() model.remote.assignAttributes(attributes) return model } handler(nil, models) } else { handler(nil, nil) } } Alamofire.request(url, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers as HTTPHeaders) .responseJSON(completionHandler: responseHandler) // Alamofire.request(method, url, parameters: parameters, encoding: .JSON, headers: headers).responseJSON { response in // // } } open class RemoteClass { let subject: Lunch.Type var nestedUnder = [String: Any]() init(subject: Lunch.Type) { self.subject = subject } func pathForAction(_ action: RESTAction, instance: Lunch) -> String { return pathForAction(action, remoteId: instance.remote.id!) } func pathForAction(_ action: RESTAction, remoteId: Any?) -> String { let resourceName = subjectClassName().underscoreCased().pluralize() var nesting = "" for (model, id) in nestedUnder { nesting += "\(model.pluralize())/\(id)/" } switch action { case .show, .update, .destroy: assert(remoteId != nil, "You need an remoteId for this action") return "\(nesting)\(resourceName)/\(remoteId!)" default: return "\(nesting)\(resourceName)" } } func urlForAction(_ action: RESTAction, remoteId: Any?) -> String { return "\(Options.baseUrl!)/\(pathForAction(action, remoteId: remoteId))" } // MARK: REST class methods open func all<T: Lunch>(_ callback: @escaping ([T])->()) { let url = urlForAction(.index, remoteId: nil) request(.get, url: url) { _, collection in callback(collection!) } } open func find<T: Lunch>(_ identifier: NSNumber, _ callback: @escaping (T?) -> ()) { find(Int(identifier), callback) } open func find<T: Lunch>(_ identifier: Int, _ callback: @escaping (T?) -> ()) { let url = urlForAction(.show, remoteId: identifier as AnyObject?) request(.get, url: url, allowEmptyForStatusCodes: [404]) { object, _ in callback(object) } } fileprivate func subjectClassName() -> String { return String(describing: subject).components(separatedBy: ".").last! } } open class Remote: NSObject { let subject: Lunch let subjectClass: Lunch.Type var changedAttributes = [String: Any]() var isKVOEnabled = false private var context = 0 open var id: Any? { return subject.value(forKey: remoteIdentifier()) } init(subject: Lunch) { self.subject = subject self.subjectClass = object_getClass(subject) as! Lunch.Type } deinit { removePropertyObservers() } fileprivate func remoteIdentifier() -> String { return subjectClass.remoteIdentifier?() ?? "remoteId" } open func attributes() -> [String: AnyObject] { var attributes = subject.local.attributes() attributes["id"] = attributes.removeValue(forKey: remoteIdentifier()) return (attributes as NSDictionary).underscoreKeys() } open func attributesToSend() -> [String: AnyObject] { let attrs = attributes() as NSDictionary let only: [String] if isKVOEnabled { let changes = changedAttributes as NSDictionary only = changes.stringKeys() } else { only = nonNilAttributes() } let attributesToSend = attrs.only(keys: only) as! [String: AnyObject] //TODO: use preferences to determine if underscore or not return (attributesToSend as NSDictionary).underscoreKeys() } // MARK: Associations open func associated(_ accociation: Lunch.Type) -> RemoteClass { let accociateRemote = RemoteClass(subject: accociation) let key = subjectClassName().underscoreCased() accociateRemote.nestedUnder[key] = id return accociateRemote } // MARK: Dirty attributes func nonNilAttributes() -> [String] { var keys = [String]() for (key, value) in attributes() { if !(value is NSNull) { keys.append(key) } } return keys } open func isDirty() -> Bool { return (!isKVOEnabled && nonNilAttributes().count > 0) || (isKVOEnabled && changedAttributes.count > 0) } open func isChanged(_ propertyName: String) -> Bool { if !isKVOEnabled && nonNilAttributes().contains(propertyName.underscoreCased()) { return true } for (key, _) in changedAttributes { if key.underscoreCased() == propertyName.underscoreCased() { return true } } return false } open func oldValueFor(_ propertyName: String) -> Any? { if let oldValue: Any = changedAttributes[propertyName] { return (oldValue is NSNull) ? nil : oldValue } return nil } // MARK: Observers func addPropertyObservers() { if isKVOEnabled { return } for property in subject.local.properties() { subject.addObserver(self, forKeyPath: property, options: [.new, .old], context: &context) } isKVOEnabled = true } func removePropertyObservers() { for property in subject.local.properties() { subject.removeObserver(self, forKeyPath: property) } isKVOEnabled = false } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &self.context else { return } guard changedAttributes[keyPath!] == nil else { return } let old = change![NSKeyValueChangeKey.oldKey] changedAttributes[keyPath!] = old } func remoteClassInstance() -> RemoteClass { return RemoteClass(subject: subjectClass) } // MARK: REST instance methods open func reload<T: Lunch>(_ callback: @escaping (T?)->()) { let url = remoteClassInstance().urlForAction(.show, remoteId: id) request(.get, url: url) { object, _ in callback(object) } } open func save<T: Lunch>(_ callback: @escaping (T)->()) { let action: RESTAction = (id == nil) ? .create : .update let url = remoteClassInstance().urlForAction(action, remoteId: id) let parameters = attributesToSend() let method: Alamofire.HTTPMethod = (action == .create) ? .post : .patch request(method, url: url, parameters: parameters) { object, _ in callback(object!) } } open func destroy<T: Lunch>(_ callback: @escaping (T?)->()) { let url = remoteClassInstance().urlForAction(.destroy, remoteId:id) request(.delete, url: url) { object, _ in callback(object) } } open func assignAttributes(_ attributeChanges: [String: Any]) { for (key, value) in attributeChanges { assignAttribute(key, withValue: value) } } open func assignAttribute(_ attributeName: String, withValue value: Any?) { var attributeName = attributeName if attributeName == "id" { attributeName = remoteIdentifier() } subject.local.assignAttribute(attributeName, withValue: value) addPropertyObservers() } fileprivate func subjectClassName() -> String { return String(describing: subjectClass).components(separatedBy: ".").last! } }
mit
1d2d3b513025caf7cd904003fb0607ae
29.054313
207
0.581482
4.753411
false
false
false
false
xiangwangfeng/M80AttributedLabel
SwiftDemo/Classes/LineBreakModeViewController.swift
1
1655
// // LineBreakModeViewController.swift // SwiftDemo // // Created by amao on 2016/10/13. // Copyright © 2016年 amao. All rights reserved. // import UIKit class LineBreakModeViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() self.title = "LineBreakMode" let text = "有关美国的一切,可以用一句话来描述:“Americans business is business”,这句话的意思就是说,那个国家永远是在经商热中,而且永远是一千度的白热。所以你要是看了前文之后以为那里有某种气氛会有助于人立志写作就错了。连我哥哥到了那里都后悔了,觉得不该学逻辑,应当学商科或者计算机。虽然他依旧未证出的逻辑定理,但是看到有钱人豪华的住房,也免不了唠叨几句他对妻儿的责任。" let modes : [CTLineBreakMode] = [.byWordWrapping,.byCharWrapping,.byClipping,.byTruncatingHead,.byTruncatingMiddle,.byTruncatingTail] for mode in modes { let label = M80AttributedLabel() label.text = text label.lineBreakMode = mode label.numberOfLines = 2 label.frame = CGRect.init(x: 20, y: 20 + Int(mode.rawValue) * 80, width: Int(self.view.bounds.width - 40.0), height: 70) label.layer.borderColor = UIColor.orange.cgColor label.layer.borderWidth = 1 self.view.addSubview(label) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
18f4ae71aa66600ec69d82ff3b0adea9
29.090909
215
0.633686
3.386189
false
false
false
false
mownier/sambag
Sambag/Source/SambagMonthYearPickerViewController.swift
1
9209
// // SambagMonthYearPickerViewController.swift // Sambag // // Created by Mounir Ybanez on 03/06/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit public protocol SambagMonthYearPickerViewControllerDelegate: AnyObject { func sambagMonthYearPickerDidSet(_ viewController: SambagMonthYearPickerViewController, result: SambagMonthYearPickerResult) func sambagMonthYearPickerDidCancel(_ viewController: SambagMonthYearPickerViewController) } @objc protocol SambagMonthYearPickerViewControllerInteraction: AnyObject { func didTapSet() func didTapCancel() } public class SambagMonthYearPickerViewController: UIViewController { lazy var alphaTransition = AlphaTransitioning() var contentView: UIView! var titleLabel: UILabel! var strip1: UIView! var strip2: UIView! var strip3: UIView! var okayButton: UIButton! var cancelButton: UIButton! var monthWheel: WheelViewController! var yearWheel: WheelViewController! var result: SambagMonthYearPickerResult { var result = SambagMonthYearPickerResult() result.month = SambagMonth(rawValue: monthWheel.selectedIndexPath.row + 1)! result.year = Int(yearWheel.items[yearWheel.selectedIndexPath.row])! return result } public weak var delegate: SambagMonthYearPickerViewControllerDelegate? public var theme: SambagTheme = .dark public var limit: SambagSelectionLimit? public convenience init() { self.init(nibName: nil, bundle: nil) } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) initSetup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initSetup() } public override func loadView() { super.loadView() let attrib = theme.attribute view.backgroundColor = UIColor.black.withAlphaComponent(0.6) contentView = UIView() contentView.backgroundColor = attrib.contentViewBackgroundColor contentView.layer.cornerRadius = 3 contentView.layer.masksToBounds = true titleLabel = UILabel() titleLabel.text = "Set month and year" titleLabel.textColor = attrib.titleTextColor titleLabel.font = attrib.titleFont okayButton = UIButton() okayButton.setTitleColor(attrib.buttonTextColor, for: .normal) okayButton.setTitle("Set", for: .normal) okayButton.addTarget(self, action: #selector(self.didTapSet), for: .touchUpInside) okayButton.titleLabel?.font = attrib.buttonFont cancelButton = UIButton() cancelButton.setTitleColor(attrib.buttonTextColor, for: .normal) cancelButton.setTitle("Cancel", for: .normal) cancelButton.addTarget(self, action: #selector(self.didTapCancel), for: .touchUpInside) cancelButton.titleLabel?.font = attrib.buttonFont strip1 = UIView() strip1.backgroundColor = attrib.stripColor strip2 = UIView() strip2.backgroundColor = UIColor.gray.withAlphaComponent(0.2) strip3 = UIView() strip3.backgroundColor = strip2.backgroundColor let now = Date() let calendar = Calendar.current let year = calendar.component(.year, from: now) let month = calendar.component(.month, from: now) var items = [String]() for i in 1..<13 { let month = SambagMonth(rawValue: i)! items.append("\(month)") } monthWheel = WheelViewController() monthWheel.items = items monthWheel.gradientColor = attrib.contentViewBackgroundColor monthWheel.stripColor = attrib.stripColor monthWheel.cellTextFont = attrib.wheelFont monthWheel.cellTextColor = attrib.wheelTextColor monthWheel.selectedIndexPath.row = month - 1 items.removeAll() let offset: Int = 101 for i in 1..<offset { items.append("\(year - (offset - i))") } for i in 0..<offset { items.append("\(year + i)") } yearWheel = WheelViewController() yearWheel.items = items yearWheel.gradientColor = monthWheel.gradientColor yearWheel.stripColor = monthWheel.stripColor yearWheel.cellTextFont = monthWheel.cellTextFont yearWheel.cellTextColor = monthWheel.cellTextColor yearWheel.selectedIndexPath.row = offset - 1 guard let selectionLimit = limit, let minDate = selectionLimit.minDate, let maxDate = selectionLimit.maxDate, selectionLimit.isValid else { return } let selectedDate = selectionLimit.selectedDate let minYear = calendar.component(.year, from: minDate) let maxYear = calendar.component(.year, from: maxDate) let selectedYear = calendar.component(.year, from: selectedDate) let selectedMonth = calendar.component(.month, from: selectedDate) let years: [Int] = (minYear...maxYear).map { $0 } yearWheel.items = years.map { "\($0)" } if let index = years.firstIndex(of: selectedYear) { yearWheel.selectedIndexPath.row = index } monthWheel.selectedIndexPath.row = selectedMonth - 1 } public override func viewDidLayoutSubviews() { var rect = CGRect.zero let contentViewHorizontalMargin: CGFloat = 20 let contentViewWidth: CGFloat = min(368, view.frame.width - contentViewHorizontalMargin * 2) rect.origin.x = 20 rect.size.width = contentViewWidth - rect.origin.x * 2 rect.origin.y = 20 rect.size.height = titleLabel.sizeThatFits(rect.size).height titleLabel.frame = rect rect.origin.x = 0 rect.origin.y = rect.maxY + rect.origin.y rect.size.width = contentViewWidth rect.size.height = 2 strip1.frame = rect let wheelWidth: CGFloat = 72 let wheelSpacing: CGFloat = 24 let totalWidth: CGFloat = wheelWidth * 2 + wheelSpacing rect.origin.y = rect.maxY + 20 rect.size.width = wheelWidth rect.size.height = 210 rect.origin.x = (contentViewWidth - totalWidth) / 2 monthWheel.itemHeight = rect.height / 3 monthWheel.view.frame = rect rect.origin.x = rect.maxX + wheelSpacing yearWheel.itemHeight = monthWheel.itemHeight yearWheel.view.frame = rect rect.origin.y = rect.maxY + 20 rect.origin.x = 0 rect.size.width = strip1.frame.width rect.size.height = 1 strip2.frame = rect rect.origin.y = rect.maxY rect.size.width = (contentViewWidth / 2) - 1 rect.size.height = 48 cancelButton.frame = rect rect.origin.x = rect.maxX rect.size.width = 1 strip3.frame = rect rect.origin.x = rect.maxX rect.size.width = cancelButton.frame.width okayButton.frame = rect rect.size.height = rect.maxY rect.size.width = contentViewWidth rect.origin.x = (view.frame.width - rect.width) / 2 rect.origin.y = (view.frame.height - rect.height) / 2 contentView.frame = rect contentView.bounds.size = rect.size if view.frame.height < rect.height + 10 { let scale = view.frame.height / (rect.height + 10) contentView.transform = CGAffineTransform(scaleX: scale, y: scale) } else { contentView.transform = CGAffineTransform.identity } if(contentView.superview == nil) { view.addSubview(contentView) contentView.addSubview(titleLabel) contentView.addSubview(strip1) contentView.addSubview(strip2) contentView.addSubview(strip3) contentView.addSubview(okayButton) contentView.addSubview(cancelButton) contentView.addSubview(monthWheel.view) contentView.addSubview(yearWheel.view) addChild(monthWheel) addChild(yearWheel) monthWheel.didMove(toParent: self) yearWheel.didMove(toParent: self) } } func initSetup() { transitioningDelegate = alphaTransition modalPresentationStyle = .custom } } extension SambagMonthYearPickerViewController: SambagMonthYearPickerViewControllerInteraction { func didTapSet() { var result = SambagMonthYearPickerResult() result.month = SambagMonth(rawValue: monthWheel.selectedIndexPath.row + 1)! result.year = Int(yearWheel.items[yearWheel.selectedIndexPath.row])! delegate?.sambagMonthYearPickerDidSet(self, result: result) } func didTapCancel() { delegate?.sambagMonthYearPickerDidCancel(self) } }
mit
9d78ff5b0feeb4dad582650e422ef726
34.011407
128
0.63119
4.778412
false
false
false
false
jmgrosen/homepit2
HomePit2/FindAccessoriesController.swift
1
4616
// // FindAccessoriesController.swift // HomePit2 // // Created by John Grosen on 6/29/14. // Copyright (c) 2014 John Grosen. All rights reserved. // import UIKit import HomeKit class FindAccessoriesController: UITableViewController, HMAccessoryBrowserDelegate, UIAlertViewDelegate { var home: HMHome! = nil var addedAccessoryHandler: ((HMAccessory) -> Void)! = nil var accessories: HMAccessory[] = [] var accessoryBrowser = HMAccessoryBrowser() override func awakeFromNib() { super.awakeFromNib() self.accessoryBrowser.delegate = self println("now searching for accessories") } override func viewDidLoad() { super.viewDidLoad() self.accessoryBrowser.startSearchingForNewAccessories() let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray) let itemIndicator = UIBarButtonItem(customView: activityIndicator) self.navigationItem.setRightBarButtonItem(itemIndicator, animated: false) activityIndicator.startAnimating() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) self.accessories = [] self.accessoryBrowser.stopSearchingForNewAccessories() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // #pragma mark - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.accessories.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let acc = self.accessories[indexPath.row] cell.textLabel.text = acc.name return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println("\(self.parentViewController.parentViewController)") let acc = self.accessories[indexPath.row] let message = "Are you sure you want to pair with \(acc.name)?" var alert = UIAlertController(title: "Pair?", message: "Are you sure you want to pair with \"\(acc.name)\"?", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { _ in if let selectedRow = self.tableView.indexPathForSelectedRow() { self.tableView.deselectRowAtIndexPath(selectedRow, animated: true) } })) alert.addAction(UIAlertAction(title: "Pair", style: .Default, handler: { action in self.home.addAccessory(acc, /* nil */ { error in if let error = error { var errorAlert = UIAlertController(title: "Pairing Failed", message: nil, preferredStyle: .Alert) errorAlert.addAction(UIAlertAction(title: "Close", style: .Cancel, handler: nil)) } else { self.dismissViewControllerAnimated(true, completion: nil) self.addedAccessoryHandler(acc) } }) })) self.presentViewController(alert, animated: true, completion: nil) } @IBAction func cancelClicked(AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } // #pragma mark - Accessory delegate func accessoryBrowser(browser: HMAccessoryBrowser, didFindNewAccessory accessory: HMAccessory!) { self.accessories.insert(accessory, atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } func accessoryBrowser(browser: HMAccessoryBrowser, didRemoveNewAccessory accessory: HMAccessory!) { let idx = $.indexOf(self.accessories, value: accessory) self.accessories.removeAtIndex(idx!) let indexPath = NSIndexPath(forRow: idx!, inSection: 0) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } }
bsd-3-clause
98f40e74013b6501c8c25342064e5b76
38.801724
141
0.664645
5.424207
false
false
false
false
apple/swift
validation-test/stdlib/String.swift
5
69995
// RUN: %empty-directory(%t) // RUN: %target-clang -fobjc-arc %S/Inputs/NSSlowString/NSSlowString.m -c -o %t/NSSlowString.o // RUN: %target-build-swift -I %S/Inputs/NSSlowString/ %t/NSSlowString.o %s -Xfrontend -disable-access-control -o %t/String // RUN: %target-codesign %t/String // RUN: %target-run %t/String // REQUIRES: executable_test // XFAIL: interpret // UNSUPPORTED: freestanding // With a non-optimized stdlib the test takes very long. // REQUIRES: optimized_stdlib import StdlibUnittest import StdlibCollectionUnittest #if _runtime(_ObjC) import NSSlowString import Foundation // For NSRange #endif #if os(Windows) import ucrt #endif extension Collection { internal func index(_nth n: Int) -> Index { precondition(n >= 0) return index(startIndex, offsetBy: n) } internal func index(_nthLast n: Int) -> Index { precondition(n >= 0) return index(endIndex, offsetBy: -n) } } extension String { var nativeCapacity: Int { switch self._classify()._form { case ._native: break default: preconditionFailure() } return self._classify()._capacity } var capacity: Int { return self._classify()._capacity } var unusedCapacity: Int { return Swift.max(0, self._classify()._capacity - self._classify()._count) } var bufferID: ObjectIdentifier? { return _rawIdentifier() } func _rawIdentifier() -> ObjectIdentifier? { return self._classify()._objectIdentifier } var byteWidth: Int { return _classify()._isASCII ? 1 : 2 } } extension Substring { var bufferID: ObjectIdentifier? { return base.bufferID } } // A thin wrapper around _StringGuts implementing RangeReplaceableCollection struct StringFauxUTF16Collection: RangeReplaceableCollection, RandomAccessCollection { typealias Element = UTF16.CodeUnit typealias Index = Int typealias Indices = CountableRange<Int> init(_ guts: _StringGuts) { self._str = String(guts) } init() { self.init(_StringGuts()) } var _str: String var _guts: _StringGuts { return _str._guts } var startIndex: Index { return 0 } var endIndex: Index { return _str.utf16.count } var indices: Indices { return startIndex..<endIndex } subscript(position: Index) -> Element { return _str.utf16[_str._toUTF16Index(position)] } mutating func replaceSubrange<C>( _ subrange: Range<Index>, with newElements: C ) where C : Collection, C.Element == Element { var utf16 = Array(_str.utf16) utf16.replaceSubrange(subrange, with: newElements) self._str = String(decoding: utf16, as: UTF16.self) } mutating func reserveCapacity(_ n: Int) { _str.reserveCapacity(n) } } var StringTests = TestSuite("StringTests") StringTests.test("sizeof") { #if arch(i386) || arch(arm) || arch(arm64_32) expectEqual(12, MemoryLayout<String>.size) #else expectEqual(16, MemoryLayout<String>.size) #endif } StringTests.test("AssociatedTypes-UTF8View") { typealias View = String.UTF8View expectCollectionAssociatedTypes( collectionType: View.self, iteratorType: View.Iterator.self, subSequenceType: Substring.UTF8View.self, indexType: View.Index.self, indicesType: DefaultIndices<View>.self) } StringTests.test("AssociatedTypes-UTF16View") { typealias View = String.UTF16View expectCollectionAssociatedTypes( collectionType: View.self, iteratorType: View.Iterator.self, subSequenceType: Substring.UTF16View.self, indexType: View.Index.self, indicesType: View.Indices.self) } StringTests.test("AssociatedTypes-UnicodeScalarView") { typealias View = String.UnicodeScalarView expectCollectionAssociatedTypes( collectionType: View.self, iteratorType: View.Iterator.self, subSequenceType: Substring.UnicodeScalarView.self, indexType: View.Index.self, indicesType: DefaultIndices<View>.self) } StringTests.test("AssociatedTypes-CharacterView") { expectCollectionAssociatedTypes( collectionType: String.self, iteratorType: String.Iterator.self, subSequenceType: Substring.self, indexType: String.Index.self, indicesType: DefaultIndices<String>.self) } func checkUnicodeScalarViewIteration( _ expectedScalars: [UInt32], _ str: String ) { do { let us = str.unicodeScalars var i = us.startIndex let end = us.endIndex var decoded: [UInt32] = [] while i != end { expectTrue(i < us.index(after: i)) // Check for Comparable conformance decoded.append(us[i].value) i = us.index(after: i) } expectEqual(expectedScalars, decoded) } do { let us = str.unicodeScalars let start = us.startIndex var i = us.endIndex var decoded: [UInt32] = [] while i != start { i = us.index(before: i) decoded.append(us[i].value) } expectEqual(expectedScalars, decoded) } } StringTests.test("unicodeScalars") { checkUnicodeScalarViewIteration([], "") checkUnicodeScalarViewIteration([ 0x0000 ], "\u{0000}") checkUnicodeScalarViewIteration([ 0x0041 ], "A") checkUnicodeScalarViewIteration([ 0x007f ], "\u{007f}") checkUnicodeScalarViewIteration([ 0x0080 ], "\u{0080}") checkUnicodeScalarViewIteration([ 0x07ff ], "\u{07ff}") checkUnicodeScalarViewIteration([ 0x0800 ], "\u{0800}") checkUnicodeScalarViewIteration([ 0xd7ff ], "\u{d7ff}") checkUnicodeScalarViewIteration([ 0x8000 ], "\u{8000}") checkUnicodeScalarViewIteration([ 0xe000 ], "\u{e000}") checkUnicodeScalarViewIteration([ 0xfffd ], "\u{fffd}") checkUnicodeScalarViewIteration([ 0xffff ], "\u{ffff}") checkUnicodeScalarViewIteration([ 0x10000 ], "\u{00010000}") checkUnicodeScalarViewIteration([ 0x10ffff ], "\u{0010ffff}") } StringTests.test("Index/Comparable") { let empty = "" expectTrue(empty.startIndex == empty.endIndex) expectFalse(empty.startIndex != empty.endIndex) expectTrue(empty.startIndex <= empty.endIndex) expectTrue(empty.startIndex >= empty.endIndex) expectFalse(empty.startIndex > empty.endIndex) expectFalse(empty.startIndex < empty.endIndex) let nonEmpty = "borkus biqualificated" expectFalse(nonEmpty.startIndex == nonEmpty.endIndex) expectTrue(nonEmpty.startIndex != nonEmpty.endIndex) expectTrue(nonEmpty.startIndex <= nonEmpty.endIndex) expectFalse(nonEmpty.startIndex >= nonEmpty.endIndex) expectFalse(nonEmpty.startIndex > nonEmpty.endIndex) expectTrue(nonEmpty.startIndex < nonEmpty.endIndex) } StringTests.test("Index/Hashable") { let s = "abcdef" let t = Set(s.indices) expectEqual(s.count, t.count) expectTrue(t.contains(s.startIndex)) } StringTests.test("ForeignIndexes/Valid") { // It is actually unclear what the correct behavior is. This test is just a // change detector. // // <rdar://problem/18037897> Design, document, implement invalidation model // for foreign String indexes do { let donor = "abcdef" let acceptor = "uvwxyz" expectEqual("u", acceptor[donor.startIndex]) expectEqual("wxy", acceptor[donor.index(_nth: 2)..<donor.index(_nth: 5)]) } do { let donor = "abcdef" let acceptor = "\u{1f601}\u{1f602}\u{1f603}" expectEqual("\u{1f601}", acceptor[donor.startIndex]) // Scalar alignment fixes and checks were added in 5.1, so we don't get the // expected behavior on prior runtimes. guard _hasSwift_5_1() else { return } // Donor's second index is scalar-aligned in donor, but not acceptor. This // will trigger a stdlib assertion. let donorSecondIndex = donor.index(after: donor.startIndex) if _isStdlibInternalChecksEnabled() { expectCrash { _ = acceptor[donorSecondIndex] } } else { expectEqual(1, acceptor[donorSecondIndex].utf8.count) expectEqual(0x9F, acceptor[donorSecondIndex].utf8.first!) } } } StringTests.test("ForeignIndexes/UnexpectedCrash") { let donor = "\u{1f601}\u{1f602}\u{1f603}" let acceptor = "abcdef" // Adjust donor.startIndex to ensure it caches a stride let start = donor.index(before: donor.index(after: donor.startIndex)) // Grapheme stride cache under noop scalar alignment was fixed in 5.1, so we // get a different answer prior. guard _hasSwift_5_1() else { return } // `start` has a cached stride greater than 1, so subscript will trigger an // assertion when it makes a multi-grapheme-cluster Character. if _isStdlibInternalChecksEnabled() { expectCrash { _ = acceptor[start] } } else { expectEqual("abcd", String(acceptor[start])) } } StringTests.test("ForeignIndexes/subscript(Index)/OutOfBoundsTrap") { let donor = "abcdef" let acceptor = "uvw" expectEqual("u", acceptor[donor.index(_nth: 0)]) expectEqual("v", acceptor[donor.index(_nth: 1)]) expectEqual("w", acceptor[donor.index(_nth: 2)]) let i = donor.index(_nth: 3) expectCrashLater() _ = acceptor[i] } StringTests.test("String/subscript(_:Range)") { let s = "foobar" let from = s.startIndex let to = s.index(before: s.endIndex) let actual = s[from..<to] expectEqual("fooba", actual) } StringTests.test("String/subscript(_:ClosedRange)") { let s = "foobar" let from = s.startIndex let to = s.index(before: s.endIndex) let actual = s[from...to] expectEqual(s, actual) } StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/1") { let donor = "abcdef" let acceptor = "uvw" expectEqual("uvw", acceptor[donor.startIndex..<donor.index(_nth: 3)]) let r = donor.startIndex..<donor.index(_nth: 4) expectCrashLater() _ = acceptor[r] } StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/2") { let donor = "abcdef" let acceptor = "uvw" expectEqual("uvw", acceptor[donor.startIndex..<donor.index(_nth: 3)]) let r = donor.index(_nth: 4)..<donor.index(_nth: 5) expectCrashLater() _ = acceptor[r] } StringTests.test("ForeignIndexes/subscript(ClosedRange)/OutOfBoundsTrap/1") { let donor = "abcdef" let acceptor = "uvw" expectEqual("uvw", acceptor[donor.startIndex...donor.index(_nth: 2)]) let r = donor.startIndex...donor.index(_nth: 3) expectCrashLater() _ = acceptor[r] } StringTests.test("ForeignIndexes/subscript(ClosedRange)/OutOfBoundsTrap/2") { let donor = "abcdef" let acceptor = "uvw" expectEqual("uvw", acceptor[donor.startIndex...donor.index(_nth: 2)]) let r = donor.index(_nth: 3)...donor.index(_nth: 5) expectCrashLater() _ = acceptor[r] } StringTests.test("ForeignIndexes/replaceSubrange/OutOfBoundsTrap/1") { let donor = "abcdef" var acceptor = "uvw" acceptor.replaceSubrange( donor.startIndex..<donor.index(_nth: 1), with: "u") expectEqual("uvw", acceptor) let r = donor.startIndex..<donor.index(_nth: 4) expectCrashLater() acceptor.replaceSubrange(r, with: "") } StringTests.test("ForeignIndexes/replaceSubrange/OutOfBoundsTrap/2") { let donor = "abcdef" var acceptor = "uvw" acceptor.replaceSubrange( donor.startIndex..<donor.index(_nth: 1), with: "u") expectEqual("uvw", acceptor) let r = donor.index(_nth: 4)..<donor.index(_nth: 5) expectCrashLater() acceptor.replaceSubrange(r, with: "") } StringTests.test("ForeignIndexes/removeAt/OutOfBoundsTrap") { do { let donor = "abcdef" var acceptor = "uvw" let removed = acceptor.remove(at: donor.startIndex) expectEqual("u", removed) expectEqual("vw", acceptor) } let donor = "abcdef" var acceptor = "uvw" let i = donor.index(_nth: 4) expectCrashLater() acceptor.remove(at: i) } StringTests.test("ForeignIndexes/removeSubrange/OutOfBoundsTrap/1") { do { let donor = "abcdef" var acceptor = "uvw" acceptor.removeSubrange( donor.startIndex..<donor.index(after: donor.startIndex)) expectEqual("vw", acceptor) } let donor = "abcdef" var acceptor = "uvw" let r = donor.startIndex..<donor.index(_nth: 4) expectCrashLater() acceptor.removeSubrange(r) } StringTests.test("ForeignIndexes/removeSubrange/OutOfBoundsTrap/2") { let donor = "abcdef" var acceptor = "uvw" let r = donor.index(_nth: 4)..<donor.index(_nth: 5) expectCrashLater() acceptor.removeSubrange(r) } StringTests.test("hasPrefix") .skip(.nativeRuntime("String.hasPrefix undefined without _runtime(_ObjC)")) .code { #if _runtime(_ObjC) expectTrue("".hasPrefix("")) expectFalse("".hasPrefix("a")) expectTrue("a".hasPrefix("")) expectTrue("a".hasPrefix("a")) // U+0301 COMBINING ACUTE ACCENT // U+00E1 LATIN SMALL LETTER A WITH ACUTE expectFalse("abc".hasPrefix("a\u{0301}")) expectFalse("a\u{0301}bc".hasPrefix("a")) expectTrue("\u{00e1}bc".hasPrefix("a\u{0301}")) expectTrue("a\u{0301}bc".hasPrefix("\u{00e1}")) #else expectUnreachable() #endif } StringTests.test("literalConcatenation") { do { // UnicodeScalarLiteral + UnicodeScalarLiteral var s = "1" + "2" expectType(String.self, &s) expectEqual("12", s) } do { // UnicodeScalarLiteral + ExtendedGraphemeClusterLiteral var s = "1" + "a\u{0301}" expectType(String.self, &s) expectEqual("1a\u{0301}", s) } do { // UnicodeScalarLiteral + StringLiteral var s = "1" + "xyz" expectType(String.self, &s) expectEqual("1xyz", s) } do { // ExtendedGraphemeClusterLiteral + UnicodeScalar var s = "a\u{0301}" + "z" expectType(String.self, &s) expectEqual("a\u{0301}z", s) } do { // ExtendedGraphemeClusterLiteral + ExtendedGraphemeClusterLiteral var s = "a\u{0301}" + "e\u{0302}" expectType(String.self, &s) expectEqual("a\u{0301}e\u{0302}", s) } do { // ExtendedGraphemeClusterLiteral + StringLiteral var s = "a\u{0301}" + "xyz" expectType(String.self, &s) expectEqual("a\u{0301}xyz", s) } do { // StringLiteral + UnicodeScalar var s = "xyz" + "1" expectType(String.self, &s) expectEqual("xyz1", s) } do { // StringLiteral + ExtendedGraphemeClusterLiteral var s = "xyz" + "a\u{0301}" expectType(String.self, &s) expectEqual("xyza\u{0301}", s) } do { // StringLiteral + StringLiteral var s = "xyz" + "abc" expectType(String.self, &s) expectEqual("xyzabc", s) } } StringTests.test("substringDoesNotCopy/Swift3") .xfail(.always("Swift 3 compatibility: Self-sliced Strings are copied")) .code { let size = 16 for sliceStart in [0, 2, 8, size] { for sliceEnd in [0, 2, 8, sliceStart + 1] { if sliceStart > size || sliceEnd > size || sliceEnd < sliceStart { continue } var s0 = String(repeating: "x", count: size) let originalIdentity = s0.bufferID s0 = String(s0[s0.index(_nth: sliceStart)..<s0.index(_nth: sliceEnd)]) expectEqual(originalIdentity, s0.bufferID) } } } StringTests.test("substringDoesNotCopy/Swift4") { let size = 16 for sliceStart in [0, 2, 8, size] { for sliceEnd in [0, 2, 8, sliceStart + 1] { if sliceStart > size || sliceEnd > size || sliceEnd < sliceStart { continue } let s0 = String(repeating: "x", count: size) let originalIdentity = s0.bufferID let s1 = s0[s0.index(_nth: sliceStart)..<s0.index(_nth: sliceEnd)] expectEqual(s1.bufferID, originalIdentity) } } } StringTests.test("appendToEmptyString") { let x = "Bumfuzzle" expectNil(x.bufferID) // Appending to empty string literal should replace it. var a1 = "" a1 += x expectNil(a1.bufferID) // Appending to native string should keep the existing buffer. var b1 = "" b1.reserveCapacity(20) let b1ID = b1.bufferID b1 += x expectEqual(b1.bufferID, b1ID) // .append(_:) should have the same behavior as += var a2 = "" a2.append(x) expectNil(a2.bufferID) var b2 = "" b2.reserveCapacity(20) let b2ID = b2.bufferID b2.append(x) expectEqual(b2.bufferID, b2ID) } StringTests.test("Swift3Slice/Empty") { let size = 16 let s = String(repeating: "x", count: size) expectNotNil(s.bufferID) for i in 0 ... size { let slice = s[s.index(_nth: i)..<s.index(_nth: i)] // Empty substrings still have indices relative to their base and can refer // to the whole string. If the whole string has storage, so should its // substring. expectNotNil(slice.bufferID) } } StringTests.test("Swift3Slice/Full") { let size = 16 let s = String(repeating: "x", count: size) let slice = s[s.startIndex..<s.endIndex] // Most Swift 3 substrings are extracted into their own buffer, // but if the substring covers the full original string, it is used instead. expectEqual(slice.bufferID, s.bufferID) } StringTests.test("appendToSubstring") { for initialSize in 1..<16 { for sliceStart in [0, 2, 8, initialSize] { for sliceEnd in [0, 2, 8, sliceStart + 1] { if sliceStart > initialSize || sliceEnd > initialSize || sliceEnd < sliceStart { continue } var s0 = String(repeating: "x", count: initialSize) s0 = String(s0[s0.index(_nth: sliceStart)..<s0.index(_nth: sliceEnd)]) s0 += "x" expectEqual( String( repeating: "x", count: sliceEnd - sliceStart + 1), s0) } } } } StringTests.test("appendToSubstringBug") .xfail(.always("Swift 3 compatibility: Self-sliced Strings are copied")) .code { // String used to have a heap overflow bug when one attempted to append to a // substring that pointed to the end of a string buffer. // // Unused capacity // VVV // String buffer [abcdefghijk ] // ^ ^ // +----+ // Substring -----------+ // // In the example above, there are only three elements of unused capacity. // The bug was that the implementation mistakenly assumed 9 elements of // unused capacity (length of the prefix "abcdef" plus truly unused elements // at the end). func stringWithUnusedCapacity() -> (String, Int) { var s0 = String(repeating: "x", count: 17) if s0.unusedCapacity == 0 { s0 += "y" } let cap = s0.unusedCapacity expectNotEqual(0, cap) // This sorta checks for the original bug expectEqual( cap, String(s0[s0.index(_nth: 1)..<s0.endIndex]).unusedCapacity) return (s0, cap) } do { var (s, _) = { ()->(String, Int) in let (s0, unused) = stringWithUnusedCapacity() return (String(s0[s0.index(_nth: 5)..<s0.endIndex]), unused) }() let originalID = s.bufferID // Appending to a String always results in storage that // starts at the beginning of its native buffer s += "z" expectNotEqual(originalID, s.bufferID) } do { var (s, _) = { ()->(Substring, Int) in let (s0, unused) = stringWithUnusedCapacity() return (s0[s0.index(_nth: 5)..<s0.endIndex], unused) }() let originalID = s.bufferID // FIXME: Ideally, appending to a Substring with a unique buffer reference // does not reallocate unless necessary. Today, however, it appears to do // so unconditionally unless the slice falls at the beginning of its buffer. s += "z" expectNotEqual(originalID, s.bufferID) } // Try again at the beginning of the buffer do { var (s, unused) = { ()->(Substring, Int) in let (s0, unused) = stringWithUnusedCapacity() return (s0[...], unused) }() let originalID = s.bufferID s += "z" expectEqual(originalID, s.bufferID) s += String(repeating: "z", count: unused - 1) expectEqual(originalID, s.bufferID) s += "." expectNotEqual(originalID, s.bufferID) unused += 0 // warning suppression } } StringTests.test("COW/removeSubrange/start") { var str = "12345678" str.reserveCapacity(1024) // Ensure on heap let literalIdentity = str.bufferID // Check literal-to-heap reallocation. do { let slice = str expectNotNil(literalIdentity) expectEqual(literalIdentity, str.bufferID) expectEqual(literalIdentity, slice.bufferID) expectEqual("12345678", str) expectEqual("12345678", slice) // This mutation should reallocate the string. str.removeSubrange(str.startIndex..<str.index(_nth: 1)) expectNotEqual(literalIdentity, str.bufferID) expectEqual(literalIdentity, slice.bufferID) let heapStrIdentity = str.bufferID expectEqual("2345678", str) expectEqual("12345678", slice) // No more reallocations are expected. str.removeSubrange(str.startIndex..<str.index(_nth: 1)) expectEqual(heapStrIdentity, str.bufferID) expectEqual(literalIdentity, slice.bufferID) expectEqual("345678", str) expectEqual("12345678", slice) } // Check heap-to-heap reallocation. expectEqual("345678", str) do { str.reserveCapacity(1024) // Ensure on heap let heapStrIdentity1 = str.bufferID let slice = str expectNotNil(heapStrIdentity1) expectEqual(heapStrIdentity1, str.bufferID) expectEqual(heapStrIdentity1, slice.bufferID) expectEqual("345678", str) expectEqual("345678", slice) // This mutation should reallocate the string. str.removeSubrange(str.startIndex..<str.index(_nth: 1)) expectNotEqual(heapStrIdentity1, str.bufferID) expectEqual(heapStrIdentity1, slice.bufferID) let heapStrIdentity2 = str.bufferID expectEqual("45678", str) expectEqual("345678", slice) // No more reallocations are expected. str.removeSubrange(str.startIndex..<str.index(_nth: 1)) expectEqual(heapStrIdentity2, str.bufferID) expectEqual(heapStrIdentity1, slice.bufferID) expectEqual("5678", str) expectEqual("345678", slice) } } StringTests.test("COW/removeSubrange/end") { var str = "12345678" str.reserveCapacity(1024) // Ensure on heap let literalIdentity = str.bufferID // Check literal-to-heap reallocation. expectEqual("12345678", str) do { let slice = str expectNotNil(literalIdentity) expectEqual(literalIdentity, str.bufferID) expectEqual(literalIdentity, slice.bufferID) expectEqual("12345678", str) expectEqual("12345678", slice) // This mutation should reallocate the string. str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex) expectNotEqual(literalIdentity, str.bufferID) expectEqual(literalIdentity, slice.bufferID) let heapStrIdentity = str.bufferID expectEqual("1234567", str) expectEqual("12345678", slice) // No more reallocations are expected. str.append("x") str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex) expectEqual(heapStrIdentity, str.bufferID) expectEqual(literalIdentity, slice.bufferID) expectEqual("1234567", str) expectEqual("12345678", slice) str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex) str.append("x") str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex) expectEqual(heapStrIdentity, str.bufferID) expectEqual(literalIdentity, slice.bufferID) expectEqual("123456", str) expectEqual("12345678", slice) } // Check heap-to-heap reallocation. expectEqual("123456", str) do { str.reserveCapacity(1024) // Ensure on heap let heapStrIdentity1 = str.bufferID let slice = str expectNotNil(heapStrIdentity1) expectEqual(heapStrIdentity1, str.bufferID) expectEqual(heapStrIdentity1, slice.bufferID) expectEqual("123456", str) expectEqual("123456", slice) // This mutation should reallocate the string. str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex) expectNotEqual(heapStrIdentity1, str.bufferID) expectEqual(heapStrIdentity1, slice.bufferID) let heapStrIdentity = str.bufferID expectEqual("12345", str) expectEqual("123456", slice) // No more reallocations are expected. str.append("x") str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex) expectEqual(heapStrIdentity, str.bufferID) expectEqual(heapStrIdentity1, slice.bufferID) expectEqual("12345", str) expectEqual("123456", slice) str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex) str.append("x") str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex) expectEqual(heapStrIdentity, str.bufferID) expectEqual(heapStrIdentity1, slice.bufferID) expectEqual("1234", str) expectEqual("123456", slice) } } StringTests.test("COW/replaceSubrange/end") { // Check literal-to-heap reallocation. do { var str = "12345678" str.reserveCapacity(1024) // Ensure on heap let literalIdentity = str.bufferID var slice = str[str.startIndex..<str.index(_nth: 7)] expectNotNil(literalIdentity) expectEqual(literalIdentity, str.bufferID) expectEqual(literalIdentity, slice.bufferID) expectEqual("12345678", str) expectEqual("1234567", slice) // This mutation should reallocate the string. slice.replaceSubrange(slice.endIndex..<slice.endIndex, with: "a") expectNotEqual(literalIdentity, slice.bufferID) expectEqual(literalIdentity, str.bufferID) let heapStrIdentity = slice.bufferID expectEqual("1234567a", slice) expectEqual("12345678", str) // No more reallocations are expected. slice.replaceSubrange( slice.index(_nthLast: 1)..<slice.endIndex, with: "b") expectEqual(heapStrIdentity, slice.bufferID) expectEqual(literalIdentity, str.bufferID) expectEqual("1234567b", slice) expectEqual("12345678", str) } // Check literal-to-heap reallocation. do { var str = "12345678" let literalIdentity = str.bufferID // Move the string to the heap. str.reserveCapacity(32) expectNotEqual(literalIdentity, str.bufferID) let heapStrIdentity1 = str.bufferID expectNotNil(heapStrIdentity1) // FIXME: We have to use Swift 4's Substring to get the desired storage // semantics; in Swift 3 mode, self-sliced strings get allocated a new // buffer immediately. var slice = str[str.startIndex..<str.index(_nth: 7)] expectEqual(heapStrIdentity1, str.bufferID) expectEqual(heapStrIdentity1, slice.bufferID) // This mutation should reallocate the string. slice.replaceSubrange(slice.endIndex..<slice.endIndex, with: "a") expectNotEqual(heapStrIdentity1, slice.bufferID) expectEqual(heapStrIdentity1, str.bufferID) let heapStrIdentity2 = slice.bufferID expectEqual("1234567a", slice) expectEqual("12345678", str) // No more reallocations are expected. slice.replaceSubrange( slice.index(_nthLast: 1)..<slice.endIndex, with: "b") expectEqual(heapStrIdentity2, slice.bufferID) expectEqual(heapStrIdentity1, str.bufferID) expectEqual("1234567b", slice) expectEqual("12345678", str) } } func asciiString< S: Sequence >(_ content: S) -> String where S.Iterator.Element == Character { var s = String() s.append(contentsOf: content) expectTrue(s._classify()._isASCII) return s } StringTests.test("stringGutsExtensibility") .skip(.nativeRuntime("Foundation dependency")) .code { #if _runtime(_ObjC) let ascii = UTF16.CodeUnit(UnicodeScalar("X").value) let nonAscii = UTF16.CodeUnit(UnicodeScalar("é").value) for k in 0..<3 { for count in 1..<16 { for boundary in 0..<count { var x = ( k == 0 ? asciiString("b") : k == 1 ? ("b" as NSString as String) : ("b" as NSMutableString as String) ) if k == 0 { expectTrue(x._guts.isFastUTF8) } for i in 0..<count { x.append(String( decoding: repeatElement(i < boundary ? ascii : nonAscii, count: 3), as: UTF16.self)) } // Make sure we can append pure ASCII to wide storage x.append(String( decoding: repeatElement(ascii, count: 2), as: UTF16.self)) expectEqualSequence( [UTF16.CodeUnit(UnicodeScalar("b").value)] + Array(repeatElement(ascii, count: 3*boundary)) + repeatElement(nonAscii, count: 3*(count - boundary)) + repeatElement(ascii, count: 2), StringFauxUTF16Collection(x.utf16) ) } } } #else expectUnreachable() #endif } StringTests.test("stringGutsReserve") .skip(.nativeRuntime("Foundation dependency")) .code { #if _runtime(_ObjC) guard #available(macOS 10.13, iOS 11.0, tvOS 11.0, *) else { return } for k in 0...7 { var base: String var startedNative: Bool let shared: String = "X" // Managed native, unmanaged native, or small func isSwiftNative(_ s: String) -> Bool { switch s._classify()._form { case ._native: return true case ._small: return true case ._immortal: return true default: return false } } switch k { case 0: (base, startedNative) = (String(), true) case 1: (base, startedNative) = (asciiString("x"), true) case 2: (base, startedNative) = ("Ξ", true) #if arch(i386) || arch(arm) || arch(arm64_32) case 3: (base, startedNative) = ("x" as NSString as String, false) case 4: (base, startedNative) = ("x" as NSMutableString as String, false) #else case 3: (base, startedNative) = ("x" as NSString as String, true) case 4: (base, startedNative) = ("x" as NSMutableString as String, true) #endif case 5: (base, startedNative) = (shared, true) case 6: (base, startedNative) = ("xá" as NSString as String, false) case 7: (base, startedNative) = ("xá" as NSMutableString as String, false) default: fatalError("case unhandled!") } expectEqual(isSwiftNative(base), startedNative) let originalBuffer = base.bufferID let isUnique = base._guts.isUniqueNative let startedUnique = startedNative && base._classify()._objectIdentifier != nil && isUnique base.reserveCapacity(16) // Now it's unique // If it was already native and unique, no reallocation if startedUnique && startedNative { expectEqual(originalBuffer, base.bufferID) } else { expectNotEqual(originalBuffer, base.bufferID) } // Reserving up to the capacity in a unique native buffer is a no-op let nativeBuffer = base.bufferID let currentCapacity = base.capacity base.reserveCapacity(currentCapacity) expectEqual(nativeBuffer, base.bufferID) // Reserving more capacity should reallocate base.reserveCapacity(currentCapacity + 1) expectNotEqual(nativeBuffer, base.bufferID) // None of this should change the string contents var expected: String switch k { case 0: expected = "" case 1,3,4: expected = "x" case 2: expected = "Ξ" case 5: expected = shared case 6,7: expected = "xá" default: fatalError("case unhandled!") } expectEqual(expected, base) } #else expectUnreachable() #endif } func makeStringGuts(_ base: String) -> _StringGuts { var x = String(_StringGuts()) // make sure some - but not all - replacements will have to grow the buffer x.reserveCapacity(base._classify()._count * 3 / 2) let capacity = x.capacity x.append(base) // Widening the guts should not make it lose its capacity, // but the allocator may decide to get more storage. expectGE(x.capacity, capacity) return x._guts } StringTests.test("StringGutsReplace") { let narrow = "01234567890" let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ" for s1 in [narrow, wide] { for s2 in [narrow, wide] { let g1 = makeStringGuts(s1) let g2 = makeStringGuts(s2 + s2) checkRangeReplaceable( { StringFauxUTF16Collection(g1) }, { StringFauxUTF16Collection(g2)[0..<$0] } ) checkRangeReplaceable( { StringFauxUTF16Collection(g1) }, { Array(StringFauxUTF16Collection(g2))[0..<$0] } ) } } } StringTests.test("UnicodeScalarViewReplace") { let narrow = "01234567890" let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ" for s1 in [narrow, wide] { for s2 in [narrow, wide] { let doubleS2 = Array(String(makeStringGuts(s2 + s2)).utf16) checkRangeReplaceable( { () -> String.UnicodeScalarView in String(makeStringGuts(s1)).unicodeScalars }, { String(decoding: doubleS2[0..<$0], as: UTF16.self).unicodeScalars } ) checkRangeReplaceable( { String(makeStringGuts(s1)).unicodeScalars }, { Array(String(makeStringGuts(s2 + s2)).unicodeScalars)[0..<$0] } ) } } } StringTests.test("StringRRC") { let narrow = "01234567890" let wide = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪ" for s1 in [narrow, wide] { for s2 in [narrow, wide] { let doubleS2 = Array(String(makeStringGuts(s2 + s2)).utf16) checkRangeReplaceable( { () -> String in String(makeStringGuts(s1)) }, { String(decoding: doubleS2[0..<$0], as: UTF16.self) } ) checkRangeReplaceable( { String(makeStringGuts(s1)) }, { Array(String(makeStringGuts(s2 + s2)))[0..<$0] } ) } } } StringTests.test("reserveCapacity") { var s = "" let id0 = s.bufferID let oldCap = s.capacity let x: Character = "x" // Help the typechecker - <rdar://problem/17128913> s.insert(contentsOf: repeatElement(x, count: s.capacity + 1), at: s.endIndex) expectNotEqual(id0, s.bufferID) s = "" print("empty capacity \(s.capacity)") s.reserveCapacity(oldCap + 2) print("reserving \(oldCap + 2) [actual capacity: \(s.capacity)]") let id1 = s.bufferID s.insert(contentsOf: repeatElement(x, count: oldCap + 2), at: s.endIndex) print("extending by \(oldCap + 2) [actual capacity: \(s.capacity)]") expectEqual(id1, s.bufferID) s.insert(contentsOf: repeatElement(x, count: s.capacity + 100), at: s.endIndex) expectNotEqual(id1, s.bufferID) } StringTests.test("toInt") { expectNil(Int("")) expectNil(Int("+")) expectNil(Int("-")) expectEqual(20, Int("+20")) expectEqual(0, Int("0")) expectEqual(-20, Int("-20")) expectNil(Int("-cc20")) expectNil(Int(" -20")) expectNil(Int(" \t 20ddd")) expectEqual(Int.min, Int("\(Int.min)")) expectEqual(Int.min + 1, Int("\(Int.min + 1)")) expectEqual(Int.max, Int("\(Int.max)")) expectEqual(Int.max - 1, Int("\(Int.max - 1)")) expectNil(Int("\(Int.min)0")) expectNil(Int("\(Int.max)0")) // Make a String from an Int, mangle the String's characters, // then print if the new String is or is not still an Int. func testConvertibilityOfStringWithModification( _ initialValue: Int, modification: (_ chars: inout [UTF8.CodeUnit]) -> Void ) { var chars = Array(String(initialValue).utf8) modification(&chars) let str = String(decoding: chars, as: UTF8.self) expectNil(Int(str)) } testConvertibilityOfStringWithModification(Int.min) { $0[2] += 1; () // underflow by lots } testConvertibilityOfStringWithModification(Int.max) { $0[1] += 1; () // overflow by lots } // Test values lower than min. do { let base = UInt(Int.max) expectEqual(Int.min + 1, Int("-\(base)")) expectEqual(Int.min, Int("-\(base + 1)")) for i in 2..<20 { expectNil(Int("-\(base + UInt(i))")) } } // Test values greater than min. do { let base = UInt(Int.max) for i in UInt(0)..<20 { expectEqual(-Int(base - i) , Int("-\(base - i)")) } } // Test values greater than max. do { let base = UInt(Int.max) expectEqual(Int.max, Int("\(base)")) for i in 1..<20 { expectNil(Int("\(base + UInt(i))")) } } // Test values lower than max. do { let base = Int.max for i in 0..<20 { expectEqual(base - i, Int("\(base - i)")) } } } // Make sure strings don't grow unreasonably quickly when appended-to StringTests.test("growth") { var s = "" var s2 = s for _ in 0..<20 { s += "x" s2 = s } expectEqual(s2, s) expectLE(s.nativeCapacity, 40) } StringTests.test("Construction") { expectEqual("abc", String(["a", "b", "c"] as [Character])) } StringTests.test("Conversions") { // Whether we are natively ASCII or small ASCII func isKnownASCII(_ s: String) -> Bool { return s.byteWidth == 1 } do { let c: Character = "a" let x = String(c) expectTrue(isKnownASCII(x)) let s: String = "a" expectEqual(s, x) } do { let c: Character = "\u{B977}" let x = String(c) expectFalse(isKnownASCII(x)) let s: String = "\u{B977}" expectEqual(s, x) } } #if canImport(Glibc) import Glibc #endif StringTests.test("lowercased()") { // Use setlocale so tolower() is correct on ASCII. setlocale(LC_ALL, "C") // Check the ASCII domain. let asciiDomain: [Int32] = Array(0..<128) expectEqualFunctionsForDomain( asciiDomain, { String(UnicodeScalar(Int(tolower($0)))!) }, { String(UnicodeScalar(Int($0))!).lowercased() }) expectEqual("", "".lowercased()) expectEqual("abcd", "abCD".lowercased()) expectEqual("абвг", "абВГ".lowercased()) expectEqual("たちつてと", "たちつてと".lowercased()) // // Special casing. // // U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE // to lower case: // U+0069 LATIN SMALL LETTER I // U+0307 COMBINING DOT ABOVE expectEqual("\u{0069}\u{0307}", "\u{0130}".lowercased()) // U+0049 LATIN CAPITAL LETTER I // U+0307 COMBINING DOT ABOVE // to lower case: // U+0069 LATIN SMALL LETTER I // U+0307 COMBINING DOT ABOVE expectEqual("\u{0069}\u{0307}", "\u{0049}\u{0307}".lowercased()) } StringTests.test("uppercased()") { // Use setlocale so toupper() is correct on ASCII. setlocale(LC_ALL, "C") // Check the ASCII domain. let asciiDomain: [Int32] = Array(0..<128) expectEqualFunctionsForDomain( asciiDomain, { String(UnicodeScalar(Int(toupper($0)))!) }, { String(UnicodeScalar(Int($0))!).uppercased() }) expectEqual("", "".uppercased()) expectEqual("ABCD", "abCD".uppercased()) expectEqual("АБВГ", "абВГ".uppercased()) expectEqual("たちつてと", "たちつてと".uppercased()) // // Special casing. // // U+0069 LATIN SMALL LETTER I // to upper case: // U+0049 LATIN CAPITAL LETTER I expectEqual("\u{0049}", "\u{0069}".uppercased()) // U+00DF LATIN SMALL LETTER SHARP S // to upper case: // U+0053 LATIN CAPITAL LETTER S // U+0073 LATIN SMALL LETTER S // But because the whole string is converted to uppercase, we just get two // U+0053. expectEqual("\u{0053}\u{0053}", "\u{00df}".uppercased()) // U+FB01 LATIN SMALL LIGATURE FI // to upper case: // U+0046 LATIN CAPITAL LETTER F // U+0069 LATIN SMALL LETTER I // But because the whole string is converted to uppercase, we get U+0049 // LATIN CAPITAL LETTER I. expectEqual("\u{0046}\u{0049}", "\u{fb01}".uppercased()) } StringTests.test("unicodeViews") { // Check the UTF views work with slicing // U+FFFD REPLACEMENT CHARACTER // U+1F3C2 SNOWBOARDER // U+2603 SNOWMAN let winter = "\u{1F3C2}\u{2603}" // slices // First scalar is 4 bytes long, so this should be invalid expectNil( String(winter.utf8[ winter.utf8.startIndex ..< winter.utf8.index(after: winter.utf8.index(after: winter.utf8.startIndex)) ])) /* // FIXME: note changed String(describing:) results expectEqual( "\u{FFFD}", String(describing: winter.utf8[ winter.utf8.startIndex ..< winter.utf8.index(after: winter.utf8.index(after: winter.utf8.startIndex)) ])) */ expectEqual( "\u{1F3C2}", String( winter.utf8[winter.utf8.startIndex..<winter.utf8.index(_nth: 4)])) expectEqual( "\u{1F3C2}", String( winter.utf16[winter.utf16.startIndex..<winter.utf16.index(_nth: 2)])) expectEqual( "\u{1F3C2}", String( winter.unicodeScalars[ winter.unicodeScalars.startIndex..<winter.unicodeScalars.index(_nth: 1) ])) // views expectEqual( winter, String( winter.utf8[winter.utf8.startIndex..<winter.utf8.index(_nth: 7)])) expectEqual( winter, String( winter.utf16[winter.utf16.startIndex..<winter.utf16.index(_nth: 3)])) expectEqual( winter, String( winter.unicodeScalars[ winter.unicodeScalars.startIndex..<winter.unicodeScalars.index(_nth: 2) ])) let ga = "\u{304b}\u{3099}" expectEqual(ga, String(ga.utf8[ga.utf8.startIndex..<ga.utf8.index(_nth: 6)])) } // Validate that index conversion does something useful for Cocoa // programmers. StringTests.test("indexConversion") .skip(.nativeRuntime("Foundation dependency")) .code { #if _runtime(_ObjC) let re : NSRegularExpression do { re = try NSRegularExpression( pattern: "([^ ]+)er", options: NSRegularExpression.Options()) } catch { fatalError("couldn't build regexp: \(error)") } let s = "go further into the larder to barter." var matches: [String] = [] re.enumerateMatches( in: s, options: NSRegularExpression.MatchingOptions(), range: NSRange(0..<s.utf16.count) ) { result, flags, stop in let r = result!.range(at: 1) let start = String.Index(_encodedOffset: r.location) let end = String.Index(_encodedOffset: r.location + r.length) matches.append(String(s.utf16[start..<end])!) } expectEqual(["furth", "lard", "bart"], matches) #else expectUnreachable() #endif } StringTests.test("String.append(_: UnicodeScalar)") { var s = "" do { // U+0061 LATIN SMALL LETTER A let input: UnicodeScalar = "\u{61}" s.append(String(input)) expectEqual(["\u{61}"], Array(s.unicodeScalars)) } do { // U+304B HIRAGANA LETTER KA let input: UnicodeScalar = "\u{304b}" s.append(String(input)) expectEqual(["\u{61}", "\u{304b}"], Array(s.unicodeScalars)) } do { // U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK let input: UnicodeScalar = "\u{3099}" s.append(String(input)) expectEqual(["\u{61}", "\u{304b}", "\u{3099}"], Array(s.unicodeScalars)) } do { // U+1F425 FRONT-FACING BABY CHICK let input: UnicodeScalar = "\u{1f425}" s.append(String(input)) expectEqual( ["\u{61}", "\u{304b}", "\u{3099}", "\u{1f425}"], Array(s.unicodeScalars)) } } StringTests.test("String.append(_: Character)") { let baseCharacters: [Character] = [ // U+0061 LATIN SMALL LETTER A "\u{61}", // U+304B HIRAGANA LETTER KA // U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK "\u{304b}\u{3099}", // U+3072 HIRAGANA LETTER HI // U+309A COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK "\u{3072}\u{309A}", // U+1F425 FRONT-FACING BABY CHICK "\u{1f425}", // U+0061 LATIN SMALL LETTER A // U+0300 COMBINING GRAVE ACCENT // U+0301 COMBINING ACUTE ACCENT "\u{61}\u{0300}\u{0301}", // U+0061 LATIN SMALL LETTER A // U+0300 COMBINING GRAVE ACCENT // U+0301 COMBINING ACUTE ACCENT // U+0302 COMBINING CIRCUMFLEX ACCENT "\u{61}\u{0300}\u{0301}\u{0302}", // U+0061 LATIN SMALL LETTER A // U+0300 COMBINING GRAVE ACCENT // U+0301 COMBINING ACUTE ACCENT // U+0302 COMBINING CIRCUMFLEX ACCENT // U+0303 COMBINING TILDE "\u{61}\u{0300}\u{0301}\u{0302}\u{0303}", ] let baseStrings = [""] + baseCharacters.map { String($0) } for baseIdx in baseStrings.indices { for prefix in ["", " "] { let base = baseStrings[baseIdx] for inputIdx in baseCharacters.indices { let input = (prefix + String(baseCharacters[inputIdx])).last! var s = base s.append(input) expectEqualSequence( Array(base) + [input], Array(s), "baseIdx=\(baseIdx) inputIdx=\(inputIdx)") } } } } internal func decodeCString< C : UnicodeCodec >(_ s: String, as codec: C.Type) -> (result: String, repairsMade: Bool)? { let units = s.unicodeScalars.map({ $0.value }) + [0] return units.map({ C.CodeUnit($0) }).withUnsafeBufferPointer { String.decodeCString($0.baseAddress, as: C.self) } } StringTests.test("String.decodeCString/UTF8") { let actual = decodeCString("foobar", as: UTF8.self) expectFalse(actual!.repairsMade) expectEqual("foobar", actual!.result) } StringTests.test("String.decodeCString/UTF16") { let actual = decodeCString("foobar", as: UTF16.self) expectFalse(actual!.repairsMade) expectEqual("foobar", actual!.result) } StringTests.test("String.decodeCString/UTF32") { let actual = decodeCString("foobar", as: UTF32.self) expectFalse(actual!.repairsMade) expectEqual("foobar", actual!.result) } internal struct ReplaceSubrangeTest { let original: String let newElements: String let rangeSelection: RangeSelection let expected: String let closedExpected: String? let loc: SourceLoc internal init( original: String, newElements: String, rangeSelection: RangeSelection, expected: String, closedExpected: String? = nil, file: String = #file, line: UInt = #line ) { self.original = original self.newElements = newElements self.rangeSelection = rangeSelection self.expected = expected self.closedExpected = closedExpected self.loc = SourceLoc(file, line, comment: "replaceSubrange() test data") } } internal struct RemoveSubrangeTest { let original: String let rangeSelection: RangeSelection let expected: String let closedExpected: String let loc: SourceLoc internal init( original: String, rangeSelection: RangeSelection, expected: String, closedExpected: String? = nil, file: String = #file, line: UInt = #line ) { self.original = original self.rangeSelection = rangeSelection self.expected = expected self.closedExpected = closedExpected ?? expected self.loc = SourceLoc(file, line, comment: "replaceSubrange() test data") } } let replaceSubrangeTests = [ ReplaceSubrangeTest( original: "", newElements: "", rangeSelection: .emptyRange, expected: "" ), ReplaceSubrangeTest( original: "", newElements: "meela", rangeSelection: .emptyRange, expected: "meela" ), ReplaceSubrangeTest( original: "eela", newElements: "m", rangeSelection: .leftEdge, expected: "meela", closedExpected: "mela" ), ReplaceSubrangeTest( original: "meel", newElements: "a", rangeSelection: .rightEdge, expected: "meela", closedExpected: "meea" ), ReplaceSubrangeTest( original: "a", newElements: "meel", rangeSelection: .leftEdge, expected: "meela", closedExpected: "meel" ), ReplaceSubrangeTest( original: "m", newElements: "eela", rangeSelection: .rightEdge, expected: "meela", closedExpected: "eela" ), ReplaceSubrangeTest( original: "alice", newElements: "bob", rangeSelection: .offsets(1, 1), expected: "aboblice", closedExpected: "abobice" ), ReplaceSubrangeTest( original: "alice", newElements: "bob", rangeSelection: .offsets(1, 2), expected: "abobice", closedExpected: "abobce" ), ReplaceSubrangeTest( original: "alice", newElements: "bob", rangeSelection: .offsets(1, 3), expected: "abobce", closedExpected: "abobe" ), ReplaceSubrangeTest( original: "alice", newElements: "bob", rangeSelection: .offsets(1, 4), expected: "abobe", closedExpected: "abob" ), ReplaceSubrangeTest( original: "alice", newElements: "bob", rangeSelection: .offsets(1, 5), expected: "abob" ), ReplaceSubrangeTest( original: "bob", newElements: "meela", rangeSelection: .offsets(1, 2), expected: "bmeelab", closedExpected: "bmeela" ), ReplaceSubrangeTest( original: "bobbobbobbobbobbobbobbobbobbob", newElements: "meela", rangeSelection: .offsets(1, 2), expected: "bmeelabbobbobbobbobbobbobbobbobbob", closedExpected: "bmeelabobbobbobbobbobbobbobbobbob" ), ReplaceSubrangeTest( original: "bob", newElements: "meelameelameelameelameela", rangeSelection: .offsets(1, 2), expected: "bmeelameelameelameelameelab", closedExpected: "bmeelameelameelameelameela" ), ] let removeSubrangeTests = [ RemoveSubrangeTest( original: "", rangeSelection: .emptyRange, expected: "" ), RemoveSubrangeTest( original: "a", rangeSelection: .middle, expected: "" ), RemoveSubrangeTest( original: "perdicus", rangeSelection: .leftHalf, expected: "icus" ), RemoveSubrangeTest( original: "perdicus", rangeSelection: .rightHalf, expected: "perd" ), RemoveSubrangeTest( original: "alice", rangeSelection: .middle, expected: "ae" ), RemoveSubrangeTest( original: "perdicus", rangeSelection: .middle, expected: "pes" ), RemoveSubrangeTest( original: "perdicus", rangeSelection: .offsets(1, 2), expected: "prdicus", closedExpected: "pdicus" ), RemoveSubrangeTest( original: "perdicus", rangeSelection: .offsets(3, 6), expected: "perus", closedExpected: "pers" ), RemoveSubrangeTest( original: "perdicusaliceandbob", rangeSelection: .offsets(3, 6), expected: "perusaliceandbob", closedExpected: "persaliceandbob" ) ] StringTests.test("String.replaceSubrange()/characters/range") { for test in replaceSubrangeTests { var theString = test.original let c = test.original let rangeToReplace = test.rangeSelection.range(in: c) let newCharacters : [Character] = Array(test.newElements) theString.replaceSubrange(rangeToReplace, with: newCharacters) expectEqual( test.expected, theString, stackTrace: SourceLocStack().with(test.loc)) // Test unique-native optimized path var uniqNative = String(Array(test.original)) uniqNative.replaceSubrange(rangeToReplace, with: newCharacters) expectEqual(theString, uniqNative, stackTrace: SourceLocStack().with(test.loc)) } } StringTests.test("String.replaceSubrange()/string/range") { for test in replaceSubrangeTests { var theString = test.original let c = test.original let rangeToReplace = test.rangeSelection.range(in: c) theString.replaceSubrange(rangeToReplace, with: test.newElements) expectEqual( test.expected, theString, stackTrace: SourceLocStack().with(test.loc)) // Test unique-native optimized path var uniqNative = String(Array(test.original)) uniqNative.replaceSubrange(rangeToReplace, with: test.newElements) expectEqual(theString, uniqNative, stackTrace: SourceLocStack().with(test.loc)) } } StringTests.test("String.replaceSubrange()/characters/closedRange") { for test in replaceSubrangeTests { guard let closedExpected = test.closedExpected else { continue } var theString = test.original let c = test.original let rangeToReplace = test.rangeSelection.closedRange(in: c) let newCharacters = Array(test.newElements) theString.replaceSubrange(rangeToReplace, with: newCharacters) expectEqual( closedExpected, theString, stackTrace: SourceLocStack().with(test.loc)) // Test unique-native optimized path var uniqNative = String(Array(test.original)) uniqNative.replaceSubrange(rangeToReplace, with: newCharacters) expectEqual(theString, uniqNative, stackTrace: SourceLocStack().with(test.loc)) } } StringTests.test("String.replaceSubrange()/string/closedRange") { for test in replaceSubrangeTests { guard let closedExpected = test.closedExpected else { continue } var theString = test.original let c = test.original let rangeToReplace = test.rangeSelection.closedRange(in: c) theString.replaceSubrange(rangeToReplace, with: test.newElements) expectEqual( closedExpected, theString, stackTrace: SourceLocStack().with(test.loc)) // Test unique-native optimized path var uniqNative = String(Array(test.original)) uniqNative.replaceSubrange(rangeToReplace, with: test.newElements) expectEqual(theString, uniqNative, stackTrace: SourceLocStack().with(test.loc)) } } StringTests.test("String.removeSubrange()/range") { for test in removeSubrangeTests { var theString = test.original let c = test.original let rangeToRemove = test.rangeSelection.range(in: c) theString.removeSubrange(rangeToRemove) expectEqual( test.expected, theString, stackTrace: SourceLocStack().with(test.loc)) // Test unique-native optimized path var uniqNative = String(Array(test.original)) uniqNative.removeSubrange(rangeToRemove) expectEqual(theString, uniqNative, stackTrace: SourceLocStack().with(test.loc)) } } StringTests.test("String.removeSubrange()/closedRange") { for test in removeSubrangeTests { switch test.rangeSelection { case .emptyRange: continue default: break } var theString = test.original let c = test.original let rangeToRemove = test.rangeSelection.closedRange(in: c) theString.removeSubrange(rangeToRemove) expectEqual( test.closedExpected, theString, stackTrace: SourceLocStack().with(test.loc)) // Test unique-native optimized path var uniqNative = String(Array(test.original)) uniqNative.removeSubrange(rangeToRemove) expectEqual(theString, uniqNative, stackTrace: SourceLocStack().with(test.loc)) } } //===----------------------------------------------------------------------===// // COW(🐄) tests //===----------------------------------------------------------------------===// public let testSuffix = "z" StringTests.test("COW.Smoke") { var s1 = "COW Smoke Cypseloides" + testSuffix let identity1 = s1._rawIdentifier() var s2 = s1 expectEqual(identity1, s2._rawIdentifier()) s2.append(" cryptus") expectTrue(identity1 != s2._rawIdentifier()) s1.remove(at: s1.startIndex) expectEqual(identity1, s1._rawIdentifier()) _fixLifetime(s1) _fixLifetime(s2) } struct COWStringTest { let test: String let name: String } var testCases: [COWStringTest] { return [ COWStringTest(test: "abcdefghijklmnopqrstuvwxyz", name: "ASCII"), COWStringTest(test: "🐮🐄🤠👢🐴", name: "Unicode") ] } for test in testCases { StringTests.test("COW.\(test.name).IndexesDontAffectUniquenessCheck") { let s = test.test + testSuffix let identity1 = s._rawIdentifier() let startIndex = s.startIndex let endIndex = s.endIndex expectNotEqual(startIndex, endIndex) expectLT(startIndex, endIndex) expectLE(startIndex, endIndex) expectGT(endIndex, startIndex) expectGE(endIndex, startIndex) expectEqual(identity1, s._rawIdentifier()) // Keep indexes alive during the calls above _fixLifetime(startIndex) _fixLifetime(endIndex) } } for test in testCases { StringTests.test("COW.\(test.name).SubscriptWithIndexDoesNotReallocate") { let s = test.test + testSuffix let identity1 = s._rawIdentifier() let startIndex = s.startIndex let empty = startIndex == s.endIndex expectNotEqual((s.startIndex < s.endIndex), empty) expectLE(s.startIndex, s.endIndex) expectEqual((s.startIndex >= s.endIndex), empty) expectGT(s.endIndex, s.startIndex) expectEqual(identity1, s._rawIdentifier()) } } for test in testCases { StringTests.test("COW.\(test.name).RemoveAtDoesNotReallocate") { do { var s = test.test + testSuffix let identity1 = s._rawIdentifier() let index1 = s.startIndex expectEqual(identity1, s._rawIdentifier()) let _ = s.remove(at: index1) expectEqual(identity1, s._rawIdentifier()) } do { let s1 = test.test + testSuffix let identity1 = s1._rawIdentifier() var s2 = s1 expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) let index1 = s1.startIndex expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) let _ = s2.remove(at: index1) expectEqual(identity1, s1._rawIdentifier()) expectTrue(identity1 == s2._rawIdentifier()) } } } for test in testCases { StringTests.test("COW.\(test.name).RemoveAtDoesNotReallocate") { do { var s = test.test + testSuffix expectGT(s.count, 0) s.removeAll() let identity1 = s._rawIdentifier() expectEqual(0, s.count) expectEqual(identity1, s._rawIdentifier()) } do { var s = test.test + testSuffix let identity1 = s._rawIdentifier() expectGT(s.count, 3) s.removeAll(keepingCapacity: true) expectEqual(identity1, s._rawIdentifier()) expectEqual(0, s.count) } do { let s1 = test.test + testSuffix let identity1 = s1._rawIdentifier() expectGT(s1.count, 0) var s2 = s1 s2.removeAll() let identity2 = s2._rawIdentifier() expectEqual(identity1, s1._rawIdentifier()) expectTrue(identity2 != identity1) expectGT(s1.count, 0) expectEqual(0, s2.count) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } do { let s1 = test.test + testSuffix let identity1 = s1._rawIdentifier() expectGT(s1.count, 0) var s2 = s1 s2.removeAll(keepingCapacity: true) let identity2 = s2._rawIdentifier() expectEqual(identity1, s1._rawIdentifier()) expectTrue(identity2 != identity1) expectGT(s1.count, 0) expectEqual(0, s2.count) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } } } for test in testCases { StringTests.test("COW.\(test.name).CountDoesNotReallocate") { let s = test.test + testSuffix let identity1 = s._rawIdentifier() expectGT(s.count, 0) expectEqual(identity1, s._rawIdentifier()) } } for test in testCases { StringTests.test("COW.\(test.name).GenerateDoesNotReallocate") { let s = test.test + testSuffix let identity1 = s._rawIdentifier() var iter = s.makeIterator() var copy = String() while let value = iter.next() { copy.append(value) } expectEqual(copy, s) expectEqual(identity1, s._rawIdentifier()) } } for test in testCases { StringTests.test("COW.\(test.name).EqualityTestDoesNotReallocate") { let s1 = test.test + testSuffix let identity1 = s1._rawIdentifier() var s2 = test.test + testSuffix let identity2 = s2._rawIdentifier() expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity2, s2._rawIdentifier()) s2.remove(at: s2.startIndex) expectNotEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity2, s2._rawIdentifier()) } } enum _Ordering: Int, Equatable { case less = -1 case equal = 0 case greater = 1 var flipped: _Ordering { switch self { case .less: return .greater case .equal: return .equal case .greater: return .less } } init(signedNotation int: Int) { self = int < 0 ? .less : int == 0 ? .equal : .greater } } struct ComparisonTestCase { var strings: [String] // var test: (String, String) -> Void var comparison: _Ordering init(_ strings: [String], _ comparison: _Ordering) { self.strings = strings self.comparison = comparison } func test() { for pair in zip(strings, strings[1...]) { switch comparison { case .less: expectLT(pair.0, pair.1) if !pair.0.isEmpty { // Test mixed String/Substring expectTrue(pair.0.dropLast() < pair.1) } case .greater: expectGT(pair.0, pair.1) if !pair.1.isEmpty { // Test mixed String/Substring expectTrue(pair.0 > pair.1.dropLast()) } case .equal: expectEqual(pair.0, pair.1) if !pair.0.isEmpty { // Test mixed String/Substring expectTrue(pair.0.dropLast() == pair.1.dropLast()) expectFalse(pair.0.dropFirst() == pair.1) expectFalse(pair.0 == pair.1.dropFirst()) } } } } func testOpaqueStrings() { #if _runtime(_ObjC) let opaqueStrings = strings.map { NSSlowString(string: $0) as String } for pair in zip(opaqueStrings, opaqueStrings[1...]) { switch comparison { case .less: expectLT(pair.0, pair.1) case .greater: expectGT(pair.0, pair.1) case .equal: expectEqual(pair.0, pair.1) } } expectEqualSequence(strings, opaqueStrings) #endif } func testOpaqueSubstrings() { #if _runtime(_ObjC) for pair in zip(strings, strings[1...]) { let string1 = pair.0.dropLast() let string2 = pair.1 let opaqueString = (NSSlowString(string: pair.0) as String).dropLast() guard string1.count > 0 else { return } expectEqual(string1, opaqueString) expectEqual(string1 < string2, opaqueString < string2) expectEqual(string1 > string2, opaqueString > string2) expectEqual(string1 == string2, opaqueString == string2) } #endif } } let comparisonTestCases = [ ComparisonTestCase(["a", "a"], .equal), ComparisonTestCase(["abcdefg", "abcdefg"], .equal), ComparisonTestCase(["", "Z", "a", "b", "c", "\u{00c5}", "á"], .less), ComparisonTestCase(["ábcdefg", "ábcdefgh", "ábcdefghi"], .less), ComparisonTestCase(["abcdefg", "abcdefgh", "abcdefghi"], .less), ComparisonTestCase(["á", "\u{0061}\u{0301}"], .equal), ComparisonTestCase(["à", "\u{0061}\u{0301}", "â", "\u{e3}", "a\u{0308}"], .less), // Exploding scalars AND exploding segments ComparisonTestCase(["\u{fa2}", "\u{fa1}\u{fb7}"], .equal), ComparisonTestCase([ "\u{fa2}\u{fa2}\u{fa2}\u{fa2}", "\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}" ], .equal), ComparisonTestCase([ "\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}", "\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}" ], .equal), ComparisonTestCase([ "a\u{fa2}\u{fa2}a\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}\u{fa2}", "a\u{fa1}\u{fb7}\u{fa1}\u{fb7}a\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}\u{fa1}\u{fb7}" ], .equal), ComparisonTestCase(["a\u{301}\u{0301}", "\u{e1}"], .greater), ComparisonTestCase(["😀", "😀"], .equal), ComparisonTestCase(["\u{2f9df}", "\u{8f38}"], .equal), ComparisonTestCase([ "a", "\u{2f9df}", // D87E DDDF as written, but normalizes to 8f38 "\u{2f9df}\u{2f9df}", // D87E DDDF as written, but normalizes to 8f38 "👨🏻", // D83D DC68 D83C DFFB "👨🏻‍⚕️", // D83D DC68 D83C DFFB 200D 2695 FE0F "👩‍⚕️", // D83D DC69 200D 2695 FE0F "👩🏾", // D83D DC69 D83C DFFE "👩🏾‍⚕", // D83D DC69 D83C DFFE 200D 2695 FE0F "😀", // D83D DE00 "😅", // D83D DE05 "🧀" // D83E DDC0 -- aka a really big scalar ], .less), ComparisonTestCase(["f̛̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦ͘͜͟͢͝͞͠͡", "ơ̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͥͦͧͨͩͪͫͬͭͮ͘"], .less), ComparisonTestCase(["\u{f90b}", "\u{5587}"], .equal), ComparisonTestCase(["a\u{1D160}a", "a\u{1D158}\u{1D1C7}"], .less), ComparisonTestCase(["a\u{305}\u{315}", "a\u{315}\u{305}"], .equal), ComparisonTestCase(["a\u{315}bz", "a\u{315}\u{305}az"], .greater), ComparisonTestCase(["\u{212b}", "\u{00c5}"], .equal), ComparisonTestCase([ "A", "a", "aa", "ae", "ae🧀", "az", "aze\u{300}", "ae\u{301}", "ae\u{301}ae\u{301}", "ae\u{301}ae\u{301}ae\u{301}", "ae\u{301}ae\u{301}ae\u{301}ae\u{301}", "ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}", "ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}", "ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}", "ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}", "ae\u{301}\u{302}", "ae\u{302}", "ae\u{302}{303}", "ae\u{302}🧀", "ae\u{303}", "x\u{0939}x", "x\u{0939}\u{093a}x", "x\u{0939}\u{093a}\u{093b}x", "\u{f90b}\u{f90c}\u{f90d}", // Normalizes to BMP scalars "\u{FFEE}", // half width CJK dot "🧀", // D83E DDC0 -- aka a really big scalar ], .less), ComparisonTestCase(["ư̴̵̶̷̸̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡", "ì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘"], .greater), ComparisonTestCase(["ư̴̵̶̷̸̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡", "aì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘"], .greater), ComparisonTestCase(["ì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘", "ì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘"], .equal) ] for test in comparisonTestCases { StringTests.test("Comparison.\(test.strings)") { test.test() } StringTests.test("Comparison.OpaqueString.\(test.strings)") .skip(.linuxAny(reason: "NSSlowString requires ObjC interop")) .code { test.testOpaqueStrings() } StringTests.test("Comparison.OpaqueSubstring.\(test.strings)") .skip(.linuxAny(reason: "NSSlowString requires ObjC interop")) .code { test.testOpaqueSubstrings() } } StringTests.test("Comparison.Substrings") { let str = "abcdefg" let expectedStr = "bcdef" let substring = str.dropFirst().dropLast() expectEqual(expectedStr, substring) } StringTests.test("Comparison.Substrings/Opaque") .skip(.linuxAny(reason: "NSSlowString requires ObjC interop")) .code { #if _runtime(_ObjC) let str = NSSlowString(string: "abcdefg") as String let expectedStr = NSSlowString(string: "bcdef") as String let substring = str.dropFirst().dropLast() expectEqual(expectedStr, substring) #endif } StringTests.test("NormalizationBufferCrashRegressionTest") { let str = "\u{0336}\u{0344}\u{0357}\u{0343}\u{0314}\u{0351}\u{0340}\u{0300}\u{0340}\u{0360}\u{0314}\u{0357}\u{0315}\u{0301}\u{0344}a" let set = Set([str]) expectTrue(set.contains(str)) } StringTests.test("NormalizationCheck") { let str = "\u{0336}\u{0344}\u{0357}\u{0343}\u{0314}\u{0351}\u{0340}\u{0300}\u{0340}\u{0360}\u{0314}\u{0357}\u{0315}\u{0301}\u{0344}a" let nfcCodeUnits = str._nfcCodeUnits let expectedCodeUnits: [UInt8] = [0xCC, 0xB6, 0xCC, 0x88, 0xCC, 0x81, 0xCD, 0x97, 0xCC, 0x93, 0xCC, 0x94, 0xCD, 0x91, 0xCC, 0x80, 0xCC, 0x80, 0xCC, 0x80, 0xCC, 0x94, 0xCD, 0x97, 0xCC, 0x81, 0xCC, 0x88, 0xCC, 0x81, 0xCC, 0x95, 0xCD, 0xA0, 0x61] expectEqual(expectedCodeUnits, nfcCodeUnits) } StringTests.test("NormalizationCheck/Opaque") .skip(.linuxAny(reason: "NSSlowString requires ObjC interop")) .code { #if _runtime(_ObjC) let str = "\u{0336}\u{0344}\u{0357}\u{0343}\u{0314}\u{0351}\u{0340}\u{0300}\u{0340}\u{0360}\u{0314}\u{0357}\u{0315}\u{0301}\u{0344}a" let opaqueString = NSSlowString(string: str) as String let nfcCodeUnits = opaqueString._nfcCodeUnits let expectedCodeUnits: [UInt8] = [0xCC, 0xB6, 0xCC, 0x88, 0xCC, 0x81, 0xCD, 0x97, 0xCC, 0x93, 0xCC, 0x94, 0xCD, 0x91, 0xCC, 0x80, 0xCC, 0x80, 0xCC, 0x80, 0xCC, 0x94, 0xCD, 0x97, 0xCC, 0x81, 0xCC, 0x88, 0xCC, 0x81, 0xCC, 0x95, 0xCD, 0xA0, 0x61] expectEqual(expectedCodeUnits, nfcCodeUnits) #endif } func expectBidirectionalCount(_ count: Int, _ string: String) { var i = 0 var index = string.endIndex while index != string.startIndex { i += 1 string.formIndex(before: &index) } expectEqual(count, i) } if #available(SwiftStdlib 5.6, *) { StringTests.test("GraphemeBreaking.Indic Sequences") { let test1 = "\u{0915}\u{0924}" // 2 expectEqual(2, test1.count) expectBidirectionalCount(2, test1) let test2 = "\u{0915}\u{094D}\u{0924}" // 1 expectEqual(1, test2.count) expectBidirectionalCount(1, test2) let test3 = "\u{0915}\u{094D}\u{094D}\u{0924}" // 1 expectEqual(1, test3.count) expectBidirectionalCount(1, test3) let test4 = "\u{0915}\u{094D}\u{200D}\u{0924}" // 1 expectEqual(1, test4.count) expectBidirectionalCount(1, test4) let test5 = "\u{0915}\u{093C}\u{200D}\u{094D}\u{0924}" // 1 expectEqual(1, test5.count) expectBidirectionalCount(1, test5) let test6 = "\u{0915}\u{093C}\u{094D}\u{200D}\u{0924}" // 1 expectEqual(1, test6.count) expectBidirectionalCount(1, test6) let test7 = "\u{0915}\u{094D}\u{0924}\u{094D}\u{092F}" // 1 expectEqual(1, test7.count) expectBidirectionalCount(1, test7) let test8 = "\u{0915}\u{094D}\u{0061}" // 2 expectEqual(2, test8.count) expectBidirectionalCount(2, test8) let test9 = "\u{0061}\u{094D}\u{0924}" // 2 expectEqual(2, test9.count) expectBidirectionalCount(2, test9) let test10 = "\u{003F}\u{094D}\u{0924}" // 2 expectEqual(2, test10.count) expectBidirectionalCount(2, test10) #if _runtime(_ObjC) let test11Foreign = NSString(string: "\u{930}\u{93e}\u{91c}\u{94d}") // 2 let test11 = test11Foreign as String expectEqual(2, test11.count) expectBidirectionalCount(2, test11) #endif let test12 = "a\u{0915}\u{093C}\u{200D}\u{094D}\u{0924}a" // 3 expectEqual(3, test12.count) expectBidirectionalCount(3, test12) } } StringTests.test("SmallString.zeroTrailingBytes") { if #available(SwiftStdlib 5.8, *) { let full: _SmallString.RawBitPattern = (.max, .max) withUnsafeBytes(of: full) { expectTrue($0.allSatisfy({ $0 == 0xff })) } let testIndices = [1, 7, 8, _SmallString.capacity] for i in testIndices { // The internal invariants in `_zeroTrailingBytes(of:from:)` expectTrue(0 < i && i <= _SmallString.capacity) print(i) var bits = full _SmallString.zeroTrailingBytes(of: &bits, from: i) withUnsafeBytes(of: bits) { expectTrue($0[..<i].allSatisfy({ $0 == 0xff })) expectTrue($0[i...].allSatisfy({ $0 == 0 })) } bits = (0, 0) } } } runAllTests()
apache-2.0
65f5b26545a396b60841fabd318a74c3
28.184155
245
0.650836
3.678441
false
true
false
false
reza-ryte-club/firefox-ios
Client/Frontend/UIConstants.swift
4
5884
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared public struct UIConstants { static let DefaultHomePage = NSURL(string: "\(WebServer.sharedInstance.base)/about/home/#panel=0")! static let AppBackgroundColor = UIColor.blackColor() static let PrivateModePurple = UIColor(red: 207 / 255, green: 104 / 255, blue: 255 / 255, alpha: 1) static let PrivateModeLocationBackgroundColor = UIColor(red: 31 / 255, green: 31 / 255, blue: 31 / 255, alpha: 1) static let PrivateModeLocationBorderColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.15) static let PrivateModeActionButtonTintColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.8) static let PrivateModeTextHighlightColor = UIColor(red: 120 / 255, green: 120 / 255, blue: 165 / 255, alpha: 1) static let PrivateModeReaderModeBackgroundColor = UIColor(red: 89 / 255, green: 89 / 255, blue: 89 / 255, alpha: 1) static let ToolbarHeight: CGFloat = 44 static let DefaultRowHeight: CGFloat = 58 static let DefaultPadding: CGFloat = 10 static let SnackbarButtonHeight: CGFloat = 48 static let DeviceFontSize: CGFloat = DeviceInfo.deviceModel().rangeOfString("iPad") != nil ? 18 : 15 static let DefaultMediumFontSize: CGFloat = 14 static let DefaultMediumFont: UIFont = UIFont.systemFontOfSize(DefaultMediumFontSize, weight: UIFontWeightRegular) static let DefaultMediumBoldFont = UIFont.boldSystemFontOfSize(DefaultMediumFontSize) static let DefaultSmallFontSize: CGFloat = 11 static let DefaultSmallFont = UIFont.systemFontOfSize(DefaultSmallFontSize, weight: UIFontWeightRegular) static let DefaultSmallFontBold = UIFont.systemFontOfSize(DefaultSmallFontSize, weight: UIFontWeightBold) static let DefaultStandardFontSize: CGFloat = 17 static let DefaultStandardFontBold = UIFont.boldSystemFontOfSize(DefaultStandardFontSize) static let DefaultStandardFont: UIFont = UIFont.systemFontOfSize(DefaultStandardFontSize, weight: UIFontWeightRegular) // These highlight colors are currently only used on Snackbar buttons when they're pressed static let HighlightColor = UIColor(red: 205/255, green: 223/255, blue: 243/255, alpha: 0.9) static let HighlightText = UIColor(red: 42/255, green: 121/255, blue: 213/255, alpha: 1.0) static let PanelBackgroundColor = UIColor.whiteColor() static let SeparatorColor = UIColor(rgb: 0xcccccc) static let HighlightBlue = UIColor(red:76/255, green:158/255, blue:255/255, alpha:1) static let DestructiveRed = UIColor(red: 255/255, green: 64/255, blue: 0/255, alpha: 1.0) static let BorderColor = UIColor.blackColor().colorWithAlphaComponent(0.25) static let BackgroundColor = UIColor(red: 0.21, green: 0.23, blue: 0.25, alpha: 1) // settings static let TableViewHeaderBackgroundColor = UIColor(red: 242/255, green: 245/255, blue: 245/255, alpha: 1.0) static let TableViewHeaderTextColor = UIColor(red: 130/255, green: 135/255, blue: 153/255, alpha: 1.0) static let TableViewRowTextColor = UIColor(red: 53.55/255, green: 53.55/255, blue: 53.55/255, alpha: 1.0) static let TableViewSeparatorColor = UIColor(rgb: 0xD1D1D4) // Firefox Orange static let ControlTintColor = UIColor(red: 240.0 / 255, green: 105.0 / 255, blue: 31.0 / 255, alpha: 1) /// JPEG compression quality for persisted screenshots. Must be between 0-1. static let ScreenshotQuality: Float = 0.3 } /// Strings that will be used for features that haven't yet landed. private struct TempStrings { // Bug 1109675 - Request Desktop Site let requestDesktopSite = NSLocalizedString("Request Desktop Site", comment: "Pending feature; currently unused string! Tooltip label triggered by long pressing the refresh button.") let requestMobileSite = NSLocalizedString("Request Mobile Site", comment: "Pending feature; currently unused string! Tooltip label triggered by long pressing the refresh button a second time.") // Bug 1182303 - Checkbox to block alert spam. let disableAlerts = NSLocalizedString("Disable additional page dialogs", comment: "Pending feature; currently unused string! Checkbox label shown after multiple alerts are shown") // Bug 1186013 - Prompt for going to clipboard URL let goToCopiedURL = NSLocalizedString("Go to copied URL?", comment: "Pending feature; currently unused string! Prompt message shown when browser is opened with URL on the clipboard") let goToCopiedURLButton = NSLocalizedString("Go", comment: "Pending feature; currently unused string! Button to browse to URL on the clipboard when browser is opened") // Bug 1196227 - (pbmode) [Meta] Private Browsing let openInNewPrivateTab = NSLocalizedString("Open In New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab") } /// Old strings that will be removed when we kill 1.0. We need to keep them around for now for l10n export. private struct ObsoleteStrings { let introMultiplePages = NSLocalizedString("Browse multiple Web pages at the same time with tabs.", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo") let introPersonalize = NSLocalizedString("Personalize your Firefox just the way you like in Settings.", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo") let introConnect = NSLocalizedString("Connect Firefox everywhere you use it.", tableName: "Intro", comment: "See http://mzl.la/1T8gxwo") let settingsSearchSuggestions = NSLocalizedString("Show search suggestions", comment: "Label for show search suggestions setting.") let settingsSignIn = NSLocalizedString("Sign in", comment: "Text message / button in the settings table view") }
mpl-2.0
1789c07f7256fb27dc1f3bc9251e9ff7
65.863636
197
0.74949
4.400898
false
false
false
false
airbnb/lottie-ios
Example/iOS/AppDelegate.swift
2
974
// Created by Cal Stephens on 12/9/21. // Copyright © 2021 Airbnb Inc. All rights reserved. import Lottie import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application( _: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // We don't ever want a single animation to crash the Example app, // so we stub out `assert` and `assertionFailure` to just `print`. LottieLogger.shared = .printToConsole Configuration.applyCurrentConfiguration() let window = UIWindow(frame: UIScreen.main.bounds) let navigationController = UINavigationController( rootViewController: SampleListViewController(directory: "Samples")) navigationController.navigationBar.prefersLargeTitles = true window.rootViewController = navigationController window.makeKeyAndVisible() self.window = window return true } }
apache-2.0
341b84ac42385445cad455001619f0d9
26.027778
76
0.742035
5.203209
false
true
false
false
xmartlabs/Bender
Sources/Helpers/Constants.swift
1
2063
// // Constants.swift // Bender // // Created by Mathias Claassen on 3/14/17. // Copyright © 2017 Xmartlabs. All rights reserved. // import CoreVideo import Metal struct Constants { static let FloatSize = MemoryLayout<Float>.size static let HalfSize = MemoryLayout<Float>.size / 2 } extension Constants { /// TensorFlow ops struct Ops { static let Add = "Add" static let Assign = "Assign" static let AvgPool = "AvgPool" static let BatchToSpace = "BatchToSpaceND" static let BatchNormGlobal = "BatchNormWithGlobalNormalization" static let FusedBatchNorm = "FusedBatchNorm" static let BiasAdd = "BiasAdd" static let Concat = "ConcatV2" static let ConcatV1 = "Concat" static let Conv = "Conv2D" static let Const = "Const" static let Dense = "Dense" static let DepthwiseConv = "DepthwiseConv2dNative" static let InstanceNormAdd = "InstanceNormAdd" static let InstanceNormMul = "InstanceNormMul" static let MatMul = "MatMul" static let MaxPool = "MaxPool" static let Mul = "Mul" static let Mean = "Mean" static let Pow = "Pow" static let RealDiv = "RealDiv" static let QuantizedConv2D = "QuantizedConv2D" static let QuantizedRelu = "QuantizedRelu" static let QuantizedReshape = "QuantizedReshape" static let QuantizeV2 = "QuantizeV2" static let Relu = "Relu" static let Relu6 = "Relu6" static let Reshape = "Reshape" static let Rsqrt = "Rsqrt" static let Shape = "Shape" static let Sigmoid = "Sigmoid" static let Softmax = "Softmax" static let SpaceToBatch = "SpaceToBatchND" static let Sub = "Sub" static let Switch = "Switch" static let Tanh = "Tanh" static let Variable = "VariableV2" } /// Custom attributes added to TensorFlow nodes during graph conversion struct CustomAttr { static let neuron = "neuron" } }
mit
9e9804b3bc05098e3fbdee54548bc544
28.042254
75
0.628031
3.935115
false
false
false
false
jverkoey/FigmaKit
Sources/FigmaKit/Node/VectorNode.swift
1
9192
extension Node { /// A Figma Vector node. /// /// https://www.figma.com/developers/api#vector-props public class VectorNode: Node { /// Bounding box of the node in absolute space coordinates. public let absoluteBoundingBox: FigmaKit.Rectangle /// How this node blends with nodes behind it in the scene. public let blendMode: BlendMode /// Horizontal and vertical layout constraints for node. public let constraints: LayoutConstraint /// An array of effects attached to this node. public let effects: [Effect] /// An array of export settings representing images to export from the node. public let exportSettings: [ExportSetting] /// An array of paths representing the object fill. public let fillGeometry: [Path] /// An array of fill paints applied to the node. public let fills: [Paint] /// Does this node mask sibling nodes in front of it? public let isMask: Bool /// Determines if the layer should stretch along the parent’s counter axis. /// This property is only provided for direct children of auto-layout frames. public let layoutAlign: LayoutAlign? /// This property is applicable only for direct children of auto-layout frames, ignored otherwise. /// Determines whether a layer should stretch along the parent’s primary axis. public let layoutGrow: LayoutGrow? /// If true, layer is locked and cannot be edited. public let locked: Bool /// Opacity of the node. public let opacity: Double /// Keep height and width constrained to same ratio. public let preserveRatio: Bool /// The top two rows of a matrix that represents the 2D transform of this node relative to its parent. /// /// The bottom row of the matrix is implicitly always (0, 0, 1). Use to transform coordinates in geometry. public let relativeTransform: Transform /// Width and height of element. /// /// This is different from the width and height of the bounding box in that the absolute bounding box /// represents the element after scaling and rotation. public let size: FigmaKit.Vector /// The end caps of vector paths. public let strokeCap: StrokeCap /// An array of floating point numbers describing the pattern of dash length and gap lengths that the vector path follows. /// /// For example a value of [1, 2] indicates that the path has a dash of length 1 followed by a gap of length 2, repeated. public let strokeDashes: [Double] /// An array of paths representing the object stroke. public let strokeGeometry: [Path] /// How corners in vector paths are rendered. public let strokeJoin: StrokeJoin /// An array of fill paints applied to the node. public let strokes: [Paint] /// Only valid if strokeJoin is .miter. /// /// The corner angle, in degrees, below which strokeJoin will be set to .bevel to avoid super sharp corners. public let strokeMiterAngle: Double /// The weight of strokes on the node. public let strokeWeight: Double /// A mapping of a StyleType to style ID of styles present on this node. /// /// The style ID can be used to look up more information about the style in the top-level styles field. public let styles: [String: String] /// The duration of the prototyping transition on this node (in milliseconds). public let transitionDuration: Double? /// The easing curve used in the prototyping transition on this node. public let transitionEasing: EasingType? /// Node ID of node to transition to in prototyping. public let transitionNodeID: String? private enum CodingKeys: String, CodingKey { case absoluteBoundingBox case blendMode case constraints case effects case exportSettings case fillGeometry case fills case isMask case layoutAlign case layoutGrow case locked case opacity case preserveRatio case relativeTransform case size case strokeCap case strokeDashes case strokeJoin case strokes case strokeGeometry case strokeMiterAngle case strokeWeight case styles case transitionDuration case transitionEasing case transitionNodeID } public required init(from decoder: Decoder) throws { let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys) self.absoluteBoundingBox = try keyedDecoder.decode( FigmaKit.Rectangle.self, forKey: .absoluteBoundingBox) self.blendMode = try keyedDecoder.decode(BlendMode.self, forKey: .blendMode) self.constraints = try keyedDecoder.decode(LayoutConstraint.self, forKey: .constraints) if keyedDecoder.contains(.effects) { let effectsDecoder = try keyedDecoder.nestedUnkeyedContainer(forKey: .effects) self.effects = try Effect.decodePolymorphicArray(from: effectsDecoder) } else { self.effects = [] } self.exportSettings = try keyedDecoder.decodeIfPresent([ExportSetting].self, forKey: .exportSettings) ?? [] self.fillGeometry = try keyedDecoder.decodeIfPresent([Path].self, forKey: .fillGeometry) ?? [] if keyedDecoder.contains(.fills) { let fillsDecoder = try keyedDecoder.nestedUnkeyedContainer(forKey: .fills) self.fills = try Paint.decodePolymorphicArray(from: fillsDecoder) } else { self.fills = [] } self.isMask = try keyedDecoder.decodeIfPresent(Bool.self, forKey: .isMask) ?? false self.layoutAlign = try keyedDecoder.decodeIfPresent(LayoutAlign.self, forKey: .layoutAlign) self.layoutGrow = try keyedDecoder.decodeIfPresent(LayoutGrow.self, forKey: .layoutGrow) self.locked = try keyedDecoder.decodeIfPresent(Bool.self, forKey: .locked) ?? false self.opacity = try keyedDecoder.decodeIfPresent(Double.self, forKey: .opacity) ?? 1 self.preserveRatio = try keyedDecoder.decodeIfPresent(Bool.self, forKey: .preserveRatio) ?? false self.relativeTransform = try keyedDecoder.decode(Transform.self, forKey: .relativeTransform) self.size = try keyedDecoder.decode(FigmaKit.Vector.self, forKey: .size) self.strokeCap = try keyedDecoder.decodeIfPresent(StrokeCap.self, forKey: .strokeCap) ?? .none self.strokeDashes = try keyedDecoder.decodeIfPresent([Double].self, forKey: .strokeDashes) ?? [] self.strokeJoin = try keyedDecoder.decodeIfPresent(StrokeJoin.self, forKey: .strokeJoin) ?? .miter if keyedDecoder.contains(.strokes) { let strokesDecoder = try keyedDecoder.nestedUnkeyedContainer(forKey: .strokes) self.strokes = try Paint.decodePolymorphicArray(from: strokesDecoder) } else { self.strokes = [] } self.strokeGeometry = try keyedDecoder.decodeIfPresent([Path].self, forKey: .strokeGeometry) ?? [] self.strokeMiterAngle = try keyedDecoder.decodeIfPresent(Double.self, forKey: .strokeMiterAngle) ?? 28.96 self.strokeWeight = try keyedDecoder.decode(Double.self, forKey: .strokeWeight) self.styles = try keyedDecoder.decodeIfPresent([String: String].self, forKey: .styles) ?? [:] self.transitionDuration = try keyedDecoder.decodeIfPresent( Double.self, forKey: .transitionDuration) self.transitionEasing = try keyedDecoder.decodeIfPresent( EasingType.self, forKey: .transitionEasing) self.transitionNodeID = try keyedDecoder.decodeIfPresent( String.self, forKey: .transitionNodeID) try super.init(from: decoder) } public enum LayoutAlign: String, Codable { case inherit = "INHERIT" case stretch = "STRETCH" } public enum LayoutGrow: Int, Codable { case fixedSize = 0 case stretch = 1 } public override func encode(to encoder: Encoder) throws { fatalError("Not yet implemented") } override var contentDescription: String { return """ - absoluteBoundingBox: \(absoluteBoundingBox) - blendMode: \(blendMode) - constraints: \(constraints) - effects: \(effects.description.indented(by: 2)) - exportSettings: \(exportSettings.description.indented(by: 2)) - fillGeometry: \(fillGeometry) - fills: \(fills.description.indented(by: 2)) - layoutAlign: \(String(describing: layoutAlign)) - layoutGrow: \(String(describing: layoutGrow)) - locked: \(locked) - opacity: \(opacity) - preserveRatio: \(preserveRatio) - relativeTransform: \(relativeTransform) - size: \(size) - strokeCap: \(strokeCap) - strokeDashes: \(strokeDashes) - strokeJoin: \(strokeJoin) - strokes: \(strokes.description.indented(by: 2)) - strokeGeometry: \(strokeGeometry) - strokeMiterAngle: \(strokeMiterAngle) - strokeWeight: \(strokeWeight) - styles: \(styles) - transitionDuration: \(String(describing: transitionDuration)) - transitionEasing: \(String(describing: transitionEasing)) - transitionNodeID: \(String(describing: transitionNodeID)) """ } } }
apache-2.0
6c039c28a218bf12e6361f341972fde0
43.601942
126
0.686221
4.58483
false
false
false
false
hhroc/yellr-ios
Yellr/Yellr/PrintlnMagic.swift
1
2762
// // PrintlnMagic.swift // // Created by Arthur Sabintsev on 1/28/15. // Copyright (c) 2015 Arthur Ariel Sabintsev. All rights reserved. // import Foundation /** This method is called using `MyAppName.println()`, where MyAppName is the name of your .xcodeproj file. Writes the textual representation of `object` and a newline character into the standard output. The textual representation is obtained from the `object` using its protocol conformances, in the following order of preference: `Streamable`, `Printable`, `DebugPrintable`. This functional also augments the original function with the filename, function name, and line number of the object that is being logged. :param: object A textual representation of the object. :param: file Defaults to the name of the file that called println(). Do not override this default. :param: function Defaults to the name of the function within the file in which println() was called. Do not override this default. :param: line Defaults to the line number within the file in which println() was called. Do not override this default. */ public func println<T>(object: T, _ file: String = __FILE__, _ function: String = __FUNCTION__, _ line: Int = __LINE__) { let enabled = YellrConstants.AppInfo.DevMode //let filename = file.lastPathComponent.stringByDeletingPathExtension let filename = NSURL(fileURLWithPath: file).URLByDeletingPathExtension?.lastPathComponent if (enabled) { print("\n") print("\(filename).\(function)[\(line)]: \(object)\n") } } /** Writes the textual representation of `object` and a newline character into the standard output. The textual representation is obtained from the `object` using its protocol conformances, in the following order of preference: `Streamable`, `Printable`, `DebugPrintable`. This functional also augments the original function with the filename, function name, and line number of the object that is being logged. :param: object A textual representation of the object. :param: file Defaults to the name of the file that called magic(). Do not override this default. :param: function Defaults to the name of the function within the file in which magic() was called. Do not override this default. :param: line Defaults to the line number within the file in which magic() was called. Do not override this default. */ public func magic<T>(object: T, _ file: String = __FILE__, _ function: String = __FUNCTION__, _ line: Int = __LINE__) { //let filename = file.lastPathComponent.stringByDeletingPathExtension let filename = NSURL(fileURLWithPath: file).URLByDeletingPathExtension?.lastPathComponent print("\(filename).\(function)[\(line)]: \(object)\n") }
mit
2975fca7a787fb9ec1ee3281d19556d1
48.321429
141
0.730992
4.557756
false
false
false
false
remirobert/Dotzu-Objective-c
Pods/Dotzu/Dotzu/ManagerListLogViewController.swift
1
5999
// // ManagerListLogViewController.swift // exampleWindow // // Created by Remi Robert on 06/12/2016. // Copyright © 2016 Remi Robert. All rights reserved. // import UIKit class ManagerListLogViewController: UIViewController { @IBOutlet weak var tableview: UITableView! @IBOutlet weak var labelEmptyState: UILabel! @IBOutlet weak var segment: UISegmentedControl! private let dataSourceLogs = ListLogDataSource<Log>() fileprivate let dataSourceNetwork = ListLogDataSource<LogRequest>() private var obsLogs: NotificationObserver<Void>! private var obsSettings: NotificationObserver<Void>! private var obsNetwork: NotificationObserver<Void>! fileprivate var state: ManagerListLogState = .logs { didSet { if state == .logs { tableview.dataSource = dataSourceLogs dataSourceLogs.reloadData() } else { tableview.dataSource = dataSourceNetwork dataSourceNetwork.reloadData() } let count = state == .logs ? dataSourceLogs.count : dataSourceNetwork.count let lastPath = state == .logs ? dataSourceLogs.lastPath : dataSourceNetwork.lastPath tableview.reloadData() if count > 0 { tableview.scrollToRow(at: lastPath, at: .top, animated: false) } labelEmptyState.isHidden = count > 0 } } @IBAction func didChangeState(_ sender: Any) { state = ManagerListLogState(rawValue: segment.selectedSegmentIndex) ?? .logs } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let lastPath = state == .logs ? dataSourceLogs.lastPath : dataSourceNetwork.lastPath let count = state == .logs ? dataSourceLogs.count : dataSourceNetwork.count if count > 0 { tableview.scrollToRow(at: lastPath, at: .top, animated: false) } labelEmptyState.isHidden = count > 0 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) LogNotificationApp.resetCountBadge.post(Void()) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) LogNotificationApp.resetCountBadge.post(Void()) } @IBAction func resetLogs(_ sender: Any) { dataSourceLogs.reset() dataSourceNetwork.reset() let storeLogs = StoreManager<Log>(store: .log) let storeNetwork = StoreManager<LogRequest>(store: .network) storeLogs.reset() storeNetwork.reset() labelEmptyState.isHidden = false tableview.reloadData() } private func initTableView() { labelEmptyState.isHidden = true tableview.registerCellWithNib(cell: LogTableViewCell.self) tableview.registerCellWithNib(cell: LogNetworkTableViewCell.self) tableview.estimatedRowHeight = 50 tableview.rowHeight = UITableViewAutomaticDimension tableview.dataSource = dataSourceLogs tableview.delegate = self } override func viewDidLoad() { super.viewDidLoad() segment.tintColor = Color.mainGreen initTableView() dataSourceNetwork.reloadData() dataSourceLogs.reloadData() obsSettings = NotificationObserver(notification: LogNotificationApp.settingsChanged, block: { [weak self] _ in guard let weakSelf = self else { return } weakSelf.tableview.reloadData() }) obsNetwork = NotificationObserver(notification: LogNotificationApp.stopRequest, block: { [weak self] _ in guard let weakSelf = self, weakSelf.state == .network else { return } DispatchQueue.main.async { weakSelf.dataSourceNetwork.reloadData() weakSelf.tableview.reloadData() weakSelf.labelEmptyState.isHidden = weakSelf.dataSourceNetwork.count > 0 let lastPath = weakSelf.dataSourceNetwork.lastPath let lastVisiblePath = weakSelf.tableview.indexPathsForVisibleRows?.last if let lastVisiblePath = lastVisiblePath { if lastVisiblePath.row + 1 >= lastPath.row { weakSelf.tableview.scrollToRow(at: lastPath, at: .top, animated: false) } } } }) obsLogs = NotificationObserver(notification: LogNotificationApp.refreshLogs, block: { [weak self] _ in guard let weakSelf = self, weakSelf.state == .logs else { return } DispatchQueue.main.async { weakSelf.dataSourceLogs.reloadData() weakSelf.tableview.reloadData() weakSelf.labelEmptyState.isHidden = weakSelf.dataSourceLogs.count > 0 let lastPath = weakSelf.dataSourceLogs.lastPath let lastVisiblePath = weakSelf.tableview.indexPathsForVisibleRows?.last if let lastVisiblePath = lastVisiblePath { if lastVisiblePath.row + 1 >= lastPath.row { weakSelf.tableview.scrollToRow(at: lastPath, at: .top, animated: false) } } } }) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let controller = segue.destination as? DetailRequestViewController, let req = sender as? LogRequest { controller.log = req } else if let controller = segue.destination as? ContainerFilterViewController { controller.state = state } } } extension ManagerListLogViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if state == .logs { return } guard let LogRequest = dataSourceNetwork[indexPath.row] else {return} performSegue(withIdentifier: "detailRequestSegue", sender: LogRequest) } }
mit
cb4052662ec61278efc2ea3ecb8b8ce2
38.460526
118
0.638379
5.166236
false
false
false
false
JacobMao/iConsoleS
iConsoleS/iConsoleSViewController.swift
1
6415
// // iConsoleSViewController.swift // iConsoleS // // Created by Jacob Mao on 15/9/26. // Copyright © 2015年 JacobMao. All rights reserved. // import UIKit typealias T_CloseConsoleBlockType = () -> Void class iConsoleSViewController: UIViewController { // MARK: Views private lazy var infoTextView: UITextView = { let textView = UITextView() textView.isEditable = false textView.textColor = Style.textColor textView.backgroundColor = Style.backgroundColor textView.indicatorStyle = Style.indicatorStyle textView.font = Style.textFont textView.alwaysBounceVertical = true return textView }() private lazy var actionButton: UIButton = { let but = UIButton(type: .custom) but.setTitle("⚙", for: .normal) but.setTitleColor(Style.textColor, for: .normal) but.setTitleColor(Style.textColor.withAlphaComponent(0.5), for: .highlighted) but.titleLabel?.font = but.titleLabel?.font.withSize(Style.touchAreaOfActionButton.width) but.autoresizingMask = [] but.addTarget(self, action: #selector(iConsoleSViewController.clickedActionButton), for: .touchUpInside) return but }() // MARK: Properties private struct Style { static let backgroundColor: UIColor = UIColor.black static let textColor: UIColor = UIColor.white static let indicatorStyle: UIScrollViewIndicatorStyle = .white static let textFont: UIFont? = UIFont(name: "Courier", size: 12) static let touchAreaOfActionButton: CGSize = CGSize(width: 40, height: 40) } let closeConsoleBlock: T_CloseConsoleBlockType? // MARK: - Life Cycle init(closeConsoleBlock: T_CloseConsoleBlockType?) { self.closeConsoleBlock = closeConsoleBlock super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { self.closeConsoleBlock = nil super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() setupTextView() setupActionButton() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func log(_ logMessage: String) { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } strongSelf.infoTextView.text = strongSelf.infoTextView.text + ">>> " + logMessage + "\n" } } } // MARK: Private Methods private extension iConsoleSViewController { func encodeString(_ rawString: String) -> String? { return rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) } func setupTextView() { if infoTextView.superview == nil { view.addSubview(infoTextView) } infoTextView.frame = view.bounds } func setupActionButton() { if actionButton.superview == nil { view.addSubview(actionButton) } let xOffset = view.bounds.size.width - Style.touchAreaOfActionButton.width - 5 let yOffset = view.bounds.size.height - Style.touchAreaOfActionButton.height - 5 actionButton.frame = CGRect(x: xOffset, y: yOffset, width: Style.touchAreaOfActionButton.width, height: Style.touchAreaOfActionButton.height) } // MARK: Alert Actions var sendMailAction: UIAlertAction { return UIAlertAction(title: "Send by Email", style: .default) { [weak self] (action) in guard let strongSelf = self, let encodedSubject = strongSelf.encodeString("log from iConsoleS"), let encodedContent = strongSelf.encodeString(strongSelf.infoTextView.text) else { return } let urlString = "mailto:?subject=\(encodedSubject)&body=\(encodedContent)" if let mailURL = URL(string: urlString) { UIApplication.shared.open(mailURL, options: [:], completionHandler: nil) } } } var closeAction: UIAlertAction { return UIAlertAction(title: "Close Console", style: .default) { [weak self] (action) in self?.closeConsoleBlock?() } } var gotoTopAction: UIAlertAction { return UIAlertAction(title: "Go to Top", style: .default) { [weak self] (action) in self?.infoTextView.scrollRangeToVisible(NSMakeRange(0, 0)) } } var gotoBottomAction: UIAlertAction { return UIAlertAction(title: "Go to Bottom", style: .default) { [weak self] (action) in guard let strongSelf = self else { return; } let scrollRect = CGRect(x: 0, y: strongSelf.infoTextView.contentSize.height - 1, width: strongSelf.infoTextView.contentSize.width, height: 1) strongSelf.infoTextView.scrollRectToVisible(scrollRect, animated: true) } } var clearAction: UIAlertAction { return UIAlertAction(title: "Clear Log", style: .destructive) { [weak self] (action) in self?.infoTextView.text = nil } } // MARK: UI Actions @objc func clickedActionButton(sender: UIButton) { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel)) alertController.addAction(sendMailAction) alertController.addAction(closeAction) alertController.addAction(gotoTopAction) alertController.addAction(gotoBottomAction) alertController.addAction(clearAction) self.present(alertController, animated: true, completion: nil) } @objc func handleSwipeGesture(gesture: UISwipeGestureRecognizer) { if gesture.state == .ended { closeConsoleBlock?() } } }
mit
6ceecb3fa3b484c7a2fdde3f7669b77f
34.027322
112
0.61014
5.067194
false
false
false
false
DrabWeb/Komikan
Komikan/Komikan/KMImageFilterUtilities.swift
1
4523
// // KMImageFilterUtilities.swift // Komikan // // Created by Seth on 2016-01-29. // import Foundation import AppKit class KMImageFilterUtilities { func applyColorAndSharpness(_ image : NSImage, saturation : CGFloat, brightness : CGFloat, contrast : CGFloat, sharpness : CGFloat) -> NSImage { // Store the original image var originalImage = image; // Create a variable for the input image as a CIImage var inputImage = CIImage(data: (originalImage.tiffRepresentation)!); // Create the filter for the color controls var filter = CIFilter(name: "CIColorControls"); // Load the defaults for the filter filter!.setDefaults(); // Set the filters image to the input image filter!.setValue(inputImage, forKey: kCIInputImageKey); // Set the saturation filter!.setValue(saturation, forKey: "inputSaturation"); // Set the brightness filter!.setValue(brightness, forKey: "inputBrightness"); // Set the contrast filter!.setValue(contrast, forKey: "inputContrast"); // Create the output image as a CIImage var outputImage = filter!.value(forKey: kCIOutputImageKey) as! CIImage; // Create the rect for the output image as its full size var outputImageRect = NSRectFromCGRect(outputImage.extent); // Create the color controlled image, with the full size let colorControlledImage = NSImage(size: outputImageRect.size); // Lock focus on the image colorControlledImage.lockFocus(); // Draw the image onto the NSImage outputImage.draw(at: NSZeroPoint, from: outputImageRect, operation: .copy, fraction: 1.0); // Unlock the images focus colorControlledImage.unlockFocus(); // Set originalImage to the color controlled image originalImage = colorControlledImage; // Set inputImage to the color controlled image as a CIImage inputImage = CIImage(data: (originalImage.tiffRepresentation)!); // Set filter to the sharpen filter filter = CIFilter(name: "CISharpenLuminance"); // Load the filter defaults filter!.setDefaults(); // Set the filters image to be the input image filter!.setValue(inputImage, forKey: kCIInputImageKey); // Set its sharpness filter!.setValue(sharpness, forKey: "inputSharpness"); // Set outputImage to the filters image as a CGImage outputImage = filter!.value(forKey: kCIOutputImageKey) as! CIImage; // Set outputImageRect to the now sharpened images full size outputImageRect = NSRectFromCGRect(outputImage.extent); // Create sharpenedImage, and set it to have the size of the output image let sharpenedImage = NSImage(size: outputImageRect.size); // Lock focus on the image sharpenedImage.lockFocus(); // Draw the output image onto sharpenedImage outputImage.draw(at: NSZeroPoint, from: outputImageRect, operation: .copy, fraction: 1.0); // Unlock the focus sharpenedImage.unlockFocus(); // Return the now color controlled and sharpened image return sharpenedImage; } func applyColorAndSharpnessMultiple(_ images : [NSImage], saturation : CGFloat, brightness : CGFloat, contrast : CGFloat, sharpness : CGFloat) -> [NSImage] { // Create the variable that will hold all the filtered images var filteredImages : [NSImage] = [NSImage()]; // For every image in the passed images... for(_, currentImage) in images.enumerated() { // Create the variable for storing this images filtered version, and set it to the current image filtered with the passed amounts let filteredImage : NSImage = applyColorAndSharpness(currentImage, saturation: saturation, brightness: brightness, contrast: contrast, sharpness: sharpness); // Append the new filtered image onto filteredImages filteredImages.append(filteredImage); } // Remove the first element from the filteredImages array, its always blank filteredImages.removeFirst(); // Return the fitered images return filteredImages; } }
gpl-3.0
f9fda31733fc4e8567ce80d327e26b68
38.675439
169
0.63365
5.390942
false
false
false
false
crescentflare/SmartMockServer
MockLibIOS/Example/SmartMockLib/Network/ServiceService.swift
1
1801
// // ServiceService.swift // SmartMockLib Example // // Provides the service API integration // import UIKit import Alamofire import ObjectMapper class ServiceService { let mockableAlamofire: MockableAlamofire init(mockableAlamofire: MockableAlamofire) { self.mockableAlamofire = mockableAlamofire } func loadServices(success: @escaping ([Service]) -> Void, failure: @escaping (ApiError?) -> Void) { mockableAlamofire.request("services").responseArray { (response: DataResponse<[Service]>) in if let serviceArray = response.result.value { if response.response?.statusCode ?? 0 >= 200 && response.response?.statusCode ?? 0 < 300 { success(serviceArray) return } } if response.data != nil { failure(Mapper<ApiError>().map(JSONString: String(data: response.data!, encoding: String.Encoding.utf8) ?? "{}")) } else { failure(nil) } } } func loadService(serviceId: String, success: @escaping (Service) -> Void, failure: @escaping (ApiError?) -> Void) { mockableAlamofire.request("services/" + serviceId).responseObject { (response: DataResponse<Service>) in if let service = response.result.value { if response.response?.statusCode ?? 0 >= 200 && response.response?.statusCode ?? 0 < 300 { success(service) return } } if response.data != nil { failure(Mapper<ApiError>().map(JSONString: String(data: response.data!, encoding: String.Encoding.utf8) ?? "{}")) } else { failure(nil) } } } }
mit
cfa8de37f34e2a7c7ca1f420c44f85ff
33.634615
129
0.565242
4.739474
false
false
false
false
bvic23/VinceRP
VinceRP/Common/Util/FunctionalSet.swift
1
2662
// // Created by Viktor Belenyesi on 21/04/15. // Copyright (c) 2015 Viktor Belenyesi. All rights reserved. // public func toSet<T:Hashable>(e: T...) -> Set<T> { return Set(e) } extension Set { public func partition(@noescape filterFunc: (Generator.Element) -> Bool) -> (Set<Generator.Element>, Set<Generator.Element>) { let result1 = self.filter(filterFunc) let result2 = self.filter{!filterFunc($0)} return (Set(result1), Set(result2)) } public func groupBy<U>(@noescape filterFunc: (Generator.Element) -> U) -> [U : Set<Generator.Element>] { var result = [U: Set<Generator.Element>]() for i in self { let u = filterFunc(i) guard let bag = result[u] else { result[u] = toSet(i) continue } result[u] = bag ++ toSet(i) } return result } } extension SequenceType where Generator.Element: Hashable { public func hasElementPassingTest(@noescape filterFunc: (Self.Generator.Element) -> Bool) -> Bool { let result = self.filter(filterFunc) return result.count > 0 } } extension SequenceType where Generator.Element: Comparable { public func min(fallbackValue: Self.Generator.Element) -> Self.Generator.Element { guard let result = self.minElement() else { return fallbackValue } return result } public func max(fallbackValue: Self.Generator.Element) -> Self.Generator.Element { guard let result = self.maxElement() else { return fallbackValue } return result } } extension Set: Flattenable { public func filter(@noescape includeElement: (Element) -> Bool) -> Set<Element> { let arr = Array(self) let result = arr.filter(includeElement) return Set(result) } public func map<U>(@noescape transform: (Element) -> U) -> Set<U> { let arr = Array(self) let result = arr.map(transform) return Set<U>(result) } public func flatMap<U:SequenceType>(transform: (Element) -> U) -> Set<U.Generator.Element> { let arr = Array(self) let result = arr.flatMap(transform) return Set<U.Generator.Element>(result) } } extension Set where Element:SequenceType, Element.Generator.Element: Hashable { public func flatten() -> Set<Element.Generator.Element> { return self.flatMap{$0} } } infix operator ++ { associativity left precedence 160 } public func ++<T:Hashable>(left: Set<T>, right: Set<T>) -> Set<T> { return left.union(right) }
mit
1826ca9ad630ce4a295b37258011b96e
27.934783
130
0.604433
4.021148
false
false
false
false
narner/AudioKit
AudioKit/Common/Nodes/Effects/Filters/Low Shelf Filter/AKLowShelfFilter.swift
1
3834
// // AKLowShelfFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// AudioKit version of Apple's LowShelfFilter Audio Unit /// open class AKLowShelfFilter: AKNode, AKToggleable, AUEffect, AKInput { /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(appleEffect: kAudioUnitSubType_LowShelfFilter) private var au: AUWrapper private var mixer: AKMixer /// Cutoff Frequency (Hz) ranges from 10 to 200 (Default: 80) @objc open dynamic var cutoffFrequency: Double = 80 { didSet { cutoffFrequency = (10...200).clamp(cutoffFrequency) au[kAULowShelfParam_CutoffFrequency] = cutoffFrequency } } /// Gain (dB) ranges from -40 to 40 (Default: 0) @objc open dynamic var gain: Double = 0 { didSet { gain = (-40...40).clamp(gain) au[kAULowShelfParam_Gain] = gain } } /// Dry/Wet Mix (Default 100) @objc open dynamic var dryWetMix: Double = 100 { didSet { dryWetMix = (0...100).clamp(dryWetMix) inputGain?.volume = 1 - dryWetMix / 100 effectGain?.volume = dryWetMix / 100 } } private var lastKnownMix: Double = 100 private var inputGain: AKMixer? private var effectGain: AKMixer? var inputMixer = AKMixer() // Store the internal effect fileprivate var internalEffect: AVAudioUnitEffect // MARK: - Initialization /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted = true /// Initialize the low shelf filter node /// /// - Parameters: /// - input: Input node to process /// - cutoffFrequency: Cutoff Frequency (Hz) ranges from 10 to 200 (Default: 80) /// - gain: Gain (dB) ranges from -40 to 40 (Default: 0) /// @objc public init( _ input: AKNode? = nil, cutoffFrequency: Double = 80, gain: Double = 0) { self.cutoffFrequency = cutoffFrequency self.gain = gain inputGain = AKMixer() inputGain?.volume = 0 mixer = AKMixer(inputGain) effectGain = AKMixer() effectGain?.volume = 1 input?.connect(to: inputMixer) inputMixer.connect(to: [inputGain!, effectGain!]) let effect = _Self.effect self.internalEffect = effect au = AUWrapper(effect) super.init(avAudioNode: mixer.avAudioNode) AudioKit.engine.attach(effect) if let node = effectGain?.avAudioNode { AudioKit.engine.connect(node, to: effect) } AudioKit.engine.connect(effect, to: mixer.avAudioNode) au[kAULowShelfParam_CutoffFrequency] = cutoffFrequency au[kAULowShelfParam_Gain] = gain } public var inputNode: AVAudioNode { return inputMixer.avAudioNode } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing @objc open func start() { if isStopped { dryWetMix = lastKnownMix isStarted = true } } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { if isPlaying { lastKnownMix = dryWetMix dryWetMix = 0 isStarted = false } } /// Disconnect the node override open func disconnect() { stop() AudioKit.detach(nodes: [inputMixer.avAudioNode, inputGain!.avAudioNode, effectGain!.avAudioNode, mixer.avAudioNode]) AudioKit.engine.detach(self.internalEffect) } }
mit
5666c0f08b6aa650c483971356bb803e
28.259542
117
0.603705
4.737948
false
false
false
false
jeremiahyan/ResearchKit
samples/ORKSample/ORKSample/ProfileViewController.swift
3
7302
/* Copyright (c) 2015, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import ResearchKit import HealthKit class ProfileViewController: UITableViewController, HealthClientType { // MARK: Properties let healthObjectTypes = [ HKObjectType.characteristicType(forIdentifier: HKCharacteristicTypeIdentifier.dateOfBirth)!, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.height)!, HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bodyMass)! ] var healthStore: HKHealthStore? @IBOutlet var applicationNameLabel: UILabel! // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() guard let healthStore = healthStore else { fatalError("healhStore not set") } // Ensure the table view automatically sizes its rows. tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension // Request authrization to query the health objects that need to be shown. let typesToRequest = Set<HKObjectType>(healthObjectTypes) healthStore.requestAuthorization(toShare: nil, read: typesToRequest) { (authorized, _) in guard authorized else { return } // Reload the table view cells on the main thread. OperationQueue.main.addOperation { var allRowIndexPaths: [IndexPath] = [] for index in 0..<self.healthObjectTypes.count { allRowIndexPaths.append(IndexPath(row: index, section: 0)) } self.tableView.reloadRows(at: allRowIndexPaths, with: .automatic) } } } // MARK: UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return healthObjectTypes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: ProfileStaticTableViewCell.reuseIdentifier, for: indexPath) as? ProfileStaticTableViewCell else { fatalError("Unable to dequeue a ProfileStaticTableViewCell") } let objectType = healthObjectTypes[(indexPath as NSIndexPath).row] switch objectType.identifier { case HKCharacteristicTypeIdentifier.dateOfBirth.rawValue: configureCellWithDateOfBirth(cell) case HKQuantityTypeIdentifier.height.rawValue: let title = NSLocalizedString("Height", comment: "") configureCell(cell, withTitleText: title, valueForQuantityTypeIdentifier: objectType.identifier) case HKQuantityTypeIdentifier.bodyMass.rawValue: let title = NSLocalizedString("Weight", comment: "") configureCell(cell, withTitleText: title, valueForQuantityTypeIdentifier: objectType.identifier) default: fatalError("Unexpected health object type identifier - \(objectType.identifier)") } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } // MARK: Cell configuration func configureCellWithDateOfBirth(_ cell: ProfileStaticTableViewCell) { // Set the default cell content. cell.titleLabel.text = NSLocalizedString("Date of Birth", comment: "") cell.valueLabel.text = NSLocalizedString("-", comment: "") // Update the value label with the date of birth from the health store. guard let healthStore = healthStore else { return } do { let dateOfBirth = try healthStore.dateOfBirth() let now = Date() let ageComponents = Calendar.current.dateComponents([.year], from: dateOfBirth, to: now) let age = ageComponents.year cell.valueLabel.text = "\(age ?? 0)" } catch { } } func configureCell(_ cell: ProfileStaticTableViewCell, withTitleText titleText: String, valueForQuantityTypeIdentifier identifier: String) { // Set the default cell content. cell.titleLabel.text = titleText cell.valueLabel.text = NSLocalizedString("-", comment: "") /* Check a health store has been set and a `HKQuantityType` can be created with the identifier provided. */ guard let healthStore = healthStore, let quantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: identifier)) else { return } // Get the most recent entry from the health store. healthStore.mostRecentQauntitySampleOfType(quantityType) { quantity, _ in guard let quantity = quantity else { return } // Update the cell on the main thread. OperationQueue.main.addOperation() { guard let indexPath = self.indexPathForObjectTypeIdentifier(identifier) else { return } guard let cell = self.tableView.cellForRow(at: indexPath) as? ProfileStaticTableViewCell else { return } cell.valueLabel.text = "\(quantity)" } } } // MARK: Convenience func indexPathForObjectTypeIdentifier(_ identifier: String) -> IndexPath? { for (index, objectType) in healthObjectTypes.enumerated() where objectType.identifier == identifier { return IndexPath(row: index, section: 0) } return nil } }
bsd-3-clause
3c7626fa23feab1589ed568c9eb56434
43.254545
231
0.684196
5.704688
false
false
false
false
mennovf/Swift-MathEagle
MathEagle/Source/Linear Algebra/MatrixVector.swift
1
1417
// // MatrixVector.swift // SwiftMath // // Created by Rugen Heidbuchel on 11/01/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Foundation // MARK: Vector - Matrix Product public func * <T: MatrixCompatible> (left: Vector<T>, right: Matrix<T>) -> Vector<T> { if left.length != right.dimensions.rows { NSException(name: "Unequal dimensions", reason: "The vector's length (\(left.length)) is not equal to the matrix's number of rows (\(right.dimensions.rows)).", userInfo: nil).raise() } if left.length == 0 { return Vector() } var elements = [T]() var i = 0 while i < left.length { elements.append(left.dotProduct(right.column(i))) i++ } return Vector(elements) } public func * <T: MatrixCompatible> (left: Matrix<T>, right: Vector<T>) -> Vector<T> { if right.length != left.dimensions.columns { NSException(name: "Unequal dimensions", reason: "The vector's length (\(right.length)) is not equal to the matrix's number of columns (\(left.dimensions.columns)).", userInfo: nil).raise() } if right.length == 0 { return Vector() } var elements = [T]() var i = 0 while i < right.length { elements.append(right.dotProduct(left.row(i))) i++ } return Vector(elements) }
mit
0f007a909e329701c526ffbdb2d40d7b
23.877193
196
0.587862
3.903581
false
false
false
false
gspd-mobi/rage-ios
Sources/RxRage/RageRxSwift.swift
1
3737
import Foundation import Rage import RxSwift extension RageRequest { open func taskObservable() -> Observable<Result<RageResponse, RageError>> { return Observable.deferred { () -> Observable<Result<RageResponse, RageError>> in return Observable.create { observer in self.sendPluginsWillSendRequest() let request = self.rawRequest() self.sendPluginsDidSendRequest(request) if let stub = self.getStubData() { let rageResponse = RageResponse(request: self, data: stub, response: nil, error: nil) self.sendPluginsDidReceiveResponse(rageResponse, rawRequest: request) observer.onNext(.success(rageResponse)) return Disposables.create() } let startDate = Date() let task = self.session.dataTask(with: request, completionHandler: { data, response, error in let requestDuration = Date().timeIntervalSince(startDate) * 1000 let rageResponse = RageResponse(request: self, data: data, response: response, error: error as NSError?, timeMillis: requestDuration) self.sendPluginsDidReceiveResponse(rageResponse, rawRequest: request) if rageResponse.isSuccess() { observer.onNext(.success(rageResponse)) } else { let rageError = RageError(response: rageResponse) observer.onNext(.failure(rageError)) } observer.onCompleted() }) task.resume() return Disposables.create { task.cancel() } } } } public func executeResponseObservable() -> Observable<RageResponse> { return taskObservable() .flatMap { result -> Observable<RageResponse> in switch result { case .success(let response): return Observable.just(response) case .failure(let error): return Observable.error(error) } } } public func executeStringObservable() -> Observable<String> { return taskObservable() .flatMap { result -> Observable<String> in switch result { case .success(let response): guard let data = response.data else { return Observable.error(RageError(type: RageErrorType.emptyNetworkResponse)) } let resultString = String(data: data, encoding: String.Encoding.utf8)! return Observable.just(resultString) case .failure(let error): return Observable.error(error) } } } public func executeDataObservable() -> Observable<Data> { return taskObservable() .flatMap { result -> Observable<Data> in switch result { case .success(let response): guard let data = response.data else { return Observable.error(RageError(type: RageErrorType.emptyNetworkResponse)) } return Observable.just(data) case .failure(let error): return Observable.error(error) } } } }
mit
48871d0772cb4d3a74d3796d403a383c
37.927083
109
0.504683
6.027419
false
false
false
false
google/iosched-ios
Source/IOsched/Screens/Schedule/ViewModel/ScheduleDisplayableViewModel.swift
1
8966
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import MaterialComponents class ScheduleDisplayableViewModel: NSObject, UICollectionViewDataSource { private(set) var wrappedModel: SessionListViewModel /// A map to store cell height calculations for faster layout. This is invalidated whenever the /// user's device font size changes. fileprivate var cachedHeights: [SessionViewModel: CGFloat] = [:] lazy var measureCell: ScheduleViewCollectionViewCell = self.setupMeasureCell() private func setupMeasureCell() -> ScheduleViewCollectionViewCell { return ScheduleViewCollectionViewCell(frame: CGRect()) } @available(*, unavailable) override init() { fatalError("Use init(wrappedModel:)") } init(wrappedModel: SessionListViewModel) { self.wrappedModel = wrappedModel super.init() } var conferenceDays: [ConferenceDayViewModel] { return wrappedModel.conferenceDays } func filterSelected() { wrappedModel.didSelectFilter() } func didSelectAccount() { wrappedModel.didSelectAccount() } func showOnlySavedEvents() { wrappedModel.shouldShowOnlySavedItems = true } func showAllEvents() { wrappedModel.shouldShowOnlySavedItems = false } // MARK: - ScheduleViewModelLayout func sizeForHeader(inSection section: Int, inFrame frame: CGRect) -> CGSize { guard eventsForSection(section).count > 0 else { return .zero } return CGSize(width: frame.size.width, height: MDCCellDefaultOneLineHeight) } func heightForCell(at indexPath: IndexPath, inFrame frame: CGRect) -> CGFloat { let session = self.session(for: indexPath) if let cached = cachedHeights[session] { return cached } measureCell.bounds = frame measureCell.contentView.bounds = frame populateCell(measureCell, forItemAt: indexPath) let height = measureCell.heightForContents(maxWidth: frame.size.width) cachedHeights[session] = height return height } func invalidateHeights() { cachedHeights = [:] } // MARK: - UICollectionViewDataSource private func slotForSection(_ section: Int) -> ConferenceTimeSlotViewModel { let days = wrappedModel.conferenceDays.count var section = section for i in 0 ..< days { let slots = wrappedModel.slots(forDayWithIndex: i) if slots.count <= section { section -= slots.count } else { return slots[section] } } let totalSections = conferenceDays.reduce(0) { $0 + $1.slots.count } fatalError("Section out of bounds: \(section), days: \(totalSections)") } private func eventsForSection(_ section: Int) -> [SessionViewModel] { let days = wrappedModel.conferenceDays.count var section = section for i in 0 ..< days { let slots = wrappedModel.slots(forDayWithIndex: i) if slots.count <= section { section -= slots.count } else { let dayIndex = i let slotIndex = section return wrappedModel.events(forDayWithIndex: dayIndex, andSlotIndex: slotIndex) } } return [] } func numberOfSections(in collectionView: UICollectionView) -> Int { // Treat the wrapped model's data as a single view, where breaks between // days are special index paths that can be navigated to via tab bar buttons above the // collection view. Individual sections represent time slots in each day. var totalSlots = 0 for i in 0 ..< conferenceDays.count { let slots = wrappedModel.slots(forDayWithIndex: i) totalSlots += slots.count } return totalSlots } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let items = eventsForSection(section).count return items } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: ScheduleViewCollectionViewCell.reuseIdentifier(), for: indexPath ) populateCell(cell, forItemAt: indexPath) return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView( ofKind: kind, withReuseIdentifier: ScheduleSectionHeaderReusableView.reuseIdentifier(), for: indexPath ) if kind == UICollectionView.elementKindSectionHeader, let headerView = view as? ScheduleSectionHeaderReusableView { view.isHidden = self.collectionView(collectionView, numberOfItemsInSection: indexPath.section) == 0 populateSupplementaryView(headerView, forItemAt: indexPath) } return view } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { didSelectItemAt(indexPath: indexPath) } private func session(for indexPath: IndexPath) -> SessionViewModel { let events = eventsForSection(indexPath.section) return events[indexPath.item] } func populateCell(_ cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = cell as? ScheduleViewCollectionViewCell else { return } let session = self.session(for: indexPath) cell.viewModel = session cell.isUserInteractionEnabled = true cell.onBookmarkTapped { sessionID in self.wrappedModel.toggleBookmark(sessionID: sessionID) } } func populateSupplementaryView(_ view: ScheduleSectionHeaderReusableView, forItemAt indexPath: IndexPath) { let slot = slotForSection(indexPath.section) view.date = slot.time } func didSelectItemAt(indexPath: IndexPath) { let event = session(for: indexPath) wrappedModel.didSelectSession(event) } func previewViewControllerForItemAt(indexPath: IndexPath) -> UIViewController? { let event = session(for: indexPath) return wrappedModel.detailsViewController(for: event) } func isEmpty() -> Bool { for i in 0 ..< wrappedModel.conferenceDays.count { if !isEmpty(forDayWithIndex: i) { return false } } return true } func isEmpty(forDayWithIndex index: Int) -> Bool { let slots = wrappedModel.slots(forDayWithIndex: index) guard !slots.isEmpty else { return true } for i in 0 ..< slots.count { let eventCount = wrappedModel.events(forDayWithIndex: index, andSlotIndex: i).count if eventCount > 0 { return false } } return true } func dayForSection(_ section: Int) -> Int { var section = section for i in 0 ..< wrappedModel.conferenceDays.count { let sectionsInDay = wrappedModel.slots(forDayWithIndex: i).count if section < sectionsInDay { return i } section -= sectionsInDay } let total = wrappedModel.conferenceDays.reduce(0) { $0 + $1.slots.count } fatalError("Section out of bounds: \(section), total sections across all days: \(total)") } // MARK: - View updates var viewUpdateCallback: ((_ indexPath: IndexPath?) -> Void)? func onUpdate(_ viewUpdateCallback: @escaping (_ indexPath: IndexPath?) -> Void) { wrappedModel.onUpdate { indexPath in viewUpdateCallback(indexPath) } } func updateModel() { wrappedModel.updateModel() } func indexPath(forDay day: Int) -> IndexPath? { guard day < wrappedModel.conferenceDays.count && day >= 0 else { return nil } guard !isEmpty(forDayWithIndex: day) else { return nil } var sectionForDay = 0 for i in 0 ..< day { sectionForDay += wrappedModel.slots(forDayWithIndex: i).count } let totalDaySlots = wrappedModel.slots(forDayWithIndex: day).count var sectionInDay = 0 while wrappedModel.events(forDayWithIndex: day, andSlotIndex: sectionInDay).isEmpty { if sectionInDay >= totalDaySlots { return nil } sectionInDay += 1 } let section = sectionForDay + sectionInDay return IndexPath(item: 0, section: section) } func collectionView(_ collectionView: UICollectionView, scrollToDay day: Int, animated: Bool = true) { if let indexPath = indexPath(forDay: day) { collectionView.scrollToItem(at: indexPath, at: .top, animated: animated) } } }
apache-2.0
25dd634179151bf332e49bf969473f59
31.603636
97
0.694624
4.652828
false
false
false
false
WilliamHester/Breadit-iOS
Breadit/LoginManager.swift
1
1035
// // LoginManager.swift // Breadit // // Created by William Hester on 5/4/16. // Copyright © 2016 William Hester. All rights reserved. // import Foundation import Realm import RealmSwift struct LoginManager { private static var instance = LoginManager() static var singleton: LoginManager { return LoginManager.instance } var account: Account? { didSet { saveCurrentUser() } } init() { let prefs = NSUserDefaults.standardUserDefaults() if let username = prefs.stringForKey("account") { let realm = try! Realm() account = realm.objects(Account).filter("username = '\(username)'").first } } private func saveCurrentUser() { let prefs = NSUserDefaults.standardUserDefaults() prefs.setObject(account?.username ?? "", forKey: "account") prefs.synchronize() } func getAccessToken() -> String { return account?.accessToken ?? "" } }
apache-2.0
39aa21113e35de2e28116a1a15f830fb
21
85
0.591876
4.995169
false
false
false
false
joerocca/GitHawk
Classes/Search/SearchResultSectionController.swift
1
2035
// // SearchResultSectionController.swift // Freetime // // Created by Sherlock, James on 28/07/2017. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import IGListKit protocol SearchResultSectionControllerDelegate: class { func didSelect(sectionController: SearchResultSectionController, repo: RepositoryDetails) } final class SearchResultSectionController: ListGenericSectionController<SearchRepoResult> { private weak var delegate: SearchResultSectionControllerDelegate? private let client: GithubClient init(client: GithubClient, delegate: SearchResultSectionControllerDelegate) { self.client = client self.delegate = delegate super.init() } override func sizeForItem(at index: Int) -> CGSize { guard let width = collectionContext?.containerSize.width else { fatalError("Missing context") } return CGSize(width: width, height: Styles.Sizes.tableCellHeight + Styles.Sizes.rowSpacing * 2) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: SearchRepoResultCell.self, for: self, at: index) as? SearchRepoResultCell, let object = object else { fatalError("Missing context, object, or cell is wrong type") } cell.configure(result: object) return cell } override func didSelectItem(at index: Int) { guard let object = object else { return } let repo = RepositoryDetails( owner: object.owner, name: object.name, defaultBranch: object.defaultBranch, hasIssuesEnabled: object.hasIssuesEnabled ) delegate?.didSelect(sectionController: self, repo: repo) let repoViewController = RepositoryViewController(client: client, repo: repo) let navigation = UINavigationController(rootViewController: repoViewController) viewController?.showDetailViewController(navigation, sender: nil) } }
mit
19c50afda400116e1f3d095dcff6bebe
33.474576
142
0.70059
5.175573
false
false
false
false
ahoppen/swift
test/Distributed/SIL/distributed_actor_default_init_sil_4.swift
5
2658
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/../Inputs/FakeDistributedActorSystems.swift // RUN: %target-swift-frontend -module-name default_deinit -primary-file %s -emit-sil -disable-availability-checking -I %t | %FileCheck %s --enable-var-scope --dump-input=fail // REQUIRES: concurrency // REQUIRES: distributed /// The convention in this test is that the Swift declaration comes before its FileCheck lines. import Distributed import FakeDistributedActorSystems typealias DefaultDistributedActorSystem = FakeActorSystem // ==== ---------------------------------------------------------------------------------------------------------------- class SomeClass {} enum Err : Error { case blah } distributed actor MyDistActor { var localOnlyField: SomeClass init?(system_async_fail_throws: FakeActorSystem, cond: Bool) async throws { self.actorSystem = system_async_fail_throws guard cond else { throw Err.blah } self.localOnlyField = SomeClass() } // CHECK-LABEL: // MyDistActor.init(system_async_fail_throws:cond:) // CHECK: sil hidden @$s14default_deinit11MyDistActorC24system_async_fail_throws4condACSg015FakeDistributedE7Systems0kE6SystemV_SbtYaKcfc : $@convention(method) @async (@owned FakeActorSystem, Bool, @owned MyDistActor) -> (@owned Optional<MyDistActor>, @error Error) { // CHECK: bb0([[SYSTEM:%[0-9]+]] : $FakeActorSystem, [[COND:%[0-9]+]] : $Bool, [[SELF:%[0-9]+]] : $MyDistActor): // CHECK: cond_br {{%[0-9]+}}, [[SUCCESS_BB:bb[0-9]+]], [[FAIL_BB:bb[0-9]+]] // CHECK: [[SUCCESS_BB]]: // CHECK: hop_to_executor {{%[0-9]+}} // CHECK: [[READY_FN:%[0-9]+]] = function_ref @$s27FakeDistributedActorSystems0aC6SystemV10actorReadyyyx0B00bC0RzAA0C7AddressV2IDRtzlF : $@convention(method) <τ_0_0 where τ_0_0 : DistributedActor, τ_0_0.ID == ActorAddress> (@guaranteed τ_0_0, @guaranteed FakeActorSystem) -> () // CHECK: = apply [[READY_FN]] // CHECK: br [[RET_BB:bb[0-9]+]] // CHECK: [[FAIL_BB]]: // CHECK: [[RESIGN_FN:%[0-9]+]] = function_ref @$s27FakeDistributedActorSystems0aC6SystemV8resignIDyyAA0C7AddressVF : $@convention(method) (@guaranteed ActorAddress, @guaranteed FakeActorSystem) -> () // CHECK: = apply [[RESIGN_FN]] // CHECK: builtin "destroyDefaultActor" // CHECK: throw {{%[0-9]+}} : $Error // CHECK: [[RET_BB]]: // CHECK: return // CHECK: } // end sil function '$s14default_deinit11MyDistActorC24system_async_fail_throws4condACSg015FakeDistributedE7Systems0kE6SystemV_SbtYaKcfc' }
apache-2.0
9be38c3cd69b7e37dd94968b1c637b55
50.038462
281
0.680482
3.543391
false
false
false
false
justindarc/firefox-ios
content-blocker-lib-ios/src/ContentBlocker.swift
1
10254
/* 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 WebKit import Shared enum BlocklistName: String { case advertising = "disconnect-advertising" case analytics = "disconnect-analytics" case content = "disconnect-content" case social = "disconnect-social" var filename: String { return self.rawValue } static var all: [BlocklistName] { return [.advertising, .analytics, .content, .social] } static var basic: [BlocklistName] { return [.advertising, .analytics, .social] } static var strict: [BlocklistName] { return [.content] } static func forStrictMode(isOn: Bool) -> [BlocklistName] { return BlocklistName.basic + (isOn ? BlocklistName.strict : []) } } enum BlockerStatus: String { case Disabled case NoBlockedURLs // When TP is enabled but nothing is being blocked case Whitelisted case Blocking } struct NoImageModeDefaults { static let Script = "[{'trigger':{'url-filter':'.*','resource-type':['image']},'action':{'type':'block'}}]".replacingOccurrences(of: "'", with: "\"") static let ScriptName = "images" } class ContentBlocker { var whitelistedDomains = WhitelistedDomains() let ruleStore: WKContentRuleListStore = WKContentRuleListStore.default() var blockImagesRule: WKContentRuleList? var setupCompleted = false static let shared = ContentBlocker() private init() { let blockImages = NoImageModeDefaults.Script ruleStore.compileContentRuleList(forIdentifier: NoImageModeDefaults.ScriptName, encodedContentRuleList: blockImages) { rule, error in assert(rule != nil && error == nil) self.blockImagesRule = rule } // Read the whitelist at startup if let list = readWhitelistFile() { whitelistedDomains.domainSet = Set(list) } TPStatsBlocklistChecker.shared.startup() removeOldListsByDateFromStore() { self.removeOldListsByNameFromStore() { self.compileListsNotInStore { self.setupCompleted = true NotificationCenter.default.post(name: .contentBlockerTabSetupRequired, object: nil) } } } } func prefsChanged() { // This class func needs to notify all the active instances of ContentBlocker to update. NotificationCenter.default.post(name: .contentBlockerTabSetupRequired, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } // Function to install or remove TP for a tab func setupTrackingProtection(forTab tab: ContentBlockerTab, isEnabled: Bool, rules: [BlocklistName]) { removeTrackingProtection(forTab: tab) if !isEnabled { return } for list in rules { let name = list.filename ruleStore.lookUpContentRuleList(forIdentifier: name) { rule, error in guard let rule = rule else { let msg = "lookUpContentRuleList for \(name): \(error?.localizedDescription ?? "empty rules")" print("Content blocker error: \(msg)") return } self.add(contentRuleList: rule, toTab: tab) } } } private func removeTrackingProtection(forTab tab: ContentBlockerTab) { tab.currentWebView()?.configuration.userContentController.removeAllContentRuleLists() // Add back the block images rule (if needed) after having removed all rules. if let rule = blockImagesRule, tab.imageContentBlockingEnabled() { add(contentRuleList: rule, toTab: tab) } } private func add(contentRuleList: WKContentRuleList, toTab tab: ContentBlockerTab) { tab.currentWebView()?.configuration.userContentController.add(contentRuleList) } func noImageMode(enabled: Bool, forTab tab: ContentBlockerTab) { guard let rule = blockImagesRule else { return } if enabled { add(contentRuleList: rule, toTab: tab) } else { tab.currentWebView()?.configuration.userContentController.remove(rule) } // Async required here to ensure remove() call is processed. DispatchQueue.main.async() { [weak tab] in tab?.currentWebView()?.evaluateJavaScript("window.__firefox__.NoImageMode.setEnabled(\(enabled))") } } } // MARK: Initialization code // The rule store can compile JSON rule files into a private format which is cached on disk. // On app boot, we need to check if the ruleStore's data is out-of-date, or if the names of the rule files // no longer match. Finally, any JSON rule files that aren't in the ruleStore need to be compiled and stored in the // ruleStore. extension ContentBlocker { private func loadJsonFromBundle(forResource file: String, completion: @escaping (_ jsonString: String) -> Void) { DispatchQueue.global().async { guard let path = Bundle.main.path(forResource: file, ofType: "json"), let source = try? String(contentsOfFile: path, encoding: .utf8) else { assert(false) return } DispatchQueue.main.async { completion(source) } } } private func lastModifiedSince1970(forFileAtPath path: String) -> Date? { do { let url = URL(fileURLWithPath: path) let attr = try FileManager.default.attributesOfItem(atPath: url.path) guard let date = attr[FileAttributeKey.modificationDate] as? Date else { return nil } return date } catch { return nil } } private func dateOfMostRecentBlockerFile() -> Date? { let blocklists = BlocklistName.all return blocklists.reduce(Date(timeIntervalSince1970: 0)) { result, list in guard let path = Bundle.main.path(forResource: list.filename, ofType: "json") else { return result } if let date = lastModifiedSince1970(forFileAtPath: path) { return date > result ? date : result } return result } } func removeAllRulesInStore(completion: @escaping () -> Void) { ruleStore.getAvailableContentRuleListIdentifiers { available in guard let available = available else { completion() return } let deferreds: [Deferred<Void>] = available.map { filename in let result = Deferred<Void>() self.ruleStore.removeContentRuleList(forIdentifier: filename) { _ in result.fill(()) } return result } all(deferreds).uponQueue(.main) { _ in completion() } } } // If any blocker files are newer than the date saved in prefs, // remove all the content blockers and reload them. func removeOldListsByDateFromStore(completion: @escaping () -> Void) { guard let fileDate = dateOfMostRecentBlockerFile(), let prefsNewestDate = UserDefaults.standard.object(forKey: "blocker-file-date") as? Date else { completion() return } if fileDate <= prefsNewestDate { completion() return } UserDefaults.standard.set(fileDate, forKey: "blocker-file-date") removeAllRulesInStore() { completion() } } func removeOldListsByNameFromStore(completion: @escaping () -> Void) { var noMatchingIdentifierFoundForRule = false ruleStore.getAvailableContentRuleListIdentifiers { available in guard let available = available else { completion() return } let blocklists = BlocklistName.all.map { $0.filename } for contentRuleIdentifier in available { if !blocklists.contains(where: { $0 == contentRuleIdentifier }) { noMatchingIdentifierFoundForRule = true break } } guard let fileDate = self.dateOfMostRecentBlockerFile(), let prefsNewestDate = UserDefaults.standard.object(forKey: "blocker-file-date") as? Date else { completion() return } if fileDate <= prefsNewestDate && !noMatchingIdentifierFoundForRule { completion() return } UserDefaults.standard.set(fileDate, forKey: "blocker-file-date") self.removeAllRulesInStore { completion() } } } func compileListsNotInStore(completion: @escaping () -> Void) { let blocklists = BlocklistName.all.map { $0.filename } let deferreds: [Deferred<Void>] = blocklists.map { filename in let result = Deferred<Void>() ruleStore.lookUpContentRuleList(forIdentifier: filename) { contentRuleList, error in if contentRuleList != nil { result.fill(()) return } self.loadJsonFromBundle(forResource: filename) { jsonString in var str = jsonString guard let range = str.range(of: "]", options: String.CompareOptions.backwards) else { return } str = str.replacingCharacters(in: range, with: self.whitelistAsJSON() + "]") self.ruleStore.compileContentRuleList(forIdentifier: filename, encodedContentRuleList: str) { rule, error in if let error = error { print("Content blocker error: \(error)") assert(false) } assert(rule != nil) result.fill(()) } } } return result } all(deferreds).uponQueue(.main) { _ in completion() } } }
mpl-2.0
74a66ac5c2e4aa2b3f3e50f6306ecb5a
36.287273
164
0.598401
5.104032
false
false
false
false
2345Team/Swifter-Tips
15.Any和AnyObject/Any和AnyObject/Any和AnyObject/ViewController.swift
1
1938
// // ViewController.swift // Any和AnyObject // // Created by wanglili on 16/9/7. // Copyright © 2016年 wanglili. All rights reserved. // import UIKit class ViewController: UIViewController { //假设原来的某个 API 返回的是一个 id,那么在 Swift 中现在就将被映射为 AnyObject? (因为 id 是可以指向 nil 的,所以在这里我们需要一个 Optional 的版本) func someMethod() -> AnyObject? { return "123" } override func viewDidLoad() { super.viewDidLoad() // 所有的 class 都隐式地实现了这个接口,这也是 AnyObject 只适用于 class 类型的原因 let anyObject: AnyObject? = self.someMethod() // as? 返回一个你试图想转成的类型的可选值 if let someInstance = anyObject as? String { // ... // 这里我们拿到了具体 SomeRealClass 的实例 someInstance.startIndex } /* struct 类型,并不能由 AnyObject 来表示,于是 Apple 提出了一个更为特殊的 Any,除了 class 以外,它还可以表示包括 struct 和 enum 在内的所有类型。 */ // 我们在这里声明了一个 Int 和一个 String,按理说它们都应该只能被 Any 代表,而不能被 AnyObject 代表的 // 因为我们显式地声明了需要 AnyObject,编译器认为我们需要的的是 Cocoa 类型而非原生类型,而帮我们进行了自动的转换 let swiftInt: Int = 1 let swiftString: String = "miao" var array: [AnyObject] = [] array.append(swiftInt) array.append(swiftString) print(array.first) print(array.last) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
7bde24493e9756cc4442c9534bd4dcfe
26.203704
105
0.605174
3.795866
false
false
false
false
huangboju/Moots
UICollectionViewLayout/MagazineLayout-master/MagazineLayout/LayoutCore/Types/ElementLocationFramePairs.swift
1
3530
// Created by bryankeller on 8/17/18. // Copyright © 2018 Airbnb, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CoreGraphics // MARK: - ElementLocationFramePairs /// Stores pairs of `ElementLocationFramePair`s in an efficient way for appending to and /// iterating over. /// /// The main reason this exists (and why its implementation uses a singly-linked-list) is so that, /// as we find the section and item index and frame for an element in a visible rect, we can append /// it to this data structure without copy-on-write performance issues, or array buffer resizing /// issues. (The cost of appending to an array is much more expensive due to copy-on-write and the /// backing buffer needing to be resized). struct ElementLocationFramePairs { // MARK: Lifecycle init() { } init(elementLocationFramePair: ElementLocationFramePair) { append(elementLocationFramePair) } // MARK: Internal mutating func append(_ elementLocationFramePair: ElementLocationFramePair) { if first == nil { first = elementLocationFramePair } else { last.next = elementLocationFramePair } last = elementLocationFramePair } // MARK: Fileprivate fileprivate var first: ElementLocationFramePair? // MARK: Private private var last: ElementLocationFramePair! } // MARK: Sequence extension ElementLocationFramePairs: Sequence { func makeIterator() -> ElementLocationFramePairsIterator { return ElementLocationFramePairsIterator(self) } } // MARK: - ElementLocationFramePairsIterator /// Used for iterating through `ElementLocationFramePairs` instances struct ElementLocationFramePairsIterator: IteratorProtocol { typealias Element = ElementLocationFramePair // MARK: Lifecycle init(_ elementLocationFramePairs: ElementLocationFramePairs) { self.elementLocationFramePairs = elementLocationFramePairs } // MARK: Internal mutating func next() -> ElementLocationFramePair? { if lastReturnedElement == nil { lastReturnedElement = elementLocationFramePairs.first } else { lastReturnedElement = lastReturnedElement?.next } return lastReturnedElement } // MARK: Private private let elementLocationFramePairs: ElementLocationFramePairs private var lastReturnedElement: ElementLocationFramePair? } // MARK: - ElementLocationFramePair /// Encapsulates a `ElementLocation` and a `CGRect` frame for an element. final class ElementLocationFramePair { // MARK: Lifecycle init(elementLocation: ElementLocation, frame: CGRect) { self.elementLocation = elementLocation self.frame = frame } // MARK: Internal let elementLocation: ElementLocation let frame: CGRect // MARK: Fileprivate fileprivate var next: ElementLocationFramePair? } // MARK: Equatable extension ElementLocationFramePair: Equatable { static func == (lhs: ElementLocationFramePair, rhs: ElementLocationFramePair) -> Bool { return lhs.elementLocation == rhs.elementLocation && lhs.frame == rhs.frame } }
mit
226e5bf4358fee41bf1abbc9b8b8616e
25.335821
99
0.748654
4.367574
false
false
false
false
mrdepth/EVEUniverse
Neocom/Neocom/Fitting/Stats/FittingEditorFuelStats.swift
2
1843
// // FittingEditorFuelStats.swift // Neocom // // Created by Artem Shimanski on 4/10/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp import Expressible import EVEAPI struct FittingEditorFuelStats: View { @Environment(\.managedObjectContext) private var managedObjectContext @ObservedObject var ship: DGMShip let formatter = UnitFormatter(unit: .none, style: .short) private func header(text: Text, image: Image) -> some View { HStack { Icon(image, size: .small) text }.frame(maxWidth: .infinity).offset(x: -16) } private func cell(_ damage: Double) -> some View { Text(formatter.string(from: damage)).fixedSize().frame(maxWidth: .infinity) } var body: some View { let structure = ship as? DGMStructure let fuelUse = structure?.fuelUse ?? DGMFuelUnitsPerHour(0) // let perHour = UnitFormatter.localizedString(from: fuelUse * DGMHours(1), unit: .none, style: .long) let perDay = UnitFormatter.localizedString(from: fuelUse * DGMDays(1), unit: .none, style: .long) return Group { if structure != nil { Section(header: Text("FUEL")) { HStack { Icon(Image("fuel")) Text("\(perDay) units/day") } } } } } } #if DEBUG struct FittingEditorFuelStats_Previews: PreviewProvider { static var previews: some View { return List { FittingEditorFuelStats(ship: DGMStructure.testKeepstar()) }.listStyle(GroupedListStyle()) .environmentObject(PricesData(esi: ESI())) .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
3aafc6b94fc949fae43e5ff5e9be667f
28.238095
109
0.590119
4.438554
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeTracking/AwesomeTracking/Classes/AwesomeTrackingParams.swift
1
2384
// // AwesomeTrackingParams.swift // AwesomeTracking // // Created by Leonardo Vinicius Kaminski Ferreira on 13/06/18. // import Foundation public enum AwesomeTrackingParams: String { // MARK: - Quest app case email case userID = "auth0 id" case questID = "quest_id" case platform case contentID = "content_id" case contentName = "content_name" case assetID = "asset_id" case timeElapsed = "time_elapsed" case timeOfDay = "time stamp" case date case boolean case identifier case dayPosition = "day_position" case network case dayType = "type" case cartValue = "cart_value" case tribeId = "tribe_id" case ratingValue = "rating_value" case productId = "product_id" case sectionId = "section_id" case pagePosition = "page_position" case communityURL = "community_URL" case time case provider case currency case mediaSource = "media_source" case userType = "user_type" case questName = "quest_name" case communityName = "community name" case academyId = "academy id" case device case os case cohortID = "cohort_id" case cohortName = "cohort_name" // MARK: - Mindvalley app case courseID = "course_id" case chapterID = "chapter_id" case chapterPosition = "chapter_position" case url case selectedTopicsIds = "Selected Topics IDs" case chosenEpisode = "Chosen Episode ID" case suggestedEpisodes = "Suggested Episodes IDs" case userSkipped = "User Skipped" case loginType = "Login Type" case appsflyerLink = "appsflyer_link" case channelId = "channel_id" case serieId = "series_id" case episodeId = "episode_id" case timeWatched = "time_watched" case localisation case appId = "app_id" case application = "application" case categoryName = "category name" case categoryId = "category_id" case answerId = "answer_id" case day case screen case courseName case mediaId case mediaType case mediaName case channelName case seriesId case seriesName case mediaContentTitle case part case view case category case categoryLocation case groupName case groupId // MARK: - Soulvana app case sessionLenght = "session lenght" case immersionType = "immersion type" }
mit
d83922d33d5f8d0e34bb0e763cd1dec3
24.634409
63
0.658977
4.054422
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/MembershipAcademies.swift
1
1523
// // MembershipAcademies.swift // AwesomeCore // // Created by Leonardo Vinicius Kaminski Ferreira on 25/10/17. // import Foundation public struct MembershipAcademies: Codable { public let academies: [MembershipAcademy] } public struct MembershipAcademy: Codable { public let id: Int public let title: String public let description: String public let domainURL: String public let isDisplayingRating: Bool } // MARK: - Coding keys extension MembershipAcademy { private enum CodingKeys: String, CodingKey { case id case title case description case domainURL = "domain" case isDisplayingRating = "display_rating" } } // MARK: - Equatable extension MembershipAcademies { public static func ==(lhs: MembershipAcademies, rhs: MembershipAcademies) -> Bool { if lhs.academies.first?.id != rhs.academies.first?.id { return false } return true } } extension MembershipAcademy { public static func ==(lhs: MembershipAcademy, rhs: MembershipAcademy) -> Bool { if lhs.id != rhs.id { return false } if lhs.title != rhs.title { return false } if lhs.description != rhs.description { return false } if lhs.domainURL != rhs.domainURL { return false } if lhs.isDisplayingRating != rhs.isDisplayingRating { return false } return true } }
mit
e64717384c9742a48c0445c449bd5774
21.397059
87
0.611293
4.314448
false
false
false
false
mmadjer/RxStateFlow
Example/Example/ViewController.swift
1
3031
// // ViewController.swift // Example // // Copyright © 2016 Miroslav Madjer. All rights reserved. // import UIKit import RealmSwift import RxCocoa import RxRealm import RxStateFlow import RxSwift class ViewController: UIViewController { @IBOutlet weak var undoButton: UIBarButtonItem! @IBOutlet weak var valueLabel: UILabel! @IBOutlet weak var stepper: UIStepper! { didSet { stepper.maximumValue = Double(store.state.value.maxCounterValue) stepper.minimumValue = Double(store.state.value.minCounterValue) } } internal var bag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() let realm = try? Realm() let history = realm!.objects(History.self).first! Observable.collection(from: history.records) .map { !$0.isEmpty } .bindTo(undoButton.rx.isEnabled) .addDisposableTo(bag) // Subscribe to store changes store.state.asDriver().drive(onNext: { state in self.updateView(state) }).addDisposableTo(bag) store.errors.asDriver().drive(onNext: { error in self.handleErrors(error) }).addDisposableTo(bag) } // MARK: - Action methods @IBAction func stepperValueChanged(_ sender: UIStepper) { store.dispatch(event: UpdateCounter(value: Int(sender.value))) } @IBAction func onTap(_ sender: UITapGestureRecognizer) { store.dispatch(command: IncreaseCounter()) } @IBAction func onSwipeLeft(_ sender: UISwipeGestureRecognizer) { store.dispatch(command: IncreaseCounter()) } @IBAction func onSwipeRight(_ sender: UISwipeGestureRecognizer) { store.dispatch(command: DecreaseCounter()) } @IBAction func onUndo(_ sender: AnyObject) { store.dispatch(event: HistoryEvent.undo) } @IBAction func onReset(_ sender: AnyObject) { store.dispatch(event: CounterEvent.reset) } // MARK: - Helper methods fileprivate func updateView(_ state: AppState) { valueLabel.text = String(Int(state.counter)) stepper.value = Double(state.counter) } fileprivate func handleErrors(_ error: Error?) { if let error = error { var message = error.localizedDescription switch error { case CounterError.minReached: message = "Minimum reached" case CounterError.maxReached: message = "Maximum reached" default: break } let alert = UIAlertController(title: "Ooops", message: message, preferredStyle: .alert) let action = UIAlertAction(title: "Ok", style: .default, handler: { _ in store.dispatch(event: ErrorEvent.remove) }) alert.addAction(action) present(alert, animated: true, completion: nil) } } }
mit
aff68b6696ac95e5db1cf39a796d813b
28.134615
84
0.60363
4.879227
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Views/Custom/CommentEditView.swift
1
7057
// // CommentEditView.swift // Inbbbox // // Created by Peter Bruz on 15/02/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit class CommentEditView: UIView { // Private Properties fileprivate var didUpdateConstraints = false fileprivate let topInset = CGFloat(10) fileprivate let bottomInset = CGFloat(10) fileprivate let buttonSize = CGFloat(24) fileprivate var isEditing = true { didSet { deleteLabel.text = deleteLabelText let imageName = isEditing ? "ic-delete-comment" : "ic-report-comment" deleteButton.setImage(UIImage(named: imageName), for: .normal) likeButton.isHidden = isEditing likeLabel.isHidden = isEditing setUpConstraints() } } fileprivate var isLiked = false { didSet { let imageName = isLiked ? "ic-like-details-active" : "ic-like-details" likeButton.setImage(UIImage(named: imageName), for: .normal) } } fileprivate var deleteLabelText: String { if isEditing { return Localized("CommentEditView.Delete", comment: "Editing comment, delete.") } else { return Localized("CommentEditView.Report", comment: "Editing comment, report content") } } // Colors fileprivate let viewBackgroundColor = UIColor.clear // public UI Components let likeButton = UIButton() let likeLabel = UILabel() let cancelButton = UIButton() let cancelLabel = UILabel() let deleteButton = UIButton() let deleteLabel = UILabel() let contentView: UIView = { if Settings.Customization.CurrentColorMode == .nightMode { return UIView.withColor(ColorModeProvider.current().shotDetailsCommentCollectionViewCellBackground) } else { return UIVisualEffectView(effect: UIBlurEffect(style: .light)) } }() // MARK: Life Cycle override init(frame: CGRect) { super.init(frame: frame) backgroundColor = viewBackgroundColor setupSubviews() } @available(*, unavailable, message: "Use init(frame: CGRect) method instead") required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: UI override class var requiresConstraintBasedLayout: Bool { return true } func setUpConstraints() { let distanceBetweenButtons = CGFloat(60) let buttonsCenterOffset = CGFloat(-5) let buttonsToLabelsAdditionalOffset = CGFloat(10) var deleteButtonOffset = -(distanceBetweenButtons / 2 + buttonSize / 2) var cancelButtonOffset = distanceBetweenButtons / 2 + buttonSize / 2 if !isEditing { deleteButtonOffset = 0 cancelButtonOffset = distanceBetweenButtons + buttonSize } if !didUpdateConstraints { contentView.autoPinEdgesToSuperviewEdges() likeButton.autoAlignAxis(.horizontal, toSameAxisOf: likeButton.superview!, withOffset: buttonsCenterOffset) likeButton.autoAlignAxis(.vertical, toSameAxisOf: likeButton.superview!, withOffset: -(distanceBetweenButtons + buttonSize)) likeButton.autoSetDimensions(to: CGSize(width: buttonSize, height: buttonSize)) likeLabel.autoAlignAxis(.horizontal, toSameAxisOf: likeButton, withOffset: buttonSize / 2 + buttonsToLabelsAdditionalOffset) likeLabel.autoAlignAxis(.vertical, toSameAxisOf: likeButton) deleteButton.autoAlignAxis(.horizontal, toSameAxisOf: deleteButton.superview!, withOffset: buttonsCenterOffset) deleteButton.autoAlignAxis(.vertical, toSameAxisOf: deleteButton.superview!, withOffset: deleteButtonOffset) deleteButton.autoSetDimensions(to: CGSize(width: buttonSize, height: buttonSize)) deleteLabel.autoAlignAxis(.horizontal, toSameAxisOf: deleteButton, withOffset: buttonSize / 2 + buttonsToLabelsAdditionalOffset) deleteLabel.autoAlignAxis(.vertical, toSameAxisOf: deleteButton) cancelButton.autoAlignAxis(.horizontal, toSameAxisOf: deleteButton) cancelButton.autoAlignAxis(.vertical, toSameAxisOf: cancelButton.superview!, withOffset: cancelButtonOffset) cancelButton.autoSetDimensions(to: CGSize(width: buttonSize, height: buttonSize)) cancelLabel.autoAlignAxis(.horizontal, toSameAxisOf: deleteLabel) cancelLabel.autoAlignAxis(.vertical, toSameAxisOf: cancelButton) didUpdateConstraints = true } } // MARK: Public func configureForEditing() { isEditing = true } func configureForReporting() { isEditing = false } func setLiked(withValue value: Bool) { isLiked = value } // MARK: Private fileprivate func setupSubviews() { setupBlurView() setupCancelButton() setupDeleteButton() setupLikeButton() setupCancelLabel() setupDeleteLabel() setupLikeLabel() } fileprivate func setupBlurView() { addSubview(contentView) } fileprivate func setupCancelButton() { cancelButton.setImage(UIImage(named: "ic-cancel-comment"), for: .normal) cancelButton.contentMode = .scaleAspectFit contentView.addSubview(cancelButton) } fileprivate func setupDeleteButton() { deleteButton.setImage(UIImage(named: "ic-delete-comment"), for: .normal) deleteButton.contentMode = .scaleAspectFit contentView.addSubview(deleteButton) } fileprivate func setupLikeButton() { likeButton.setImage(UIImage(named: "ic-like-details"), for: .normal) likeButton.contentMode = .scaleAspectFit contentView.addSubview(likeButton) } fileprivate func setupCancelLabel() { cancelLabel.font = UIFont.systemFont(ofSize: 10, weight: UIFontWeightRegular) cancelLabel.textColor = ColorModeProvider.current().shotDetailsCommentEditLabelTextColor cancelLabel.text = Localized("CommentEditView.Cancel", comment: "Cancel editing comment.") contentView.addSubview(cancelLabel) } fileprivate func setupDeleteLabel() { deleteLabel.font = UIFont.systemFont(ofSize: 10, weight: UIFontWeightRegular) deleteLabel.textColor = ColorModeProvider.current().shotDetailsCommentEditLabelTextColor deleteLabel.text = deleteLabelText contentView.addSubview(deleteLabel) } fileprivate func setupLikeLabel() { likeLabel.font = UIFont.systemFont(ofSize: 10, weight: UIFontWeightRegular) likeLabel.textColor = ColorModeProvider.current().shotDetailsCommentEditLabelTextColor likeLabel.text = Localized("CommentEditView.Like", comment: "Mark selected comment as liked.") contentView.addSubview(likeLabel) } }
gpl-3.0
3375a97725da13aac77365cc011d32e5
35
111
0.6661
5.329305
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Views/LightWeightAlert.swift
1
1182
// // LightWeightAlert.swift // breadwallet // // Created by Adrian Corscadden on 2017-06-20. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit class LightWeightAlert: UIView { init(message: String) { super.init(frame: .zero) self.label.text = message setup() } let effect = UIBlurEffect(style: .dark) let background = UIVisualEffectView() let container = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: UIBlurEffect(style: .dark))) private let label = UILabel(font: .customBold(size: 16.0)) private func setup() { addSubview(background) background.constrain(toSuperviewEdges: nil) background.contentView.addSubview(container) container.contentView.addSubview(label) container.constrain(toSuperviewEdges: nil) label.constrain(toSuperviewEdges: UIEdgeInsets(top: C.padding[2], left: C.padding[2], bottom: -C.padding[2], right: -C.padding[2])) layer.cornerRadius = 4.0 layer.masksToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
9d7c3030f8ee46dc4d2012a3613bc7ca
29.282051
139
0.672312
4.217857
false
false
false
false
kesun421/firefox-ios
XCUITests/ReaderViewUITest.swift
1
6714
/* 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 XCTest class ReaderViewTest: BaseTestCase { func testLoadReaderContent() { navigator.goto(BrowserTab) app.buttons["Reader View"].tap() // The settings of reader view are shown as well as the content of the web site waitforExistence(app.buttons["Display Settings"]) XCTAssertTrue(app.webViews.staticTexts["The Book of Mozilla"].exists) } private func addContentToReaderView() { navigator.goto(BrowserTab) waitUntilPageLoad() app.buttons["Reader View"].tap() waitforExistence(app.buttons["Add to Reading List"]) app.buttons["Add to Reading List"].tap() } private func checkReadingListNumberOfItems(items: Int) { waitforExistence(app.tables["ReadingTable"]) let list = app.tables["ReadingTable"].cells.count XCTAssertEqual(list, UInt(items), "The number of items in the reading table is not correct") } func testAddToReadingList() { // Initially reading list is empty navigator.goto(HomePanel_ReadingList) // Check the button is selected (is disabled and the rest bookmarks and so are enabled) XCTAssertFalse(app.buttons["HomePanels.ReadingList"].isEnabled) XCTAssertTrue(app.buttons["HomePanels.Bookmarks"].isEnabled) checkReadingListNumberOfItems(items: 0) // Add item to reading list and check that it appears addContentToReaderView() navigator.goto(HomePanel_ReadingList) waitforExistence(app.buttons["HomePanels.ReadingList"]) // Check that there is one item let savedToReadingList = app.tables["ReadingTable"].cells.staticTexts["The Book of Mozilla"] XCTAssertTrue(savedToReadingList.exists) checkReadingListNumberOfItems(items: 1) } func testMarkAsReadAndUreadFromReaderView() { addContentToReaderView() // Mark the content as read, so the mark as unread buttons appear app.buttons["Mark as Read"].tap() waitforExistence(app.buttons["Mark as Unread"]) // Mark the content as unread, so the mark as read button appear app.buttons["Mark as Unread"].tap() waitforExistence(app.buttons["Mark as Read"]) } func testRemoveFromReadingView() { addContentToReaderView() // Once the content has been added, remove it waitforExistence(app.buttons["Remove from Reading List"]) app.buttons["Remove from Reading List"].tap() // Check that instead of the remove icon now it is shown the add to read list waitforExistence(app.buttons["Add to Reading List"]) // Go to reader list view to check that there is not any item there navigator.goto(HomePanel_ReadingList) waitforExistence(app.buttons["HomePanels.ReadingList"]) navigator.goto(HomePanel_ReadingList) checkReadingListNumberOfItems(items: 0) } func testMarkAsReadAndUnreadFromReadingList() { addContentToReaderView() navigator.goto(HomePanel_ReadingList) waitforExistence(app.buttons["HomePanels.ReadingList"]) navigator.goto(HomePanel_ReadingList) // Check that there is one item let savedToReadingList = app.tables["ReadingTable"].cells.staticTexts["The Book of Mozilla"] XCTAssertTrue(savedToReadingList.exists) // Mark it as read/unread savedToReadingList.swipeLeft() waitforExistence(app.buttons["Mark as Read"]) app.buttons["Mark as Read"].tap() savedToReadingList.swipeLeft() waitforExistence(app.buttons["Mark as Unread"]) } func testRemoveFromReadingList() { addContentToReaderView() navigator.goto(HomePanel_ReadingList) waitforExistence(app.buttons["HomePanels.ReadingList"]) navigator.goto(HomePanel_ReadingList) let savedToReadingList = app.tables["ReadingTable"].cells.staticTexts["The Book of Mozilla"] savedToReadingList.swipeLeft() waitforExistence(app.buttons["Remove"]) // Remove the item from reading list app.buttons["Remove"].tap() XCTAssertFalse(savedToReadingList.exists) // Reader list view should be empty checkReadingListNumberOfItems(items: 0) } func testAddToReadingListFromPageOptionsMenu() { // First time Reading list is empty navigator.goto(HomePanel_ReadingList) checkReadingListNumberOfItems(items: 0) // Add item to Reading List from Page Options Menu navigator.goto(BrowserTab) waitUntilPageLoad() navigator.browserPerformAction(.addReadingListOption) // Now there should be an item on the list navigator.nowAt(BrowserTab) navigator.browserPerformAction(.openReadingListOption) checkReadingListNumberOfItems(items: 1) } func testOpenSavedForReadingLongPressInNewTab() { // Add item to Reading List addContentToReaderView() navigator.browserPerformAction(.openReadingListOption) let numTab = app.buttons["Show Tabs"].value as? String XCTAssertEqual(numTab, "1") // Long tap on the item just saved let savedToReadingList = app.tables["ReadingTable"].cells.staticTexts["The Book of Mozilla"] savedToReadingList.press(forDuration: 1) // Select to open in New Tab waitforExistence(app.tables["Context Menu"]) app.tables.cells["quick_action_new_tab"].tap() // Now there should be two tabs open let numTabAfter = app.buttons["Show Tabs"].value as? String XCTAssertEqual(numTabAfter, "2") } func testRemoveSavedForReadingLongPress() { // Add item to Reading List addContentToReaderView() navigator.browserPerformAction(.openReadingListOption) // Long tap on the item just saved and choose remove let savedToReadingList = app.tables["ReadingTable"].cells.staticTexts["The Book of Mozilla"] savedToReadingList.press(forDuration: 1) waitforExistence(app.tables["Context Menu"]) app.tables.cells["action_remove"].tap() // Verify the item has been removed waitforNoExistence(app.tables["ReadingTable"].cells.staticTexts["The Book of Mozilla"]) XCTAssertFalse(app.tables["ReadingTable"].cells.staticTexts["The Book of Mozilla"].exists) } func testOpenSavedForReadingLongPressInPrivateTab() { // To Be defined once the new FxScreenGraph lands } }
mpl-2.0
f140fcfaf0b9265763f76bc73dd28870
38.263158
100
0.682752
5.204651
false
true
false
false
brentdax/swift
test/SILGen/builtins.swift
1
34189
// RUN: %target-swift-emit-silgen -enable-sil-ownership -parse-stdlib %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s // RUN: %target-swift-emit-sil -enable-sil-ownership -Onone -parse-stdlib %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck -check-prefix=CANONICAL %s import Swift protocol ClassProto : class { } struct Pointer { var value: Builtin.RawPointer } // CHECK-LABEL: sil hidden @$s8builtins3foo{{[_0-9a-zA-Z]*}}F func foo(_ x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 { // CHECK: builtin "cmp_eq_Int1" return Builtin.cmp_eq_Int1(x, y) } // CHECK-LABEL: sil hidden @$s8builtins8load_pod{{[_0-9a-zA-Z]*}}F func load_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @$s8builtins8load_obj{{[_0-9a-zA-Z]*}}F func load_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @$s8builtins12load_raw_pod{{[_0-9a-zA-Z]*}}F func load_raw_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @$s8builtins12load_raw_obj{{[_0-9a-zA-Z]*}}F func load_raw_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @$s8builtins18load_invariant_pod{{[_0-9a-zA-Z]*}}F func load_invariant_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [invariant] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadInvariant(x) } // CHECK-LABEL: sil hidden @$s8builtins18load_invariant_obj{{[_0-9a-zA-Z]*}}F func load_invariant_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [invariant] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadInvariant(x) } // CHECK-LABEL: sil hidden @$s8builtins8load_gen{{[_0-9a-zA-Z]*}}F func load_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}} return Builtin.load(x) } // CHECK-LABEL: sil hidden @$s8builtins8move_pod{{[_0-9a-zA-Z]*}}F func move_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @$s8builtins8move_obj{{[_0-9a-zA-Z]*}}F func move_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [take] [[ADDR]] // CHECK-NOT: copy_value [[VAL]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @$s8builtins8move_gen{{[_0-9a-zA-Z]*}}F func move_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}} return Builtin.take(x) } // CHECK-LABEL: sil hidden @$s8builtins11destroy_pod{{[_0-9a-zA-Z]*}}F func destroy_pod(_ x: Builtin.RawPointer) { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box // CHECK-NOT: pointer_to_address // CHECK-NOT: destroy_addr // CHECK-NOT: destroy_value // CHECK: destroy_value [[XBOX]] : ${{.*}}{ // CHECK-NOT: destroy_value return Builtin.destroy(Builtin.Int64.self, x) // CHECK: return } // CHECK-LABEL: sil hidden @$s8builtins11destroy_obj{{[_0-9a-zA-Z]*}}F func destroy_obj(_ x: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(Builtin.NativeObject.self, x) } // CHECK-LABEL: sil hidden @$s8builtins11destroy_gen{{[_0-9a-zA-Z]*}}F func destroy_gen<T>(_ x: Builtin.RawPointer, _: T) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(T.self, x) } // CHECK-LABEL: sil hidden @$s8builtins10assign_pod{{[_0-9a-zA-Z]*}}F func assign_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { var x = x var y = y // CHECK: alloc_box // CHECK: alloc_box // CHECK-NOT: alloc_box // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: destroy_value // CHECK: destroy_value // CHECK-NOT: destroy_value Builtin.assign(x, y) // CHECK: return } // CHECK-LABEL: sil hidden @$s8builtins10assign_obj{{[_0-9a-zA-Z]*}}F func assign_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: assign {{%.*}} to [[ADDR]] // CHECK-NOT: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @$s8builtins12assign_tuple{{[_0-9a-zA-Z]*}}F func assign_tuple(_ x: (Builtin.Int64, Builtin.NativeObject), y: Builtin.RawPointer) { var x = x var y = y // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*(Builtin.Int64, Builtin.NativeObject) // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @$s8builtins10assign_gen{{[_0-9a-zA-Z]*}}F func assign_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] {{%.*}} to [[ADDR]] : Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @$s8builtins8init_pod{{[_0-9a-zA-Z]*}}F func init_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: store {{%.*}} to [trivial] [[ADDR]] // CHECK-NOT: destroy_value [[ADDR]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @$s8builtins8init_obj{{[_0-9a-zA-Z]*}}F func init_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK-NOT: load [[ADDR]] // CHECK: store [[SRC:%.*]] to [init] [[ADDR]] // CHECK-NOT: destroy_value [[SRC]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @$s8builtins8init_gen{{[_0-9a-zA-Z]*}}F func init_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[OTHER_LOC:%.*]] to [initialization] [[ADDR]] // CHECK-NOT: destroy_addr [[OTHER_LOC]] Builtin.initialize(x, y) } class C {} class D {} // CHECK-LABEL: sil hidden @$s8builtins22class_to_native_object{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @guaranteed $C): // CHECK-NEXT: debug_value // CHECK-NEXT: [[OBJ:%.*]] = unchecked_ref_cast [[ARG:%.*]] to $Builtin.NativeObject // CHECK-NEXT: [[OBJ_COPY:%.*]] = copy_value [[OBJ]] // CHECK-NEXT: return [[OBJ_COPY]] func class_to_native_object(_ c:C) -> Builtin.NativeObject { return Builtin.castToNativeObject(c) } // CHECK-LABEL: sil hidden @$s8builtins32class_archetype_to_native_object{{[_0-9a-zA-Z]*}}F func class_archetype_to_native_object<T : C>(_ t: T) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NEXT: [[OBJ_COPY:%.*]] = copy_value [[OBJ]] // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ_COPY]] return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @$s8builtins34class_existential_to_native_object{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassProto): // CHECK-NEXT: debug_value // CHECK-NEXT: [[REF:%[0-9]+]] = open_existential_ref [[ARG]] : $ClassProto // CHECK-NEXT: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject // CHECK-NEXT: [[PTR_COPY:%.*]] = copy_value [[PTR]] // CHECK-NEXT: return [[PTR_COPY]] func class_existential_to_native_object(_ t:ClassProto) -> Builtin.NativeObject { return Builtin.unsafeCastToNativeObject(t) } // CHECK-LABEL: sil hidden @$s8builtins24class_from_native_object{{[_0-9a-zA-Z]*}}F func class_from_native_object(_ p: Builtin.NativeObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK: [[C_RETURN:%.*]] = copy_value [[C]] // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C_RETURN]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @$s8builtins34class_archetype_from_native_object{{[_0-9a-zA-Z]*}}F func class_archetype_from_native_object<T : C>(_ p: Builtin.NativeObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $T // CHECK: [[C_RETURN:%.*]] = copy_value [[C]] // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C_RETURN]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @$s8builtins41objc_class_existential_from_native_object{{[_0-9a-zA-Z]*}}F func objc_class_existential_from_native_object(_ p: Builtin.NativeObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $AnyObject // CHECK: [[C_RETURN:%.*]] = copy_value [[C]] // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C_RETURN]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @$s8builtins20class_to_raw_pointer{{[_0-9a-zA-Z]*}}F func class_to_raw_pointer(_ c: C) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } func class_archetype_to_raw_pointer<T : C>(_ t: T) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(t) } protocol CP: class {} func existential_to_raw_pointer(_ p: CP) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(p) } // CHECK-LABEL: sil hidden @$s8builtins18obj_to_raw_pointer{{[_0-9a-zA-Z]*}}F func obj_to_raw_pointer(_ c: Builtin.NativeObject) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } // CHECK-LABEL: sil hidden @$s8builtins22class_from_raw_pointer{{[_0-9a-zA-Z]*}}F func class_from_raw_pointer(_ p: Builtin.RawPointer) -> C { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } func class_archetype_from_raw_pointer<T : C>(_ p: Builtin.RawPointer) -> T { return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @$s8builtins20obj_from_raw_pointer{{[_0-9a-zA-Z]*}}F func obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @$s8builtins28existential_from_raw_pointer{{[_0-9a-zA-Z]*}}F func existential_from_raw_pointer(_ p: Builtin.RawPointer) -> AnyObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @$s8builtins9gep_raw64{{[_0-9a-zA-Z]*}}F func gep_raw64(_ p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int64(p, i) } // CHECK-LABEL: sil hidden @$s8builtins9gep_raw32{{[_0-9a-zA-Z]*}}F func gep_raw32(_ p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int32(p, i) } // CHECK-LABEL: sil hidden @$s8builtins3gep{{[_0-9a-zA-Z]*}}F func gep<Elem>(_ p: Builtin.RawPointer, i: Builtin.Word, e: Elem.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[GEP:%.*]] = index_addr [[P2A]] : $*Elem, %1 : $Builtin.Word // CHECK: [[A2P:%.*]] = address_to_pointer [[GEP]] // CHECK: return [[A2P]] return Builtin.gep_Word(p, i, e) } public final class Header { } // CHECK-LABEL: sil hidden @$s8builtins20allocWithTailElems_1{{[_0-9a-zA-Z]*}}F func allocWithTailElems_1<T>(n: Builtin.Word, ty: T.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T * %0 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_1(Header.self, n, ty) } // CHECK-LABEL: sil hidden @$s8builtins20allocWithTailElems_3{{[_0-9a-zA-Z]*}}F func allocWithTailElems_3<T1, T2, T3>(n1: Builtin.Word, ty1: T1.Type, n2: Builtin.Word, ty2: T2.Type, n3: Builtin.Word, ty3: T3.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T1 * %0 : $Builtin.Word] [tail_elems $T2 * %2 : $Builtin.Word] [tail_elems $T3 * %4 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_3(Header.self, n1, ty1, n2, ty2, n3, ty3) } // CHECK-LABEL: sil hidden @$s8builtins16projectTailElems{{[_0-9a-zA-Z]*}}F func projectTailElems<T>(h: Header, ty: T.Type) -> Builtin.RawPointer { // CHECK: bb0([[ARG1:%.*]] : @guaranteed $Header // CHECK: [[TA:%.*]] = ref_tail_addr [[ARG1]] : $Header // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: return [[A2P]] return Builtin.projectTailElems(h, ty) } // CHECK: } // end sil function '$s8builtins16projectTailElems1h2tyBpAA6HeaderC_xmtlF' // CHECK-LABEL: sil hidden @$s8builtins11getTailAddr{{[_0-9a-zA-Z]*}}F func getTailAddr<T1, T2>(start: Builtin.RawPointer, i: Builtin.Word, ty1: T1.Type, ty2: T2.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[TA:%.*]] = tail_addr [[P2A]] : $*T1, %1 : $Builtin.Word, $T2 // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: return [[A2P]] return Builtin.getTailAddr_Word(start, i, ty1, ty2) } // CHECK-LABEL: sil hidden @$s8builtins25beginUnpairedModifyAccess{{[_0-9a-zA-Z]*}}F func beginUnpairedModifyAccess<T1>(address: Builtin.RawPointer, scratch: Builtin.RawPointer, ty1: T1.Type) { // CHECK: [[P2A_ADDR:%.*]] = pointer_to_address %0 // CHECK: [[P2A_SCRATCH:%.*]] = pointer_to_address %1 // CHECK: begin_unpaired_access [modify] [dynamic] [builtin] [[P2A_ADDR]] : $*T1, [[P2A_SCRATCH]] : $*Builtin.UnsafeValueBuffer // CHECK: [[RESULT:%.*]] = tuple () // CHECK: [[RETURN:%.*]] = tuple () // CHECK: return [[RETURN]] : $() Builtin.beginUnpairedModifyAccess(address, scratch, ty1); } // CHECK-LABEL: sil hidden @$s8builtins30performInstantaneousReadAccess{{[_0-9a-zA-Z]*}}F func performInstantaneousReadAccess<T1>(address: Builtin.RawPointer, scratch: Builtin.RawPointer, ty1: T1.Type) { // CHECK: [[P2A_ADDR:%.*]] = pointer_to_address %0 // CHECK: [[SCRATCH:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: begin_unpaired_access [read] [dynamic] [no_nested_conflict] [builtin] [[P2A_ADDR]] : $*T1, [[SCRATCH]] : $*Builtin.UnsafeValueBuffer // CHECK-NOT: end_{{.*}}access // CHECK: [[RESULT:%.*]] = tuple () // CHECK: [[RETURN:%.*]] = tuple () // CHECK: return [[RETURN]] : $() Builtin.performInstantaneousReadAccess(address, ty1); } // CHECK-LABEL: sil hidden @$s8builtins8condfail{{[_0-9a-zA-Z]*}}F func condfail(_ i: Builtin.Int1) { Builtin.condfail(i) // CHECK: cond_fail {{%.*}} : $Builtin.Int1 } struct S {} @objc class O {} @objc protocol OP1 {} @objc protocol OP2 {} protocol P {} // CHECK-LABEL: sil hidden @$s8builtins10canBeClass{{[_0-9a-zA-Z]*}}F func canBeClass<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(O.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(OP1.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompo = OP1 & OP2 // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(ObjCCompo.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(S.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(C.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(P.self) typealias MixedCompo = OP1 & P // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompo.self) // CHECK: builtin "canBeClass"<T> Builtin.canBeClass(T.self) } // FIXME: "T.Type.self" does not parse as an expression // CHECK-LABEL: sil hidden @$s8builtins18canBeClassMetatype{{[_0-9a-zA-Z]*}}F func canBeClassMetatype<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 0 typealias OT = O.Type Builtin.canBeClass(OT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias OP1T = OP1.Type Builtin.canBeClass(OP1T.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompoT = (OP1 & OP2).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(ObjCCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias ST = S.Type Builtin.canBeClass(ST.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias CT = C.Type Builtin.canBeClass(CT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias PT = P.Type Builtin.canBeClass(PT.self) typealias MixedCompoT = (OP1 & P).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias TT = T.Type Builtin.canBeClass(TT.self) } // CHECK-LABEL: sil hidden @$s8builtins11fixLifetimeyyAA1CCF : $@convention(thin) (@guaranteed C) -> () { func fixLifetime(_ c: C) { // CHECK: bb0([[ARG:%.*]] : @guaranteed $C): // CHECK: fix_lifetime [[ARG]] : $C Builtin.fixLifetime(c) } // CHECK: } // end sil function '$s8builtins11fixLifetimeyyAA1CCF' // CHECK-LABEL: sil hidden @$s8builtins20assert_configuration{{[_0-9a-zA-Z]*}}F func assert_configuration() -> Builtin.Int32 { return Builtin.assert_configuration() // CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32 // CHECK: return [[APPLY]] : $Builtin.Int32 } // CHECK-LABEL: sil hidden @$s8builtins17assumeNonNegativeyBwBwF func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word { return Builtin.assumeNonNegative_Word(x) // CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word // CHECK: return [[APPLY]] : $Builtin.Word } // CHECK-LABEL: sil hidden @$s8builtins11autoreleaseyyAA1OCF : $@convention(thin) (@guaranteed O) -> () { // ==> SEMANTIC ARC TODO: This will be unbalanced... should we allow it? // CHECK: bb0([[ARG:%.*]] : @guaranteed $O): // CHECK: unmanaged_autorelease_value [[ARG]] // CHECK: } // end sil function '$s8builtins11autoreleaseyyAA1OCF' func autorelease(_ o: O) { Builtin.autorelease(o) } // The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during // diagnostics. // CHECK-LABEL: sil hidden @$s8builtins11unreachable{{[_0-9a-zA-Z]*}}F // CHECK: builtin "unreachable"() // CHECK: return // CANONICAL-LABEL: sil hidden @$s8builtins11unreachableyyF : $@convention(thin) () -> () { func unreachable() { Builtin.unreachable() } // CHECK-LABEL: sil hidden @$s8builtins15reinterpretCast_1xBw_AA1DCAA1CCSgAGtAG_BwtF : $@convention(thin) (@guaranteed C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C) // CHECK: bb0([[ARG1:%.*]] : @guaranteed $C, [[ARG2:%.*]] : @trivial $Builtin.Word): // CHECK-NEXT: debug_value // CHECK-NEXT: debug_value // CHECK-NEXT: [[ARG1_TRIVIAL:%.*]] = unchecked_trivial_bit_cast [[ARG1]] : $C to $Builtin.Word // CHECK-NEXT: [[ARG1_D:%.*]] = unchecked_ref_cast [[ARG1]] : $C to $D // CHECK-NEXT: [[ARG1_OPT:%.*]] = unchecked_ref_cast [[ARG1]] : $C to $Optional<C> // CHECK-NEXT: [[ARG2_FROM_WORD:%.*]] = unchecked_bitwise_cast [[ARG2]] : $Builtin.Word to $C // CHECK-NEXT: [[ARG2_FROM_WORD_COPY:%.*]] = copy_value [[ARG2_FROM_WORD]] // CHECK-NEXT: [[ARG1_D_COPY:%.*]] = copy_value [[ARG1_D]] // CHECK-NEXT: [[ARG1_OPT_COPY:%.*]] = copy_value [[ARG1_OPT]] // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ARG1_TRIVIAL]] : $Builtin.Word, [[ARG1_D_COPY]] : $D, [[ARG1_OPT_COPY]] : $Optional<C>, [[ARG2_FROM_WORD_COPY:%.*]] : $C) // CHECK: return [[RESULT]] func reinterpretCast(_ c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) { return (Builtin.reinterpretCast(c) as Builtin.Word, Builtin.reinterpretCast(c) as D, Builtin.reinterpretCast(c) as C?, Builtin.reinterpretCast(x) as C) } // CHECK-LABEL: sil hidden @$s8builtins19reinterpretAddrOnly{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnly<T, U>(_ t: T) -> U { // CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @$s8builtins28reinterpretAddrOnlyToTrivial{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnlyToTrivial<T>(_ t: T) -> Int { // CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT:%.*]] : $*T to $*Int // CHECK: [[VALUE:%.*]] = load [trivial] [[ADDR]] // CHECK-NOT: destroy_addr [[INPUT]] return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @$s8builtins27reinterpretAddrOnlyLoadable{{[_0-9a-zA-Z]*}}F func reinterpretAddrOnlyLoadable<T>(_ a: Int, _ b: T) -> (T, Int) { // CHECK: [[BUF:%.*]] = alloc_stack $Int // CHECK: store {{%.*}} to [trivial] [[BUF]] // CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]] : $*Int to $*T // CHECK: copy_addr [[RES1]] to [initialization] return (Builtin.reinterpretCast(a) as T, // CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int // CHECK: load [trivial] [[RES]] Builtin.reinterpretCast(b) as Int) } // CHECK-LABEL: sil hidden @$s8builtins18castToBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: [[BO:%.*]] = ref_to_bridge_object {{%.*}} : $C, {{%.*}} : $Builtin.Word // CHECK: [[BO_COPY:%.*]] = copy_value [[BO]] // CHECK: return [[BO_COPY]] func castToBridgeObject(_ c: C, _ w: Builtin.Word) -> Builtin.BridgeObject { return Builtin.castToBridgeObject(c, w) } // CHECK-LABEL: sil hidden @$s8builtins23castRefFromBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C func castRefFromBridgeObject(_ bo: Builtin.BridgeObject) -> C { return Builtin.castReferenceFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @$s8builtins30castBitPatternFromBridgeObject{{[_0-9a-zA-Z]*}}F // CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word // CHECK-NOT: destroy_value [[BO]] func castBitPatternFromBridgeObject(_ bo: Builtin.BridgeObject) -> Builtin.Word { return Builtin.castBitPatternFromBridgeObject(bo) } // ---------------------------------------------------------------------------- // isUnique variants // ---------------------------------------------------------------------------- // NativeObject // CHECK-LABEL: sil hidden @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Optional<Builtin.NativeObject>): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Optional<Builtin.NativeObject> // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Optional<Builtin.NativeObject> // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject nonNull // CHECK-LABEL: sil hidden @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.NativeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.NativeObject // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) // CHECK-LABEL: sil hidden @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Optional<Builtin.UnknownObject>): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Optional<Builtin.UnknownObject> // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) nonNull // CHECK-LABEL: sil hidden @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.UnknownObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.UnknownObject // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // BridgeObject nonNull // CHECK-LABEL: sil hidden @$s8builtins8isUnique{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.BridgeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[BUILTIN:%.*]] = is_unique [[WRITE]] : $*Builtin.BridgeObject // CHECK: return func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // BridgeObject nonNull native // CHECK-LABEL: sil hidden @$s8builtins15isUnique_native{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*Builtin.BridgeObject): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 // CHECK: [[CAST:%.*]] = unchecked_addr_cast [[WRITE]] : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: return func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique_native(&ref)) } // ---------------------------------------------------------------------------- // Builtin.castReference // ---------------------------------------------------------------------------- class A {} protocol PUnknown {} protocol PClass : class {} // CHECK-LABEL: sil hidden @$s8builtins19refcast_generic_any{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr T in %{{.*}} : $*T to AnyObject in %{{.*}} : $*AnyObject func refcast_generic_any<T>(_ o: T) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @$s8builtins17refcast_class_anyyyXlAA1ACF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $A): // CHECK: [[ARG_CASTED:%.*]] = unchecked_ref_cast [[ARG]] : $A to $AnyObject // CHECK: [[ARG_CASTED_COPY:%.*]] = copy_value [[ARG_CASTED]] // CHECK-NOT: destroy_value [[ARG]] // CHECK: return [[ARG_CASTED_COPY]] // CHECK: } // end sil function '$s8builtins17refcast_class_anyyyXlAA1ACF' func refcast_class_any(_ o: A) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @$s8builtins20refcast_punknown_any{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}} : $*PUnknown to AnyObject in %{{.*}} : $*AnyObject func refcast_punknown_any(_ o: PUnknown) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @$s8builtins18refcast_pclass_anyyyXlAA6PClass_pF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $PClass): // CHECK: [[ARG_CAST:%.*]] = unchecked_ref_cast [[ARG]] : $PClass to $AnyObject // CHECK: [[ARG_CAST_COPY:%.*]] = copy_value [[ARG_CAST]] // CHECK: return [[ARG_CAST_COPY]] // CHECK: } // end sil function '$s8builtins18refcast_pclass_anyyyXlAA6PClass_pF' func refcast_pclass_any(_ o: PClass) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @$s8builtins20refcast_any_punknown{{[_0-9a-zA-Z]*}}F // CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}} : $*AnyObject to PUnknown in %{{.*}} : $*PUnknown func refcast_any_punknown(_ o: AnyObject) -> PUnknown { return Builtin.castReference(o) } // => SEMANTIC ARC TODO: This function is missing a borrow + extract + copy. // // CHECK-LABEL: sil hidden @$s8builtins22unsafeGuaranteed_class{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @guaranteed $A): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<A>([[P_COPY]] : $A) // CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]] // CHECK: destroy_value [[R]] // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: return [[P_COPY]] : $A // CHECK: } func unsafeGuaranteed_class(_ a: A) -> A { Builtin.unsafeGuaranteed(a) return a } // CHECK-LABEL: $s8builtins24unsafeGuaranteed_generic{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @guaranteed $T): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]] // CHECK: destroy_value [[R]] // CHECK: [[P_RETURN:%.*]] = copy_value [[P]] // CHECK: return [[P_RETURN]] : $T // CHECK: } func unsafeGuaranteed_generic<T: AnyObject> (_ a: T) -> T { Builtin.unsafeGuaranteed(a) return a } // CHECK_LABEL: sil hidden @$s8builtins31unsafeGuaranteed_generic_return{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @guaranteed $T): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: ([[R:%.*]], [[K:%.*]]) = destructure_tuple [[T]] // CHECK: [[S:%.*]] = tuple ([[R]] : $T, [[K]] : $Builtin.Int8) // CHECK: return [[S]] : $(T, Builtin.Int8) // CHECK: } func unsafeGuaranteed_generic_return<T: AnyObject> (_ a: T) -> (T, Builtin.Int8) { return Builtin.unsafeGuaranteed(a) } // CHECK-LABEL: sil hidden @$s8builtins19unsafeGuaranteedEnd{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @trivial $Builtin.Int8): // CHECK: builtin "unsafeGuaranteedEnd"([[P]] : $Builtin.Int8) // CHECK: [[S:%.*]] = tuple () // CHECK: return [[S]] : $() // CHECK: } func unsafeGuaranteedEnd(_ t: Builtin.Int8) { Builtin.unsafeGuaranteedEnd(t) } // CHECK-LABEL: sil hidden @$s8builtins10bindMemory{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[P:%.*]] : @trivial $Builtin.RawPointer, [[I:%.*]] : @trivial $Builtin.Word, [[T:%.*]] : @trivial $@thick T.Type): // CHECK: bind_memory [[P]] : $Builtin.RawPointer, [[I]] : $Builtin.Word to $*T // CHECK: return {{%.*}} : $() // CHECK: } func bindMemory<T>(ptr: Builtin.RawPointer, idx: Builtin.Word, _: T.Type) { Builtin.bindMemory(ptr, idx, T.self) } //===----------------------------------------------------------------------===// // RC Operations //===----------------------------------------------------------------------===// // SILGen test: // // CHECK-LABEL: sil hidden @$s8builtins6retain{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () { // CHECK: bb0([[P:%.*]] : @guaranteed $Builtin.NativeObject): // CHECK: unmanaged_retain_value [[P]] // CHECK: } // end sil function '$s8builtins6retain{{[_0-9a-zA-Z]*}}F' // SIL Test. This makes sure that we properly clean up in -Onone SIL. // CANONICAL-LABEL: sil hidden @$s8builtins6retain{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () { // CANONICAL: bb0([[P:%.*]] : $Builtin.NativeObject): // CANONICAL: strong_retain [[P]] // CANONICAL-NOT: retain // CANONICAL-NOT: release // CANONICAL: } // end sil function '$s8builtins6retain{{[_0-9a-zA-Z]*}}F' func retain(ptr: Builtin.NativeObject) { Builtin.retain(ptr) } // SILGen test: // // CHECK-LABEL: sil hidden @$s8builtins7release{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () { // CHECK: bb0([[P:%.*]] : @guaranteed $Builtin.NativeObject): // CHECK: unmanaged_release_value [[P]] // CHECK-NOT: destroy_value [[P]] // CHECK: } // end sil function '$s8builtins7release{{[_0-9a-zA-Z]*}}F' // SIL Test. Make sure even in -Onone code, we clean this up properly: // CANONICAL-LABEL: sil hidden @$s8builtins7release{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@guaranteed Builtin.NativeObject) -> () { // CANONICAL: bb0([[P:%.*]] : $Builtin.NativeObject): // CANONICAL-NEXT: debug_value // CANONICAL-NEXT: strong_release [[P]] // CANONICAL-NEXT: tuple // CANONICAL-NEXT: tuple // CANONICAL-NEXT: return // CANONICAL: } // end sil function '$s8builtins7release{{[_0-9a-zA-Z]*}}F' func release(ptr: Builtin.NativeObject) { Builtin.release(ptr) } //===----------------------------------------------------------------------===// // Other Operations //===----------------------------------------------------------------------===// func once_helper() {} // CHECK-LABEL: sil hidden @$s8builtins4once7controlyBp_tF // CHECK: [[T0:%.*]] = function_ref @$s8builtins11once_helperyyFTo : $@convention(c) () -> () // CHECK-NEXT: builtin "once"(%0 : $Builtin.RawPointer, [[T0]] : $@convention(c) () -> ()) func once(control: Builtin.RawPointer) { Builtin.once(control, once_helper) } // CHECK-LABEL: sil hidden @$s8builtins19valueToBridgeObjectyBbSuF : $@convention(thin) (UInt) -> @owned Builtin.BridgeObject { // CHECK: bb0([[UINT:%.*]] : @trivial $UInt): // CHECK: [[CAST:%.*]] = value_to_bridge_object [[UINT]] : $UInt // CHECK: [[RET:%.*]] = copy_value [[CAST]] : $Builtin.BridgeObject // CHECK: return [[RET]] : $Builtin.BridgeObject // CHECK: } // end sil function '$s8builtins19valueToBridgeObjectyBbSuF' func valueToBridgeObject(_ x: UInt) -> Builtin.BridgeObject { return Builtin.valueToBridgeObject(x) } // CHECK-LABEL: sil hidden @$s8builtins10assumeTrueyyBi1_F // CHECK: builtin "assume_Int1"({{.*}} : $Builtin.Int1) // CHECK: return func assumeTrue(_ x: Builtin.Int1) { Builtin.assume_Int1(x) }
apache-2.0
62bc7f9d07bafb6770363d89abf87dad
40.643118
193
0.625494
3.211139
false
false
false
false
fuku2014/spritekit-original-game
src/libs/chatview/src/ChatModel.swift
1
1319
import UIKit enum NSBubbleType { case BubbleTypeMine case BubbleTypeSomeoneElse } let textInsetsMine : UIEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 11, right: 17) let textInsetsSomeone : UIEdgeInsets = UIEdgeInsets(top: 5, left: 15, bottom: 11, right: 10) class ChatModel: NSObject { var type : NSBubbleType var view : UIView var insets : UIEdgeInsets init(view : UIView, type : NSBubbleType, insets : UIEdgeInsets) { self.view = view self.type = type self.insets = insets super.init() } convenience init(text : String, type : NSBubbleType) { let font : UIFont = UIFont.systemFontOfSize(UIFont.systemFontSize()) let size : CGSize = CGSizeMake(220, 9999) let label : UILabel = UILabel(frame: CGRectMake(0, 0, size.width, size.height)) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.ByWordWrapping label.text = text label.font = font label.backgroundColor = UIColor.clearColor() label.sizeToFit() let insets : UIEdgeInsets = (type == NSBubbleType.BubbleTypeMine ? textInsetsMine : textInsetsSomeone) self.init(view: label, type: type, insets: insets) } }
apache-2.0
87cae9ff3734730338a075012c8f39ab
32.820513
110
0.623958
4.32459
false
false
false
false
lotpb/iosSQLswift
mySQLswift/CollectionViewCell.swift
1
9431
// // CCollectionViewCell.swift // mySQLswift // // Created by Peter Balsamo on 12/17/15. // Copyright © 2015 Peter Balsamo. All rights reserved. // import UIKit import Parse class CollectionViewCell: UICollectionViewCell { //-----------youtube--------- override init(frame: CGRect) { super.init(frame: frame) setupViews() } func setupViews() { } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) //fatalError("init(coder:) has not been implemented") } //--------------------------------- // News @IBOutlet weak var imageView: UIImageView? @IBOutlet weak var profileView: UIImageView? @IBOutlet weak var titleLabel: UILabel? @IBOutlet weak var sourceLabel: UILabel? @IBOutlet weak var likeButton: UIButton? @IBOutlet weak var actionBtn: UIButton? @IBOutlet weak var numLabel: UILabel? @IBOutlet weak var uploadbyLabel: UILabel? // Snapshot Controller / UserView Controller @IBOutlet weak var user2ImageView: UIImageView? // Snapshot Controller / UserView Controller @IBOutlet weak var loadingSpinner: UIActivityIndicatorView? override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = 5.0 self.clipsToBounds = true } } class VideoCell: CollectionViewCell { var video: Video? { didSet { } } let thumbnailImageView: CustomImageView = { let imageView = CustomImageView() imageView.userInteractionEnabled = true imageView.backgroundColor = UIColor.blackColor() imageView.image = UIImage(named: "taylor_swift_blank_space") imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true return imageView }() let userProfileImageView: CustomImageView = { let imageView = CustomImageView() imageView.image = UIImage(named: "taylor_swift_profile") imageView.layer.cornerRadius = 22 imageView.layer.masksToBounds = true imageView.contentMode = .ScaleAspectFill //cell.profileView?.layer.cornerRadius = (cell.profileView?.frame.size.width)! / 2 imageView.layer.borderColor = UIColor.lightGrayColor().CGColor imageView.layer.borderWidth = 0.5 imageView.userInteractionEnabled = true //cell.profileView?.tag = indexPath.row return imageView }() let separatorView: UIView = { let view = UIView() view.backgroundColor = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1) return view }() let titleLabelnew: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Taylor Swift - Blank Space" label.numberOfLines = 2 return label }() let subtitlelabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "TaylorSwiftVEVO • 1,604,684,607 views • 2 years ago" label.textColor = UIColor.lightGrayColor() return label }() let actionButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.tintColor = UIColor.lightGrayColor() let imagebutton : UIImage? = UIImage(named:"nav_more_icon.png")!.imageWithRenderingMode(.AlwaysTemplate) button.setImage(imagebutton, forState: .Normal) return button }() let likeButt: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.tintColor = UIColor.lightGrayColor() let imagebutton : UIImage? = UIImage(named:"Thumb Up.png")!.imageWithRenderingMode(.AlwaysTemplate) button.setImage(imagebutton, forState: .Normal) return button }() let numberLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "10" label.textColor = UIColor.blueColor() return label }() let uploadbylabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Uploaded by:" return label }() var titleLabelHeightConstraint: NSLayoutConstraint? override func setupViews() { addSubview(thumbnailImageView) addSubview(separatorView) addSubview(userProfileImageView) addSubview(titleLabelnew) addSubview(subtitlelabel) addSubview(actionButton) addSubview(likeButt) addSubview(numberLabel) addSubview(uploadbylabel) addConstraintsWithFormat("H:|-16-[v0]-16-|", views: thumbnailImageView) addConstraintsWithFormat("H:|-16-[v0(44)]", views: userProfileImageView) addConstraintsWithFormat("H:|-16-[v0(25)]", views: actionButton) //vertical constraints addConstraintsWithFormat("V:|-16-[v0]-8-[v1(44)]-21-[v2(25)]-10-[v3(1)]|", views: thumbnailImageView, userProfileImageView, actionButton, separatorView) addConstraintsWithFormat("H:|[v0]|", views: separatorView) //top constraint addConstraint(NSLayoutConstraint(item: titleLabelnew, attribute: .Top, relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Bottom, multiplier: 1, constant: 6)) //left constraint addConstraint(NSLayoutConstraint(item: titleLabelnew, attribute: .Left, relatedBy: .Equal, toItem: userProfileImageView, attribute: .Right, multiplier: 1, constant: 8)) //right constraint addConstraint(NSLayoutConstraint(item: titleLabelnew, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Right, multiplier: 1, constant: 0)) //height constraint titleLabelHeightConstraint = NSLayoutConstraint(item: titleLabelnew, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0, constant: 44) addConstraint(titleLabelHeightConstraint!) //top constraint addConstraint(NSLayoutConstraint(item: subtitlelabel, attribute: .Top, relatedBy: .Equal, toItem: titleLabelnew, attribute: .Bottom, multiplier: 1, constant: 1)) //left constraint addConstraint(NSLayoutConstraint(item: subtitlelabel, attribute: .Left, relatedBy: .Equal, toItem: userProfileImageView, attribute: .Right, multiplier: 1, constant: 8)) //right constraint addConstraint(NSLayoutConstraint(item: subtitlelabel, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Right, multiplier: 1, constant: 0)) //height constraint addConstraint(NSLayoutConstraint(item: subtitlelabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0, constant: 21)) //top constraint addConstraint(NSLayoutConstraint(item: likeButt, attribute: .Top, relatedBy: .Equal, toItem: subtitlelabel, attribute: .Bottom, multiplier: 1, constant: 1)) //left constraint addConstraint(NSLayoutConstraint(item: likeButt, attribute: .Left, relatedBy: .Equal, toItem: actionButton, attribute: .Right, multiplier: 1, constant: 12)) //right constraint //addConstraint(NSLayoutConstraint(item: likeButt, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Right, multiplier: 1, constant: 0)) //height constraint addConstraint(NSLayoutConstraint(item: likeButt, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0, constant: 25)) //top constraint addConstraint(NSLayoutConstraint(item: numberLabel, attribute: .Top, relatedBy: .Equal, toItem: subtitlelabel, attribute: .Bottom, multiplier: 1, constant: 1)) //left constraint addConstraint(NSLayoutConstraint(item: numberLabel, attribute: .Left, relatedBy: .Equal, toItem: likeButt, attribute: .Right, multiplier: 1, constant: 1)) //right constraint //addConstraint(NSLayoutConstraint(item: numberLabel, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Right, multiplier: 1, constant: 0)) //height constraint addConstraint(NSLayoutConstraint(item: numberLabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0, constant: 25)) //top constraint addConstraint(NSLayoutConstraint(item: uploadbylabel, attribute: .Top, relatedBy: .Equal, toItem: subtitlelabel, attribute: .Bottom, multiplier: 1, constant: 1)) //left constraint addConstraint(NSLayoutConstraint(item: uploadbylabel, attribute: .Left, relatedBy: .Equal, toItem: numberLabel, attribute: .Right, multiplier: 1, constant: 5)) //right constraint //addConstraint(NSLayoutConstraint(item: uploadbylabel, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Right, multiplier: 1, constant: 0)) //height constraint addConstraint(NSLayoutConstraint(item: uploadbylabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0, constant: 25)) } }
gpl-2.0
4c67438e7711400f25552fa77bc7b6b2
42.638889
178
0.670274
5.021843
false
false
false
false
jopamer/swift
stdlib/public/core/Sort.swift
1
21511
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // sorted()/sort() //===----------------------------------------------------------------------===// extension Sequence where Element: Comparable { /// Returns the elements of the sequence, sorted. /// /// You can sort any sequence of elements that conform to the `Comparable` /// protocol by calling this method. Elements are sorted in ascending order. /// /// The sorting algorithm is not stable. A nonstable sort may change the /// relative order of elements that compare equal. /// /// Here's an example of sorting a list of students' names. Strings in Swift /// conform to the `Comparable` protocol, so the names are sorted in /// ascending order according to the less-than operator (`<`). /// /// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// let sortedStudents = students.sorted() /// print(sortedStudents) /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" /// /// To sort the elements of your sequence in descending order, pass the /// greater-than operator (`>`) to the `sorted(by:)` method. /// /// let descendingStudents = students.sorted(by: >) /// print(descendingStudents) /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" /// /// - Returns: A sorted array of the sequence's elements. /// /// - Complexity: O(*n* log *n*), where *n* is the length of the sequence. @inlinable public func sorted() -> [Element] { var result = ContiguousArray(self) result.sort() return Array(result) } } extension Sequence { /// Returns the elements of the sequence, sorted using the given predicate as /// the comparison between elements. /// /// When you want to sort a sequence of elements that don't conform to the /// `Comparable` protocol, pass a predicate to this method that returns /// `true` when the first element passed should be ordered before the /// second. The elements of the resulting array are ordered according to the /// given predicate. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also `true`. /// (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// The sorting algorithm is not stable. A nonstable sort may change the /// relative order of elements for which `areInIncreasingOrder` does not /// establish an order. /// /// In the following example, the predicate provides an ordering for an array /// of a custom `HTTPResponse` type. The predicate orders errors before /// successes and sorts the error responses by their error code. /// /// enum HTTPResponse { /// case ok /// case error(Int) /// } /// /// let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)] /// let sortedResponses = responses.sorted { /// switch ($0, $1) { /// // Order errors by code /// case let (.error(aCode), .error(bCode)): /// return aCode < bCode /// /// // All successes are equivalent, so none is before any other /// case (.ok, .ok): return false /// /// // Order errors before successes /// case (.error, .ok): return true /// case (.ok, .error): return false /// } /// } /// print(sortedResponses) /// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]" /// /// You also use this method to sort elements that conform to the /// `Comparable` protocol in descending order. To sort your sequence in /// descending order, pass the greater-than operator (`>`) as the /// `areInIncreasingOrder` parameter. /// /// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// let descendingStudents = students.sorted(by: >) /// print(descendingStudents) /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" /// /// Calling the related `sorted()` method is equivalent to calling this /// method and passing the less-than operator (`<`) as the predicate. /// /// print(students.sorted()) /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" /// print(students.sorted(by: <)) /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; /// otherwise, `false`. /// - Returns: A sorted array of the sequence's elements. /// /// - Complexity: O(*n* log *n*), where *n* is the length of the sequence. @inlinable public func sorted( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray(self) try result.sort(by: areInIncreasingOrder) return Array(result) } } extension MutableCollection where Self: RandomAccessCollection, Element: Comparable { /// Sorts the collection in place. /// /// You can sort any mutable collection of elements that conform to the /// `Comparable` protocol by calling this method. Elements are sorted in /// ascending order. /// /// The sorting algorithm is not stable. A nonstable sort may change the /// relative order of elements that compare equal. /// /// Here's an example of sorting a list of students' names. Strings in Swift /// conform to the `Comparable` protocol, so the names are sorted in /// ascending order according to the less-than operator (`<`). /// /// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// students.sort() /// print(students) /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" /// /// To sort the elements of your collection in descending order, pass the /// greater-than operator (`>`) to the `sort(by:)` method. /// /// students.sort(by: >) /// print(students) /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" /// /// - Complexity: O(*n* log *n*), where *n* is the length of the collection. @inlinable public mutating func sort() { let didSortUnsafeBuffer = _withUnsafeMutableBufferPointerIfSupported { buffer -> Void? in buffer.sort() } if didSortUnsafeBuffer == nil { _introSort(&self, subRange: startIndex..<endIndex, by: <) } } } extension MutableCollection where Self: RandomAccessCollection { /// Sorts the collection in place, using the given predicate as the /// comparison between elements. /// /// When you want to sort a collection of elements that doesn't conform to /// the `Comparable` protocol, pass a closure to this method that returns /// `true` when the first element passed should be ordered before the /// second. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also `true`. /// (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// The sorting algorithm is not stable. A nonstable sort may change the /// relative order of elements for which `areInIncreasingOrder` does not /// establish an order. /// /// In the following example, the closure provides an ordering for an array /// of a custom enumeration that describes an HTTP response. The predicate /// orders errors before successes and sorts the error responses by their /// error code. /// /// enum HTTPResponse { /// case ok /// case error(Int) /// } /// /// var responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)] /// responses.sort { /// switch ($0, $1) { /// // Order errors by code /// case let (.error(aCode), .error(bCode)): /// return aCode < bCode /// /// // All successes are equivalent, so none is before any other /// case (.ok, .ok): return false /// /// // Order errors before successes /// case (.error, .ok): return true /// case (.ok, .error): return false /// } /// } /// print(responses) /// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]" /// /// Alternatively, use this method to sort a collection of elements that do /// conform to `Comparable` when you want the sort to be descending instead /// of ascending. Pass the greater-than operator (`>`) operator as the /// predicate. /// /// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// students.sort(by: >) /// print(students) /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; /// otherwise, `false`. If `areInIncreasingOrder` throws an error during /// the sort, the elements may be in a different order, but none will be /// lost. /// /// - Complexity: O(*n* log *n*), where *n* is the length of the collection. @inlinable public mutating func sort( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows { let didSortUnsafeBuffer = try _withUnsafeMutableBufferPointerIfSupported { buffer -> Void? in try buffer.sort(by: areInIncreasingOrder) } if didSortUnsafeBuffer == nil { try _introSort( &self, subRange: startIndex..<endIndex, by: areInIncreasingOrder) } } } @inlinable internal func _insertionSort<C: MutableCollection & BidirectionalCollection>( _ elements: inout C, subRange range: Range<C.Index>, by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool ) rethrows { if !range.isEmpty { let start = range.lowerBound // Keep track of the end of the initial sequence of sorted // elements. var sortedEnd = start // One element is trivially already-sorted, thus pre-increment // Continue until the sorted elements cover the whole sequence elements.formIndex(after: &sortedEnd) while sortedEnd != range.upperBound { // get the first unsorted element let x: C.Element = elements[sortedEnd] // Look backwards for x's position in the sorted sequence, // moving elements forward to make room. var i = sortedEnd repeat { let predecessor: C.Element = elements[elements.index(before: i)] // If clouser throws the error, We catch the error put the element at right // place and rethrow the error. do { // if x doesn't belong before y, we've found its position if !(try areInIncreasingOrder(x, predecessor)) { break } } catch { elements[i] = x throw error } // Move y forward elements[i] = predecessor elements.formIndex(before: &i) } while i != start if i != sortedEnd { // Plop x into position elements[i] = x } elements.formIndex(after: &sortedEnd) } } } /// Sorts the elements at `elements[a]`, `elements[b]`, and `elements[c]`. /// Stable. /// /// The indices passed as `a`, `b`, and `c` do not need to be consecutive, but /// must be in strict increasing order. /// /// - Precondition: `a < b && b < c` /// - Postcondition: `elements[a] <= elements[b] && elements[b] <= elements[c]` @inlinable public // @testable func _sort3<C: MutableCollection & RandomAccessCollection>( _ elements: inout C, _ a: C.Index, _ b: C.Index, _ c: C.Index, by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool ) rethrows { // There are thirteen possible permutations for the original ordering of // the elements at indices `a`, `b`, and `c`. The comments in the code below // show the relative ordering of the three elements using a three-digit // number as shorthand for the position and comparative relationship of // each element. For example, "312" indicates that the element at `a` is the // largest of the three, the element at `b` is the smallest, and the element // at `c` is the median. This hypothetical input array has a 312 ordering for // `a`, `b`, and `c`: // // [ 7, 4, 3, 9, 2, 0, 3, 7, 6, 5 ] // ^ ^ ^ // a b c // // - If each of the three elements is distinct, they could be ordered as any // of the permutations of 1, 2, and 3: 123, 132, 213, 231, 312, or 321. // - If two elements are equivalent and one is distinct, they could be // ordered as any permutation of 1, 1, and 2 or 1, 2, and 2: 112, 121, 211, // 122, 212, or 221. // - If all three elements are equivalent, they are already in order: 111. switch ((try areInIncreasingOrder(elements[b], elements[a])), (try areInIncreasingOrder(elements[c], elements[b]))) { case (false, false): // 0 swaps: 123, 112, 122, 111 break case (true, true): // 1 swap: 321 // swap(a, c): 312->123 elements.swapAt(a, c) case (true, false): // 1 swap: 213, 212 --- 2 swaps: 312, 211 // swap(a, b): 213->123, 212->122, 312->132, 211->121 elements.swapAt(a, b) if (try areInIncreasingOrder(elements[c], elements[b])) { // 132 (started as 312), 121 (started as 211) // swap(b, c): 132->123, 121->112 elements.swapAt(b, c) } case (false, true): // 1 swap: 132, 121 --- 2 swaps: 231, 221 // swap(b, c): 132->123, 121->112, 231->213, 221->212 elements.swapAt(b, c) if (try areInIncreasingOrder(elements[b], elements[a])) { // 213 (started as 231), 212 (started as 221) // swap(a, b): 213->123, 212->122 elements.swapAt(a, b) } } } /// Reorders `elements` and returns an index `p` such that every element in /// `elements[range.lowerBound..<p]` is less than every element in /// `elements[p..<range.upperBound]`. /// /// - Precondition: The count of `range` must be >= 3: /// `elements.distance(from: range.lowerBound, to: range.upperBound) >= 3` @inlinable internal func _partition<C: MutableCollection & RandomAccessCollection>( _ elements: inout C, subRange range: Range<C.Index>, by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool ) rethrows -> C.Index { var lo = range.lowerBound var hi = elements.index(before: range.upperBound) // Sort the first, middle, and last elements, then use the middle value // as the pivot for the partition. let half = numericCast(elements.distance(from: lo, to: hi)) as UInt / 2 let mid = elements.index(lo, offsetBy: numericCast(half)) try _sort3(&elements, lo, mid, hi , by: areInIncreasingOrder) let pivot = elements[mid] // Loop invariants: // * lo < hi // * elements[i] < pivot, for i in range.lowerBound..<lo // * pivot <= elements[i] for i in hi..<range.upperBound Loop: while true { FindLo: do { elements.formIndex(after: &lo) while lo != hi { if !(try areInIncreasingOrder(elements[lo], pivot)) { break FindLo } elements.formIndex(after: &lo) } break Loop } FindHi: do { elements.formIndex(before: &hi) while hi != lo { if (try areInIncreasingOrder(elements[hi], pivot)) { break FindHi } elements.formIndex(before: &hi) } break Loop } elements.swapAt(lo, hi) } return lo } @inlinable public // @testable func _introSort<C: MutableCollection & RandomAccessCollection>( _ elements: inout C, subRange range: Range<C.Index> , by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool ) rethrows { let count = elements.distance(from: range.lowerBound, to: range.upperBound) if count < 2 { return } // Set max recursion depth to 2*floor(log(N)), as suggested in the introsort // paper: http://www.cs.rpi.edu/~musser/gp/introsort.ps let depthLimit = 2 * count._binaryLogarithm() try _introSortImpl( &elements, subRange: range, by: areInIncreasingOrder, depthLimit: depthLimit) } @inlinable internal func _introSortImpl<C: MutableCollection & RandomAccessCollection>( _ elements: inout C, subRange range: Range<C.Index> , by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool, depthLimit: Int ) rethrows { // Insertion sort is better at handling smaller regions. if elements.distance(from: range.lowerBound, to: range.upperBound) < 20 { try _insertionSort( &elements, subRange: range , by: areInIncreasingOrder) return } if depthLimit == 0 { try _heapSort( &elements, subRange: range , by: areInIncreasingOrder) return } // Partition and sort. // We don't check the depthLimit variable for underflow because this variable // is always greater than zero (see check above). let partIdx: C.Index = try _partition( &elements, subRange: range , by: areInIncreasingOrder) try _introSortImpl( &elements, subRange: range.lowerBound..<partIdx, by: areInIncreasingOrder, depthLimit: depthLimit &- 1) try _introSortImpl( &elements, subRange: partIdx..<range.upperBound, by: areInIncreasingOrder, depthLimit: depthLimit &- 1) } @inlinable internal func _siftDown<C: MutableCollection & RandomAccessCollection>( _ elements: inout C, index: C.Index, subRange range: Range<C.Index>, by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool ) rethrows { let countToIndex = elements.distance(from: range.lowerBound, to: index) let countFromIndex = elements.distance(from: index, to: range.upperBound) // Check if left child is within bounds. If not, return, because there are // no children of the given node in the heap. if countToIndex + 1 >= countFromIndex { return } let left = elements.index(index, offsetBy: countToIndex + 1) var largest = index if (try areInIncreasingOrder(elements[largest], elements[left])) { largest = left } // Check if right child is also within bounds before trying to examine it. if countToIndex + 2 < countFromIndex { let right = elements.index(after: left) if (try areInIncreasingOrder(elements[largest], elements[right])) { largest = right } } // If a child is bigger than the current node, swap them and continue sifting // down. if largest != index { elements.swapAt(index, largest) try _siftDown( &elements, index: largest, subRange: range , by: areInIncreasingOrder) } } @inlinable internal func _heapify<C: MutableCollection & RandomAccessCollection>( _ elements: inout C, subRange range: Range<C.Index>, by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool ) rethrows { // Here we build a heap starting from the lowest nodes and moving to the root. // On every step we sift down the current node to obey the max-heap property: // parent >= max(leftChild, rightChild) // // We skip the rightmost half of the array, because these nodes don't have // any children. let root = range.lowerBound var node = elements.index( root, offsetBy: elements.distance( from: range.lowerBound, to: range.upperBound) / 2) while node != root { elements.formIndex(before: &node) try _siftDown( &elements, index: node, subRange: range , by: areInIncreasingOrder) } } @inlinable internal func _heapSort<C: MutableCollection & RandomAccessCollection>( _ elements: inout C, subRange range: Range<C.Index> , by areInIncreasingOrder: (C.Element, C.Element) throws -> Bool ) rethrows { var hi = range.upperBound let lo = range.lowerBound try _heapify(&elements, subRange: range, by: areInIncreasingOrder) elements.formIndex(before: &hi) while hi != lo { elements.swapAt(lo, hi) try _siftDown(&elements, index: lo, subRange: lo..<hi, by: areInIncreasingOrder) elements.formIndex(before: &hi) } }
apache-2.0
46c553e8f46d93065d14afa1c1e70124
35.213805
91
0.627725
3.985733
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCryptoDomain/Sources/FeatureCryptoDomainData/Repositories/SearchDomainRepository.swift
1
1616
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import FeatureCryptoDomainDomain import Foundation import OrderedCollections public final class SearchDomainRepository: SearchDomainRepositoryAPI { // MARK: - Properties private let apiClient: SearchDomainClientAPI // MARK: - Setup public init(apiClient: SearchDomainClientAPI) { self.apiClient = apiClient } public func searchResults( searchKey: String, freeOnly: Bool ) -> AnyPublisher<[SearchDomainResult], SearchDomainRepositoryError> { if freeOnly { return apiClient .getFreeSearchResults(searchKey: searchKey) .map { response in let suggestions = response.suggestions.map(SearchDomainResult.init) let results = OrderedSet(suggestions) return Array(results) } .mapError(SearchDomainRepositoryError.networkError) .eraseToAnyPublisher() } else { return apiClient .getSearchResults(searchKey: searchKey) .map { response in let searchedDomain = SearchDomainResult(from: response.searchedDomain) let suggestions = response.suggestions.map(SearchDomainResult.init) let results = OrderedSet([searchedDomain] + suggestions) return Array(results) } .mapError(SearchDomainRepositoryError.networkError) .eraseToAnyPublisher() } } }
lgpl-3.0
3c2bb4411bd0f8cc0b53060a6b36a004
33.361702
90
0.613003
5.851449
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00130-swift-lexer-leximpl.swift
11
2293
// 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 // RUN: not %target-swift-frontend %s -parse k) func yx<jih>() -> (jih, jih -> jih) -> jih { cb n cb.x = { } { jih) { vu } } protocol yx { class func x() } class cb: yx{ class func x {} ih k<ut> { po vu(ut, () -> ()) } func n<cb { ih n { func k ml _ = k } } class dcb { typealias po = po } func dcb<ut>() { v> : jih { func po(po: ji.ay) { } } func dcb<k: kji, ut ts qp<ut> == k.s.n>(w : k) -> ut? { wv (po : ut?) in w { rq let cb = po { u cb } } u cb } let w : [r?] = [cb, ihg, cb] xw(dcb(w)) func yx<ut : sr>(po: ut) { } yx(l dc sr) func dcb(po: r = hg) { } let n = dcb n() on n<cb : kji> { ml po: cb } func dcb<cb>() -> [n<cb>] { u [] } protocol jih { typealias nm } class vu<lk> { edc <jih: jih ts jih.nm == lk>(k: jih.nm) { } } func x(n: () -> ()) { } class dcb { ml _ = x() { } } protocol jih { typealias gfe } on nm<ut : jih> { let vu: ut let x: ut.gfe } protocol vu { typealias ba func jih<ut ts ut.gfe == ba>(yx: nm<ut>) } on lk : vu { typealias ba = r func jih<ut ts ut.gfe == ba>(yx: nm<ut>) { } } class jih: jih { } class nm : vu { } typealias vu = nm func ^(dcb: sr, o) -> o { u !(dcb) } func dcb(cb: ed, ut: ed) -> (((ed, ed) -> ed) -> ed) { u { (gfe: (ed, ed) -> ed) -> ed in u gfe(cb, ut) } } func po(t: (((ed, ed) -> ed) -> ed)) -> ed { u t({ (s: ed, nm:ed) -> ed in u s }) } po(dcb(fed, dcb(fe, gf))) on jih<ut> { let dcb: [(ut, () -> ())] = [] } po protocol n : po { func po class dcb<yx : po, jih : po ts yx.cb == jih> { } protocol po { typealias cb typealias k } on n<vu : po> : po { typealias jih } class n { func po((ed, n))(dcb: (ed, kj)) { po(dcb) } } class jih<ut : jih> { } ml x = fed ml hgf: r -> r = { u $hg } let yx: r = { (cb: r, yx: r -> r) -> r in u yx(cb) }
apache-2.0
66597c708d1c3b65f8fee24ad5c66b6e
15.615942
78
0.485826
2.455032
false
false
false
false
swiftingio/architecture-wars-mvc
MyCards/MyCards/UITextField+Extension.swift
1
406
// // UITextField+Extension.swift // MyCards // // Created by Maciej Piotrowski on 03/02/17. // import UIKit extension UITextField { class func makeNameField() -> UITextField { let name = UITextField() name.autocorrectionType = .no name.autocapitalizationType = .none name.placeholder = .EnterCardName name.returnKeyType = .done return name } }
mit
c680818969c172b7d305c92e2a36c916
20.368421
47
0.640394
4.273684
false
false
false
false
remypanicker/firefox-ios
Client/Application/WebServer.swift
7
3018
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation private let WebServerSharedInstance = WebServer() class WebServer { class var sharedInstance: WebServer { return WebServerSharedInstance } let server: GCDWebServer = GCDWebServer() var base: String { return "http://localhost:\(server.port)" } func start() -> Bool { if !server.running { try! server.startWithOptions([GCDWebServerOption_Port: 0, GCDWebServerOption_BindToLocalhost: true, GCDWebServerOption_AutomaticallySuspendInBackground: false]) } return server.running } /// Convenience method to register a dynamic handler. Will be mounted at $base/$module/$resource func registerHandlerForMethod(method: String, module: String, resource: String, handler: (request: GCDWebServerRequest!) -> GCDWebServerResponse!) { server.addHandlerForMethod(method, path: "/\(module)/\(resource)", requestClass: GCDWebServerRequest.self, processBlock: handler) } /// Convenience method to register a resource in the main bundle. Will be mounted at $base/$module/$resource func registerMainBundleResource(resource: String, module: String) { if let path = NSBundle.mainBundle().pathForResource(resource, ofType: nil) { server.addGETHandlerForPath("/\(module)/\(resource)", filePath: path, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true) } } /// Convenience method to register all resources in the main bundle of a specific type. Will be mounted at $base/$module/$resource func registerMainBundleResourcesOfType(type: String, module: String) { for path: NSString in NSBundle.pathsForResourcesOfType(type, inDirectory: NSBundle.mainBundle().bundlePath) { let resource = path.lastPathComponent server.addGETHandlerForPath("/\(module)/\(resource)", filePath: path as String, isAttachment: false, cacheAge: UInt.max, allowRangeRequests: true) } } /// Return a full url, as a string, for a resource in a module. No check is done to find out if the resource actually exist. func URLForResource(resource: String, module: String) -> String { return "\(base)/\(module)/\(resource)" } /// Return a full url, as an NSURL, for a resource in a module. No check is done to find out if the resource actually exist. func URLForResource(resource: String, module: String) -> NSURL { return NSURL(string: "\(base)/\(module)/\(resource)")! } func updateLocalURL(url: NSURL) -> NSURL? { let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) if components?.host == "localhost" && components?.scheme == "http" { components?.port = WebServer.sharedInstance.server.port } return components?.URL } }
mpl-2.0
1793688dfad6d039a9a7c435887ae67f
46.171875
172
0.690855
4.723005
false
false
false
false
tjw/swift
stdlib/private/StdlibCollectionUnittest/CheckCollectionType.swift
1
82402
//===----------------------------------------------------------------------===// // // 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 StdlibUnittest internal var checksAdded: Set<String> = [] public struct SubscriptRangeTest { public let expected: [OpaqueValue<Int>] public let collection: [OpaqueValue<Int>] public let bounds: Range<Int> public let count: Int public let loc: SourceLoc public var isEmpty: Bool { return count == 0 } public func bounds<C : Collection>(in c: C) -> Range<C.Index> { let i = c.startIndex return c.index(i, offsetBy: numericCast(bounds.lowerBound)) ..< c.index(i, offsetBy: numericCast(bounds.upperBound)) } public init( expected: [Int], collection: [Int], bounds: Range<Int>, count: Int, file: String = #file, line: UInt = #line ) { self.expected = expected.map(OpaqueValue.init) self.collection = collection.map(OpaqueValue.init) self.bounds = bounds self.count = count self.loc = SourceLoc(file, line, comment: "test data") } } public struct PrefixThroughTest { public var collection: [Int] public let position: Int public let expected: [Int] public let loc: SourceLoc init( collection: [Int], position: Int, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection self.position = position self.expected = expected self.loc = SourceLoc(file, line, comment: "prefix(through:) test data") } } public struct PrefixUpToTest { public var collection: [Int] public let end: Int public let expected: [Int] public let loc: SourceLoc public init( collection: [Int], end: Int, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection self.end = end self.expected = expected self.loc = SourceLoc(file, line, comment: "prefix(upTo:) test data") } } internal struct RemoveFirstNTest { let collection: [Int] let numberToRemove: Int let expectedCollection: [Int] let loc: SourceLoc init( collection: [Int], numberToRemove: Int, expectedCollection: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection self.numberToRemove = numberToRemove self.expectedCollection = expectedCollection self.loc = SourceLoc(file, line, comment: "removeFirst(n: Int) test data") } } public struct SuffixFromTest { public var collection: [Int] public let start: Int public let expected: [Int] public let loc: SourceLoc init( collection: [Int], start: Int, expected: [Int], file: String = #file, line: UInt = #line ) { self.collection = collection self.start = start self.expected = expected self.loc = SourceLoc(file, line, comment: "suffix(from:) test data") } } public let subscriptRangeTests = [ // Slice an empty collection. SubscriptRangeTest( expected: [], collection: [], bounds: 0..<0, count: 0), // Slice to the full extent. SubscriptRangeTest( expected: [1010], collection: [1010], bounds: 0..<1, count: 1), SubscriptRangeTest( expected: [1010, 2020, 3030], collection: [1010, 2020, 3030], bounds: 0..<3, count: 3), SubscriptRangeTest( expected: [1010, 2020, 3030, 4040, 5050], collection: [1010, 2020, 3030, 4040, 5050], bounds: 0..<5, count: 5), // Slice an empty prefix. SubscriptRangeTest( expected: [], collection: [1010, 2020, 3030], bounds: 0..<0, count: 3), // Slice a prefix. SubscriptRangeTest( expected: [1010, 2020], collection: [1010, 2020, 3030], bounds: 0..<2, count: 3), SubscriptRangeTest( expected: [1010, 2020], collection: [1010, 2020, 3030, 4040, 5050], bounds: 0..<2, count: 5), // Slice an empty suffix. SubscriptRangeTest( expected: [], collection: [1010, 2020, 3030], bounds: 3..<3, count: 3), // Slice a suffix. SubscriptRangeTest( expected: [2020, 3030], collection: [1010, 2020, 3030], bounds: 1..<3, count: 3), SubscriptRangeTest( expected: [4040, 5050], collection: [1010, 2020, 3030, 4040, 5050], bounds: 3..<5, count: 5), // Slice an empty range in the middle. SubscriptRangeTest( expected: [], collection: [1010, 2020, 3030], bounds: 1..<1, count: 3), SubscriptRangeTest( expected: [], collection: [1010, 2020, 3030], bounds: 2..<2, count: 3), // Slice the middle part. SubscriptRangeTest( expected: [2020], collection: [1010, 2020, 3030], bounds: 1..<2, count: 3), SubscriptRangeTest( expected: [3030], collection: [1010, 2020, 3030, 4040], bounds: 2..<3, count: 4), SubscriptRangeTest( expected: [2020, 3030, 4040], collection: [1010, 2020, 3030, 4040, 5050, 6060], bounds: 1..<4, count: 6), ] public let prefixUpToTests = [ PrefixUpToTest( collection: [], end: 0, expected: [] ), PrefixUpToTest( collection: [1010, 2020, 3030, 4040, 5050], end: 3, expected: [1010, 2020, 3030] ), PrefixUpToTest( collection: [1010, 2020, 3030, 4040, 5050], end: 5, expected: [1010, 2020, 3030, 4040, 5050] ), ] public let prefixThroughTests = [ PrefixThroughTest( collection: [1010, 2020, 3030, 4040, 5050], position: 0, expected: [1010] ), PrefixThroughTest( collection: [1010, 2020, 3030, 4040, 5050], position: 2, expected: [1010, 2020, 3030] ), PrefixThroughTest( collection: [1010, 2020, 3030, 4040, 5050], position: 4, expected: [1010, 2020, 3030, 4040, 5050] ), ] public let suffixFromTests = [ SuffixFromTest( collection: [], start: 0, expected: [] ), SuffixFromTest( collection: [1010, 2020, 3030, 4040, 5050], start: 0, expected: [1010, 2020, 3030, 4040, 5050] ), SuffixFromTest( collection: [1010, 2020, 3030, 4040, 5050], start: 3, expected: [4040, 5050] ), SuffixFromTest( collection: [1010, 2020, 3030, 4040, 5050], start: 5, expected: [] ), ] let removeFirstTests: [RemoveFirstNTest] = [ RemoveFirstNTest( collection: [1010], numberToRemove: 0, expectedCollection: [1010] ), RemoveFirstNTest( collection: [1010], numberToRemove: 1, expectedCollection: [] ), RemoveFirstNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 0, expectedCollection: [1010, 2020, 3030, 4040, 5050] ), RemoveFirstNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 1, expectedCollection: [2020, 3030, 4040, 5050] ), RemoveFirstNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 2, expectedCollection: [3030, 4040, 5050] ), RemoveFirstNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 3, expectedCollection: [4040, 5050] ), RemoveFirstNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 4, expectedCollection: [5050] ), RemoveFirstNTest( collection: [1010, 2020, 3030, 4040, 5050], numberToRemove: 5, expectedCollection: [] ), ] extension Collection { public func nthIndex(_ offset: Int) -> Index { return self.index(self.startIndex, offsetBy: numericCast(offset)) } } public struct DistanceFromToTest { public let startOffset: Int public let endOffset: Int public var expectedDistance : Int { return endOffset - startOffset } public let loc: SourceLoc public init( start: Int, end: Int, file: String = #file, line: UInt = #line ) { self.startOffset = start self.endOffset = end self.loc = SourceLoc(file, line, comment: "distance(from:to:) test data") } } public struct IndexOffsetByTest { public let startOffset: Int public let distance: Int public let limit: Int? public let expectedOffset: Int? public let loc: SourceLoc public init( startOffset: Int, distance: Int, expectedOffset: Int?, limitedBy limit: Int? = nil, file: String = #file, line: UInt = #line ) { self.startOffset = startOffset self.distance = distance self.expectedOffset = expectedOffset self.limit = limit self.loc = SourceLoc(file, line, comment: "index(_:offsetBy:) test data") } } public let distanceFromToTests = [ // 0 - 1: no distance. DistanceFromToTest(start: 0, end: 0), DistanceFromToTest(start: 10, end: 10), // 2 - 3: forward distance. DistanceFromToTest(start: 10, end: 13), DistanceFromToTest(start: 7, end: 10), // 4 - 6: backward distance. DistanceFromToTest(start: 12, end: 4), DistanceFromToTest(start: 8, end: 2), DistanceFromToTest(start: 19, end: 0) ] public let indexOffsetByTests = [ IndexOffsetByTest(startOffset: 0, distance: 0, expectedOffset: 0), IndexOffsetByTest(startOffset: 7, distance: 0, expectedOffset: 7), IndexOffsetByTest(startOffset: 0, distance: -1, expectedOffset: -1), IndexOffsetByTest(startOffset: 4, distance: -9, expectedOffset: -5), IndexOffsetByTest(startOffset: 8, distance: -2, expectedOffset: 6), IndexOffsetByTest(startOffset: 4, distance: -4, expectedOffset: 0), IndexOffsetByTest(startOffset: 3, distance: 12, expectedOffset: 15), IndexOffsetByTest(startOffset: 9, distance: 1, expectedOffset: 10), IndexOffsetByTest(startOffset: 2, distance: 4, expectedOffset: 6), IndexOffsetByTest(startOffset: 0, distance: 9, expectedOffset: 9), IndexOffsetByTest( startOffset: 0, distance: 0, expectedOffset: 0, limitedBy: 0), IndexOffsetByTest( startOffset: 0, distance: 0, expectedOffset: 0, limitedBy: 10), IndexOffsetByTest( startOffset: 0, distance: 10, expectedOffset: nil, limitedBy: 0), IndexOffsetByTest( startOffset: 0, distance: -10, expectedOffset: nil, limitedBy: 0), IndexOffsetByTest( startOffset: 0, distance: 10, expectedOffset: 10, limitedBy: 10), IndexOffsetByTest( startOffset: 0, distance: 20, expectedOffset: nil, limitedBy: 10), IndexOffsetByTest( startOffset: 10, distance: -20, expectedOffset: nil, limitedBy: 0), IndexOffsetByTest( startOffset: 5, distance: 5, expectedOffset: 10, limitedBy: 2), IndexOffsetByTest( startOffset: 5, distance: 5, expectedOffset: nil, limitedBy: 5), IndexOffsetByTest( startOffset: 5, distance: -5, expectedOffset: 0, limitedBy: 7), IndexOffsetByTest( startOffset: 5, distance: -5, expectedOffset: nil, limitedBy: 5) ] public struct IndexAfterTest { public let start: Int public let end: Int public let loc: SourceLoc public init(start: Int, end: Int, file: String = #file, line: UInt = #line) { self.start = start self.end = end self.loc = SourceLoc(file, line, comment: "index(after:) and formIndex(after:) test data") } } public let indexAfterTests = [ IndexAfterTest(start: 0, end: 1), IndexAfterTest(start: 0, end: 10), IndexAfterTest(start: 5, end: 12), IndexAfterTest(start: -58, end: -54), ] internal func _allIndices<C : Collection>( into c: C, in bounds: Range<C.Index> ) -> [C.Index] { var result: [C.Index] = [] var i = bounds.lowerBound while i != bounds.upperBound { result.append(i) i = c.index(after: i) } return result } internal enum _SubSequenceSubscriptOnIndexMode { case inRange case outOfRangeToTheLeft case outOfRangeToTheRight case baseEndIndex case sliceEndIndex static var all: [_SubSequenceSubscriptOnIndexMode] { return [ .inRange, .outOfRangeToTheLeft, .outOfRangeToTheRight, .baseEndIndex, .sliceEndIndex, ] } } internal enum _SubSequenceSubscriptOnRangeMode { case inRange case outOfRangeToTheLeftEmpty case outOfRangeToTheLeftNonEmpty case outOfRangeToTheRightEmpty case outOfRangeToTheRightNonEmpty case outOfRangeBothSides case baseEndIndex static var all: [_SubSequenceSubscriptOnRangeMode] { return [ .inRange, .outOfRangeToTheLeftEmpty, .outOfRangeToTheLeftNonEmpty, .outOfRangeToTheRightEmpty, .outOfRangeToTheRightNonEmpty, .outOfRangeBothSides, .baseEndIndex, ] } } extension TestSuite { public func addCollectionTests< C, CollectionWithEquatableElement >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Iterator.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Iterator.Element, extractValue: @escaping (C.Iterator.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ( [CollectionWithEquatableElement.Iterator.Element] ) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping ( MinimalEquatableValue) -> CollectionWithEquatableElement.Iterator.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Iterator.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, outOfBoundsSubscriptOffset: Int = 1, collectionIsBidirectional: Bool = false ) where C : Collection, CollectionWithEquatableElement : Collection, CollectionWithEquatableElement.Iterator.Element : Equatable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addSequenceTests( testNamePrefix, makeSequence: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeSequenceOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks) func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { return makeCollection(elements.map(wrapValue)) } func makeWrappedCollectionWithEquatableElement( _ elements: [MinimalEquatableValue] ) -> CollectionWithEquatableElement { return makeCollectionOfEquatable(elements.map(wrapValueIntoEquatable)) } testNamePrefix += String(describing: C.Type.self) //===------------------------------------------------------------------===// // generate() //===------------------------------------------------------------------===// self.test("\(testNamePrefix).generate()/semantics") { for test in subscriptRangeTests { let c = makeWrappedCollection(test.collection) for _ in 0..<3 { checkSequence( test.collection.map(wrapValue), c, resiliencyChecks: .none) { extractValue($0).value == extractValue($1).value } } } } //===------------------------------------------------------------------===// // Index //===------------------------------------------------------------------===// if resiliencyChecks.creatingOutOfBoundsIndicesBehavior != .none { self.test("\(testNamePrefix).Index/OutOfBounds/Right/NonEmpty") { let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init)) let index = c.endIndex expectCrashLater() _blackHole(c.index(index, offsetBy: numericCast(outOfBoundsIndexOffset))) } self.test("\(testNamePrefix).Index/OutOfBounds/Right/Empty") { let c = makeWrappedCollection([]) let index = c.endIndex expectCrashLater() _blackHole(c.index(index, offsetBy: numericCast(outOfBoundsIndexOffset))) } } //===------------------------------------------------------------------===// // subscript(_: Index) //===------------------------------------------------------------------===// if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior != .none { self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Right/NonEmpty/Get") { let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init)) var index = c.endIndex expectCrashLater() index = c.index(index, offsetBy: numericCast(outOfBoundsSubscriptOffset)) _blackHole(c[index]) } self.test("\(testNamePrefix).subscript(_: Index)/OutOfBounds/Right/Empty/Get") { let c = makeWrappedCollection([]) var index = c.endIndex expectCrashLater() index = c.index(index, offsetBy: numericCast(outOfBoundsSubscriptOffset)) _blackHole(c[index]) } let tests = cartesianProduct( subscriptRangeTests, _SubSequenceSubscriptOnIndexMode.all) self.test("\(testNamePrefix).SubSequence.subscript(_: Index)/Get/OutOfBounds") .forEach(in: tests) { (test, mode) in let elements = test.collection let sliceFromLeft = test.bounds.lowerBound let sliceFromRight = elements.count - test.bounds.upperBound print("\(elements)/sliceFromLeft=\(sliceFromLeft)/sliceFromRight=\(sliceFromRight)") let base = makeWrappedCollection(elements) let sliceStartIndex = base.index(base.startIndex, offsetBy: numericCast(sliceFromLeft)) let sliceEndIndex = base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight)) var slice = base[sliceStartIndex..<sliceEndIndex] expectType(C.SubSequence.self, &slice) var index: C.Index = base.startIndex switch mode { case .inRange: let sliceNumericIndices = sliceFromLeft..<(elements.count - sliceFromRight) for (i, index) in base.indices.enumerated() { if sliceNumericIndices.contains(i) { expectEqual( elements[i].value, extractValue(slice[index]).value) expectEqual( extractValue(base[index]).value, extractValue(slice[index]).value) } } return case .outOfRangeToTheLeft: if sliceFromLeft == 0 { return } index = base.index( base.startIndex, offsetBy: numericCast(sliceFromLeft - 1)) case .outOfRangeToTheRight: if sliceFromRight == 0 { return } index = base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight)) case .baseEndIndex: index = base.endIndex case .sliceEndIndex: index = sliceEndIndex } expectCrashLater() _blackHole(slice[index]) } } //===------------------------------------------------------------------===// // subscript(_: Range) //===------------------------------------------------------------------===// self.test("\(testNamePrefix).subscript(_: Range)/Get/semantics") { for test in subscriptRangeTests { let base = makeWrappedCollection(test.collection) let sliceBounds = test.bounds(in: base) let slice = base[sliceBounds] expectEqual(sliceBounds.lowerBound, slice.startIndex) expectEqual(sliceBounds.upperBound, slice.endIndex) /* // TODO: swift-3-indexing-model: uncomment the following. // FIXME: improve checkForwardCollection to check the SubSequence type. checkCollection( expected: test.expected.map(wrapValue), slice, resiliencyChecks: .none) { extractValue($0).value == extractValue($1).value } */ } } if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior != .none { self.test("\(testNamePrefix).subscript(_: Range)/OutOfBounds/Right/NonEmpty/Get") { let c = makeWrappedCollection([ 1010, 2020, 3030 ].map(OpaqueValue.init)) var index = c.endIndex expectCrashLater() index = c.index(index, offsetBy: numericCast(outOfBoundsSubscriptOffset)) _blackHole(c[index..<index]) } self.test("\(testNamePrefix).subscript(_: Range)/OutOfBounds/Right/Empty/Get") { let c = makeWrappedCollection([]) var index = c.endIndex expectCrashLater() index = c.index(index, offsetBy: numericCast(outOfBoundsSubscriptOffset)) _blackHole(c[index..<index]) } let tests = cartesianProduct( subscriptRangeTests, _SubSequenceSubscriptOnRangeMode.all) self.test( "\(testNamePrefix).SubSequence.subscript(_: Range)/Get/OutOfBounds") .forEach(in: tests) { (test, mode) in let elements = test.collection let sliceFromLeft = test.bounds.lowerBound let sliceFromRight = elements.count - test.bounds.upperBound print( "\(elements)/sliceFromLeft=\(sliceFromLeft)" + "/sliceFromRight=\(sliceFromRight)") let base = makeWrappedCollection(elements) let sliceStartIndex = base.index(base.startIndex, offsetBy: numericCast(sliceFromLeft)) let sliceEndIndex = base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight)) var slice = base[sliceStartIndex..<sliceEndIndex] expectType(C.SubSequence.self, &slice) var bounds: Range<C.Index> = base.startIndex..<base.startIndex switch mode { case .inRange: let sliceNumericIndices = sliceFromLeft..<(elements.count - sliceFromRight + 1) for (i, subSliceStartIndex) in base.indices.enumerated() { for (j, subSliceEndIndex) in base.indices.enumerated() { if i <= j && sliceNumericIndices.contains(i) && sliceNumericIndices.contains(j) { let subSlice = slice[subSliceStartIndex..<subSliceEndIndex] for (k, index) in subSlice.indices.enumerated() { expectEqual( elements[i + k].value, extractValue(subSlice[index]).value) expectEqual( extractValue(base[index]).value, extractValue(subSlice[index]).value) expectEqual( extractValue(slice[index]).value, extractValue(subSlice[index]).value) } } } } return case .outOfRangeToTheLeftEmpty: if sliceFromLeft == 0 { return } let index = base.index( base.startIndex, offsetBy: numericCast(sliceFromLeft - 1)) bounds = index..<index break case .outOfRangeToTheLeftNonEmpty: if sliceFromLeft == 0 { return } let index = base.index( base.startIndex, offsetBy: numericCast(sliceFromLeft - 1)) bounds = index..<sliceStartIndex break case .outOfRangeToTheRightEmpty: if sliceFromRight == 0 { return } let index = base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight + 1)) bounds = index..<index break case .outOfRangeToTheRightNonEmpty: if sliceFromRight == 0 { return } let index = base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight + 1)) bounds = sliceEndIndex..<index break case .outOfRangeBothSides: if sliceFromLeft == 0 { return } if sliceFromRight == 0 { return } bounds = base.index( base.startIndex, offsetBy: numericCast(sliceFromLeft - 1)) ..< base.index( base.startIndex, offsetBy: numericCast(elements.count - sliceFromRight + 1)) break case .baseEndIndex: if sliceFromRight == 0 { return } bounds = sliceEndIndex..<base.endIndex break } expectCrashLater() _blackHole(slice[bounds]) } } // FIXME: swift-3-indexing-model - add tests for the following? // _failEarlyRangeCheck(index: Index, bounds: Range<Index>) // _failEarlyRangeCheck(range: Range<Index>, bounds: Range<Index>) //===------------------------------------------------------------------===// // isEmpty //===------------------------------------------------------------------===// self.test("\(testNamePrefix).isEmpty/semantics") { for test in subscriptRangeTests { let c = makeWrappedCollection(test.collection) expectEqual(test.isEmpty, c.isEmpty) } } //===------------------------------------------------------------------===// // count //===------------------------------------------------------------------===// self.test("\(testNamePrefix).count/semantics") { for test in subscriptRangeTests { let c = makeWrappedCollection(test.collection) expectEqual(test.count, numericCast(c.count) as Int) } } //===------------------------------------------------------------------===// // index(of:)/index(where:) //===------------------------------------------------------------------===// self.test("\(testNamePrefix).index(of:)/semantics") { for test in findTests { let c = makeWrappedCollectionWithEquatableElement(test.sequence) var result = c.index(of: wrapValueIntoEquatable(test.element)) expectType( Optional<CollectionWithEquatableElement.Index>.self, &result) let zeroBasedIndex = result.map { numericCast(c.distance(from: c.startIndex, to: $0)) as Int } expectEqual( test.expected, zeroBasedIndex, stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).index(where:)/semantics") { for test in findTests { let closureLifetimeTracker = LifetimeTracked(0) expectEqual(1, LifetimeTracked.instances) let c = makeWrappedCollectionWithEquatableElement(test.sequence) let result = c.index { (candidate) in _blackHole(closureLifetimeTracker) return extractValueFromEquatable(candidate).value == test.element.value } let zeroBasedIndex = result.map { numericCast(c.distance(from: c.startIndex, to: $0)) as Int } expectEqual( test.expected, zeroBasedIndex, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// // first //===------------------------------------------------------------------===// self.test("\(testNamePrefix).first") { for test in subscriptRangeTests { let c = makeWrappedCollection(test.collection) let result = c.first if test.isEmpty { expectNil(result) } else { expectOptionalEqual( test.collection[0], result.map(extractValue) ) { $0.value == $1.value } } } } //===------------------------------------------------------------------===// // indices //===------------------------------------------------------------------===// self.test("\(testNamePrefix).indices") { // TODO: swift-3-indexing-model: improve this test. `indices` // is not just a `Range` anymore, it can be anything. for test in subscriptRangeTests { let c = makeWrappedCollection(test.collection) let indices = c.indices expectEqual(c.startIndex, indices.startIndex) expectEqual(c.endIndex, indices.endIndex) } } //===------------------------------------------------------------------===// // dropFirst() //===------------------------------------------------------------------===// self.test("\(testNamePrefix).dropFirst/semantics") { for test in dropFirstTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) let result = s.dropFirst(test.dropElements) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// // dropLast() //===------------------------------------------------------------------===// self.test("\(testNamePrefix).dropLast/semantics") { for test in dropLastTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) let result = s.dropLast(test.dropElements) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// // prefix() //===------------------------------------------------------------------===// self.test("\(testNamePrefix).prefix/semantics") { for test in prefixTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) let result = s.prefix(test.maxLength) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// // suffix() //===------------------------------------------------------------------===// self.test("\(testNamePrefix).suffix/semantics") { for test in suffixTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) let result = s.suffix(test.maxLength) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// // split() //===------------------------------------------------------------------===// self.test("\(testNamePrefix).split/semantics") { for test in splitTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) let result = s.split( maxSplits: test.maxSplits, omittingEmptySubsequences: test.omittingEmptySubsequences ) { extractValue($0).value == test.separator } expectEqualSequence(test.expected, result.map { $0.map { extractValue($0).value } }, stackTrace: SourceLocStack().with(test.loc)) { $0 == $1 } } } //===------------------------------------------------------------------===// // prefix(through:) //===------------------------------------------------------------------===// self.test("\(testNamePrefix).prefix(through:)/semantics") { for test in prefixThroughTests { let c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) let index = c.index( c.startIndex, offsetBy: numericCast(test.position)) let result = c.prefix(through: index) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// // prefix(upTo:) //===------------------------------------------------------------------===// self.test("\(testNamePrefix).prefix(upTo:)/semantics") { for test in prefixUpToTests { let c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) let index = c.index(c.startIndex, offsetBy: numericCast(test.end)) let result = c.prefix(upTo: index) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// // suffix(from:) //===------------------------------------------------------------------===// self.test("\(testNamePrefix).suffix(from:)/semantics") { for test in suffixFromTests { let c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) let index = c.index(c.startIndex, offsetBy: numericCast(test.start)) let result = c.suffix(from: index) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// // removeFirst()/slice //===------------------------------------------------------------------===// self.test("\(testNamePrefix).removeFirst()/slice/semantics") { for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) { let c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) var slice = c[...] let survivingIndices = _allIndices( into: slice, in: slice.index(after: slice.startIndex)..<slice.endIndex) let removedElement = slice.removeFirst() expectEqual(test.collection.first, extractValue(removedElement).value) expectEqualSequence( test.expectedCollection, slice.map { extractValue($0).value }, "removeFirst() shouldn't mutate the tail of the slice", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.expectedCollection, survivingIndices.map { extractValue(slice[$0]).value }, "removeFirst() shouldn't invalidate indices", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.collection, c.map { extractValue($0).value }, "removeFirst() shouldn't mutate the collection that was sliced", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).removeFirst()/slice/empty/semantics") { let c = makeWrappedCollection(Array<OpaqueValue<Int>>()) var slice = c[c.startIndex..<c.startIndex] expectCrashLater() _ = slice.removeFirst() // Should trap. } //===------------------------------------------------------------------===// // removeFirst(n: Int)/slice //===------------------------------------------------------------------===// self.test("\(testNamePrefix).removeFirst(n: Int)/slice/semantics") { for test in removeFirstTests { let c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) var slice = c[...] let survivingIndices = _allIndices( into: slice, in: slice.index( slice.startIndex, offsetBy: numericCast(test.numberToRemove)) ..< slice.endIndex ) slice.removeFirst(test.numberToRemove) expectEqualSequence( test.expectedCollection, slice.map { extractValue($0).value }, "removeFirst() shouldn't mutate the tail of the slice", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.expectedCollection, survivingIndices.map { extractValue(slice[$0]).value }, "removeFirst() shouldn't invalidate indices", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.collection, c.map { extractValue($0).value }, "removeFirst() shouldn't mutate the collection that was sliced", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).removeFirst(n: Int)/slice/empty/semantics") { let c = makeWrappedCollection(Array<OpaqueValue<Int>>()) var slice = c[c.startIndex..<c.startIndex] expectCrashLater() slice.removeFirst(1) // Should trap. } self.test( "\(testNamePrefix).removeFirst(n: Int)/slice/removeNegative/semantics") { let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) var slice = c[c.startIndex..<c.startIndex] expectCrashLater() slice.removeFirst(-1) // Should trap. } self.test( "\(testNamePrefix).removeFirst(n: Int)/slice/removeTooMany/semantics") { let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) var slice = c[c.startIndex..<c.startIndex] expectCrashLater() slice.removeFirst(3) // Should trap. } //===------------------------------------------------------------------===// // popFirst()/slice //===------------------------------------------------------------------===// self.test("\(testNamePrefix).popFirst()/slice/semantics") { // This can just reuse the test data for removeFirst() for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) { let c = makeWrappedCollection(test.collection.map(OpaqueValue.init)) var slice = c[...] let survivingIndices = _allIndices( into: slice, in: slice.index(after: slice.startIndex)..<slice.endIndex) let removedElement = slice.popFirst()! expectEqual(test.collection.first, extractValue(removedElement).value) expectEqualSequence( test.expectedCollection, slice.map { extractValue($0).value }, "popFirst() shouldn't mutate the tail of the slice", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.expectedCollection, survivingIndices.map { extractValue(slice[$0]).value }, "popFirst() shouldn't invalidate indices", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.collection, c.map { extractValue($0).value }, "popFirst() shouldn't mutate the collection that was sliced", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).popFirst()/slice/empty/semantics") { let c = makeWrappedCollection(Array<OpaqueValue<Int>>()) var slice = c[c.startIndex..<c.startIndex] expectNil(slice.popFirst()) } //===------------------------------------------------------------------===// self.addCommonTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset, collectionIsBidirectional: collectionIsBidirectional) } // addCollectionTests public func addBidirectionalCollectionTests< C, CollectionWithEquatableElement >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Iterator.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Iterator.Element, extractValue: @escaping (C.Iterator.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ( [CollectionWithEquatableElement.Iterator.Element] ) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping ( MinimalEquatableValue) -> CollectionWithEquatableElement.Iterator.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Iterator.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, outOfBoundsSubscriptOffset: Int = 1, collectionIsBidirectional: Bool = true ) where C : BidirectionalCollection, CollectionWithEquatableElement : BidirectionalCollection, CollectionWithEquatableElement.Iterator.Element : Equatable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset, collectionIsBidirectional: collectionIsBidirectional) func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { return makeCollection(elements.map(wrapValue)) } testNamePrefix += String(describing: C.Type.self) // FIXME: swift-3-indexing-model - add tests for the follow? // index(before: of i: Index) -> Index // formIndex(before: i: inout Index) // FIXME: swift-3-indexing-model - // enhance the following for negative direction? // advance(i: Index, by n: Int) -> Index // advance( // i: Index, by n: Int, limitedBy: Index) -> Index // distance(from start: Index, to end: Index) -> Int //===------------------------------------------------------------------===// // last //===------------------------------------------------------------------===// self.test("\(testNamePrefix).last") { for test in subscriptRangeTests { let c = makeWrappedCollection(test.collection) let result = c.last if test.isEmpty { expectNil(result) } else { expectOptionalEqual( test.collection[test.count - 1], result.map(extractValue) ) { $0.value == $1.value } } } } //===------------------------------------------------------------------===// // removeLast()/slice //===------------------------------------------------------------------===// self.test("\(testNamePrefix).removeLast()/slice/semantics") { for test in removeLastTests.filter({ $0.numberToRemove == 1 }) { let c = makeWrappedCollection(test.collection) var slice = c[...] let survivingIndices = _allIndices( into: slice, in: slice.startIndex ..< slice.index( slice.endIndex, offsetBy: numericCast(-test.numberToRemove)) ) let removedElement = slice.removeLast() expectEqual( test.collection.last!.value, extractValue(removedElement).value) expectEqualSequence( test.expectedCollection, slice.map { extractValue($0).value }, "removeLast() shouldn't mutate the head of the slice", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.expectedCollection, survivingIndices.map { extractValue(slice[$0]).value }, "removeLast() shouldn't invalidate indices", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.collection.map { $0.value }, c.map { extractValue($0).value }, "removeLast() shouldn't mutate the collection that was sliced", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).removeLast()/slice/empty/semantics") { let c = makeWrappedCollection(Array<OpaqueValue<Int>>()) var slice = c[c.startIndex..<c.startIndex] expectCrashLater() _ = slice.removeLast() // Should trap. } //===------------------------------------------------------------------===// // removeLast(n: Int)/slice //===------------------------------------------------------------------===// self.test("\(testNamePrefix).removeLast(n: Int)/slice/semantics") { for test in removeLastTests { let c = makeWrappedCollection(test.collection) var slice = c[...] let survivingIndices = _allIndices( into: slice, in: slice.startIndex ..< slice.index( slice.endIndex, offsetBy: numericCast(-test.numberToRemove)) ) slice.removeLast(test.numberToRemove) expectEqualSequence( test.expectedCollection, slice.map { extractValue($0).value }, "removeLast() shouldn't mutate the head of the slice", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.expectedCollection, survivingIndices.map { extractValue(slice[$0]).value }, "removeLast() shouldn't invalidate indices", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.collection.map { $0.value }, c.map { extractValue($0).value }, "removeLast() shouldn't mutate the collection that was sliced", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).removeLast(n: Int)/slice/empty/semantics") { let c = makeWrappedCollection(Array<OpaqueValue<Int>>()) var slice = c[c.startIndex..<c.startIndex] expectCrashLater() slice.removeLast(1) // Should trap. } self.test( "\(testNamePrefix).removeLast(n: Int)/slice/removeNegative/semantics" ) { let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) var slice = c[c.startIndex..<c.startIndex] expectCrashLater() slice.removeLast(-1) // Should trap. } self.test( "\(testNamePrefix).removeLast(n: Int)/slice/removeTooMany/semantics" ) { let c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init)) var slice = c[c.startIndex..<c.startIndex] expectCrashLater() slice.removeLast(3) // Should trap. } //===------------------------------------------------------------------===// // popLast()/slice //===------------------------------------------------------------------===// self.test("\(testNamePrefix).popLast()/slice/semantics") { // This can just reuse the test data for removeLast() for test in removeLastTests.filter({ $0.numberToRemove == 1 }) { let c = makeWrappedCollection(test.collection) var slice = c[...] let survivingIndices = _allIndices( into: slice, in: slice.startIndex ..< slice.index( slice.endIndex, offsetBy: numericCast(-test.numberToRemove)) ) let removedElement = slice.popLast()! expectEqual( test.collection.last!.value, extractValue(removedElement).value) expectEqualSequence( test.expectedCollection, slice.map { extractValue($0).value }, "popLast() shouldn't mutate the head of the slice", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.expectedCollection, survivingIndices.map { extractValue(slice[$0]).value }, "popLast() shouldn't invalidate indices", stackTrace: SourceLocStack().with(test.loc) ) expectEqualSequence( test.collection.map { $0.value }, c.map { extractValue($0).value }, "popLast() shouldn't mutate the collection that was sliced", stackTrace: SourceLocStack().with(test.loc)) } } self.test("\(testNamePrefix).popLast()/slice/empty/semantics") { let c = makeWrappedCollection(Array<OpaqueValue<Int>>()) var slice = c[c.startIndex..<c.startIndex] expectNil(slice.popLast()) } //===------------------------------------------------------------------===// // Index //===------------------------------------------------------------------===// if resiliencyChecks.creatingOutOfBoundsIndicesBehavior != .none { self.test("\(testNamePrefix).Index/OutOfBounds/Left/NonEmpty") { let c = makeWrappedCollection( [ 1010, 2020, 3030 ].map(OpaqueValue.init)) let index = c.startIndex expectCrashLater() _blackHole( c.index(index, offsetBy: numericCast(-outOfBoundsIndexOffset))) } self.test("\(testNamePrefix).Index/OutOfBounds/Left/Empty") { let c = makeWrappedCollection([]) let index = c.startIndex expectCrashLater() _blackHole( c.index(index, offsetBy: numericCast(-outOfBoundsIndexOffset))) } } //===------------------------------------------------------------------===// // subscript(_: Index) //===------------------------------------------------------------------===// if resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior != .none { self.test( "\(testNamePrefix).subscript(_: Index)/OutOfBounds/Left/NonEmpty/Get" ) { let c = makeWrappedCollection( [ 1010, 2020, 3030 ].map(OpaqueValue.init)) var index = c.startIndex expectCrashLater() index = c.index( index, offsetBy: numericCast(-outOfBoundsSubscriptOffset)) _blackHole(c[index]) } self.test( "\(testNamePrefix).subscript(_: Index)/OutOfBounds/Left/Empty/Get" ) { let c = makeWrappedCollection([]) var index = c.startIndex expectCrashLater() index = c.index( index, offsetBy: numericCast(-outOfBoundsSubscriptOffset)) _blackHole(c[index]) } } //===------------------------------------------------------------------===// // subscript(_: Range) //===------------------------------------------------------------------===// if resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior != .none { self.test( "\(testNamePrefix).subscript(_: Range)/OutOfBounds/Left/NonEmpty/Get" ) { let c = makeWrappedCollection( [ 1010, 2020, 3030 ].map(OpaqueValue.init)) var index = c.startIndex expectCrashLater() index = c.index( index, offsetBy: numericCast(-outOfBoundsSubscriptOffset)) _blackHole(c[index..<index]) } self.test( "\(testNamePrefix).subscript(_: Range)/OutOfBounds/Left/Empty/Get" ) { let c = makeWrappedCollection([]) var index = c.startIndex expectCrashLater() index = c.index( index, offsetBy: numericCast(-outOfBoundsSubscriptOffset)) _blackHole(c[index..<index]) } } //===------------------------------------------------------------------===// // dropLast() //===------------------------------------------------------------------===// self.test("\(testNamePrefix).dropLast/semantics") { for test in dropLastTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) let result = s.dropLast(test.dropElements) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// // suffix() //===------------------------------------------------------------------===// self.test("\(testNamePrefix).suffix/semantics") { for test in suffixTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) let result = s.suffix(test.maxLength) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// self.addCommonTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset, collectionIsBidirectional: collectionIsBidirectional) } // addBidirectionalCollectionTests public func addRandomAccessCollectionTests< C, CollectionWithEquatableElement >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Iterator.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Iterator.Element, extractValue: @escaping (C.Iterator.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ( [CollectionWithEquatableElement.Iterator.Element] ) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping ( MinimalEquatableValue) -> CollectionWithEquatableElement.Iterator.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Iterator.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, outOfBoundsSubscriptOffset: Int = 1, collectionIsBidirectional: Bool = true ) where C : RandomAccessCollection, CollectionWithEquatableElement : RandomAccessCollection, CollectionWithEquatableElement.Iterator.Element : Equatable { var testNamePrefix = testNamePrefix if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } addBidirectionalCollectionTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset, collectionIsBidirectional: collectionIsBidirectional) testNamePrefix += String(describing: C.Type.self) func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C { return makeCollection(elements.map(wrapValue)) } //===------------------------------------------------------------------===// // prefix() //===------------------------------------------------------------------===// self.test("\(testNamePrefix).prefix/semantics") { for test in prefixTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) let result = s.prefix(test.maxLength) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// // suffix() //===------------------------------------------------------------------===// self.test("\(testNamePrefix).suffix/semantics") { for test in suffixTests { let s = makeWrappedCollection(test.sequence.map(OpaqueValue.init)) let result = s.suffix(test.maxLength) expectEqualSequence( test.expected, result.map(extractValue).map { $0.value }, stackTrace: SourceLocStack().with(test.loc)) } } //===------------------------------------------------------------------===// self.addCommonTests( testNamePrefix, makeCollection: makeCollection, wrapValue: wrapValue, extractValue: extractValue, makeCollectionOfEquatable: makeCollectionOfEquatable, wrapValueIntoEquatable: wrapValueIntoEquatable, extractValueFromEquatable: extractValueFromEquatable, resiliencyChecks: resiliencyChecks, outOfBoundsIndexOffset: outOfBoundsIndexOffset, outOfBoundsSubscriptOffset: outOfBoundsSubscriptOffset, collectionIsBidirectional: collectionIsBidirectional) } // addRandomAccessCollectionTests func addCommonTests< C, CollectionWithEquatableElement >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Iterator.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Iterator.Element, extractValue: @escaping (C.Iterator.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ( [CollectionWithEquatableElement.Iterator.Element] ) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping ( MinimalEquatableValue) -> CollectionWithEquatableElement.Iterator.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Iterator.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, outOfBoundsSubscriptOffset: Int = 1, collectionIsBidirectional: Bool ) where C : Collection, CollectionWithEquatableElement : Collection, CollectionWithEquatableElement.Iterator.Element : Equatable { if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } func toCollection(_ r: Range<Int>) -> C { return makeCollection(r.map { wrapValue(OpaqueValue($0)) }) } self.test("\(testNamePrefix).index(after:)/semantics") { for test in indexAfterTests { let c = toCollection(test.start..<test.end) var currentIndex = c.startIndex var counter = test.start repeat { expectEqual(counter, extractValue(c[currentIndex]).value, stackTrace: SourceLocStack().with(test.loc)) currentIndex = c.index(after: currentIndex) counter += 1 } while counter < test.end } } self.test("\(testNamePrefix).formIndex(after:)/semantics") { for test in indexAfterTests { let c = toCollection(test.start..<test.end) var currentIndex = c.startIndex var counter = test.start repeat { expectEqual(counter, extractValue(c[currentIndex]).value, stackTrace: SourceLocStack().with(test.loc)) c.formIndex(after: &currentIndex) counter += 1 } while counter < test.end } } self.test("\(testNamePrefix)/distance(from:to:)/semantics") .forEach(in: distanceFromToTests) { test in let c = toCollection(0..<20) let backwards = (test.startOffset > test.endOffset) if backwards && !collectionIsBidirectional { expectCrashLater() } let d = c.distance( from: c.nthIndex(test.startOffset), to: c.nthIndex(test.endOffset)) expectEqual( numericCast(test.expectedDistance), d, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/index(_:offsetBy: n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance >= 0 } ) { test in let max = 10 let c = toCollection(0..<max) if test.expectedOffset! >= max { expectCrashLater() } let new = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance)) // Since the `nthIndex(offset:)` method performs the same operation // (i.e. advances `c.startIndex` by `test.distance`, it would be // silly to compare index values. Luckily the underlying collection // contains exactly index offsets. expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/formIndex(_:offsetBy: n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance >= 0 } ) { test in let max = 10 let c = toCollection(0..<max) var new = c.nthIndex(test.startOffset) if test.expectedOffset! >= max { expectCrashLater() } c.formIndex(&new, offsetBy: numericCast(test.distance)) expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/index(_:offsetBy: -n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) let start = c.nthIndex(test.startOffset) if test.expectedOffset! < 0 || !collectionIsBidirectional { expectCrashLater() } let new = c.index(start, offsetBy: numericCast(test.distance)) expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/formIndex(_:offsetBy: -n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) var new = c.nthIndex(test.startOffset) if test.expectedOffset! < 0 || !collectionIsBidirectional { expectCrashLater() } c.formIndex(&new, offsetBy: numericCast(test.distance)) expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/index(_:offsetBy: n, limitedBy:)/semantics") { for test in indexOffsetByTests.filter( {$0.limit != nil && $0.distance >= 0} ) { let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) let new = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new!, stackTrace: SourceLocStack().with(test.loc)) } else { expectNil(new) } } } self.test("\(testNamePrefix)/formIndex(_:offsetBy: n, limitedBy:)/semantics") { for test in indexOffsetByTests.filter( {$0.limit != nil && $0.distance >= 0} ) { let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) var new = c.nthIndex(test.startOffset) let exact = c.formIndex(&new, offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new, stackTrace: SourceLocStack().with(test.loc)) expectTrue(exact, stackTrace: SourceLocStack().with(test.loc)) } else { // Clamped to the limit expectEqual(limit, new, stackTrace: SourceLocStack().with(test.loc)) expectFalse(exact, stackTrace: SourceLocStack().with(test.loc)) } } } self.test("\(testNamePrefix)/index(_:offsetBy: -n, limitedBy:)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit != nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) if collectionIsBidirectional { let new = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new!, stackTrace: SourceLocStack().with(test.loc)) } else { expectNil(new) } } else { expectCrashLater() _ = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance), limitedBy: limit) } } self.test("\(testNamePrefix)/formIndex(_:offsetBy: -n, limitedBy:)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit != nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) var new = c.nthIndex(test.startOffset) if collectionIsBidirectional { let exact = c.formIndex( &new, offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new, stackTrace: SourceLocStack().with(test.loc)) expectTrue(exact, stackTrace: SourceLocStack().with(test.loc)) } else { expectEqual(limit, new, stackTrace: SourceLocStack().with(test.loc)) expectFalse(exact, stackTrace: SourceLocStack().with(test.loc)) } } else { expectCrashLater() _ = c.formIndex(&new, offsetBy: numericCast(test.distance), limitedBy: limit) } } } func addCommonTests< C, CollectionWithEquatableElement >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Iterator.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Iterator.Element, extractValue: @escaping (C.Iterator.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ( [CollectionWithEquatableElement.Iterator.Element] ) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping ( MinimalEquatableValue) -> CollectionWithEquatableElement.Iterator.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Iterator.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, outOfBoundsSubscriptOffset: Int = 1, collectionIsBidirectional: Bool ) where C : BidirectionalCollection, CollectionWithEquatableElement : BidirectionalCollection, CollectionWithEquatableElement.Iterator.Element : Equatable { if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } func toCollection(_ r: Range<Int>) -> C { return makeCollection(r.map { wrapValue(OpaqueValue($0)) }) } self.test("\(testNamePrefix).index(after:)/semantics") { for test in indexAfterTests { let c = toCollection(test.start..<test.end) var currentIndex = c.startIndex var counter = test.start repeat { expectEqual(counter, extractValue(c[currentIndex]).value, stackTrace: SourceLocStack().with(test.loc)) currentIndex = c.index(after: currentIndex) counter += 1 } while counter < test.end } } self.test("\(testNamePrefix).formIndex(after:)/semantics") { for test in indexAfterTests { let c = toCollection(test.start..<test.end) var currentIndex = c.startIndex var counter = test.start repeat { expectEqual(counter, extractValue(c[currentIndex]).value, stackTrace: SourceLocStack().with(test.loc)) c.formIndex(after: &currentIndex) counter += 1 } while counter < test.end } } self.test("\(testNamePrefix)/distance(from:to:)/semantics") .forEach(in: distanceFromToTests) { test in let c = toCollection(0..<20) let backwards = (test.startOffset > test.endOffset) if backwards && !collectionIsBidirectional { expectCrashLater() } let d = c.distance( from: c.nthIndex(test.startOffset), to: c.nthIndex(test.endOffset)) expectEqual( numericCast(test.expectedDistance), d, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/index(_:offsetBy: n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance >= 0 } ) { test in let max = 10 let c = toCollection(0..<max) if test.expectedOffset! >= max { expectCrashLater() } let new = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance)) // Since the `nthIndex(offset:)` method performs the same operation // (i.e. advances `c.startIndex` by `test.distance`, it would be // silly to compare index values. Luckily the underlying collection // contains exactly index offsets. expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/formIndex(_:offsetBy: n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance >= 0 } ) { test in let max = 10 let c = toCollection(0..<max) var new = c.nthIndex(test.startOffset) if test.expectedOffset! >= max { expectCrashLater() } c.formIndex(&new, offsetBy: numericCast(test.distance)) expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/index(_:offsetBy: -n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) let start = c.nthIndex(test.startOffset) if test.expectedOffset! < 0 || !collectionIsBidirectional { expectCrashLater() } let new = c.index(start, offsetBy: numericCast(test.distance)) expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/formIndex(_:offsetBy: -n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) var new = c.nthIndex(test.startOffset) if test.expectedOffset! < 0 || !collectionIsBidirectional { expectCrashLater() } c.formIndex(&new, offsetBy: numericCast(test.distance)) expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/index(_:offsetBy: n, limitedBy:)/semantics") { for test in indexOffsetByTests.filter( {$0.limit != nil && $0.distance >= 0} ) { let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) let new = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new!, stackTrace: SourceLocStack().with(test.loc)) } else { expectNil(new) } } } self.test("\(testNamePrefix)/formIndex(_:offsetBy: n, limitedBy:)/semantics") { for test in indexOffsetByTests.filter( {$0.limit != nil && $0.distance >= 0} ) { let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) var new = c.nthIndex(test.startOffset) let exact = c.formIndex(&new, offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new, stackTrace: SourceLocStack().with(test.loc)) expectTrue(exact, stackTrace: SourceLocStack().with(test.loc)) } else { // Clamped to the limit expectEqual(limit, new, stackTrace: SourceLocStack().with(test.loc)) expectFalse(exact, stackTrace: SourceLocStack().with(test.loc)) } } } self.test("\(testNamePrefix)/index(_:offsetBy: -n, limitedBy:)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit != nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) if collectionIsBidirectional { let new = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new!, stackTrace: SourceLocStack().with(test.loc)) } else { expectNil(new) } } else { expectCrashLater() _ = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance), limitedBy: limit) } } self.test("\(testNamePrefix)/formIndex(_:offsetBy: -n, limitedBy:)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit != nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) var new = c.nthIndex(test.startOffset) if collectionIsBidirectional { let exact = c.formIndex( &new, offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new, stackTrace: SourceLocStack().with(test.loc)) expectTrue(exact, stackTrace: SourceLocStack().with(test.loc)) } else { expectEqual(limit, new, stackTrace: SourceLocStack().with(test.loc)) expectFalse(exact, stackTrace: SourceLocStack().with(test.loc)) } } else { expectCrashLater() _ = c.formIndex(&new, offsetBy: numericCast(test.distance), limitedBy: limit) } } } func addCommonTests< C, CollectionWithEquatableElement >( _ testNamePrefix: String = "", makeCollection: @escaping ([C.Iterator.Element]) -> C, wrapValue: @escaping (OpaqueValue<Int>) -> C.Iterator.Element, extractValue: @escaping (C.Iterator.Element) -> OpaqueValue<Int>, makeCollectionOfEquatable: @escaping ( [CollectionWithEquatableElement.Iterator.Element] ) -> CollectionWithEquatableElement, wrapValueIntoEquatable: @escaping ( MinimalEquatableValue) -> CollectionWithEquatableElement.Iterator.Element, extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Iterator.Element) -> MinimalEquatableValue), resiliencyChecks: CollectionMisuseResiliencyChecks = .all, outOfBoundsIndexOffset: Int = 1, outOfBoundsSubscriptOffset: Int = 1, collectionIsBidirectional: Bool ) where C : RandomAccessCollection, CollectionWithEquatableElement : RandomAccessCollection, CollectionWithEquatableElement.Iterator.Element : Equatable { if !checksAdded.insert( "\(testNamePrefix).\(C.self).\(#function)" ).inserted { return } func toCollection(_ r: Range<Int>) -> C { return makeCollection(r.map { wrapValue(OpaqueValue($0)) }) } self.test("\(testNamePrefix).index(after:)/semantics") { for test in indexAfterTests { let c = toCollection(test.start..<test.end) var currentIndex = c.startIndex var counter = test.start repeat { expectEqual(counter, extractValue(c[currentIndex]).value, stackTrace: SourceLocStack().with(test.loc)) currentIndex = c.index(after: currentIndex) counter += 1 } while counter < test.end } } self.test("\(testNamePrefix).formIndex(after:)/semantics") { for test in indexAfterTests { let c = toCollection(test.start..<test.end) var currentIndex = c.startIndex var counter = test.start repeat { expectEqual(counter, extractValue(c[currentIndex]).value, stackTrace: SourceLocStack().with(test.loc)) c.formIndex(after: &currentIndex) counter += 1 } while counter < test.end } } self.test("\(testNamePrefix)/distance(from:to:)/semantics") .forEach(in: distanceFromToTests) { test in let c = toCollection(0..<20) let backwards = (test.startOffset > test.endOffset) if backwards && !collectionIsBidirectional { expectCrashLater() } let d = c.distance( from: c.nthIndex(test.startOffset), to: c.nthIndex(test.endOffset)) expectEqual( numericCast(test.expectedDistance), d, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/index(_:offsetBy: n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance >= 0 } ) { test in let max = 10 let c = toCollection(0..<max) if test.expectedOffset! >= max { expectCrashLater() } let new = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance)) // Since the `nthIndex(offset:)` method performs the same operation // (i.e. advances `c.startIndex` by `test.distance`, it would be // silly to compare index values. Luckily the underlying collection // contains exactly index offsets. expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/formIndex(_:offsetBy: n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance >= 0 } ) { test in let max = 10 let c = toCollection(0..<max) var new = c.nthIndex(test.startOffset) if test.expectedOffset! >= max { expectCrashLater() } c.formIndex(&new, offsetBy: numericCast(test.distance)) expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/index(_:offsetBy: -n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) let start = c.nthIndex(test.startOffset) if test.expectedOffset! < 0 || !collectionIsBidirectional { expectCrashLater() } let new = c.index(start, offsetBy: numericCast(test.distance)) expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/formIndex(_:offsetBy: -n)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit == nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) var new = c.nthIndex(test.startOffset) if test.expectedOffset! < 0 || !collectionIsBidirectional { expectCrashLater() } c.formIndex(&new, offsetBy: numericCast(test.distance)) expectEqual(test.expectedOffset!, extractValue(c[new]).value, stackTrace: SourceLocStack().with(test.loc)) } self.test("\(testNamePrefix)/index(_:offsetBy: n, limitedBy:)/semantics") { for test in indexOffsetByTests.filter( {$0.limit != nil && $0.distance >= 0} ) { let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) let new = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new!, stackTrace: SourceLocStack().with(test.loc)) } else { expectNil(new) } } } self.test("\(testNamePrefix)/formIndex(_:offsetBy: n, limitedBy:)/semantics") { for test in indexOffsetByTests.filter( {$0.limit != nil && $0.distance >= 0} ) { let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) var new = c.nthIndex(test.startOffset) let exact = c.formIndex(&new, offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new, stackTrace: SourceLocStack().with(test.loc)) expectTrue(exact, stackTrace: SourceLocStack().with(test.loc)) } else { // Clamped to the limit expectEqual(limit, new, stackTrace: SourceLocStack().with(test.loc)) expectFalse(exact, stackTrace: SourceLocStack().with(test.loc)) } } } self.test("\(testNamePrefix)/index(_:offsetBy: -n, limitedBy:)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit != nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) if collectionIsBidirectional { let new = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new!, stackTrace: SourceLocStack().with(test.loc)) } else { expectNil(new) } } else { expectCrashLater() _ = c.index( c.nthIndex(test.startOffset), offsetBy: numericCast(test.distance), limitedBy: limit) } } self.test("\(testNamePrefix)/formIndex(_:offsetBy: -n, limitedBy:)/semantics") .forEach( in: indexOffsetByTests.filter { $0.limit != nil && $0.distance < 0 } ) { test in let c = toCollection(0..<20) let limit = c.nthIndex(test.limit.unsafelyUnwrapped) var new = c.nthIndex(test.startOffset) if collectionIsBidirectional { let exact = c.formIndex( &new, offsetBy: numericCast(test.distance), limitedBy: limit) if let expectedOffset = test.expectedOffset { expectEqual(c.nthIndex(expectedOffset), new, stackTrace: SourceLocStack().with(test.loc)) expectTrue(exact, stackTrace: SourceLocStack().with(test.loc)) } else { expectEqual(limit, new, stackTrace: SourceLocStack().with(test.loc)) expectFalse(exact, stackTrace: SourceLocStack().with(test.loc)) } } else { expectCrashLater() _ = c.formIndex(&new, offsetBy: numericCast(test.distance), limitedBy: limit) } } } }
apache-2.0
4b4d7114905cce154ba41c25f2301bc3
33.622689
116
0.59416
4.856032
false
true
false
false
burningmantech/ranger-ims-mac
IncidentsTests/ReportEntryTests.swift
1
1124
// // ReportEntryTests.swift // Incidents // // © 2015 Burning Man and its contributors. All rights reserved. // See the file COPYRIGHT.md for terms. // import XCTest class ReportEntryDescriptionTests: XCTestCase { let dateString = "1971-04-20T16:20:04Z" let tool = Ranger( handle: "Tool", name: "Wilfredo Sánchez Vega", status: "vintage" ) func test_description_nonSystem() { let date = DateTime.fromRFC3339String(dateString) let entry = ReportEntry( author: tool, text: "Random edict!\n", created: date ) XCTAssertEqual( entry.description, "Tool @ \(dateString):\nRandom edict!\n" ) } func test_description_system() { let date = DateTime.fromRFC3339String(dateString) let entry = ReportEntry( author: tool, text: "some event", created: date, systemEntry: true ) XCTAssertEqual( entry.description, "Tool @ \(dateString): some event" ) } }
apache-2.0
3e98ee61ac4014b58aa1fd9e16fe3a89
19.4
65
0.553476
4.171004
false
true
false
false
SamirTalwar/advent-of-code
2018/AOC_11_1.swift
1
1424
typealias SerialNumber = Int typealias PowerLevel = Int struct Cell: Hashable { let x: Int let y: Int static func + (cell: Cell, offset: (Int, Int)) -> Cell { return Cell(x: cell.x + offset.0, y: cell.y + offset.1) } } func main() { let serialNumber = SerialNumber(readLine()!)! let cells = (1 ... 300).flatMap { y in (1 ... 300).map { x in Cell(x: x, y: y) } } let powerLevels = Dictionary( uniqueKeysWithValues: cells.map { cell in (cell, powerLevel(of: cell, serialNumber: serialNumber)) } ) let corners = (1 ... 298).flatMap { y in (1 ... 298).map { x in Cell(x: x, y: y) } } let squarePairs = corners.map { corner -> (Cell, PowerLevel) in let squareCells = (0 ..< 3).flatMap { y in (0 ..< 3).map { x in corner + (x, y) } } let totalPowerLevel = squareCells.map { cell in powerLevels[cell]! }.reduce(0, +) return (corner, totalPowerLevel) } let squares = Dictionary(uniqueKeysWithValues: squarePairs) let (key: cell, value: totalPowerLevel) = squares.max(by: comparing { $0.value })! print(cell, "@", totalPowerLevel) } func powerLevel(of cell: Cell, serialNumber: SerialNumber) -> PowerLevel { let rackId = cell.x + 10 var powerLevel = rackId * cell.y powerLevel += serialNumber powerLevel *= rackId let hundredsDigit = (powerLevel / 100) % 10 return hundredsDigit - 5 }
mit
b592f73ef476752fa23a0fa9bc2d9a4e
32.116279
91
0.610253
3.533499
false
false
false
false
WhisperSystems/Signal-iOS
Signal/src/ViewControllers/InviteFlow.swift
1
12217
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import Social import ContactsUI import MessageUI import SignalServiceKit @objc(OWSInviteFlow) class InviteFlow: NSObject, MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate, ContactsPickerDelegate { private enum Channel { case message, mail, twitter } private let installUrl = "https://signal.org/install/" private let homepageUrl = "https://signal.org" private weak var presentingViewController: UIViewController? private var channel: Channel? @objc public required init(presentingViewController: UIViewController) { self.presentingViewController = presentingViewController super.init() } deinit { Logger.verbose("deinit") } // MARK: - @objc public func present(isAnimated: Bool, completion: (() -> Void)?) { let actions = [messageAction(), mailAction(), tweetAction()].compactMap { $0 } if actions.count > 1 { let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) actionSheetController.addAction(OWSAlerts.dismissAction) for action in actions { actionSheetController.addAction(action) } presentingViewController?.present(actionSheetController, animated: isAnimated, completion: completion) } else if messageAction() != nil { presentInviteViaSMSFlow() } else if mailAction() != nil { presentInviteViaMailFlow() } else if tweetAction() != nil { presentInviteViaTwitterFlow() } } // MARK: Twitter private func canTweet() -> Bool { return SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter) } private func tweetAction() -> UIAlertAction? { guard canTweet() else { Logger.info("Twitter not supported.") return nil } let tweetTitle = NSLocalizedString("SHARE_ACTION_TWEET", comment: "action sheet item") return UIAlertAction(title: tweetTitle, style: .default) { [weak self] _ in Logger.debug("Chose tweet") self?.presentInviteViaTwitterFlow() } } private func presentInviteViaTwitterFlow() { guard let twitterViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter) else { owsFailDebug("twitterViewController was unexpectedly nil") return } let tweetString = NSLocalizedString("SETTINGS_INVITE_TWITTER_TEXT", comment: "content of tweet when inviting via twitter - please do not translate URL") twitterViewController.setInitialText(tweetString) let tweetUrl = URL(string: installUrl) twitterViewController.add(tweetUrl) twitterViewController.add(#imageLiteral(resourceName: "twitter_sharing_image")) presentingViewController?.present(twitterViewController, animated: true, completion: nil) } // MARK: ContactsPickerDelegate func contactsPicker(_: ContactsPicker, didSelectMultipleContacts contacts: [Contact]) { Logger.debug("didSelectContacts:\(contacts)") guard let inviteChannel = channel else { Logger.error("unexpected nil channel after returning from contact picker.") presentingViewController?.dismiss(animated: true) return } switch inviteChannel { case .message: let phoneNumbers: [String] = contacts.map { $0.userTextPhoneNumbers.first }.filter { $0 != nil }.map { $0! } dismissAndSendSMSTo(phoneNumbers: phoneNumbers) case .mail: let recipients: [String] = contacts.map { $0.emails.first }.filter { $0 != nil }.map { $0! } sendMailTo(emails: recipients) default: Logger.error("unexpected channel after returning from contact picker: \(inviteChannel)") } } func contactsPicker(_: ContactsPicker, shouldSelectContact contact: Contact) -> Bool { guard let inviteChannel = channel else { Logger.error("unexpected nil channel in contact picker.") return true } switch inviteChannel { case .message: return contact.userTextPhoneNumbers.count > 0 case .mail: return contact.emails.count > 0 default: Logger.error("unexpected channel after returning from contact picker: \(inviteChannel)") } return true } func contactsPicker(_: ContactsPicker, contactFetchDidFail error: NSError) { Logger.error("with error: \(error)") presentingViewController?.dismiss(animated: true) { OWSAlerts.showErrorAlert(message: NSLocalizedString("ERROR_COULD_NOT_FETCH_CONTACTS", comment: "Error indicating that the phone's contacts could not be retrieved.")) } } func contactsPickerDidCancel(_: ContactsPicker) { Logger.debug("") presentingViewController?.dismiss(animated: true) } func contactsPicker(_: ContactsPicker, didSelectContact contact: Contact) { owsFailDebug("InviteFlow only supports multi-select") presentingViewController?.dismiss(animated: true) } // MARK: SMS private func messageAction() -> UIAlertAction? { guard MFMessageComposeViewController.canSendText() else { Logger.info("Device cannot send text") return nil } let messageTitle = NSLocalizedString("SHARE_ACTION_MESSAGE", comment: "action sheet item to open native messages app") return UIAlertAction(title: messageTitle, style: .default) { [weak self] _ in Logger.debug("Chose message.") self?.presentInviteViaSMSFlow() } } private func presentInviteViaSMSFlow() { self.channel = .message let picker = ContactsPicker(allowsMultipleSelection: true, subtitleCellType: .phoneNumber) picker.contactsPickerDelegate = self picker.title = NSLocalizedString("INVITE_FRIENDS_PICKER_TITLE", comment: "Navbar title") let navigationController = OWSNavigationController(rootViewController: picker) presentingViewController?.present(navigationController, animated: true) } public func dismissAndSendSMSTo(phoneNumbers: [String]) { presentingViewController?.dismiss(animated: true) { if phoneNumbers.count > 1 { let warning = UIAlertController(title: nil, message: NSLocalizedString("INVITE_WARNING_MULTIPLE_INVITES_BY_TEXT", comment: "Alert warning that sending an invite to multiple users will create a group message whose recipients will be able to see each other."), preferredStyle: .alert) warning.addAction(UIAlertAction(title: NSLocalizedString("BUTTON_CONTINUE", comment: "Label for 'continue' button."), style: .default, handler: { [weak self] _ in self?.sendSMSTo(phoneNumbers: phoneNumbers) })) warning.addAction(OWSAlerts.cancelAction) self.presentingViewController?.presentAlert(warning) } else { self.sendSMSTo(phoneNumbers: phoneNumbers) } } } @objc public func sendSMSTo(phoneNumbers: [String]) { let messageComposeViewController = MFMessageComposeViewController() messageComposeViewController.messageComposeDelegate = self messageComposeViewController.recipients = phoneNumbers let inviteText = NSLocalizedString("SMS_INVITE_BODY", comment: "body sent to contacts when inviting to Install Signal") messageComposeViewController.body = inviteText.appending(" \(self.installUrl)") presentingViewController?.present(messageComposeViewController, animated: true) } // MARK: MessageComposeViewControllerDelegate func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { presentingViewController?.dismiss(animated: true) { switch result { case .failed: let warning = UIAlertController(title: nil, message: NSLocalizedString("SEND_INVITE_FAILURE", comment: "Alert body after invite failed"), preferredStyle: .alert) warning.addAction(OWSAlerts.dismissAction) self.presentingViewController?.present(warning, animated: true, completion: nil) case .sent: Logger.debug("user successfully invited their friends via SMS.") case .cancelled: Logger.debug("user cancelled message invite") @unknown default: owsFailDebug("unknown MessageComposeResult: \(result)") } } } // MARK: Mail private func mailAction() -> UIAlertAction? { guard MFMailComposeViewController.canSendMail() else { Logger.info("Device cannot send mail") return nil } let mailActionTitle = NSLocalizedString("SHARE_ACTION_MAIL", comment: "action sheet item to open native mail app") return UIAlertAction(title: mailActionTitle, style: .default) { [weak self] _ in Logger.debug("Chose mail.") self?.presentInviteViaMailFlow() } } private func presentInviteViaMailFlow() { self.channel = .mail let picker = ContactsPicker(allowsMultipleSelection: true, subtitleCellType: .email) picker.contactsPickerDelegate = self picker.title = NSLocalizedString("INVITE_FRIENDS_PICKER_TITLE", comment: "Navbar title") let navigationController = OWSNavigationController(rootViewController: picker) presentingViewController?.present(navigationController, animated: true) } private func sendMailTo(emails recipientEmails: [String]) { let mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self mailComposeViewController.setBccRecipients(recipientEmails) let subject = NSLocalizedString("EMAIL_INVITE_SUBJECT", comment: "subject of email sent to contacts when inviting to install Signal") let bodyFormat = NSLocalizedString("EMAIL_INVITE_BODY", comment: "body of email sent to contacts when inviting to install Signal. Embeds {{link to install Signal}} and {{link to the Signal home page}}") let body = String.init(format: bodyFormat, installUrl, homepageUrl) mailComposeViewController.setSubject(subject) mailComposeViewController.setMessageBody(body, isHTML: false) presentingViewController?.dismiss(animated: true) { self.presentingViewController?.present(mailComposeViewController, animated: true) } } // MARK: MailComposeViewControllerDelegate func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { presentingViewController?.dismiss(animated: true) { switch result { case .failed: let warning = UIAlertController(title: nil, message: NSLocalizedString("SEND_INVITE_FAILURE", comment: "Alert body after invite failed"), preferredStyle: .alert) warning.addAction(OWSAlerts.dismissAction) self.presentingViewController?.present(warning, animated: true, completion: nil) case .sent: Logger.debug("user successfully invited their friends via mail.") case .saved: Logger.debug("user saved mail invite.") case .cancelled: Logger.debug("user cancelled mail invite.") @unknown default: owsFailDebug("unknown MFMailComposeResult: \(result)") } } } }
gpl-3.0
2cae1fc7e39bc806dded1e85680ebac2
42.169611
231
0.652615
5.596427
false
false
false
false
poetmountain/MotionMachine
Tests/Tests/MotionGroupTests.swift
1
17485
// // GroupTests.swift // MotionMachineTests // // Created by Brett Walker on 5/22/16. // Copyright © 2016 Poet & Mountain, LLC. All rights reserved. // import XCTest class MotionGroupTests: XCTestCase { // MARK: Setup tests func test_add() { let tester = Tester() let group = MotionGroup() let motion = Motion(target: tester, duration: 1.0) let motion2 = Motion(target: tester, duration: 1.0) let motion3 = Motion(target: tester, duration: 1.0) // add should add a Moveable object to the group list group.add(motion) XCTAssertEqual(group.motions.count, 1) // add array should add all Moveable objects to the group list group.add([motion2, motion3]) XCTAssertEqual(group.motions.count, 3) } func test_afterDelay() { let tester = Tester() let motion = Motion(target: tester, duration: 1.0) let motion2 = Motion(target: tester, duration: 1.0) // afterDelay should add a delay let group = MotionGroup(motions: [motion, motion2]).afterDelay(1.0) XCTAssertEqual(group.delay, 1.0) } func test_repeats() { let tester = Tester() let motion = Motion(target: tester, duration: 1.0) let motion2 = Motion(target: tester, duration: 1.0) // repeats should set repeating and amount let group = MotionGroup(motions: [motion, motion2]).repeats(1) XCTAssertTrue(group.repeating) XCTAssertEqual(group.repeatCycles, 1) // if no value provided, repeating should be infinite let group2 = MotionGroup(motions: [motion, motion2]).repeats() XCTAssertTrue(group2.repeating) XCTAssertEqual(group2.repeatCycles, REPEAT_INFINITE) } func test_reverses() { let tester = Tester() let motion = Motion(target: tester, duration: 1.0) let motion2 = Motion(target: tester, duration: 1.0) // reverses should set reversing and syncMotionsWhenReversing let group = MotionGroup(motions: [motion, motion2]).reverses(syncsChildMotions: true) XCTAssertTrue(group.reversing) XCTAssertTrue(group.syncMotionsWhenReversing) } func test_use_child_tempo() { let tester = Tester() let group = MotionGroup.init() let motion = Motion(target: tester, duration: 1.0) // specifying a group's child motion should use its own tempo should not override it with group tempo group.add(motion, useChildTempo: true) XCTAssertNotNil(motion.tempo, "child tempo should not be removed") } func test_remove() { let tester = Tester() let group = MotionGroup() let motion = Motion(target: tester, duration: 1.0) let motion2 = Motion(target: tester, duration: 1.0) group.add(motion) // remove should remove a Moveable object to the group list group.remove(motion) XCTAssertEqual(group.motions.count, 0) // remove should fail gracefully when object not in group list group.remove(motion2) XCTAssertEqual(group.motions.count, 0) } // MARK: Motion tests func test_should_end_motions_at_proper_ending_values() { let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 10.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 10.0)], duration: 0.2) let group = MotionGroup(motions: [motion, motion2]) // should assign tempo to group but remove child tempos XCTAssertNil(motion.tempo, "child tempo should be removed") XCTAssertNotNil(group.tempo, "group tempo should not be removed") let did_complete = expectation(description: "group called completed notify closure") group.completed { (group) in let motion = group.motions[0] as? Motion XCTAssertEqual(motion?.properties[0].current, motion?.properties[0].end) XCTAssertEqual(motion?.totalProgress, 1.0) let motion2 = group.motions[1] as? Motion XCTAssertEqual(motion2?.properties[0].current, motion2?.properties[0].end) XCTAssertEqual(motion2?.totalProgress, 1.0) did_complete.fulfill() } group.start() waitForExpectations(timeout: 2.0, handler: nil) } func test_delay() { let did_complete = expectation(description: "group called completed notify closure") let timestamp = CFAbsoluteTimeGetCurrent() let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 10.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 10.0)], duration: 0.2) let group = MotionGroup(motions: [motion, motion2]) .completed { (group) in let final_value = tester.value XCTAssertEqual(final_value, 10.0) XCTAssertEqual(group.totalProgress, 1.0) let new_timestamp = CFAbsoluteTimeGetCurrent() let motion = group.motions.first as! Motion XCTAssertEqual(new_timestamp, timestamp + motion.duration, accuracy: 0.9) did_complete.fulfill() } group.delay = 0.2 group.start() waitForExpectations(timeout: 1.0, handler: nil) } func test_repeating() { let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 100.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 100.0)], duration: 0.2) let did_repeat = expectation(description: "group called cycleRepeated notify closure") let did_complete = expectation(description: "group called completed notify closure") let group = MotionGroup(motions: [motion, motion2], options: [.repeats]) .cycleRepeated({ (group) in XCTAssertEqual(group.totalProgress, 0.5) XCTAssertEqual(group.cycleProgress, 0.0) XCTAssertEqual(group.cyclesCompletedCount, 1) did_repeat.fulfill() }) .completed { (group) in XCTAssertEqual(tester.value, 100.0) XCTAssertEqual(tester2.value, 100.0) let motion = group.motions.first as? Motion XCTAssertEqual(motion?.properties[0].current, motion?.properties[0].end) XCTAssertEqual(motion?.totalProgress, 1.0) let new_cycles = group.repeatCycles + 1 XCTAssertEqual(group.cyclesCompletedCount, new_cycles) XCTAssertEqual(group.cycleProgress, 1.0) XCTAssertEqual(group.totalProgress, 1.0) XCTAssertEqual(group.motionState, MotionState.stopped) did_complete.fulfill() } .repeats(1) group.start() waitForExpectations(timeout: 1.0, handler: nil) } func test_reversing() { let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 100.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 100.0)], duration: 0.2) let did_reverse = expectation(description: "group called reversed notify closure") let did_complete = expectation(description: "group called completed notify closure") let group = MotionGroup(motions: [motion, motion2], options: [.reverses]) .reversed({ (group) in XCTAssertTrue(group.totalProgress <= 0.5) XCTAssertTrue(group.cycleProgress <= 0.5) XCTAssertEqual(group.motionDirection, MotionDirection.reverse) did_reverse.fulfill() }) .completed { (group) in XCTAssertEqual(tester.value, 0.0) XCTAssertEqual(tester2.value, 0.0) let motion = group.motions.first as? Motion XCTAssertEqual(motion?.properties[0].current, motion?.properties[0].start) XCTAssertEqual(motion?.totalProgress, 1.0) XCTAssertEqual(group.cyclesCompletedCount, 1) XCTAssertEqual(group.cycleProgress, 1.0) XCTAssertEqual(group.totalProgress, 1.0) XCTAssertEqual(group.motionState, MotionState.stopped) did_complete.fulfill() } // should turn on reversing for all child motions XCTAssertTrue(motion.reversing) XCTAssertTrue(motion2.reversing) group.start() waitForExpectations(timeout: 1.0, handler: nil) } func test_reversing_when_syncMotionsWhenReversing_is_true() { let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 100.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 100.0)], duration: 0.5) let did_reverse = expectation(description: "group called reversed notify closure") let did_complete = expectation(description: "group called completed notify closure") let group = MotionGroup(motions: [motion, motion2]) .reversed({ (group) in print("reversed") XCTAssertTrue(group.totalProgress <= 0.5) XCTAssertTrue(group.cycleProgress <= 0.5) XCTAssertEqual(group.motionDirection, MotionDirection.reverse) did_reverse.fulfill() }) .completed { (group) in XCTAssertEqual(tester.value, 0.0) XCTAssertEqual(tester2.value, 0.0) let motion = group.motions.first as? Motion XCTAssertEqual(motion?.properties[0].current, motion?.properties[0].start) XCTAssertEqual(motion?.totalProgress, 1.0) XCTAssertEqual(group.cyclesCompletedCount, 1) XCTAssertEqual(group.cycleProgress, 1.0) XCTAssertEqual(group.totalProgress, 1.0) XCTAssertEqual(group.motionState, MotionState.stopped) did_complete.fulfill() } .reverses(syncsChildMotions: true) .start() let after_time = DispatchTime.now() + Double(Int64(0.3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC); DispatchQueue.main.asyncAfter(deadline: after_time, execute: { // motion with the shorter duration should wait for the other motion to finish before group reverses XCTAssertEqual(motion.motionState, MotionState.paused) XCTAssertEqual(motion2.motionState, MotionState.moving) XCTAssertEqual(group.motionDirection, MotionDirection.forward) }) waitForExpectations(timeout: 2.0, handler: nil) } // MARK: Moveable methods func test_start() { let did_start = expectation(description: "group called started notify closure") let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 10.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 10.0)], duration: 0.2) let group = MotionGroup(motions: [motion, motion2]) .started { (group) in XCTAssertEqual(group.motionState, MotionState.moving) did_start.fulfill() } group.start() // should not start when paused group.pause() group.start() XCTAssertEqual(group.motionState, MotionState.paused) waitForExpectations(timeout: 1.0, handler: nil) } func test_stop() { let did_stop = expectation(description: "group called stopped notify closure") let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 10.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 10.0)], duration: 0.2) let group = MotionGroup(motions: [motion, motion2]) .stopped { (group) in XCTAssertEqual(group.motionState, MotionState.stopped) did_stop.fulfill() } group.start() let after_time = DispatchTime.now() + Double(Int64(0.02 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC); DispatchQueue.main.asyncAfter(deadline: after_time, execute: { group.stop() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_pause() { let did_pause = expectation(description: "group called paused notify closure") let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 10.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 10.0)], duration: 0.2) let group = MotionGroup(motions: [motion, motion2]) .paused { (group) in XCTAssertEqual(group.motionState, MotionState.paused) did_pause.fulfill() } group.start() group.pause() waitForExpectations(timeout: 1.0, handler: nil) } func test_pause_while_stopped() { let tester = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 10.0)], duration: 0.2) let group = MotionGroup(motions: [motion]) group.start() group.stop() group.pause() // should not pause while stopped XCTAssertEqual(group.motionState, MotionState.stopped) } func test_resume() { let did_resume = expectation(description: "group called resumed notify closure") let did_complete = expectation(description: "group called completed notify closure") let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 10.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 10.0)], duration: 0.2) let group = MotionGroup(motions: [motion, motion2]) .resumed { (group) in XCTAssertEqual(group.motionState, MotionState.moving) did_resume.fulfill() } .completed { (group) in XCTAssertEqual(tester.value, 10.0) XCTAssertEqual(group.totalProgress, 1.0) XCTAssertEqual(group.motionState, MotionState.stopped) did_complete.fulfill() } group.start() group.pause() let after_time = DispatchTime.now() + Double(Int64(0.02 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC); DispatchQueue.main.asyncAfter(deadline: after_time, execute: { group.resume() }) waitForExpectations(timeout: 1.0, handler: nil) } func test_update() { let did_update = expectation(description: "group called updated notify closure") let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 10.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 10.0)], duration: 0.2) let group = MotionGroup(motions: [motion, motion2]) .updated { (group) in XCTAssertEqual(group.motionState, MotionState.moving) did_update.fulfill() group.stop() } group.start() waitForExpectations(timeout: 1.0, handler: nil) } func test_reset() { let did_reset = expectation(description: "motion called updated notify closure") let tester = Tester() let tester2 = Tester() let motion = Motion(target: tester, properties: [PropertyData("value", 10.0)], duration: 0.2) let motion2 = Motion(target: tester2, properties: [PropertyData("value", 10.0)], duration: 0.2) let group = MotionGroup(motions: [motion, motion2]) group.start() let after_time = DispatchTime.now() + Double(Int64(0.02 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC); DispatchQueue.main.asyncAfter(deadline: after_time, execute: { group.reset() XCTAssertEqual(group.totalProgress, 0.0) XCTAssertEqual(group.cycleProgress, 0.0) XCTAssertEqual(group.cyclesCompletedCount, 0) did_reset.fulfill() }) waitForExpectations(timeout: 1.0, handler: nil) } }
mit
41159d624dafb95dab28f0f79b62acb1
37.008696
112
0.592828
4.502704
false
true
false
false
msfeldstein/Frameless
Frameless/AppDefaults.swift
2
1057
// // AppDefaults.swift // Frameless // // Created by Jay Stakelon on 10/26/14. // Copyright (c) 2014 Jay Stakelon. All rights reserved. // enum AppDefaultKeys: String { case History = "browserHistory" case KeepHistory = "keepHistory" case Favorites = "browserFavorites" case IntroVersionSeen = "introVersionSeen" case ShakeGesture = "shake" case PanFromBottomGesture = "panFromBottom" case PanFromTopGesture = "panFromTop" case ForwardBackGesture = "panLeftRight" case FramerBonjour = "framerConnect" case KeepAwake = "keepAwake" case SearchEngine = "searchEngine" } let BLUE = UIColorFromHex(0x28AFFA) let HIGHLIGHT_BLUE = UIColorFromHex(0x28AFFA, alpha: 0.6) let GREEN = UIColorFromHex(0x7DDC16) let PURPLE = UIColorFromHex(0x9178E2) let CYAN = UIColorFromHex(0x2DD7AA) let TEXT = UIColorFromHex(0x24262A) let LIGHT_TEXT = UIColorFromHex(0xAEB2BA) let LIGHT_GREY = UIColorFromHex(0xF2F5F9) let LIGHT_GREY_BORDER = UIColorFromHex(0xCACED3) let HISTORY_UPDATED_NOTIFICATION = "HistoryUpdatedNotification"
mit
16675c13856d715e43e0ee1cdb78ecd8
30.117647
63
0.751183
3.262346
false
false
false
false
ahmed93/AAShimmerView
AAShimmerView/Classes/UIView+AAShimmerView.swift
1
2399
// // UIView+AAShimmerView.swift // AAShimmerView // // Created by Ahmed Magdi on 6/11/17. // Copyright © 2017 Ahmed Magdi. All rights reserved. // import UIKit public enum ShimmerAlignment { case center case top case bottom } public extension UIView { private static let association_subViews = ObjectAssociation<[UIView]>() private static let association_viewHeight = ObjectAssociation<CGFloat>() private static let association_viewAlpha = ObjectAssociation<CGFloat>() private static let association_FBShimmerView = ObjectAssociation<AAShimmerView>() private static let association_shimmerColors = ObjectAssociation<[UIColor]>() private static let association_shimmerVerticalAlignment = ObjectAssociation<ShimmerAlignment>() private var shimmerView: AAShimmerView? { get { return UIView.association_FBShimmerView[self] } set { UIView.association_FBShimmerView[self] = newValue } } var aaShimmerViewAlpha: CGFloat { get { return UIView.association_viewAlpha[self] ?? self.alpha } set { UIView.association_viewAlpha[self] = newValue } } public var aaShimmerSubViews: [UIView]? { get { return UIView.association_subViews[self] } set { UIView.association_subViews[self] = newValue } } public var aaShimmerHeight: CGFloat { get { return UIView.association_viewHeight[self] ?? self.frame.height } set { UIView.association_viewHeight[self] = newValue } } public var isShimmering:Bool { return shimmerView != nil } public var aashimmerColors:[UIColor]? { get { return UIView.association_shimmerColors[self] } set { UIView.association_shimmerColors[self] = newValue } } /// Vertical Alignment by default is set to center. public var aashimmerVerticalAlignment:ShimmerAlignment { get { return UIView.association_shimmerVerticalAlignment[self] ?? .center } set { UIView.association_shimmerVerticalAlignment[self] = newValue } } public func startShimmering() { if shimmerView == nil { shimmerView = AAShimmerView(rootView: self) } shimmerView?.start() } public func stopShimmering() { if shimmerView == nil { return } shimmerView?.stop() shimmerView = nil } }
mit
111daf2a3ccca02aa482af58077a6216
30.973333
99
0.667223
4.629344
false
false
false
false
wwu-pi/md2-framework
de.wwu.md2.framework/res/resources/ios/lib/controller/validator/MD2StringRangeValidator.swift
1
2403
// // MD2StringRangeValidator.swift // md2-ios-library // // Created by Christoph Rieger on 23.07.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // /** Validator to check for a given string range. */ class MD2StringRangeValidator: MD2Validator { /// Unique identification string. let identifier: MD2String /// Custom message to display. var message: (() -> MD2String)? /// Default message to display. var defaultMessage: MD2String { get { return MD2String("This value must be between \(minLength) and \(maxLength) characters long!") } } /// The minimum allowed length. var minLength: MD2Integer /// The maximum allowed length. var maxLength: MD2Integer /** Default initializer. :param: identifier The unique validator identifier. :param: message Closure of the custom method to display. :param: minLength The minimum length of a valid string. :param: maxLength The maximum langth of a valid string. */ init(identifier: MD2String, message: (() -> MD2String)?, minLength: MD2Integer, maxLength: MD2Integer) { self.identifier = identifier self.message = message self.minLength = minLength self.maxLength = maxLength } /** Validate a value. :param: value The value to check. :return: Validation result */ func isValid(value: MD2Type) -> Bool { if !(value is MD2String) || !((value as! MD2String).isSet()) || !(maxLength.isSet()) { return false } // Set default minimum length if minLength.isSet() == false { minLength.platformValue = 0 } let stringValue = (value as! MD2String).platformValue! if count(stringValue) >= minLength.platformValue! && count(stringValue) <= maxLength.platformValue! { return true } else { return false } } /** Return the message to display on wrong validation. Use custom method if set or else use default message. */ func getMessage() -> MD2String { if let _ = message { return message!() } else { return defaultMessage } } }
apache-2.0
3af24d8ebf5586e828e32be039e0454f
26.011236
108
0.573034
4.767857
false
false
false
false
koher/EasyImagy
Tests/EasyImagyTests/ConvolutionTests.swift
1
5048
import XCTest import EasyImagy class ConvolutionTests: XCTestCase { func testConvoluted() { do { let image = Image<Int>(width: 2, height: 2, pixels: [ 1, 2, 3, 4, ]) let kernel = Image<Int>(width: 5, height: 5, pixels: [ 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, ]) let convoluted = image.convoluted(with: kernel) XCTAssertEqual(convoluted[0, 0], 65) XCTAssertEqual(convoluted[1, 0], 70) XCTAssertEqual(convoluted[0, 1], 75) XCTAssertEqual(convoluted[1, 1], 80) } do { let image = Image<Int>(width: 2, height: 2, pixels: [ 1, 2, 3, 4, ]) let kernel = Image<Int>(width: 5, height: 5, pixels: [ 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 1, 5, 6, 7, 1, 1, 8, 9, 10, 1, 1, 1, 1, 1, 1, ]) let convoluted = image.convoluted(with: kernel, extrapolatedBy: .constant(0)) XCTAssertEqual(convoluted[0, 0], 87) XCTAssertEqual(convoluted[1, 0], 77) XCTAssertEqual(convoluted[0, 1], 57) XCTAssertEqual(convoluted[1, 1], 47) } do { let image = Image<Int>(width: 2, height: 2, pixels: [ 1, 2, 3, 4, ]) let kernel = Image<Int>(width: 5, height: 5, pixels: [ 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, ]) let convoluted = image.convoluted(with: kernel, extrapolatedBy: .edge) XCTAssertEqual(convoluted[0, 0], 65) XCTAssertEqual(convoluted[1, 0], 70) XCTAssertEqual(convoluted[0, 1], 75) XCTAssertEqual(convoluted[1, 1], 80) } do { let image = Image<Int>(width: 2, height: 2, pixels: [ 1, 2, 3, 4, ]) let kernel = Image<Int>(width: 5, height: 5, pixels: [ 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, ]) let convoluted = image.convoluted(with: kernel, extrapolatedBy: .repeat) XCTAssertEqual(convoluted[0, 0], 59) XCTAssertEqual(convoluted[1, 0], 68) XCTAssertEqual(convoluted[0, 1], 77) XCTAssertEqual(convoluted[1, 1], 86) } do { let image = Image<Int>(width: 2, height: 2, pixels: [1, 2, 3, 4]) let kernel = Image<Int>(width: 5, height: 5, pixels: [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ]) let convoluted = image.convoluted(with: kernel, extrapolatedBy: .reflection) XCTAssertEqual(convoluted[0, 0], 70) XCTAssertEqual(convoluted[1, 0], 65) XCTAssertEqual(convoluted[0, 1], 60) XCTAssertEqual(convoluted[1, 1], 55) } do { // `kernel` of `ImageSlice` let image = Image<Int>(width: 3, height: 2, pixels: [ 1, 2, 3, 4, 5, 6, ]) let kernel0 = Image<Int>(width: 5, height: 5, pixels: [ 99, 99, 99, 99, 99, 99, 1, 2, 3, 99, 99, 4, 5, 6, 99, 99, 7, 8, 9, 99, 99, 99, 99, 99, 99, ]) let kernel: ImageSlice<Int> = kernel0[1...3, 1...3] XCTAssertEqual(image.convoluted(with: kernel, extrapolatedBy: .constant(0)), Image<Int>(width: 3, height: 2, pixels: [ 94, 154, 106, 58, 91, 58, ])) } do { // `convoluted` for `ImageSlice` let image = Image<Int>(width: 4, height: 4, pixels: [ 99, 99, 99, 99, 99, 1, 2, 99, 99, 3, 4, 99, 99, 99, 99, 99, ]) let slice: ImageSlice<Int> = image[1...2, 1...2] let kernel = Image<Int>(width: 5, height: 5, pixels: [ 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, ]) XCTAssertEqual(slice.convoluted(with: kernel), Image<Int>(width: 2, height: 2, pixels: [ 65, 70, 75, 80, ])) } } }
mit
1a08abae553f85a1e1a69423368786ce
31.993464
130
0.386292
3.733728
false
false
false
false
Huralnyk/rxswift
RxSwiftPlayground/RxSwift.playground/Pages/09. Error Handling.xcplaygroundpage/Contents.swift
1
2843
//: [Previous](@previous) import Foundation import RxSwift import RxCocoa exampleOf(description: "catchErrorJustReturn") { let disposeBag = DisposeBag() let sequenceThatFails = PublishSubject<String>() sequenceThatFails.catchErrorJustReturn("😀") .subscribe { print($0) } .addDisposableTo(disposeBag) sequenceThatFails.onNext("Hello, world!") sequenceThatFails.onError(Error.test) } exampleOf(description: "catchError") { let disposeBag = DisposeBag() let sequenceThatFails = PublishSubject<String>() let recoverySequence = PublishSubject<String>() sequenceThatFails.catchError { print("Error:", $0) return recoverySequence }.subscribe { print($0) } sequenceThatFails.onNext("Hello, again") sequenceThatFails.onError(Error.test) sequenceThatFails.onNext("Still there?") recoverySequence.onNext("Don't worry, I've got this!") } exampleOf(description: "retry") { let disposeBag = DisposeBag() var count = 1 let sequenceThatErrors = Observable<Int>.create { o in o.onNext(1) o.onNext(2) if count < 5 { o.onError(Error.test) print("Error encountered") count += 1 } o.onNext(3) o.onCompleted() return Disposables.create() } sequenceThatErrors .retry(3) .subscribe { print($0) } .addDisposableTo(disposeBag) } exampleOf(description: "Driver onErrorJustReturn") { let disposeBag = DisposeBag() let subject = PublishSubject<Int>() subject.asDriver(onErrorJustReturn: 1000) .drive(onNext: { print($0) }).addDisposableTo(disposeBag) subject.onNext(1) subject.onNext(2) subject.onError(Error.test) subject.onNext(3) } exampleOf(description: "Driver onErrorDriveWith") { let disposeBag = DisposeBag() let subject = PublishSubject<Int>() let recoverySubject = PublishSubject<Int>() subject.asDriver(onErrorDriveWith: recoverySubject.asDriver(onErrorJustReturn: 1000)) .drive(onNext: { print($0) }).addDisposableTo(disposeBag) subject.onNext(1) subject.onNext(2) subject.onError(Error.test) subject.onNext(3) recoverySubject.onNext(4) } exampleOf(description: "Driver onErrorRecover") { let disposeBag = DisposeBag() let subject = PublishSubject<Int>() subject .asDriver(onErrorRecover: { print("Error:", $0) return Driver.just(1000) }).drive(onNext: { print($0) }).addDisposableTo(disposeBag) subject.onNext(1) subject.onNext(2) subject.onError(Error.test) subject.onNext(3) } //: [Next](@next)
mit
1d8cb9ed8d92c96f761b89214b8778b0
23.273504
89
0.619014
4.61039
false
true
false
false
s-aska/Justaway-for-iOS
JustawayShare/ShareViewController.swift
1
14670
// // ShareViewController.swift // JustawayShare // // Created by Shinichiro Aska on 3/22/16. // Copyright © 2016 Shinichiro Aska. All rights reserved. // import UIKit import Social import Accounts class ShareViewController: SLComposeServiceViewController { // MARK: Properties static let keyUserID = "keyUserID" var hasImage = false var imageData: Data? var account: ACAccount? var accounts = [ACAccount]() let previewView = UIImageView() var shareURL: URL? var indicatorView: UIActivityIndicatorView? let session: URLSession = { let configuration = URLSessionConfiguration.default return URLSession(configuration: configuration, delegate: nil, delegateQueue: nil) }() // MARK: - UIViewController override func viewDidLoad() { previewView.clipsToBounds = true previewView.contentMode = .scaleAspectFill previewView.addConstraints([ NSLayoutConstraint(item: previewView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: 60), NSLayoutConstraint(item: previewView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 60) ]) previewView.isUserInteractionEnabled = true previewView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(removeImage))) } // MARK: - SLComposeServiceViewController override func isContentValid() -> Bool { self.calcRemaining() return self.account != nil && (self.charactersRemaining?.intValue ?? 0) > 0 } func calcRemaining() { let text = textView.text ?? "" let oldValue = Int(self.charactersRemaining ?? 0) let newValue = 140 - Twitter.count(text, hasImage: hasImage) if self.charactersRemaining == nil || oldValue != newValue { self.charactersRemaining = newValue as NSNumber } } override func didSelectPost() { if let account = account { if let data = self.imageData { Twitter.updateStatusWithMedia(account, status: contentText, imageData: data) } else { Twitter.updateStatus(account, status: contentText) } } self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) } override func loadPreviewView() -> UIView! { loadNowPlayingFromShareContent() loadInputItems() return previewView } override func configurationItems() -> [Any]! { let twitter = configurationItemsTwitterAccount() return [twitter] } func configurationItemsTwitterAccount() -> SLComposeSheetConfigurationItem { let ud = UserDefaults.standard let userID = ud.object(forKey: ShareViewController.keyUserID) as? String ?? "" let twitter = SLComposeSheetConfigurationItem() twitter?.title = "Account" twitter?.tapHandler = { if self.accounts.count == 0 { DispatchQueue.main.async(execute: { () -> Void in self.showDialog("Error", message: "Twitter requires you to authorize Justaway to use your account.") }) return } let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction( title: "Close", style: .cancel, handler: { action in })) for twitterAccount in self.accounts { let account = twitterAccount actionSheet.addAction(UIAlertAction( title: account.username, style: .default, handler: { action in twitter?.value = account.username self.account = account if let userID = account.value(forKeyPath: "properties.user_id") as? String { ud.set(userID, forKey: ShareViewController.keyUserID) ud.synchronize() } })) } DispatchQueue.main.async(execute: { () -> Void in self.present(actionSheet, animated: true, completion: nil) }) } let accountStore = ACAccountStore() let accountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter) accountStore.requestAccessToAccounts(with: accountType, options: nil) { granted, error in if granted { let twitterAccounts = accountStore.accounts(with: accountType) as? [ACAccount] ?? [] if let account = twitterAccounts.first { if !userID.isEmpty { for account in twitterAccounts { let accountUserID = account.value(forKeyPath: "properties.user_id") as? String ?? "" if accountUserID == userID { DispatchQueue.main.async(execute: { () -> Void in twitter?.value = account.username }) self.account = account break } } } if self.account == nil { self.account = account DispatchQueue.main.async(execute: { () -> Void in twitter?.value = account.username self.validateContent() }) } } else { DispatchQueue.main.async(execute: { () -> Void in self.showDialog("Error", message: "There are no Twitter accounts configured. You can add or create a Twitter account in Settings.") }) } self.accounts = twitterAccounts } else { DispatchQueue.main.async(execute: { () -> Void in self.showDialog("Error", message: "Twitter requires you to authorize Justaway to use your account.") }) } } return twitter! } // MARK: - Public func loadNowPlayingFromShareContent() { GooglePlayMusic.loadMetaFromShareURL(contentText) { (music) in DispatchQueue.main.async(execute: { () -> Void in self.textView.text = "#NowPlaying " + music.titleWithArtist + "\n" + music.musicURL.absoluteString self.textView.selectedRange = NSRange.init(location: 0, length: 0) self.validateContent() }) if let imageURL = music.albumURL { self.loadImageURL(imageURL) } } } func loadInputItems() { guard let inputItems = self.extensionContext?.inputItems else { return } for inputItem in inputItems { guard let item = inputItem as? NSExtensionItem else { continue } guard let attachments = item.attachments else { continue } for attachment in attachments { guard let provider = attachment as? NSItemProvider else { continue } loadInputURL(provider) loadInputImage(provider) } } } func loadInputURL(_ provider: NSItemProvider) { if provider.hasItemConformingToTypeIdentifier("public.url") { provider.loadItem(forTypeIdentifier: "public.url", options: nil, completionHandler: { (item, error) in guard let itemURL = item as? URL else { return } if !itemURL.absoluteString.hasPrefix("http") { return } if self.textView.text.isEmpty && self.shareURL == nil { self.loadPageTitle(itemURL) } self.shareURL = itemURL DispatchQueue.main.async(execute: { () -> Void in if self.textView.text.isEmpty { self.textView.text = itemURL.absoluteString } else { self.textView.text = self.textView.text + " " + itemURL.absoluteString } self.textView.selectedRange = NSRange.init(location: 0, length: 0) self.textView.setContentOffset(CGPoint.zero, animated: false) self.validateContent() }) }) } } func loadInputImage(_ provider: NSItemProvider) { for key in ["public.jpeg", "public.image"] { if provider.hasItemConformingToTypeIdentifier(key) { provider.loadItem(forTypeIdentifier: key, options: nil, completionHandler: { (item, error) in switch item { case let imageURL as URL: self.loadImageURL(imageURL) case let image as UIImage: self.loadImage(image) case let data as Data: self.loadImageData(data) default: break } }) } } } // SFSafariViewController don't set page title to self.textView.text func loadPageTitle(_ pageURL: URL) { if let ud = UserDefaults.init(suiteName: "group.pw.aska.justaway"), let title = ud.object(forKey: "shareTitle") as? String, let shareURL = ud.url(forKey: "shareURL"), pageURL == shareURL { OperationQueue.main.addOperation { if self.textView.text.isEmpty { self.textView.text = title } else { self.textView.text = title + " " + self.textView.text } self.textView.selectedRange = NSRange.init(location: 0, length: 0) self.textView.setContentOffset(CGPoint.zero, animated: false) self.validateContent() } return } // Not Justaway.app's SFSafariViewController var urlComponents = URLComponents(string: "https://tyxd8v3j67.execute-api.ap-northeast-1.amazonaws.com/prod/ogp")! urlComponents.queryItems = [ URLQueryItem.init(name: "url", value: pageURL.absoluteString) ] guard let url = urlComponents.url else { return } let req = NSMutableURLRequest.init(url: url) req.httpMethod = "GET" let ogpCompletion = { (data: Data?, response: URLResponse?, error: Error?) -> Void in guard let data = data else { self.stopIndicator() return } do { let json: Any = try JSONSerialization.jsonObject(with: data, options: []) if let dic = json as? NSDictionary, let title = dic["title"] as? String { OperationQueue.main.addOperation { self.textView.text = title + " " + self.textView.text self.textView.selectedRange = NSRange.init(location: 0, length: 0) self.textView.setContentOffset(CGPoint.zero, animated: false) self.validateContent() self.stopIndicator() } } else { self.stopIndicator() } } catch _ as NSError { self.stopIndicator() return } } startIndicator() let configuration = URLSessionConfiguration.default let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil) session.dataTask(with: url, completionHandler: ogpCompletion).resume() } func startIndicator() { let indicatorView = UIActivityIndicatorView(frame: CGRect.init(x: 0, y: 0, width: 80, height: 80)) indicatorView.layer.cornerRadius = 10 indicatorView.activityIndicatorViewStyle = .whiteLarge indicatorView.hidesWhenStopped = true indicatorView.center = CGPoint.init(x: self.view.center.x, y: self.view.center.y - 108) indicatorView.backgroundColor = UIColor(white: 0, alpha: 0.6) self.indicatorView = indicatorView DispatchQueue.main.async(execute: { () -> Void in self.view.addSubview(indicatorView) indicatorView.startAnimating() }) } func stopIndicator() { DispatchQueue.main.async(execute: { () -> Void in self.indicatorView?.stopAnimating() self.indicatorView?.removeFromSuperview() }) } func loadImage(_ image: UIImage) { self.imageData = UIImagePNGRepresentation(image) self.hasImage = true DispatchQueue.main.async(execute: { () -> Void in self.previewView.image = image self.validateContent() }) } func loadImageData(_ data: Data) { self.imageData = data self.hasImage = true let image = UIImage(data: data) DispatchQueue.main.async(execute: { () -> Void in self.previewView.image = image self.validateContent() }) } func loadImageURL(_ imageURL: URL) { let completion = { (data: Data?, response: URLResponse?, error: Error?) -> Void in guard let data = data else { return } self.loadImageData(data) } self.session.dataTask(with: imageURL, completionHandler: completion).resume() } func removeImage() { hasImage = false imageData = nil DispatchQueue.main.async(execute: { () -> Void in self.previewView.image = nil self.previewView.removeFromSuperview() self.validateContent() }) } func showDialog(_ title: String, message: String) { let actionSheet = UIAlertController(title: title, message: message, preferredStyle: .alert) actionSheet.addAction(UIAlertAction( title: "Close", style: .cancel, handler: { action in })) self.present(actionSheet, animated: true, completion: nil) } }
mit
c03db6ed4681ebca2ae739320feacb7c
38.753388
155
0.548163
5.396983
false
false
false
false
qblu/MosaicCollectionViewLayout
MosaicCollectionViewLayoutTests/MosaicCollectionViewLayoutTests.swift
1
2790
// // MosaicCollectionViewLayoutTests.swift // MosaicCollectionViewLayoutTests // // Created by Rusty Zarse on 11/23/15. // Copyright © 2015 com.levous. All rights reserved. // import XCTest @testable import MosaicCollectionViewLayout class MosaicCollectionViewLayoutTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testOverrideSizesPerSection() { // Mosaic supports overridding let sizes: [MosaicCollectionViewLayout.MosaicCellSize] = [ .SmallSquare, .BigSquare, .SmallSquare, .SmallSquare, .BigSquare, .BigSquare, .SmallSquare, .SmallSquare, .SmallSquare, .SmallSquare, .SmallSquare, .SmallSquare ] let width: CGFloat = 300.0 let layout = MosaicCollectionViewLayout() let delegate = TestMosaicCollectionViewDelegate() delegate.interitemSpacing = 0.0 let collectionView = UICollectionView(frame: CGRectMake(0, 0, width, 100), collectionViewLayout: layout) collectionView.delegate = delegate collectionView.dataSource = delegate for (row, size) in sizes.enumerate() { // force the layout to a known distribution of sizes (verified by `SectionLayoutViewModelTests.testAddCellsOfVaryingSizes`) let indexPath = NSIndexPath(forItem: row, inSection: 0) delegate.allowedMosaicCellSizesForIndexPath[indexPath] = [size] } // three sections delegate.numberOfSections = 3 // create a custom section with three rows delegate.numberOfRowsForSection[1] = 3 var indexPath = NSIndexPath(forItem: 0, inSection: 1) delegate.sizeforIndexPath[indexPath] = CGSizeMake(200.0, 120.0) delegate.allowedMosaicCellSizesForIndexPath[indexPath] = [.CustomSizeOverride] indexPath = NSIndexPath(forItem: 1, inSection: 1) delegate.sizeforIndexPath[indexPath] = CGSizeMake(100.0, 20.0) delegate.allowedMosaicCellSizesForIndexPath[indexPath] = [.CustomSizeOverride] indexPath = NSIndexPath(forItem: 2, inSection: 1) delegate.sizeforIndexPath[indexPath] = CGSizeMake(120.0, 99.0) delegate.allowedMosaicCellSizesForIndexPath[indexPath] = [.CustomSizeOverride] let expectedCustomSectionHeight: CGFloat = 239.0 // third section indexPath = NSIndexPath(forItem: 0, inSection: 2) delegate.allowedMosaicCellSizesForIndexPath[indexPath] = [.BigSquare] layout.prepareLayout() let customSectionFrameNode = layout.attributeBuilder.layoutFrameTree.sections[1] let frameHeight = customSectionFrameNode.frame.height XCTAssertEqual(expectedCustomSectionHeight, frameHeight) } }
mit
0e96095a763007a87fae1f7de9803917
28.368421
126
0.751524
4.018732
false
true
false
false
jessesquires/JSQCoreDataKit
Sources/CoreDataStackProvider.swift
1
6103
// // Created by Jesse Squires // https://www.jessesquires.com // // // Documentation // https://jessesquires.github.io/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright © 2015-present Jesse Squires // Released under an MIT license: https://opensource.org/licenses/MIT // import CoreData /** An instance of `CoreDataStackProvider` is responsible for creating instances of `CoreDataStack`. Because the adding of the persistent store to the persistent store coordinator during initialization of a `CoreDataStack` can take an unknown amount of time, you should not perform this operation on the main queue. See this [guide](https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Conceptual/CoreData/IntegratingCoreData.html#//apple_ref/doc/uid/TP40001075-CH9-SW1) for more details. - warning: You should not create instances of `CoreDataStack` directly. Use a `CoreDataStackProvider` instead. */ public struct CoreDataStackProvider { // MARK: Typealiases /// Describes the initialization options for a persistent store. public typealias PersistentStoreOptions = [AnyHashable: Any] // MARK: Properties /// Describes default persistent store options. public static let defaultStoreOptions: PersistentStoreOptions = [ NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true ] /// The model for the stack that the factory produces. public let model: CoreDataModel /** A dictionary that specifies options for the store that the factory produces. The default value is `DefaultStoreOptions`. */ public let options: PersistentStoreOptions? // MARK: Initialization /** Constructs a new `CoreDataStackProvider` instance with the specified `model` and `options`. - parameter model: The model describing the stack. - parameter options: Options for the persistent store. - returns: A new `CoreDataStackProvider` instance. */ public init(model: CoreDataModel, options: PersistentStoreOptions? = defaultStoreOptions) { self.model = model self.options = options } // MARK: Creating a stack /** Initializes a new `CoreDataStack` instance using the factory's `model` and `options`. - warning: If a queue is provided, this operation is performed asynchronously on the specified queue, and the completion closure is executed asynchronously on the main queue. If `queue` is `nil`, then this method and the completion closure execute synchronously on the current queue. - parameter queue: The queue on which to initialize the stack. The default is a background queue with a "user initiated" quality of service class. If passing `nil`, this method is executed synchronously on the queue from which the method was called. - parameter completion: The closure to be called once initialization is complete. If a queue is provided, this is called asynchronously on the main queue. Otherwise, this is executed on the thread from which the method was originally called. */ public func createStack(onQueue queue: DispatchQueue? = .global(qos: .userInitiated), completion: @escaping (CoreDataStack.StackResult) -> Void) { let isAsync = (queue != nil) let creationClosure = { let storeCoordinator: NSPersistentStoreCoordinator do { storeCoordinator = try self._createStoreCoordinator() } catch { if isAsync { DispatchQueue.main.async { completion(.failure(error)) } } else { completion(.failure(error)) } return } let backgroundContext = self._createContext(.privateQueueConcurrencyType, name: "background") backgroundContext.persistentStoreCoordinator = storeCoordinator let mainContext = self._createContext(.mainQueueConcurrencyType, name: "main") mainContext.persistentStoreCoordinator = storeCoordinator let stack = CoreDataStack(model: self.model, mainContext: mainContext, backgroundContext: backgroundContext, storeCoordinator: storeCoordinator) if isAsync { DispatchQueue.main.async { completion(.success(stack)) } } else { completion(.success(stack)) } } if let queue = queue { queue.async(execute: creationClosure) } else { creationClosure() } } // MARK: Private private func _createStoreCoordinator() throws -> NSPersistentStoreCoordinator { let storeCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.model.managedObjectModel) try storeCoordinator.addPersistentStore(ofType: self.model.storeType.type, configurationName: nil, at: self.model.storeURL, options: self.options) return storeCoordinator } private func _createContext(_ concurrencyType: NSManagedObjectContextConcurrencyType, name: String) -> NSManagedObjectContext { let context = NSManagedObjectContext(concurrencyType: concurrencyType) context.mergePolicy = NSMergePolicy(merge: .mergeByPropertyStoreTrumpMergePolicyType) let contextName = "JSQCoreDataKit.CoreDataStack.context." context.name = contextName + name return context } } extension CoreDataStackProvider: Equatable { /// :nodoc: public static func == (lhs: CoreDataStackProvider, rhs: CoreDataStackProvider) -> Bool { lhs.model == rhs.model } }
mit
f259026fb4f58415ce48a064ee585752
37.1375
191
0.650606
5.639556
false
false
false
false
AckeeCZ/ACKategories
ACKategoriesCore/PropertyWrappers/UserDefault.swift
1
5263
import Combine import Foundation private enum Keys { static var subject = UInt8(0) } /// A type safe property wrapper to set and get values from UserDefaults with support for defaults values. /// /// Usage: /// ``` /// @UserDefault("has_seen_app_introduction", default: false) /// var hasSeenAppIntroduction: Bool /// ``` /// /// [Apple documentation on UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults) @propertyWrapper public final class UserDefault<Value: Codable> { private let key: String private let defaultValue: Value private var userDefaults: UserDefaults private let errorLogger: ((Error) -> Void)? /// - Parameters: /// - key: Key for which the value should be saved /// - default: Default value to be used /// - userDefaults: `UserDefaults` where value should be saved into. Default is `UserDefaults.standard` /// - errorLogger: Closure that is triggered with error from encoding/decoding values from setter/getter public init( _ key: String, `default`: Value, userDefaults: UserDefaults = .standard, errorLogger: ((Error) -> Void)? = { print($0) } ) { self.key = key self.defaultValue = `default` self.userDefaults = userDefaults self.errorLogger = errorLogger } public var wrappedValue: Value { get { // Check if `Value` is supported by default by `UserDefaults` if Value.self as? PropertyListValue.Type != nil { return userDefaults.object(forKey: key) as? Value ?? defaultValue } else { guard let data = userDefaults.object(forKey: key) as? Data else { return defaultValue } let decoder = JSONDecoder() // Encoding root-level `singleValueContainer` fails on iOS <= 12.0 // Thus we always encode/decode it into array, so it has a root object // Related issue: https://github.com/AckeeCZ/ACKategories/issues/89 do { return try decoder.decode([Value].self, from: data).first ?? defaultValue } catch { errorLogger?(error) return defaultValue } } } set { if Value.self as? PropertyListValue.Type != nil { userDefaults.set(newValue, forKey: key) } else { let encoder = JSONEncoder() do { let data = try encoder.encode([newValue]) userDefaults.set(data, forKey: key) } catch { errorLogger?(error) } } if #available(iOS 13.0, macOS 10.15, *) { subject.send(newValue) } } } @available(iOS 13.0, macOS 10.15, *) public var projectedValue: AnyPublisher<Value, Never> { subject.eraseToAnyPublisher() } @available(iOS 13.0, macOS 10.15, *) // cannot have stored property with limited availability, cannot be lazy since Xcode 14 private var subject: CurrentValueSubject<Value, Never> { if let subject = objc_getAssociatedObject(self, &Keys.subject) as? CurrentValueSubject<Value, Never> { return subject } let subject = CurrentValueSubject<Value, Never>(wrappedValue) objc_setAssociatedObject(self, &Keys.subject, subject, .OBJC_ASSOCIATION_RETAIN) return subject } } public extension UserDefault { convenience init<Wrapped>(_ key: String, `default`: Optional<Wrapped> = nil, userDefaults: UserDefaults = .standard) where Value == Optional<Wrapped> { self.init(key, default: `default`, userDefaults: userDefaults) } } /// Taken from: https://github.com/guillermomuntaner/Burritos/blob/master/Sources/UserDefault/UserDefault.swift /// A type than can be stored in `UserDefaults`. /// /// - From UserDefaults; /// The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. /// For NSArray and NSDictionary objects, their contents must be property list objects. For more information, see What is a /// Property List? in Property List Programming Guide. public protocol PropertyListValue {} extension Data: PropertyListValue {} extension NSData: PropertyListValue {} extension String: PropertyListValue {} extension NSString: PropertyListValue {} extension Date: PropertyListValue {} extension NSDate: PropertyListValue {} extension NSNumber: PropertyListValue {} extension Bool: PropertyListValue {} extension Int: PropertyListValue {} extension Int8: PropertyListValue {} extension Int16: PropertyListValue {} extension Int32: PropertyListValue {} extension Int64: PropertyListValue {} extension UInt: PropertyListValue {} extension UInt8: PropertyListValue {} extension UInt16: PropertyListValue {} extension UInt32: PropertyListValue {} extension UInt64: PropertyListValue {} extension Double: PropertyListValue {} extension Float: PropertyListValue {} extension Array: PropertyListValue where Element: PropertyListValue {} extension Dictionary: PropertyListValue where Key == String, Value: PropertyListValue {}
mit
03360fe66dce484bf9616b2e157611ae
37.137681
155
0.65381
4.788899
false
false
false
false
ernestopino/Koloda
Pod/Classes/KolodaView/DraggableCardView/DraggableCardView.swift
1
13499
// // DraggableCardView.swift // TinderCardsSwift // // Created by Eugene Andreyev on 4/23/15. // Copyright (c) 2015 Yalantis. All rights reserved. // import UIKit import pop protocol DraggableCardDelegate: class { func cardDraggedWithFinishPercent(card: DraggableCardView, percent: CGFloat) func cardSwippedInDirection(card: DraggableCardView, direction: SwipeResultDirection) func cardWasReset(card: DraggableCardView) func cardTapped(card: DraggableCardView) } //Drag animation constants private let rotationMax: CGFloat = 1.0 private let defaultRotationAngle = CGFloat(M_PI) / 10.0 private let scaleMin: CGFloat = 0.8 public let cardSwipeActionAnimationDuration: NSTimeInterval = 0.4 //Reset animation constants private let cardResetAnimationSpringBounciness: CGFloat = 10.0 private let cardResetAnimationSpringSpeed: CGFloat = 20.0 private let cardResetAnimationKey = "resetPositionAnimation" private let cardResetAnimationDuration: NSTimeInterval = 0.2 public class DraggableCardView: UIView { weak var delegate: DraggableCardDelegate? private var overlayView: OverlayView? private var contentView: UIView? private var panGestureRecognizer: UIPanGestureRecognizer! private var tapGestureRecognizer: UITapGestureRecognizer! private var originalLocation: CGPoint = CGPoint(x: 0.0, y: 0.0) private var animationDirection: CGFloat = 1.0 private var dragBegin = false private var xDistanceFromCenter: CGFloat = 0.0 private var yDistanceFromCenter: CGFloat = 0.0 private var actionMargin: CGFloat = 0.0 private var firstTouch = true //MARK: Lifecycle init() { super.init(frame: CGRectZero) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } override public var frame: CGRect { didSet { actionMargin = frame.size.width / 2.0 } } deinit { removeGestureRecognizer(panGestureRecognizer) removeGestureRecognizer(tapGestureRecognizer) } private func setup() { panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:")) addGestureRecognizer(panGestureRecognizer) tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapRecognized:")) addGestureRecognizer(tapGestureRecognizer) } //MARK: Configurations func configure(view: UIView, overlayView: OverlayView?) { self.overlayView?.removeFromSuperview() if let overlay = overlayView { self.overlayView = overlay overlay.alpha = 0; self.addSubview(overlay) configureOverlayView() self.insertSubview(view, belowSubview: overlay) } else { self.addSubview(view) } self.contentView?.removeFromSuperview() self.contentView = view configureContentView() } private func configureOverlayView() { if let overlay = self.overlayView { overlay.translatesAutoresizingMaskIntoConstraints = false let width = NSLayoutConstraint( item: overlay, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0) let height = NSLayoutConstraint( item: overlay, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 0) let top = NSLayoutConstraint ( item: overlay, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0) let leading = NSLayoutConstraint ( item: overlay, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0) addConstraints([width,height,top,leading]) } } private func configureContentView() { if let contentView = self.contentView { contentView.translatesAutoresizingMaskIntoConstraints = false let width = NSLayoutConstraint( item: contentView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0) let height = NSLayoutConstraint( item: contentView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 0) let top = NSLayoutConstraint ( item: contentView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0) let leading = NSLayoutConstraint ( item: contentView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0) addConstraints([width,height,top,leading]) } } //MARK: GestureRecozniers func panGestureRecognized(gestureRecognizer: UIPanGestureRecognizer) { xDistanceFromCenter = gestureRecognizer.translationInView(self).x yDistanceFromCenter = gestureRecognizer.translationInView(self).y let touchLocation = gestureRecognizer.locationInView(self) switch gestureRecognizer.state { case .Began: if firstTouch { originalLocation = center firstTouch = false } dragBegin = true animationDirection = touchLocation.y >= frame.size.height / 2 ? -1.0 : 1.0 layer.shouldRasterize = true pop_removeAllAnimations() break case .Changed: let rotationStrength = min(xDistanceFromCenter / self.frame.size.width, rotationMax) let rotationAngle = animationDirection * defaultRotationAngle * rotationStrength let scaleStrength = 1 - ((1 - scaleMin) * fabs(rotationStrength)) let scale = max(scaleStrength, scaleMin) layer.rasterizationScale = scale * UIScreen.mainScreen().scale let transform = CGAffineTransformMakeRotation(rotationAngle) let scaleTransform = CGAffineTransformScale(transform, scale, scale) self.transform = scaleTransform center = CGPoint(x: originalLocation.x + xDistanceFromCenter, y: originalLocation.y + yDistanceFromCenter) updateOverlayWithFinishPercent(xDistanceFromCenter / frame.size.width) //100% - for proportion delegate?.cardDraggedWithFinishPercent(self, percent: min(fabs(xDistanceFromCenter * 100 / frame.size.width), 100)) break case .Ended: swipeMadeAction() layer.shouldRasterize = false default : break } } func tapRecognized(recogznier: UITapGestureRecognizer) { delegate?.cardTapped(self) } //MARK: Private private func updateOverlayWithFinishPercent(percent: CGFloat) { if let overlayView = self.overlayView { overlayView.overlayState = percent > 0.0 ? OverlayMode.Right : OverlayMode.Left //Overlay is fully visible on half way let overlayStrength = min(fabs(2 * percent), 1.0) overlayView.alpha = overlayStrength } } private func swipeMadeAction() { if xDistanceFromCenter > actionMargin { rightAction() } else if xDistanceFromCenter < -actionMargin { leftAction() } else { resetViewPositionAndTransformations() } } private func rightAction() { let finishY = originalLocation.y + yDistanceFromCenter let finishPoint = CGPoint(x: CGRectGetWidth(UIScreen.mainScreen().bounds) * 2, y: finishY) self.overlayView?.overlayState = OverlayMode.Right self.overlayView?.alpha = 1.0 self.delegate?.cardSwippedInDirection(self, direction: SwipeResultDirection.Right) UIView.animateWithDuration(cardSwipeActionAnimationDuration, delay: 0.0, options: .CurveLinear, animations: { self.center = finishPoint }, completion: { _ in self.dragBegin = false self.removeFromSuperview() }) } private func leftAction() { let finishY = originalLocation.y + yDistanceFromCenter let finishPoint = CGPoint(x: -CGRectGetWidth(UIScreen.mainScreen().bounds), y: finishY) self.overlayView?.overlayState = OverlayMode.Left self.overlayView?.alpha = 1.0 self.delegate?.cardSwippedInDirection(self, direction: SwipeResultDirection.Left) UIView.animateWithDuration(cardSwipeActionAnimationDuration, delay: 0.0, options: .CurveLinear, animations: { self.center = finishPoint }, completion: { _ in self.dragBegin = false self.removeFromSuperview() }) } private func resetViewPositionAndTransformations() { self.delegate?.cardWasReset(self) let resetPositionAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPosition) resetPositionAnimation.toValue = NSValue(CGPoint: originalLocation) resetPositionAnimation.springBounciness = cardResetAnimationSpringBounciness resetPositionAnimation.springSpeed = cardResetAnimationSpringSpeed resetPositionAnimation.completionBlock = { (_, _) in self.dragBegin = false } pop_addAnimation(resetPositionAnimation, forKey: cardResetAnimationKey) UIView.animateWithDuration(cardResetAnimationDuration, delay: 0.0, options: [.CurveLinear, .AllowUserInteraction], animations: { self.transform = CGAffineTransformMakeRotation(0) self.overlayView?.alpha = 0 self.layoutIfNeeded() return }, completion: { _ in self.transform = CGAffineTransformIdentity return }) } //MARK: Public func swipeLeft () { if !dragBegin { let finishPoint = CGPoint(x: -CGRectGetWidth(UIScreen.mainScreen().bounds), y: center.y) self.delegate?.cardSwippedInDirection(self, direction: SwipeResultDirection.Left) UIView.animateWithDuration(cardSwipeActionAnimationDuration, delay: 0.0, options: .CurveLinear, animations: { self.center = finishPoint self.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_4)) return }, completion: { _ in self.removeFromSuperview() return }) } } func swipeRight () { if !dragBegin { let finishPoint = CGPoint(x: CGRectGetWidth(UIScreen.mainScreen().bounds) * 2, y: center.y) self.delegate?.cardSwippedInDirection(self, direction: SwipeResultDirection.Right) UIView.animateWithDuration(cardSwipeActionAnimationDuration, delay: 0.0, options: .CurveLinear, animations: { self.center = finishPoint self.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4)) return }, completion: { _ in self.removeFromSuperview() return }) } } }
mit
751e0e871c6791ceec541c8754868319
34.245431
127
0.57745
5.861485
false
false
false
false
mikewxk/DYLiveDemo_swift
DYLiveDemo/DYLiveDemo/Classes/Main/View/PageContentView.swift
1
5369
// // PageContentView.swift // DYLiveDemo // // Created by xiaokui wu on 12/16/16. // Copyright © 2016 wxk. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(contentView: PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int) } private let contentCellId = "contentCellId" class PageContentView: UIView { //MARK: - 属性 private var childVcs : [UIViewController] private weak var parentVc : UIViewController? private var startOffsetX : CGFloat = 0 weak var delegate : PageContentViewDelegate? private var isForbidScrollDelegate = false //MARK: - 懒加载 private lazy var collectionView : UICollectionView = {[weak self] in// 避免闭包里用self会强引用 // 创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = self!.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .Horizontal //创建collectionView let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.pagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellId) return collectionView }() //MARK: - 自定义构造函数 init(frame: CGRect, childVcs: [UIViewController], parentVc: UIViewController?) { self.childVcs = childVcs self.parentVc = parentVc super.init(frame: frame); setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: - 设置UI界面 extension PageContentView{ private func setupUI(){ // 把所有子控制器添加到父控制器中 for childVc in childVcs { parentVc?.addChildViewController(childVc) } // 添加CollectionView,cell中存放子控制器的view addSubview(collectionView) collectionView.frame = bounds } } //MARK: - UICollectionView数据源 extension PageContentView: UICollectionViewDataSource{ func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(contentCellId, forIndexPath: indexPath) // 避免复用时出问题,先移除view for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } //MARK: - UICollectionViewDelegate extension PageContentView : UICollectionViewDelegate{ func scrollViewWillBeginDragging(scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(scrollView: UIScrollView) { if isForbidScrollDelegate {return}// 点击事件 // 定义需要获取的数据 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 // 判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX{// 左滑 // 滑动的比例 progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)//floor 取整函数 // 原索引 sourceIndex = Int(currentOffsetX / scrollViewW) // 目的索引 targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } if (currentOffsetX - startOffsetX) == scrollViewW{ progress = 1.0 targetIndex = sourceIndex } }else{ progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) targetIndex = Int(currentOffsetX / scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count{ sourceIndex = childVcs.count - 1 } } // 用代理把数据传出去 delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //MARK: - 外部方法 extension PageContentView{ func setCurrentIndex(index: Int) { let offsetX = CGFloat(index) * frame.width // 禁止滚动代理 isForbidScrollDelegate = true collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
unlicense
6e4e1b929c8de95a2c3956ccf7d8a4bd
25.061224
130
0.629992
5.6567
false
false
false
false
Sage-Bionetworks/BridgeAppSDK
BridgeAppSDK/SBAConsentDocumentFactory.swift
1
4166
// // SBAConsentDocument.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit import ResearchUXFactory /** Extension used by the `SBAOnboardingManager` to build the appropriate steps for a consent flow. */ extension SBASurveyFactory { /** Return visual consent step */ open func visualConsentStep() -> SBAVisualConsentStep { return self.steps?.sba_find({ $0 is SBAVisualConsentStep }) as? SBAVisualConsentStep ?? SBAVisualConsentStep(identifier: SBAOnboardingSectionBaseType.consent.rawValue, consentDocument: self.consentDocument) } /** Return subtask step with only the steps required for reconsent */ open func reconsentStep() -> SBASubtaskStep { // Strip out the registration steps let steps = self.steps?.filter({ !isRegistrationStep($0) }) let task = SBANavigableOrderedTask(identifier: SBAOnboardingSectionBaseType.consent.rawValue, steps: steps) return SBASubtaskStep(subtask: task) } /** Return subtask step with only the steps required for consent or reconsent on login */ open func loginConsentStep() -> SBASubtaskStep { // Strip out the registration steps let steps = self.steps?.filter({ !isRegistrationStep($0) }) let task = SBANavigableOrderedTask(identifier: SBAOnboardingSectionBaseType.consent.rawValue, steps: steps) return SBAConsentSubtaskStep(subtask: task) } private func isRegistrationStep(_ step: ORKStep) -> Bool { return (step is SBARegistrationStep) || (step is ORKRegistrationStep) || (step is SBAExternalIDLoginStep) } /** Return subtask step with only the steps required for initial registration */ open func registrationConsentStep() -> SBASubtaskStep { // Strip out the reconsent steps let steps = self.steps?.filter({ (step) -> Bool in // If this is a step that conforms to the custom step protocol and the custom step type is // a reconsent subtype, then this is not to be included in the registration steps if let customStep = step as? SBACustomTypeStep, let customType = customStep.customTypeIdentifier, customType.hasPrefix("reconsent") { return false } return true }) let task = SBANavigableOrderedTask(identifier: SBAOnboardingSectionBaseType.consent.rawValue, steps: steps) return SBASubtaskStep(subtask: task) } }
bsd-3-clause
9b49a7242857db820c1c62b26707e67a
45.277778
145
0.720768
4.894242
false
false
false
false
qaisjp/mta-luac-osx
MTA Lua Compiler/FileManagerViewController.swift
1
1296
// // FileManagerViewController.swift // MTA Lua Compiler // // Created by Qais Patankar on 02/11/2014. // Copyright (c) 2014 qaisjp. All rights reserved. // import Cocoa class FileManagerViewController: NSViewController { var urls: Array<NSURL>? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func onClosePressed(sender: AnyObject) { self.dismissController(self) if (urls != nil) { (self.representedObject as MTAMainViewController).parameters = urls! } } @IBOutlet weak var fileTableView: NSTableView! @IBAction func onBrowseClick(sender: AnyObject) { // Create the File Open Dialog class. var panel:NSOpenPanel = NSOpenPanel(); panel.canChooseFiles = true; panel.canChooseDirectories = false; panel.title = "Select file(s) or folder(s) to compile"; panel.allowsMultipleSelection = true; // Display the dialog. If the OK button was pressed, process the path var buttonPressed:NSInteger = panel.runModal(); if ( buttonPressed == NSOKButton ) { self.urls = panel.URLs as? Array<NSURL> } } }
apache-2.0
c130d462f8ca4d26fcfa8289bdd65d89
24.92
80
0.619599
4.6121
false
false
false
false
marklin2012/JDUtil
JDUtilDemo/JDUtilDemo/JDUtil/JDKeyboardNotification.swift
3
3022
// // JDKeyboardNotification.swift // JDUtilDemo // // Created by O2.LinYi on 15/12/24. // Copyright © 2015年 jd.com. All rights reserved. // import UIKit /// Wrapper for the NSNotification userInfo values associated with a keyboard notification. /// /// It provides properties that retrieve userInfo dictionary values with these keys: /// /// - UIKeyboardFrameBeginUserInfoKey /// - UIKeyboardFrameEndUserInfoKey /// - UIKeyboardAnimationDurationUserInfoKey /// - UIKeyboardAnimationCurveUserInfoKey public struct KeyboardNotification { let notification: NSNotification let userInfo: NSDictionary /// Initializer /// /// :param: notification Keyboard-related notification public init(_ notification: NSNotification) { self.notification = notification if let userInfo = notification.userInfo { self.userInfo = userInfo } else { self.userInfo = NSDictionary() } } /// Start frame of the keyboard in screen coordinates public var screenFrameBegin: CGRect { if let value = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue { return value.CGRectValue() } else { return CGRectZero } } /// End frame of the keyboard in screen coordinates public var screenFrameEnd: CGRect { if let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { return value.CGRectValue() } else { return CGRectZero } } /// Keyboard animation duration public var animationDuration: Double { if let number = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber { return number.doubleValue } else { return 0.25 } } /// Keyboard animation curve /// /// Note that the value returned by this method may not correspond to a /// UIViewAnimationCurve enum value. For example, in iOS 7 and iOS 8, /// this returns the value 7. public var animationCurve: Int { if let number = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { return number.integerValue } return UIViewAnimationCurve.EaseInOut.rawValue } /// Start frame of the keyboard in coordinates of specified view /// /// :param: view UIView to whose coordinate system the frame will be converted /// :returns: frame rectangle in view's coordinate system public func frameBeginForView(view: UIView) -> CGRect { return view.convertRect(screenFrameBegin, fromView: view.window) } /// End frame of the keyboard in coordinates of specified view /// /// :param: view UIView to whose coordinate system the frame will be converted /// :returns: frame rectangle in view's coordinate system public func frameEndForView(view: UIView) -> CGRect { return view.convertRect(screenFrameEnd, fromView: view.window) } }
mit
dbac92fa49b0510650bb361b8429a882
30.778947
91
0.655184
5.420108
false
false
false
false
ksco/swift-algorithm-club-cn
Bucket Sort/BucketSort.swift
1
5066
// // BucketSort.swift // // Created by Barbara Rodeker on 4/4/16. // // 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 ////////////////////////////////////// // MARK: Main algorithm ////////////////////////////////////// /** Performs bucket sort algorithm on the given input elements. [Bucket Sort Algorithm Reference](https://en.wikipedia.org/wiki/Bucket_sort) - Parameter elements: Array of Sortable elements - Parameter distributor: Performs the distribution of each element of a bucket - Parameter sorter: Performs the sorting inside each bucket, after all the elements are distributed - Parameter buckets: An array of buckets - Returns: A new array with sorted elements */ public func bucketSort<T:Sortable>(elements: [T], distributor: Distributor,sorter: Sorter, buckets: [Bucket<T>]) -> [T] { precondition(allPositiveNumbers(elements)) precondition(enoughSpaceInBuckets(buckets, elements: elements)) var bucketsCopy = buckets for elem in elements { distributor.distribute(elem, buckets: &bucketsCopy) } var results = [T]() for bucket in bucketsCopy { results += bucket.sort(sorter) } return results } private func allPositiveNumbers<T:Sortable>(array: [T]) -> Bool { return array.filter{ $0.toInt() >= 0 }.count > 0 } private func enoughSpaceInBuckets<T:Sortable>(buckets: [Bucket<T>], elements: [T]) -> Bool { let maximumValue = elements.maxElement()?.toInt() let totalCapacity = buckets.count * (buckets.first?.capacity)! return totalCapacity >= maximumValue } ////////////////////////////////////// // MARK: Distributor ////////////////////////////////////// public protocol Distributor { func distribute<T:Sortable>(element: T, inout buckets: [Bucket<T>]) } /* * An example of a simple distribution function that send every elements to * the bucket representing the range in which it fits.An * * If the range of values to sort is 0..<49 i.e, there could be 5 buckets of capacity = 10 * So every element will be classified by the ranges: * * - 0 ..< 10 * - 10 ..< 20 * - 20 ..< 30 * - 30 ..< 40 * - 40 ..< 50 * * By following the formula: element / capacity = #ofBucket */ public struct RangeDistributor: Distributor { public init() {} public func distribute<T:Sortable>(element: T, inout buckets: [Bucket<T>]) { let value = element.toInt() let bucketCapacity = buckets.first!.capacity let bucketIndex = value / bucketCapacity buckets[bucketIndex].add(element) } } ////////////////////////////////////// // MARK: Sortable ////////////////////////////////////// public protocol IntConvertible { func toInt() -> Int } public protocol Sortable: IntConvertible, Comparable { } ////////////////////////////////////// // MARK: Sorter ////////////////////////////////////// public protocol Sorter { func sort<T:Sortable>(items: [T]) -> [T] } public struct InsertionSorter: Sorter { public init() {} public func sort<T:Sortable>(items: [T]) -> [T] { var results = items for i in 0 ..< results.count { var j = i while ( j > 0 && results[j-1] > results[j]) { let auxiliar = results[j-1] results[j-1] = results[j] results[j] = auxiliar j -= 1 } } return results } } ////////////////////////////////////// // MARK: Bucket ////////////////////////////////////// public struct Bucket<T:Sortable> { var elements: [T] let capacity: Int public init(capacity: Int) { self.capacity = capacity elements = [T]() } public mutating func add(item: T) { if (elements.count < capacity) { elements.append(item) } } public func sort(algorithm: Sorter) -> [T] { return algorithm.sort(elements) } }
mit
f7e737ea90983007eca1e27c643e3e30
28.8
121
0.599487
4.45167
false
false
false
false
UIKonf/uikonf-app
Entitas/Entitas/Group.swift
1
3743
// // Group.swift // Entitas // // Created by Maxim Zaks on 21.12.14. // Copyright (c) 2014 Maxim Zaks. All rights reserved. // /// A protocol which lets you monitor a group for changes public protocol GroupObserver : class { func entityAdded(entity : Entity) func entityRemoved(entity : Entity, withRemovedComponent removedComponent : Component) } /// A group contains all entities which apply to a certain matcher. /// Groups are created through Context.entityGroup method. /// Groups are always up to date. /// Groups are internaly cached in Context class, so you don't have to be concerned about caching them your self, just call Context.entityGroup method when you need it. public class Group { /// The matcher witch decides if entity belongs to the group. public let matcher : Matcher private var entities : [Int:Entity] = [:] private var observers : [GroupObserver] = [] private var _sortedEntities : [Entity]? init(matcher : Matcher){ self.matcher = matcher } func addEntity(e : Entity) { if let entity = entities[e.creationIndex] { return; } entities[e.creationIndex] = e _sortedEntities = nil for listener in observers { listener.entityAdded(e) } } func removeEntity(e : Entity, withRemovedComponent removedComponent : Component) { let removedEntity = entities.removeValueForKey(e.creationIndex) if removedEntity == nil { return // nothing changed, entity was not in the group } _sortedEntities = nil for listener in observers { listener.entityRemoved(e, withRemovedComponent: removedComponent) } } /// Returns how many entities are in the group public var count : Int{ get { return entities.count } } /// Returns an array of entities sorted by entity creation index public var sortedEntities: [Entity] { get { if let sortedEntities = _sortedEntities { return sortedEntities } let sortedKeys = entities.keys.array.sorted(<) var sortedEntities : [Entity] = [] for key in sortedKeys { sortedEntities.append(entities[key]!) } _sortedEntities = sortedEntities return _sortedEntities! } } /// Add observer to the group so that you get notified when entity is added or removed from the group. /// This happens when relevant components are set or removed from the entity. public func addObserver(observer : GroupObserver) { // TODO: better implemented with Set, however think about Hashable for _observer in observers { if _observer === observer { return } } observers.append(observer) } /// Remove observer from the group. Call it when you don't whant to be notified any more. Specially if you want to destroy observer object. public func removeObserver(observer : GroupObserver) { // TODO: better implemented with Set (iOS 8.3) observers = observers.filter({$0 !== observer}) } } /// Makes a group compatible with 'for in' statement and other iteration functions extension Group : SequenceType { public func generate() -> GeneratorOf<Entity> { return SequenceOf(entities.values).generate() } /// Convinience method for filtering entities from the group during iteration public func without(matcher : Matcher) -> SequenceOf<Entity> { return SequenceOf(entities.values.filter{ matcher.isMatching($0) }) } }
mit
ddf0ecbbf47f56053364776c50817499
33.348624
168
0.631846
4.842173
false
false
false
false
LoopKit/LoopKit
LoopKit/DosingDecisionStore.swift
1
23339
// // DosingDecisionStore.swift // LoopKit // // Created by Darin Krauss on 10/14/19. // Copyright © 2019 LoopKit Authors. All rights reserved. // import os.log import Foundation import CoreData public protocol DosingDecisionStoreDelegate: AnyObject { /** Informs the delegate that the dosing decision store has updated dosing decision data. - Parameter dosingDecisionStore: The dosing decision store that has updated dosing decision data. */ func dosingDecisionStoreHasUpdatedDosingDecisionData(_ dosingDecisionStore: DosingDecisionStore) } public class DosingDecisionStore { public weak var delegate: DosingDecisionStoreDelegate? private let store: PersistenceController private let expireAfter: TimeInterval private let dataAccessQueue = DispatchQueue(label: "com.loopkit.DosingDecisionStore.dataAccessQueue", qos: .utility) public let log = OSLog(category: "DosingDecisionStore") public init(store: PersistenceController, expireAfter: TimeInterval) { self.store = store self.expireAfter = expireAfter } public func storeDosingDecision(_ dosingDecision: StoredDosingDecision, completion: @escaping () -> Void) { dataAccessQueue.async { if let data = self.encodeDosingDecision(dosingDecision) { self.store.managedObjectContext.performAndWait { let object = DosingDecisionObject(context: self.store.managedObjectContext) object.data = data object.date = dosingDecision.date self.store.save() } } self.purgeExpiredDosingDecisions() completion() } } public var expireDate: Date { return Date(timeIntervalSinceNow: -expireAfter) } private func purgeExpiredDosingDecisions() { purgeDosingDecisionObjects(before: expireDate) } public func purgeDosingDecisions(before date: Date, completion: @escaping (Error?) -> Void) { dataAccessQueue.async { self.purgeDosingDecisionObjects(before: date, completion: completion) } } private func purgeDosingDecisionObjects(before date: Date, completion: ((Error?) -> Void)? = nil) { dispatchPrecondition(condition: .onQueue(dataAccessQueue)) var purgeError: Error? store.managedObjectContext.performAndWait { do { let count = try self.store.managedObjectContext.purgeObjects(of: DosingDecisionObject.self, matching: NSPredicate(format: "date < %@", date as NSDate)) self.log.info("Purged %d DosingDecisionObjects", count) } catch let error { self.log.error("Unable to purge DosingDecisionObjects: %{public}@", String(describing: error)) purgeError = error } } if let purgeError = purgeError { completion?(purgeError) return } delegate?.dosingDecisionStoreHasUpdatedDosingDecisionData(self) completion?(nil) } private static var encoder: PropertyListEncoder = { let encoder = PropertyListEncoder() encoder.outputFormat = .binary return encoder }() private func encodeDosingDecision(_ dosingDecision: StoredDosingDecision) -> Data? { do { return try Self.encoder.encode(dosingDecision) } catch let error { self.log.error("Error encoding StoredDosingDecision: %@", String(describing: error)) return nil } } private static var decoder = PropertyListDecoder() private func decodeDosingDecision(fromData data: Data) -> StoredDosingDecision? { do { return try Self.decoder.decode(StoredDosingDecision.self, from: data) } catch let error { self.log.error("Error decoding StoredDosingDecision: %@", String(describing: error)) return nil } } } extension DosingDecisionStore { public struct QueryAnchor: Equatable, RawRepresentable { public typealias RawValue = [String: Any] internal var modificationCounter: Int64 public init() { self.modificationCounter = 0 } public init?(rawValue: RawValue) { guard let modificationCounter = rawValue["modificationCounter"] as? Int64 else { return nil } self.modificationCounter = modificationCounter } public var rawValue: RawValue { var rawValue: RawValue = [:] rawValue["modificationCounter"] = modificationCounter return rawValue } } public enum DosingDecisionQueryResult { case success(QueryAnchor, [StoredDosingDecision]) case failure(Error) } public func executeDosingDecisionQuery(fromQueryAnchor queryAnchor: QueryAnchor?, limit: Int, completion: @escaping (DosingDecisionQueryResult) -> Void) { dataAccessQueue.async { var queryAnchor = queryAnchor ?? QueryAnchor() var queryResult = [StoredDosingDecisionData]() var queryError: Error? guard limit > 0 else { completion(.success(queryAnchor, [])) return } self.store.managedObjectContext.performAndWait { let storedRequest: NSFetchRequest<DosingDecisionObject> = DosingDecisionObject.fetchRequest() storedRequest.predicate = NSPredicate(format: "modificationCounter > %d", queryAnchor.modificationCounter) storedRequest.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: true)] storedRequest.fetchLimit = limit do { let stored = try self.store.managedObjectContext.fetch(storedRequest) if let modificationCounter = stored.max(by: { $0.modificationCounter < $1.modificationCounter })?.modificationCounter { queryAnchor.modificationCounter = modificationCounter } queryResult.append(contentsOf: stored.compactMap { StoredDosingDecisionData(date: $0.date, data: $0.data) }) } catch let error { queryError = error return } } if let queryError = queryError { completion(.failure(queryError)) return } // Decoding a large number of dosing decision can be very CPU intensive and may take considerable wall clock time. // Do not block DosingDecisionStore dataAccessQueue. Perform work and callback in global utility queue. DispatchQueue.global(qos: .utility).async { completion(.success(queryAnchor, queryResult.compactMap { self.decodeDosingDecision(fromData: $0.data) })) } } } } public struct StoredDosingDecisionData { public let date: Date public let data: Data public init(date: Date, data: Data) { self.date = date self.data = data } } public typealias HistoricalGlucoseValue = PredictedGlucoseValue public struct StoredDosingDecision { public var date: Date public var controllerTimeZone: TimeZone public var reason: String public var settings: Settings? public var scheduleOverride: TemporaryScheduleOverride? public var controllerStatus: ControllerStatus? public var pumpManagerStatus: PumpManagerStatus? public var pumpStatusHighlight: StoredDeviceHighlight? public var cgmManagerStatus: CGMManagerStatus? public var lastReservoirValue: LastReservoirValue? public var historicalGlucose: [HistoricalGlucoseValue]? public var originalCarbEntry: StoredCarbEntry? public var carbEntry: StoredCarbEntry? public var manualGlucoseSample: StoredGlucoseSample? public var carbsOnBoard: CarbValue? public var insulinOnBoard: InsulinValue? public var glucoseTargetRangeSchedule: GlucoseRangeSchedule? public var predictedGlucose: [PredictedGlucoseValue]? public var automaticDoseRecommendation: AutomaticDoseRecommendation? public var manualBolusRecommendation: ManualBolusRecommendationWithDate? public var manualBolusRequested: Double? public var warnings: [Issue] public var errors: [Issue] public var syncIdentifier: UUID public init(date: Date = Date(), controllerTimeZone: TimeZone = TimeZone.current, reason: String, settings: Settings? = nil, scheduleOverride: TemporaryScheduleOverride? = nil, controllerStatus: ControllerStatus? = nil, pumpManagerStatus: PumpManagerStatus? = nil, pumpStatusHighlight: StoredDeviceHighlight? = nil, cgmManagerStatus: CGMManagerStatus? = nil, lastReservoirValue: LastReservoirValue? = nil, historicalGlucose: [HistoricalGlucoseValue]? = nil, originalCarbEntry: StoredCarbEntry? = nil, carbEntry: StoredCarbEntry? = nil, manualGlucoseSample: StoredGlucoseSample? = nil, carbsOnBoard: CarbValue? = nil, insulinOnBoard: InsulinValue? = nil, glucoseTargetRangeSchedule: GlucoseRangeSchedule? = nil, predictedGlucose: [PredictedGlucoseValue]? = nil, automaticDoseRecommendation: AutomaticDoseRecommendation? = nil, manualBolusRecommendation: ManualBolusRecommendationWithDate? = nil, manualBolusRequested: Double? = nil, warnings: [Issue] = [], errors: [Issue] = [], syncIdentifier: UUID = UUID()) { self.date = date self.controllerTimeZone = controllerTimeZone self.reason = reason self.settings = settings self.scheduleOverride = scheduleOverride self.controllerStatus = controllerStatus self.pumpManagerStatus = pumpManagerStatus self.pumpStatusHighlight = pumpStatusHighlight self.cgmManagerStatus = cgmManagerStatus self.lastReservoirValue = lastReservoirValue self.historicalGlucose = historicalGlucose self.originalCarbEntry = originalCarbEntry self.carbEntry = carbEntry self.manualGlucoseSample = manualGlucoseSample self.carbsOnBoard = carbsOnBoard self.insulinOnBoard = insulinOnBoard self.glucoseTargetRangeSchedule = glucoseTargetRangeSchedule self.predictedGlucose = predictedGlucose self.automaticDoseRecommendation = automaticDoseRecommendation self.manualBolusRecommendation = manualBolusRecommendation self.manualBolusRequested = manualBolusRequested self.warnings = warnings self.errors = errors self.syncIdentifier = syncIdentifier } public struct Settings: Codable, Equatable { public let syncIdentifier: UUID public init(syncIdentifier: UUID) { self.syncIdentifier = syncIdentifier } } public struct ControllerStatus: Codable, Equatable { public enum BatteryState: String, Codable { case unknown case unplugged case charging case full } public let batteryState: BatteryState? public let batteryLevel: Float? public init(batteryState: BatteryState? = nil, batteryLevel: Float? = nil) { self.batteryState = batteryState self.batteryLevel = batteryLevel } } public struct LastReservoirValue: Codable { public let startDate: Date public let unitVolume: Double public init(startDate: Date, unitVolume: Double) { self.startDate = startDate self.unitVolume = unitVolume } } public struct Issue: Codable, Equatable { public let id: String public let details: [String: String]? public init(id: String, details: [String: String]? = nil) { self.id = id self.details = details?.isEmpty == false ? details : nil } } public struct StoredDeviceHighlight: Codable, Equatable, DeviceStatusHighlight { public var localizedMessage: String public var imageName: String public var state: DeviceStatusHighlightState public init(localizedMessage: String, imageName: String, state: DeviceStatusHighlightState) { self.localizedMessage = localizedMessage self.imageName = imageName self.state = state } } } public struct ManualBolusRecommendationWithDate: Codable { public let recommendation: ManualBolusRecommendation public let date: Date public init(recommendation: ManualBolusRecommendation, date: Date) { self.recommendation = recommendation self.date = date } } extension StoredDosingDecision: Codable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.init(date: try container.decode(Date.self, forKey: .date), controllerTimeZone: try container.decode(TimeZone.self, forKey: .controllerTimeZone), reason: try container.decode(String.self, forKey: .reason), settings: try container.decodeIfPresent(Settings.self, forKey: .settings), scheduleOverride: try container.decodeIfPresent(TemporaryScheduleOverride.self, forKey: .scheduleOverride), controllerStatus: try container.decodeIfPresent(ControllerStatus.self, forKey: .controllerStatus), pumpManagerStatus: try container.decodeIfPresent(PumpManagerStatus.self, forKey: .pumpManagerStatus), pumpStatusHighlight: try container.decodeIfPresent(StoredDeviceHighlight.self, forKey: .pumpStatusHighlight), cgmManagerStatus: try container.decodeIfPresent(CGMManagerStatus.self, forKey: .cgmManagerStatus), lastReservoirValue: try container.decodeIfPresent(LastReservoirValue.self, forKey: .lastReservoirValue), historicalGlucose: try container.decodeIfPresent([HistoricalGlucoseValue].self, forKey: .historicalGlucose), originalCarbEntry: try container.decodeIfPresent(StoredCarbEntry.self, forKey: .originalCarbEntry), carbEntry: try container.decodeIfPresent(StoredCarbEntry.self, forKey: .carbEntry), manualGlucoseSample: try container.decodeIfPresent(StoredGlucoseSample.self, forKey: .manualGlucoseSample), carbsOnBoard: try container.decodeIfPresent(CarbValue.self, forKey: .carbsOnBoard), insulinOnBoard: try container.decodeIfPresent(InsulinValue.self, forKey: .insulinOnBoard), glucoseTargetRangeSchedule: try container.decodeIfPresent(GlucoseRangeSchedule.self, forKey: .glucoseTargetRangeSchedule), predictedGlucose: try container.decodeIfPresent([PredictedGlucoseValue].self, forKey: .predictedGlucose), automaticDoseRecommendation: try container.decodeIfPresent(AutomaticDoseRecommendation.self, forKey: .automaticDoseRecommendation), manualBolusRecommendation: try container.decodeIfPresent(ManualBolusRecommendationWithDate.self, forKey: .manualBolusRecommendation), manualBolusRequested: try container.decodeIfPresent(Double.self, forKey: .manualBolusRequested), warnings: try container.decodeIfPresent([Issue].self, forKey: .warnings) ?? [], errors: try container.decodeIfPresent([Issue].self, forKey: .errors) ?? [], syncIdentifier: try container.decode(UUID.self, forKey: .syncIdentifier)) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(date, forKey: .date) try container.encode(controllerTimeZone, forKey: .controllerTimeZone) try container.encode(reason, forKey: .reason) try container.encodeIfPresent(settings, forKey: .settings) try container.encodeIfPresent(scheduleOverride, forKey: .scheduleOverride) try container.encodeIfPresent(controllerStatus, forKey: .controllerStatus) try container.encodeIfPresent(pumpManagerStatus, forKey: .pumpManagerStatus) try container.encodeIfPresent(pumpStatusHighlight, forKey: .pumpStatusHighlight) try container.encodeIfPresent(cgmManagerStatus, forKey: .cgmManagerStatus) try container.encodeIfPresent(lastReservoirValue, forKey: .lastReservoirValue) try container.encodeIfPresent(historicalGlucose, forKey: .historicalGlucose) try container.encodeIfPresent(originalCarbEntry, forKey: .originalCarbEntry) try container.encodeIfPresent(carbEntry, forKey: .carbEntry) try container.encodeIfPresent(manualGlucoseSample, forKey: .manualGlucoseSample) try container.encodeIfPresent(carbsOnBoard, forKey: .carbsOnBoard) try container.encodeIfPresent(insulinOnBoard, forKey: .insulinOnBoard) try container.encodeIfPresent(glucoseTargetRangeSchedule, forKey: .glucoseTargetRangeSchedule) try container.encodeIfPresent(predictedGlucose, forKey: .predictedGlucose) try container.encodeIfPresent(automaticDoseRecommendation, forKey: .automaticDoseRecommendation) try container.encodeIfPresent(manualBolusRecommendation, forKey: .manualBolusRecommendation) try container.encodeIfPresent(manualBolusRequested, forKey: .manualBolusRequested) try container.encodeIfPresent(!warnings.isEmpty ? warnings : nil, forKey: .warnings) try container.encodeIfPresent(!errors.isEmpty ? errors : nil, forKey: .errors) try container.encode(syncIdentifier, forKey: .syncIdentifier) } private enum CodingKeys: String, CodingKey { case date case controllerTimeZone case reason case settings case scheduleOverride case controllerStatus case pumpManagerStatus case pumpStatusHighlight case cgmManagerStatus case lastReservoirValue case historicalGlucose case originalCarbEntry case carbEntry case manualGlucoseSample case carbsOnBoard case insulinOnBoard case glucoseTargetRangeSchedule case predictedGlucose case automaticDoseRecommendation case manualBolusRecommendation case manualBolusRequested case warnings case errors case syncIdentifier } } // MARK: - Critical Event Log Export extension DosingDecisionStore: CriticalEventLog { private var exportProgressUnitCountPerObject: Int64 { 33 } private var exportFetchLimit: Int { Int(criticalEventLogExportProgressUnitCountPerFetch / exportProgressUnitCountPerObject) } public var exportName: String { "DosingDecisions.json" } public func exportProgressTotalUnitCount(startDate: Date, endDate: Date? = nil) -> Result<Int64, Error> { var result: Result<Int64, Error>? self.store.managedObjectContext.performAndWait { do { let request: NSFetchRequest<DosingDecisionObject> = DosingDecisionObject.fetchRequest() request.predicate = self.exportDatePredicate(startDate: startDate, endDate: endDate) let objectCount = try self.store.managedObjectContext.count(for: request) result = .success(Int64(objectCount) * exportProgressUnitCountPerObject) } catch let error { result = .failure(error) } } return result! } public func export(startDate: Date, endDate: Date, to stream: OutputStream, progress: Progress) -> Error? { let encoder = JSONStreamEncoder(stream: stream) var modificationCounter: Int64 = 0 var fetching = true var error: Error? while fetching && error == nil { self.store.managedObjectContext.performAndWait { do { guard !progress.isCancelled else { throw CriticalEventLogError.cancelled } let request: NSFetchRequest<DosingDecisionObject> = DosingDecisionObject.fetchRequest() request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [NSPredicate(format: "modificationCounter > %d", modificationCounter), self.exportDatePredicate(startDate: startDate, endDate: endDate)]) request.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: true)] request.fetchLimit = self.exportFetchLimit let objects = try self.store.managedObjectContext.fetch(request) if objects.isEmpty { fetching = false return } try encoder.encode(objects) modificationCounter = objects.last!.modificationCounter progress.completedUnitCount += Int64(objects.count) * exportProgressUnitCountPerObject } catch let fetchError { error = fetchError } } } if let closeError = encoder.close(), error == nil { error = closeError } return error } private func exportDatePredicate(startDate: Date, endDate: Date? = nil) -> NSPredicate { var predicate = NSPredicate(format: "date >= %@", startDate as NSDate) if let endDate = endDate { predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, NSPredicate(format: "date < %@", endDate as NSDate)]) } return predicate } } // MARK: - Core Data (Bulk) - TEST ONLY extension DosingDecisionStore { public func addStoredDosingDecisions(dosingDecisions: [StoredDosingDecision], completion: @escaping (Error?) -> Void) { guard !dosingDecisions.isEmpty else { completion(nil) return } dataAccessQueue.async { var error: Error? self.store.managedObjectContext.performAndWait { for dosingDecision in dosingDecisions { guard let data = self.encodeDosingDecision(dosingDecision) else { continue } let object = DosingDecisionObject(context: self.store.managedObjectContext) object.data = data object.date = dosingDecision.date } error = self.store.save() } guard error == nil else { completion(error) return } self.log.info("Added %d DosingDecisionObjects", dosingDecisions.count) self.delegate?.dosingDecisionStoreHasUpdatedDosingDecisionData(self) completion(nil) } } }
mit
93cfd83687ebb91537190ea66e6d4dae
42.059041
167
0.656569
5.456628
false
false
false
false
Jamol/Nutil
Sources/http/v2/H2Frame.swift
1
20619
// // H2Frame.swift // Nutil // // Created by Jamol Bao on 12/24/16. // Copyright © 2016 Jamol Bao. All rights reserved. // Contact: [email protected] // import Foundation let kH2MaxStreamId: UInt32 = 0x7FFFFFFF let kH2FrameHeaderSize = 9 let kH2PriorityPayloadSize = 5 let kH2RSTStreamPayloadSize = 4 let kH2SettingItemSize = 6 let kH2PingPayloadSize = 8 let kH2WindowUpdatePayloadSize = 4 let kH2WindowUpdateFrameSize = kH2FrameHeaderSize + kH2WindowUpdatePayloadSize let kH2DefaultFrameSize = 16384 let kH2DefaultWindowSize = 65535 let kH2MaxFrameSize = 16777215 let kH2MaxWindowSize = 2147483647 let kH2FrameFlagEndStream: UInt8 = 0x01 let kH2FrameFlagAck: UInt8 = 0x01 let kH2FrameFlagEndHeaders: UInt8 = 0x04 let kH2FrameFlagPadded: UInt8 = 0x08 let kH2FrameFlagPriority: UInt8 = 0x20 enum H2FrameType : UInt8 { case data = 0 case headers = 1 case priority = 2 case rststream = 3 case settings = 4 case pushPromise = 5 case ping = 6 case goaway = 7 case windowUpdate = 8 case continuation = 9 } enum H2SettingsID : UInt16 { case headerTableSize = 1 case enablePush = 2 case maxConcurrentStreams = 3 case initialWindowSize = 4 case maxFrameSize = 5 case maxHeaderListSize = 6 } enum H2Error : Int32 { case noError = 0 case protocolError = 1 case internalError = 2 case flowControlError = 3 case settingsTimeout = 4 case streamClosed = 5 case frameSizeError = 6 case refusedStream = 7 case cancel = 8 case compressionError = 9 case connectError = 10 case enhanceYourCalm = 11 case inadequateSecurity = 12 case http11Required = 13 } let kH2HeaderMethod = ":method" let kH2HeaderScheme = ":scheme" let kH2HeaderAuthority = ":authority" let kH2HeaderPath = ":path" let kH2HeaderStatus = ":status" let kH2HeaderCookie = "cookie" struct H2Priority { var streamId: UInt32 = 0 var weight: UInt16 = 16 var exclusive = false } struct FrameHeader { var length = 0 var type: UInt8 = 0 var flags: UInt8 = 0 var streamId: UInt32 = 0 var hasPadding: Bool { return (flags & kH2FrameFlagPadded) != 0 } var hasPriority: Bool { return (flags & kH2FrameFlagPriority) != 0 } var hasEndHeaders: Bool { return (flags & kH2FrameFlagEndHeaders) != 0 } var hasEndStream: Bool { return (flags & kH2FrameFlagEndStream) != 0 } var hasAck: Bool { return (flags & kH2FrameFlagAck) != 0 } func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { if len < kH2FrameHeaderSize { return -1 } encode_u24(dst, UInt32(length)) dst[3] = type dst[4] = flags encode_u32(dst + 5, streamId) return kH2FrameHeaderSize } mutating func decode(_ src: UnsafePointer<UInt8>, _ len: Int) -> Bool { if len < kH2FrameHeaderSize { return false } if (src[5] & 0x80) != 0 { // check reserved bit } length = Int(decode_u24(src)) type = src[3] flags = src[4] streamId = decode_u32(src + 5) return true } } class H2Frame { var hdr = FrameHeader() var streamId: UInt32 { get { return hdr.streamId } set { hdr.streamId = newValue } } func addFlags(_ flags: UInt8) { hdr.flags |= flags } func clearFlags(_ flags: UInt8) { hdr.flags &= ~flags } func getFlags() -> UInt8 { return hdr.flags } func hasEndStream() -> Bool { return (getFlags() & kH2FrameFlagEndStream) != 0 } func type() -> H2FrameType { fatalError("MUST override type") } func calcPayloadSize() -> Int { fatalError("MUST override calcPayloadSize") } func getPayloadLength() -> Int { if hdr.length > 0 { return hdr.length } else { return calcPayloadSize() } } func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { fatalError("MUST override encode") } func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { fatalError("MUST override decode") } func calcFrameSize() -> Int { return kH2FrameHeaderSize + calcPayloadSize() } func setFrameHeader(_ hdr: FrameHeader) { self.hdr = hdr } func encodeHeader(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int, _ hdr: FrameHeader) -> Int { return hdr.encode(dst, len) } func encodeHeader(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { hdr.type = type().rawValue hdr.length = calcPayloadSize() return hdr.encode(dst, len) } class func encodePriority(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int, _ pri: H2Priority) -> Int { var pri = pri if len < kH2PriorityPayloadSize { return -1 } pri.streamId &= 0x7FFFFFFF if pri.exclusive { pri.streamId |= 0x80000000 } encode_u32(dst, pri.streamId) dst[4] = UInt8(pri.weight & 0xFF) return kH2PriorityPayloadSize } class func decodePriority(_ src: UnsafePointer<UInt8>, _ len: Int) -> (err: H2Error, pri: H2Priority) { var pri = H2Priority() if len < kH2PriorityPayloadSize { return (.frameSizeError, pri) } pri.streamId = decode_u32(src) pri.exclusive = (pri.streamId >> 31) != 0 pri.streamId &= 0x7FFFFFFF pri.weight = UInt16(src[4]) + 1 return (.noError, pri) } } class DataFrame : H2Frame { var data: UnsafeRawPointer? var size = 0 override func type() -> H2FrameType { return .data } override func calcPayloadSize() -> Int { return size } func setData(_ data: UnsafeRawPointer?, _ len: Int) { self.data = data self.size = len } override func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { var pos = 0 let ret = encodeHeader(dst, len) if ret < 0 { return -1 } pos += ret if len - pos < size { return -1 } if data != nil && size > 0 { memcpy(dst + pos, data, size) pos += size } return pos } override func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { setFrameHeader(hdr) if hdr.streamId == 0 { return .protocolError } var ptr = payload var len = hdr.length var padLen = 0 if hdr.hasPadding { padLen = Int(ptr[0]) ptr += 1 if padLen >= len { return .protocolError } len -= padLen + 1 } data = UnsafeRawPointer(ptr) size = len return .noError } } class HeadersFrame : H2Frame { var pri = H2Priority() var block: UnsafeRawPointer? var bsize = 0 var headers: NameValueArray = [] var hsize = 0 override func type() -> H2FrameType { return .headers } override func calcPayloadSize() -> Int { var sz = bsize if hdr.hasPriority { sz += kH2PriorityPayloadSize } return sz } func hasPriority() -> Bool { return (getFlags() & kH2FrameFlagPriority) != 0 } func hasEndHeaders() -> Bool { return (getFlags() & kH2FrameFlagEndHeaders) != 0 } func setHeaders(_ headers: NameValueArray, _ hdrSize: Int) { self.headers = headers hsize = hdrSize } override func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { var pos = 0 var ret = encodeHeader(dst, len) if ret < 0 { return ret } pos += ret if hdr.hasPriority { ret = H2Frame.encodePriority(dst + pos, len - pos, pri) if ret < 0 { return ret } pos += ret } if len - pos < bsize { return -1 } memcpy(dst + pos, block, bsize) pos += bsize return pos } func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int, _ bsize: Int) -> Int { self.bsize = bsize var pos = 0 var ret = encodeHeader(dst, len) if ret < 0 { return ret } pos += ret if hdr.hasPriority { ret = H2Frame.encodePriority(dst + pos, len - pos, pri) if ret < 0 { return ret } pos += ret } return pos } override func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { setFrameHeader(hdr) if hdr.streamId == 0 { return .protocolError } var ptr = payload var len = hdr.length var padLen = 0 if hdr.hasPadding { padLen = Int(ptr[0]) ptr += 1 if padLen >= len { return .protocolError } len -= padLen + 1 } if hdr.hasPriority { let ret = H2Frame.decodePriority(ptr, len) if ret.err != .noError { return ret.err } ptr += kH2PriorityPayloadSize len -= kH2PriorityPayloadSize } block = UnsafeRawPointer(ptr) bsize = len return .noError } } class PriorityFrame : H2Frame { var pri = H2Priority() override func type() -> H2FrameType { return .priority } override func calcPayloadSize() -> Int { return kH2PriorityPayloadSize } override func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { var pos = 0 var ret = encodeHeader(dst, len) if ret < 0 { return ret } pos += ret ret = H2Frame.encodePriority(dst + pos, len - pos, pri) if ret < 0 { return ret } pos += ret return pos } override func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { setFrameHeader(hdr) if hdr.streamId == 0 { return .protocolError } let ret = H2Frame.decodePriority(payload, hdr.length) pri = ret.pri return ret.err } } class RSTStreamFrame : H2Frame { var errCode: UInt32 = 0 override func type() -> H2FrameType { return .rststream } override func calcPayloadSize() -> Int { return kH2RSTStreamPayloadSize } override func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { var pos = 0 let ret = encodeHeader(dst, len) if ret < 0 { return ret } pos += ret encode_u32(dst + pos, errCode) pos += 4 return pos } override func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { setFrameHeader(hdr) if hdr.streamId == 0 { return .protocolError } if hdr.length != 4 { return .frameSizeError } errCode = decode_u32(payload) return .noError } } typealias H2SettingArray = [(key: UInt16, value: UInt32)] class SettingsFrame : H2Frame { var params: H2SettingArray = [] var ack: Bool { get { return hdr.hasAck } set { if newValue { addFlags(kH2FrameFlagAck) } else { clearFlags(kH2FrameFlagAck) } } } override func type() -> H2FrameType { return .settings } override func calcPayloadSize() -> Int { return kH2SettingItemSize * params.count } func encodePayload(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int, _ para: H2SettingArray) -> Int { var pos = 0 for kv in para { if pos + kH2SettingItemSize > len { return -1 } encode_u16(dst + pos, kv.key) pos += 2 encode_u32(dst + pos, kv.value) pos += 4 } return pos } override func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { var pos = 0 var ret = encodeHeader(dst, len) if ret < 0 { return ret } pos += ret ret = encodePayload(dst + pos, len - pos, params) if ret < 0 { return ret } pos += ret return pos } override func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { setFrameHeader(hdr) if hdr.streamId != 0 { return .protocolError } if ack && hdr.length != 0 { return .frameSizeError } if hdr.length % kH2SettingItemSize != 0 { return .frameSizeError } var ptr = payload var len = hdr.length params.removeAll() while len > 0 { let key = decode_u16(ptr) let value = decode_u32(ptr + 2) params.append((key, value)) ptr += kH2SettingItemSize len -= kH2SettingItemSize } return .noError } } class PushPromiseFrame : H2Frame { var promisedStreamId: UInt32 = 0 var block: UnsafeRawPointer? var bsize = 0 var headers: NameValueArray = [] var hsize = 0 override func type() -> H2FrameType { return .pushPromise } override func calcPayloadSize() -> Int { return 4 + bsize } func hasEndHeaders() -> Bool { return (getFlags() & kH2FrameFlagEndHeaders) != 0 } func setHeaders(_ headers: NameValueArray, _ hdrSize: Int) { self.headers = headers hsize = hdrSize } override func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { var pos = 0 let ret = encodeHeader(dst, len) if ret < 0 { return ret } pos += ret if len - pos < calcPayloadSize() { return -1 } encode_u32(dst + pos, promisedStreamId) pos += 4 if block != nil && bsize > 0 { memcpy(dst + pos, block, bsize) pos += bsize } return pos } override func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { setFrameHeader(hdr) if hdr.streamId == 0 { return .protocolError } var ptr = payload var len = hdr.length var padLen = 0 if hdr.hasPadding { padLen = Int(ptr[0]) ptr += 1 if padLen >= len { return .protocolError } len -= padLen + 1 } if len < 4 { return .frameSizeError } promisedStreamId = decode_u32(ptr) & 0x7FFFFFFF ptr += 4 len -= 4 if len > 0 { block = UnsafeRawPointer(ptr) bsize = len } return .noError } } class PingFrame : H2Frame { var data = Array<UInt8>(repeating: 0, count: kH2PingPayloadSize) var ack: Bool { get { return hdr.hasAck } set { if newValue { addFlags(kH2FrameFlagAck) } else { clearFlags(kH2FrameFlagAck) } } } override func type() -> H2FrameType { return .ping } override func calcPayloadSize() -> Int { return kH2PingPayloadSize } override func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { var pos = 0 let ret = encodeHeader(dst, len) if ret < 0 { return ret } pos += ret if len - pos < calcPayloadSize() { return -1 } memcpy(dst + pos, data, kH2PingPayloadSize) pos += kH2PingPayloadSize return pos } override func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { setFrameHeader(hdr) if hdr.streamId != 0 { return .protocolError } if hdr.length != kH2PingPayloadSize { return .frameSizeError } let bbuf = UnsafeBufferPointer<UInt8>(start: payload, count: hdr.length) data = Array(bbuf) return .noError } } class GoawayFrame : H2Frame { var lastStreamId: UInt32 = 0 var errCode: UInt32 = 0 var data: UnsafeRawPointer? var size = 0 override func type() -> H2FrameType { return .goaway } override func calcPayloadSize() -> Int { return 8 + size } override func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { var pos = 0 let ret = encodeHeader(dst, len) if ret < 0 { return ret } pos += ret if len - pos < calcPayloadSize() { return -1 } encode_u32(dst + pos, lastStreamId) pos += 4 encode_u32(dst + pos, errCode) pos += 4 if size > 0 { memcpy(dst + pos, data, size) pos += size } return pos } override func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { setFrameHeader(hdr) if hdr.streamId != 0 { return .protocolError } if hdr.length < 8 { return .frameSizeError } var ptr = payload var len = hdr.length lastStreamId = decode_u32(ptr) & 0x7FFFFFFF ptr += 4 len -= 4 errCode = decode_u32(ptr) ptr += 4 len -= 4 if len > 0 { data = UnsafeRawPointer(ptr) size = len } return .noError } } class WindowUpdateFrame : H2Frame { var windowSizeIncrement: UInt32 = 0 override func type() -> H2FrameType { return .windowUpdate } override func calcPayloadSize() -> Int { return kH2WindowUpdatePayloadSize } override func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { var pos = 0 let ret = encodeHeader(dst, len) if ret < 0 { return ret } pos += ret if len - pos < calcPayloadSize() { return -1 } encode_u32(dst + pos, windowSizeIncrement) pos += 4 return pos } override func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { setFrameHeader(hdr) if hdr.length != kH2WindowUpdatePayloadSize { return .frameSizeError } windowSizeIncrement = decode_u32(payload) & 0x7FFFFFFF return .noError } } class ContinuationFrame : H2Frame { var block: UnsafeRawPointer? var bsize = 0 var headers: NameValueArray = [] var hsize = 0 override func type() -> H2FrameType { return .continuation } override func calcPayloadSize() -> Int { return bsize } func hasEndHeaders() -> Bool { return (getFlags() & kH2FrameFlagEndHeaders) != 0 } override func encode(_ dst: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int { var pos = 0 let ret = encodeHeader(dst, len) if ret < 0 { return ret } pos += ret if len - pos < calcPayloadSize() { return -1 } if block != nil && bsize > 0 { memcpy(dst + pos, block, bsize) pos += bsize } return pos } override func decode(_ hdr: FrameHeader, _ payload: UnsafePointer<UInt8>) -> H2Error { setFrameHeader(hdr) if hdr.streamId == 0 { return .protocolError } if hdr.length > 0 { block = UnsafeRawPointer(payload) bsize = hdr.length } return .noError } }
mit
b81457a84e4503b6ef4b9e20b837a68c
24.29816
107
0.523426
4.192355
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Controller/MasterViewController.swift
1
2021
// // MasterViewController.swift // SASAbus // // Copyright (C) 2011-2015 Raiffeisen Online GmbH (Norman Marmsoler, Jürgen Sprenger, Aaron Falk) <[email protected]> // // This file is part of SASAbus. // // SASAbus 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. // // SASAbus 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 SASAbus. If not, see <http://www.gnu.org/licenses/>. // import UIKit import DrawerController class MasterViewController: UIViewController { init(nibName: String?, title: String?) { super.init(nibName: nibName, bundle: nil) self.title = title } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.setupLeftMenuButton() } func setupLeftMenuButton() { let image = Asset.menuIcon.image.withRenderingMode(UIImageRenderingMode.alwaysTemplate) let leftDrawerButton = UIBarButtonItem( image: image, style: UIBarButtonItemStyle.plain, target: self, action: #selector(MasterViewController.leftDrawerButtonPress(_:)) ) leftDrawerButton.tintColor = Theme.white leftDrawerButton.accessibilityLabel = L10n.Accessibility.menu self.navigationItem.setLeftBarButton(leftDrawerButton, animated: true) } // MARK: - Button Handlers func leftDrawerButtonPress(_ sender: AnyObject?) { self.evo_drawerController?.toggleDrawerSide(.left, animated: true, completion: nil) } }
gpl-3.0
cb1c761163cbff2bdec15891c06c3828
31.063492
118
0.70297
4.529148
false
false
false
false
Zacharyg88/Alien-Adventure-3
Alien Adventure/UDItem.swift
4
1603
// // UDItem.swift // Alien Adventure // // Created by Jarrod Parkes on 9/28/15. // Copyright © 2015 Udacity. All rights reserved. // // MARK: - UDItemType enum UDItemType: Int { case weapon = 0, magic, other } // MARK: - UDItemRarity enum UDItemRarity: Int { case common = 0, uncommon, rare, legendary } // MARK: - UDItem struct UDItem { // MARK: Properties var itemID: Int var itemType: UDItemType var name: String var baseValue: Int var inscription: String? var rarity: UDItemRarity var historicalData: [String:AnyObject] // MARK: Initializer init(itemID: Int, itemType: UDItemType, name: String, baseValue: Int, inscription: String? = nil, rarity: UDItemRarity, historicalData: [String:AnyObject]) { self.itemID = itemID self.itemType = itemType self.name = name self.baseValue = baseValue self.inscription = inscription self.rarity = rarity self.historicalData = historicalData } } // MARK: - UDItem: Hashable extension UDItem: Hashable { var hashValue: Int { return itemID.hashValue } } // MARK: - UDItem (Operators) func <= (lhs: UDItem, rhs: UDItem) -> Bool { if lhs.rarity.rawValue > rhs.rarity.rawValue { return false } else if lhs.rarity.rawValue == rhs.rarity.rawValue { return lhs.baseValue <= rhs.baseValue } else { return true } } func == (lhs: UDItem, rhs: UDItem) -> Bool { return lhs.itemID == rhs.itemID } func != (lhs: UDItem, rhs: UDItem) -> Bool { return !(lhs == rhs) }
mit
4ec47b22d399338ed96bb992d22c43bb
20.36
161
0.623596
3.591928
false
false
false
false
ideastouch/MGO
mgoclient/LoginViewController.swift
1
9277
// // ViewController.swift // mgoclient // // Created by Gustavo Halperin on 9/25/14. // Copyright (c) 2014 mgo. All rights reserved. // import UIKit class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet private weak var _welcomeViewCenterYAlignment: NSLayoutConstraint! @IBOutlet private weak var _welcomeViewTopAlignment: NSLayoutConstraint! @IBOutlet private weak var _welcomeViewContainer: UIView! @IBOutlet private weak var _emailTextField: UITextField! @IBOutlet private weak var _passwordTextField: UITextField! private weak var _activeTextField: UITextField! private var _keyboardUserInfo: NSDictionary! private var _deviceIsRotating: Bool = false override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } @IBAction func tapGestureRecognizerViewAction(sender: AnyObject) { _activeTextField?.resignFirstResponder() } func animateTextFieldUp(keyboardUserInfo userInfo:NSDictionary){ let value:NSValue = _keyboardUserInfo[UIKeyboardFrameEndUserInfoKey] as NSValue var keyboardRect:CGRect = value.CGRectValue() var activeTextFieldRect:CGRect = _activeTextField.frame activeTextFieldRect = _welcomeViewContainer.convertRect(activeTextFieldRect, toView: self.view) let delta:CGFloat = activeTextFieldRect.origin.y + activeTextFieldRect.size.height - keyboardRect.origin.y if (delta > 0) { let animationCurve:NSNumber = _keyboardUserInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber let animationDuration:NSNumber = _keyboardUserInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber var welcomeViewTopAlignmentConstant:CGFloat = _welcomeViewContainer.frame.origin.y - delta UIView.animateWithDuration( animationDuration.doubleValue, delay: 0.0, options: UIViewAnimationOptions.fromRaw(UInt(animationCurve.unsignedIntValue))!, animations: { self._welcomeViewTopAlignment.constant = welcomeViewTopAlignmentConstant self._welcomeViewCenterYAlignment.priority = 250 self._welcomeViewTopAlignment.priority = 750 self.view.setNeedsLayout() }, completion: nil ) } } func keyboardWillShow(notification: NSNotification) { if !_deviceIsRotating { self._keyboardUserInfo = notification.userInfo! self.animateTextFieldUp(keyboardUserInfo: _keyboardUserInfo) } } func keyboardWillHide(notification: NSNotification) { if !_deviceIsRotating { self._keyboardUserInfo = notification.userInfo! let animationCurve:NSNumber = _keyboardUserInfo[UIKeyboardAnimationCurveUserInfoKey] as NSNumber let animationDuration:NSNumber = _keyboardUserInfo[UIKeyboardAnimationDurationUserInfoKey] as NSNumber UIView.animateWithDuration( animationDuration.doubleValue, delay: 0.0, options: UIViewAnimationOptions.fromRaw(UInt(animationCurve.unsignedIntValue))!, animations: { self._welcomeViewCenterYAlignment.priority = 750 self._welcomeViewTopAlignment.priority = 250 self.view.setNeedsLayout() }, completion:nil ) self._keyboardUserInfo = nil } } func textFieldDidBeginEditing(textField: UITextField) { _activeTextField = textField if (textField == _passwordTextField) { _passwordTextField.secureTextEntry = false if _keyboardUserInfo != nil { self.animateTextFieldUp(keyboardUserInfo: _keyboardUserInfo) } } } func textFieldShouldEndEditing(textField: UITextField) -> Bool { _activeTextField = nil if (textField == _passwordTextField) { _passwordTextField.secureTextEntry = true } return true } func textFieldShouldReturn(textField: UITextField) -> Bool { if (textField == _emailTextField) { textField.resignFirstResponder() _passwordTextField.becomeFirstResponder() } else { _passwordTextField.resignFirstResponder() } return true } override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { self._deviceIsRotating = true } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { self._deviceIsRotating = false } func loginCommunAction(valuesMatchFunc:((Void)->Void)) { var loginModel: LoginModel = LoginModel.sharedInstance loginModel._userName = _emailTextField.text loginModel._password = _passwordTextField.text if loginModel.usernameIsLegal() { if loginModel.passwordIsLegal() { valuesMatchFunc() } else { // Bad Password var alert:UIAlertController = UIAlertController( title: "Bad Password", message: "The password must contain at least one capital letter, on lower letter, one number and a minumun of 8 letters", preferredStyle: UIAlertControllerStyle.Alert) var okAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } } else { // Bad Email Address var alert:UIAlertController = UIAlertController( title: "Bad Email Address", message: "Please check your email addres.", preferredStyle: UIAlertControllerStyle.Alert) var okAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } } @IBAction func loginAction(sender: AnyObject) { self.loginCommunAction( { () -> Void in var loginModel: LoginModel = LoginModel.sharedInstance loginModel.login({ (success: Bool) -> Void in if success { self.performSegueWithIdentifier("LoginSegue", sender: self) self._passwordTextField.text = "" } else { var alert:UIAlertController = UIAlertController( title: "Bad Password", message: "The password used not mach with the registered one.\n Please try agaim or sign up with a diferent email", preferredStyle: UIAlertControllerStyle.Alert) var okAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } }) }) } @IBAction func signUpAction(sender: AnyObject) { self.loginCommunAction ( { () -> Void in var loginModel: LoginModel = LoginModel.sharedInstance loginModel.signUp({ (success: Bool) -> Void in if success { self.performSegueWithIdentifier("LoginSegue", sender: self) self._passwordTextField.text = "" } else { var alert:UIAlertController = UIAlertController( title: "User Exist", message: "The email used was registered already. Please try a diferent email", preferredStyle: UIAlertControllerStyle.Alert) var okAction:UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } }) }) } }
gpl-2.0
7904ac840e2656bcfb86de5bc8849e53
42.759434
144
0.617764
6.02794
false
false
false
false
jianwoo/WordPress-iOS
WordPress/Classes/Extensions/UIImageView+Animations.swift
13
1431
import Foundation extension UIImageView { public func displayImageWithSpringAnimation(newImage: UIImage) { let duration = 0.5 let delay = 0.2 let damping = CGFloat(0.7) let velocity = CGFloat(0.5) let scaleInitial = CGFloat(0.0) let scaleFinal = CGFloat(1.0) image = newImage hidden = false transform = CGAffineTransformMakeScale(scaleInitial, scaleInitial) var animations = { self.transform = CGAffineTransformMakeScale(scaleFinal, scaleFinal) } UIView.animateWithDuration(duration, delay: delay, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: nil, animations: animations, completion: nil ) } public func displayImageWithFadeInAnimation(newImage: UIImage) { let duration = 0.3 let alphaInitial = CGFloat(0.5) let alphaFinal = CGFloat(1.0) image = newImage; alpha = alphaInitial UIView.animateWithDuration(duration) { [weak self] in if let weakSelf = self { self?.alpha = alphaFinal } } } }
gpl-2.0
61361513ad6d9f23545bd2c6e6acc92c
28.8125
84
0.505241
5.482759
false
false
false
false
abonz/Swift
SwiftLoginScreen/SwiftLoginScreen/SignupVC.swift
32
6957
// // SignupVC.swift // SwiftLoginScreen // // Created by Carlos Butron on 12/04/14. // Copyright (c) 2015 Carlos Butron. All rights reserved. // // 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 UIKit class SignupVC: UIViewController { @IBOutlet var txtUsername : UITextField! @IBOutlet var txtPassword : UITextField! @IBOutlet var txtConfirmPassword : UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @IBAction func gotoLogin(sender : UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func signupTapped(sender : UIButton) { var username:NSString = txtUsername.text as NSString var password:NSString = txtPassword.text as NSString var confirm_password:NSString = txtConfirmPassword.text as NSString if ( username.isEqualToString("") || password.isEqualToString("") ) { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = "Please enter Username and Password" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } else if ( !password.isEqual(confirm_password) ) { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = "Passwords doesn't Match" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } else { var post:NSString = "username=\(username)&password=\(password)&c_password=\(confirm_password)" NSLog("PostData: %@",post); var url:NSURL = NSURL(string: "http://carlosbutron.es/iOS/jsonsignup.php")! var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)! var postLength:NSString = String( postData.length ) var request:NSMutableURLRequest = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.HTTPBody = postData request.setValue(postLength as String, forHTTPHeaderField: "Content-Length") request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") var reponseError: NSError? var response: NSURLResponse? var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError) if ( urlData != nil ) { let res = response as! NSHTTPURLResponse!; NSLog("Response code: %ld", res.statusCode); if (res.statusCode >= 200 && res.statusCode < 300) { var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)! NSLog("Response ==> %@", responseData); var error: NSError? let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as! NSDictionary let success:NSInteger = jsonData.valueForKey("success") as! NSInteger //[jsonData[@"success"] integerValue]; NSLog("Success: %ld", success); if(success == 1) { NSLog("Sign Up SUCCESS"); self.dismissViewControllerAnimated(true, completion: nil) } else { var error_msg:NSString if jsonData["error_message"] as? NSString != nil { error_msg = jsonData["error_message"] as! NSString } else { error_msg = "Unknown Error" } var alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = error_msg as String alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign Up Failed!" alertView.message = "Connection Failed" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } else { var alertView:UIAlertView = UIAlertView() alertView.title = "Sign in Failed!" alertView.message = "Connection Failure" if let error = reponseError { alertView.message = (error.localizedDescription) } alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.show() } } } func textFieldShouldReturn(textField: UITextField!) -> Bool { //delegate method textField.resignFirstResponder() return true } }
gpl-3.0
895ff21b0441d467570067da563a5982
40.658683
177
0.552537
5.920851
false
false
false
false
swernimo/iOS
iOS Networking with Swift/OnTheMap/OnTheMap/StudentLocation.swift
1
3665
// // studentLocations.swift // OnTheMap // // Created by Sean Wernimont on 1/28/16. // Copyright © 2016 Just One Guy. All rights reserved. // import Foundation struct StudentLocation { var objectID: String? = nil; var uniqueKey: String? = nil; var firstName: String? = nil; var lastName: String? = nil; var mapString: String? = nil; var mediaURL: String? = nil; var latitude: Double? = nil; var longitude: Double? = nil; var createdAt: String? = nil; var updatedAt: String? = nil; init(dictionary: [String: AnyObject]){ firstName = parseFirstName(dictionary); lastName = parseLastName(dictionary); latitude = parseLatitude(dictionary); longitude = parseLongitude(dictionary); mapString = parseMapString(dictionary); mediaURL = parseMediaURL(dictionary); objectID = parseObjectId(dictionary); uniqueKey = parseUniqueKey(dictionary); createdAt = parseCreatedAtDate(dictionary); updatedAt = parseUpdatedAt(dictionary); } init(){ } func parseFirstName(dictionary: [String: AnyObject]) -> String?{ guard let fName = dictionary["firstName"] as? String else{ print("could not find first name"); return nil; } return fName; } func parseLastName(dictionary: [String: AnyObject]) -> String?{ guard let lName = dictionary["lastName"] as? String else{ print("could not find last name"); return nil; } return lName; } func parseLatitude(dictionary: [String: AnyObject]) -> Double? { guard let lat = dictionary["latitude"] as? Double else{ print("could not find latitude"); return nil; } return lat; } func parseLongitude(dictionary: [String: AnyObject]) -> Double?{ guard let long = dictionary["longitude"] as? Double else{ print("could not find longitude"); return nil; } return long; } func parseMapString(dictionary: [String: AnyObject]) -> String?{ guard let map = dictionary["mapString"] as? String else{ print("could not find map string"); return nil; } return map; } func parseMediaURL(dictionary: [String: AnyObject]) -> String?{ guard let media = dictionary["mediaURL"] as? String else{ print("could not find media URL"); return nil; } return media; } func parseObjectId(dictionary: [String: AnyObject]) -> String?{ guard let id = dictionary["objectId"] as? String else{ print("could not find object id"); return nil; } return id; } func parseUniqueKey(dictionary: [String: AnyObject]) -> String?{ guard let key = dictionary["uniqueKey"] as? String else{ print("could not find unique key"); return nil; } return key; } func parseCreatedAtDate(dictionary: [String: AnyObject]) -> String?{ guard let createdDate = dictionary["createdAt"] as? String else{ print("could not find created at"); return nil; } return createdDate; } func parseUpdatedAt(dictionary: [String: AnyObject]) -> String?{ guard let updatedDate = dictionary["updatedAt"] as? String else{ print("could not find updated at"); return nil; } return updatedDate; } }
mit
c60e835edfc8084a010b96444145889d
27.858268
72
0.569323
4.885333
false
false
false
false
IC2017/NewsWatch
NewsSeconds/NewsSeconds/FoldingCell.swift
1
19868
// // FoldingCell.swift // NewsSeconds // // Created by Anantha Krishnan K G on 02/03/17. // Copyright © 2017 Ananth. All rights reserved. // import UIKit open class FoldingCell: UITableViewCell { /// UIView whitch display when cell open @IBOutlet weak open var containerView: UIView! @IBOutlet weak open var containerViewTop: NSLayoutConstraint! /// UIView whitch display when cell close @IBOutlet weak open var foregroundView: RotatedView! @IBOutlet weak open var foregroundViewTop: NSLayoutConstraint! var animationView: UIView? /// the number of folding elements. Default 2 @IBInspectable open var itemCount: NSInteger = 2 /// The color of the back cell @IBInspectable open var backViewColor: UIColor = UIColor.brown var animationItemViews: [RotatedView]? /** Folding animation types - Open: Open direction - Close: Close direction */ public enum AnimationType { case open case close } // MARK: life cicle override public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func awakeFromNib() { super.awakeFromNib() commonInit() } /** Call this method in methods init(style: UITableViewCellStyle, reuseIdentifier: String?) after creating Views */ open func commonInit() { configureDefaultState() self.selectionStyle = .none containerView.layer.cornerRadius = foregroundView.layer.cornerRadius containerView.layer.masksToBounds = true } // MARK: configure func configureDefaultState() { guard let foregroundViewTop = self.foregroundViewTop, let containerViewTop = self.containerViewTop else { fatalError("set constratins outlets") } containerViewTop.constant = foregroundViewTop.constant containerView.alpha = 0; if let height = (foregroundView.constraints.filter { $0.firstAttribute == .height && $0.secondItem == nil}).first?.constant { foregroundView.layer.anchorPoint = CGPoint(x: 0.5, y: 1) foregroundViewTop.constant += height / 2 } foregroundView.layer.transform = foregroundView.transform3d() createAnimationView(); self.contentView.bringSubview(toFront: foregroundView) } func createAnimationItemView()->[RotatedView] { guard let animationView = self.animationView else { fatalError() } var items = [RotatedView]() items.append(foregroundView) var rotatedViews = [RotatedView]() for case let itemView as RotatedView in animationView.subviews.filter({$0 is RotatedView}).sorted(by: {$0.tag < $1.tag}) { rotatedViews.append(itemView) if let backView = itemView.backView { rotatedViews.append(backView) } } items.append(contentsOf: rotatedViews) return items } func configureAnimationItems(_ animationType: AnimationType) { guard let animationViewSuperView = animationView?.subviews else { fatalError() } if animationType == .open { for view in animationViewSuperView.filter({$0 is RotatedView}) { view.alpha = 0; } } else { // close for case let view as RotatedView in animationViewSuperView.filter({$0 is RotatedView}) { if animationType == .open { view.alpha = 0 } else { view.alpha = 1 view.backView?.alpha = 0 } } } } func createAnimationView() { animationView = UIView(frame: containerView.frame) animationView?.layer.cornerRadius = foregroundView.layer.cornerRadius animationView?.backgroundColor = .clear animationView?.translatesAutoresizingMaskIntoConstraints = false animationView?.alpha = 0 guard let animationView = self.animationView else { return } self.contentView.addSubview(animationView) // copy constraints from containerView var newConstraints = [NSLayoutConstraint]() for constraint in self.contentView.constraints { if let item = constraint.firstItem as? UIView , item == containerView { let newConstraint = NSLayoutConstraint( item: animationView, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: constraint.secondItem, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant) newConstraints.append(newConstraint) } else if let item: UIView = constraint.secondItem as? UIView , item == containerView { let newConstraint = NSLayoutConstraint(item: constraint.firstItem, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: animationView, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant) newConstraints.append(newConstraint) } } self.contentView.addConstraints(newConstraints) for constraint in containerView.constraints { // added height constraint if constraint.firstAttribute == .height { let newConstraint = NSLayoutConstraint(item: animationView, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: nil, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant) animationView.addConstraint(newConstraint) } } } func addImageItemsToAnimationView() { containerView.alpha = 1; let contSize = containerView.bounds.size let forgSize = foregroundView.bounds.size // added first item var image = containerView.pb_takeSnapshot(CGRect(x: 0, y: 0, width: contSize.width, height: forgSize.height)) var imageView = UIImageView(image: image) imageView.tag = 0 imageView.layer.cornerRadius = foregroundView.layer.cornerRadius animationView?.addSubview(imageView) // added secod item image = containerView.pb_takeSnapshot(CGRect(x: 0, y: forgSize.height, width: contSize.width, height: forgSize.height)) imageView = UIImageView(image: image) let rotatedView = RotatedView(frame: imageView.frame) rotatedView.tag = 1 rotatedView.layer.anchorPoint = CGPoint.init(x: 0.5, y: 0) rotatedView.layer.transform = rotatedView.transform3d() rotatedView.addSubview(imageView) animationView?.addSubview(rotatedView) rotatedView.frame = CGRect(x: imageView.frame.origin.x, y: forgSize.height, width: contSize.width, height: forgSize.height) // added other views let itemHeight = (contSize.height - 2 * forgSize.height) / CGFloat(itemCount - 2) if itemCount == 2 { // decrease containerView height or increase itemCount assert(contSize.height - 2 * forgSize.height == 0, "contanerView.height too high") } else{ // decrease containerView height or increase itemCount assert(contSize.height - 2 * forgSize.height >= itemHeight, "contanerView.height too high") } // decrease containerView height or increase itemCount assert(contSize.height - 2 * forgSize.height >= itemHeight, "contanerView.height too high") var yPosition = 2 * forgSize.height var tag = 2 for _ in 2..<itemCount { image = containerView.pb_takeSnapshot(CGRect(x: 0, y: yPosition, width: contSize.width, height: itemHeight)) imageView = UIImageView(image: image) let rotatedView = RotatedView(frame: imageView.frame) rotatedView.addSubview(imageView) rotatedView.layer.anchorPoint = CGPoint.init(x: 0.5, y: 0) rotatedView.layer.transform = rotatedView.transform3d() animationView?.addSubview(rotatedView) rotatedView.frame = CGRect(x: 0, y: yPosition, width: rotatedView.bounds.size.width, height: itemHeight) rotatedView.tag = tag yPosition += itemHeight tag += 1; } containerView.alpha = 0; if let animationView = self.animationView { // added back view var previusView: RotatedView? for case let contener as RotatedView in animationView.subviews.sorted(by: { $0.tag < $1.tag }) where contener.tag > 0 && contener.tag < animationView.subviews.count { previusView?.addBackView(contener.bounds.size.height, color: backViewColor) previusView = contener } } animationItemViews = createAnimationItemView() } fileprivate func removeImageItemsFromAnimationView() { guard let animationView = self.animationView else { return } animationView.subviews.forEach({ $0.removeFromSuperview() }) } // MARK: public /** Open or close cell - parameter isSelected: Specify true if you want to open cell or false if you close cell. - parameter animated: Specify true if you want to animate the change in visibility or false if you want immediately. - parameter completion: A block object to be executed when the animation sequence ends. */ open func selectedAnimation(_ isSelected: Bool, animated: Bool, completion: ((Void) -> Void)?) { if isSelected { if animated { containerView.alpha = 0; openAnimation(completion) } else { foregroundView.alpha = 0 containerView.alpha = 1; } } else { if animated { closeAnimation(completion) } else { foregroundView.alpha = 1; containerView.alpha = 0; } } } open func isAnimating()->Bool { return animationView?.alpha == 1 ? true : false } // MARK: animations open func animationDuration(_ itemIndex:NSInteger, type:AnimationType)-> TimeInterval { assert(false, "added this method to cell") return 0 } func durationSequence(_ type: AnimationType)-> [TimeInterval] { var durations = [TimeInterval]() for index in 0..<itemCount-1 { let duration = animationDuration(index, type: type) durations.append(TimeInterval(duration / 2.0)) durations.append(TimeInterval(duration / 2.0)) } return durations } func openAnimation(_ completion: ((Void) -> Void)?) { removeImageItemsFromAnimationView() addImageItemsToAnimationView() guard let animationView = self.animationView else { return } animationView.alpha = 1; containerView.alpha = 0; let durations = durationSequence(.open) var delay: TimeInterval = 0 var timing = kCAMediaTimingFunctionEaseIn var from: CGFloat = 0.0; var to: CGFloat = CGFloat(-M_PI / 2) var hidden = true configureAnimationItems(.open) guard let animationItemViews = self.animationItemViews else { return } for index in 0..<animationItemViews.count { let animatedView = animationItemViews[index] animatedView.foldingAnimation(timing, from: from, to: to, duration: durations[index], delay: delay, hidden: hidden) from = from == 0.0 ? CGFloat(M_PI / 2) : 0.0; to = to == 0.0 ? CGFloat(-M_PI / 2) : 0.0; timing = timing == kCAMediaTimingFunctionEaseIn ? kCAMediaTimingFunctionEaseOut : kCAMediaTimingFunctionEaseIn; hidden = !hidden delay += durations[index] } let firstItemView = animationView.subviews.filter{$0.tag == 0}.first firstItemView?.layer.masksToBounds = true DispatchQueue.main.asyncAfter(deadline: .now() + durations[0], execute: { firstItemView?.layer.cornerRadius = 0 }) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: { self.animationView?.alpha = 0 self.containerView.alpha = 1 completion?() }) } func closeAnimation(_ completion: ((Void) -> Void)?) { removeImageItemsFromAnimationView() addImageItemsToAnimationView() guard let animationItemViews = self.animationItemViews else { fatalError() } animationView?.alpha = 1; containerView.alpha = 0; var durations: [TimeInterval] = durationSequence(.close).reversed() var delay: TimeInterval = 0 var timing = kCAMediaTimingFunctionEaseIn var from: CGFloat = 0.0; var to: CGFloat = CGFloat(M_PI / 2) var hidden = true configureAnimationItems(.close) if durations.count < animationItemViews.count { fatalError("wrong override func animationDuration(itemIndex:NSInteger, type:AnimationType)-> NSTimeInterval") } for index in 0..<animationItemViews.count { let animatedView = animationItemViews.reversed()[index] animatedView.foldingAnimation(timing, from: from, to: to, duration: durations[index], delay: delay, hidden: hidden) to = to == 0.0 ? CGFloat(M_PI / 2) : 0.0; from = from == 0.0 ? CGFloat(-M_PI / 2) : 0.0; timing = timing == kCAMediaTimingFunctionEaseIn ? kCAMediaTimingFunctionEaseOut : kCAMediaTimingFunctionEaseIn; hidden = !hidden delay += durations[index] } DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { self.animationView?.alpha = 0 completion?() }) let firstItemView = animationView?.subviews.filter{$0.tag == 0}.first firstItemView?.layer.cornerRadius = 0 firstItemView?.layer.masksToBounds = true if let durationFirst = durations.first { DispatchQueue.main.asyncAfter(deadline: .now() + delay - durationFirst * 2, execute: { firstItemView?.layer.cornerRadius = self.foregroundView.layer.cornerRadius firstItemView?.setNeedsDisplay() firstItemView?.setNeedsLayout() }) } } } // MARK: RotatedView open class RotatedView: UIView { var hiddenAfterAnimation = false var backView: RotatedView? func addBackView(_ height: CGFloat, color:UIColor) { let view = RotatedView(frame: CGRect.zero) view.backgroundColor = color view.layer.anchorPoint = CGPoint.init(x: 0.5, y: 1) view.layer.transform = view.transform3d() view.translatesAutoresizingMaskIntoConstraints = false; self.addSubview(view) backView = view view.addConstraint(NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil,attribute: .height, multiplier: 1, constant: height)) self.addConstraints([ NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: self.bounds.size.height - height + height / 2), NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) ]) } } extension RotatedView: CAAnimationDelegate { func rotatedX(_ angle : CGFloat) { var allTransofrom = CATransform3DIdentity; let rotateTransform = CATransform3DMakeRotation(angle, 1, 0, 0) allTransofrom = CATransform3DConcat(allTransofrom, rotateTransform) allTransofrom = CATransform3DConcat(allTransofrom, transform3d()) self.layer.transform = allTransofrom } func transform3d() -> CATransform3D { var transform = CATransform3DIdentity transform.m34 = 2.5 / -2000; return transform } // MARK: animations func foldingAnimation(_ timing: String, from: CGFloat, to: CGFloat, duration: TimeInterval, delay:TimeInterval, hidden:Bool) { let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.x") rotateAnimation.timingFunction = CAMediaTimingFunction(name: timing) rotateAnimation.fromValue = (from) rotateAnimation.toValue = (to) rotateAnimation.duration = duration rotateAnimation.delegate = self; rotateAnimation.fillMode = kCAFillModeForwards rotateAnimation.isRemovedOnCompletion = false; rotateAnimation.beginTime = CACurrentMediaTime() + delay self.hiddenAfterAnimation = hidden self.layer.add(rotateAnimation, forKey: "rotation.x") } public func animationDidStart(_ anim: CAAnimation) { self.layer.shouldRasterize = true self.alpha = 1 } public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if hiddenAfterAnimation { self.alpha = 0 } self.layer.removeAllAnimations() self.layer.shouldRasterize = false self.rotatedX(CGFloat(0)) } } extension UIView { func pb_takeSnapshot(_ frame: CGRect) -> UIImage? { UIGraphicsBeginImageContextWithOptions(frame.size, false, 0.0) let context = UIGraphicsGetCurrentContext(); context!.translateBy(x: frame.origin.x * -1, y: frame.origin.y * -1) guard let currentContext = UIGraphicsGetCurrentContext() else { return nil } self.layer.render(in: currentContext) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
apache-2.0
7e887a40c17f6885684d6f70dc8d7651
38.031434
157
0.588061
5.34634
false
false
false
false
anasmeister/nRF-Coventry-University
nRF Toolbox/BPM/NORBPMViewController.swift
1
14516
// // NORBMPViewController.swift // nRF Toolbox // // Created by Mostafa Berg on 06/05/16. // Copyright © 2016 Nordic Semiconductor. All rights reserved. //// Edited by Anastasios Panagoulias on 11/01/07 import UIKit import CoreBluetooth class NORBPMViewController: NORBaseViewController, CBCentralManagerDelegate, CBPeripheralDelegate, NORScannerDelegate { //MARK: - ViewController Properties var bpmServiceUUID : CBUUID var bpmBloodPressureMeasurementCharacteristicUUID : CBUUID var bpmIntermediateCuffPressureCharacteristicUUID : CBUUID var batteryServiceUUID : CBUUID var batteryLevelCharacteristicUUID : CBUUID var bluetoothManager : CBCentralManager? var connectedPeripheral : CBPeripheral? //MARK: - Referencing Outlets @IBOutlet weak var deviceName: UILabel! @IBOutlet weak var battery: UIButton! @IBOutlet weak var verticalLabel: UILabel! @IBOutlet weak var connectionButton: UIButton! @IBOutlet weak var systolic: UILabel! @IBOutlet weak var systolicUnit: UILabel! @IBOutlet weak var diastolic: UILabel! @IBOutlet weak var diastolicUnit: UILabel! @IBOutlet weak var meanAp: UILabel! @IBOutlet weak var meanApUnit: UILabel! @IBOutlet weak var pulse: UILabel! @IBOutlet weak var timestamp: UILabel! //MARK: - Referencing Actions @IBAction func connectionButtonTapped(_ sender: AnyObject) { if connectedPeripheral != nil { bluetoothManager?.cancelPeripheralConnection(connectedPeripheral!) } } @IBAction func aboutButtonTapped(_ sender: AnyObject) { self.showAbout(message: NORAppUtilities.getHelpTextForService(service: .bpm)) } //MARK: - UIViewController methods required init?(coder aDecoder: NSCoder) { bpmServiceUUID = CBUUID(string: NORServiceIdentifiers.bpmServiceUUIDString) bpmBloodPressureMeasurementCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.bpmBloodPressureMeasurementCharacteristicUUIDString) bpmIntermediateCuffPressureCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.bpmIntermediateCuffPressureCharacteristicUUIDString) batteryServiceUUID = CBUUID(string: NORServiceIdentifiers.batteryServiceUUIDString) batteryLevelCharacteristicUUID = CBUUID(string: NORServiceIdentifiers.batteryLevelCharacteristicUUIDString) super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.verticalLabel.transform = CGAffineTransform(translationX: -150.0, y: 0.0).rotated(by: CGFloat(-M_PI_2)); } //MARK: - NORBPMViewController Implementation func didEnterBackgroundCallback(notification aNotification: Notification) { let name = connectedPeripheral?.name ?? "peripheral" NORAppUtilities.showBackgroundNotification(message: "You are still connected to \(name). It will collect data also in background.") } func didBecomeActiveCallback(notification aNotification: Notification) { UIApplication.shared.cancelAllLocalNotifications() } func clearUI() { deviceName.text = "DEFAULT BPM" battery.tag = 0 battery.setTitle("n/a", for: UIControlState.disabled) systolicUnit.isHidden = true diastolicUnit.isHidden = true meanApUnit.isHidden = true systolic.text = "-" diastolic.text = "-" meanAp.text = "-" pulse.text = "-" timestamp.text = "-" } //MARK: - NORScannerDelegate methods func centralManagerDidSelectPeripheral(withManager aManager: CBCentralManager, andPeripheral aPeripheral: CBPeripheral) { clearUI() bluetoothManager = aManager bluetoothManager?.delegate = self aPeripheral.delegate = self let connectionOptions = NSDictionary(object: NSNumber(value: true as Bool), forKey: CBConnectPeripheralOptionNotifyOnNotificationKey as NSCopying) bluetoothManager?.connect(aPeripheral, options: connectionOptions as? [String : AnyObject]) } //MARK: - CBCentralManagerDelegate func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == .poweredOff { print("Bluetooth powered off") } else { print("Bluetooth powered on") } } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { DispatchQueue.main.async { self.deviceName.text = peripheral.name self.connectionButton.setTitle("DISCONNECT", for: UIControlState()) } //Following if condition display user permission alert for background notification if UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:))) { UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert, .sound], categories: nil)) } NotificationCenter.default.addObserver(self, selector: #selector(self.didEnterBackgroundCallback(notification:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.didBecomeActiveCallback(notification:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) connectedPeripheral = peripheral peripheral.discoverServices([bpmServiceUUID, batteryServiceUUID]) } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { // Scanner uses other queue to send events. We must edit UI in the main queue DispatchQueue.main.async(execute: { NORAppUtilities.showAlert(title: "Error", andMessage: "Connecting to peripheral failed. Try again") self.connectionButton.setTitle("CONNECT", for: UIControlState()) self.connectedPeripheral = nil self.clearUI() }); } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { // Scanner uses other queue to send events. We must edit UI in the main queue DispatchQueue.main.async(execute: { self.connectionButton.setTitle("CONNECT", for: UIControlState()) self.connectedPeripheral = nil if NORAppUtilities.isApplicationInactive() { let name = peripheral.name ?? "Peripheral" NORAppUtilities.showBackgroundNotification(message: "\(name) is disconnected.") } NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) }) } //MARK: - CBPeripheralDelegate func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard error == nil else { print("An error occured while discovering services: \(error!.localizedDescription)") bluetoothManager!.cancelPeripheralConnection(peripheral) return } for aService : CBService in peripheral.services! { if aService.uuid == batteryServiceUUID { peripheral.discoverCharacteristics([batteryLevelCharacteristicUUID], for: aService) } else if aService.uuid == bpmServiceUUID { peripheral.discoverCharacteristics( [bpmBloodPressureMeasurementCharacteristicUUID,bpmIntermediateCuffPressureCharacteristicUUID], for: aService) } } } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { guard error == nil else { print("Error occurred while discovering characteristic: \(error!.localizedDescription)") bluetoothManager!.cancelPeripheralConnection(peripheral) return } if service.uuid == bpmServiceUUID { for aCharacteristic :CBCharacteristic in service.characteristics! { if aCharacteristic.uuid == bpmBloodPressureMeasurementCharacteristicUUID || aCharacteristic.uuid == bpmIntermediateCuffPressureCharacteristicUUID { peripheral.setNotifyValue(true, for: aCharacteristic) } } } else if service.uuid == batteryServiceUUID { for aCharacteristic :CBCharacteristic in service.characteristics! { if aCharacteristic.uuid == batteryLevelCharacteristicUUID { peripheral.readValue(for: aCharacteristic) break } } } } // main function to read from peripheral - WORK ON THIS func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { guard error == nil else { print("Error occurred while updating characteristic value: \(error!.localizedDescription)") return } // Scanner uses other queue to send events. We must edit UI in the main queue DispatchQueue.main.async(execute: { if characteristic.uuid == self.batteryLevelCharacteristicUUID { // Decode the characteristic data let data = characteristic.value; var pointer = UnsafeMutablePointer<UInt8>(mutating: (data! as NSData).bytes.bindMemory(to: UInt8.self, capacity: data!.count)) let batteryLevel = NORCharacteristicReader.readUInt8Value(ptr: &pointer) let text = "\(batteryLevel)%" self.battery.setTitle(text, for: UIControlState.disabled) if self.battery.tag == 0 { if characteristic.properties.rawValue & CBCharacteristicProperties.notify.rawValue > 0 { peripheral.setNotifyValue(true, for: characteristic) self.battery.tag = 1 } } } else if characteristic.uuid == self.bpmBloodPressureMeasurementCharacteristicUUID || characteristic.uuid == self.bpmIntermediateCuffPressureCharacteristicUUID { let data = characteristic.value var pointer = UnsafeMutablePointer<UInt8>(mutating: (data! as NSData).bytes.bindMemory(to: UInt8.self, capacity: data!.count)) let flags = NORCharacteristicReader.readUInt8Value(ptr: &pointer) let kPA : Bool = (flags & 0x01) > 0 let timestampPresent : Bool = (flags & 0x02) > 0 let pulseRatePresent : Bool = (flags & 0x04) > 0 if kPA == true { self.systolicUnit.text = "kPa" self.diastolicUnit.text = "kPa" self.meanApUnit.text = "kPa" } else { self.systolicUnit.text = "mmHg" self.diastolicUnit.text = "mmHg" self.meanApUnit.text = "mmHg" } //Read main values if characteristic.uuid == self.bpmBloodPressureMeasurementCharacteristicUUID { let systolicValue = NORCharacteristicReader.readSFloatValue(ptr: &pointer) let diastolicValue = NORCharacteristicReader.readSFloatValue(ptr: &pointer) let meanApValue = NORCharacteristicReader.readSFloatValue(ptr: &pointer) self.systolic.text = String(format: "%.1f", systolicValue) self.diastolic.text = String(format: "%.1f", diastolicValue) self.meanAp.text = String(format: "%.1f", meanApValue) self.systolicUnit.isHidden = false self.diastolicUnit.isHidden = false self.meanApUnit.isHidden = false } else { let systolicValue = NORCharacteristicReader.readSFloatValue(ptr: &pointer) pointer += 4 self.systolic.text = String(format: "%.1f", systolicValue) self.diastolic.text = "n/a" self.meanAp.text = "n/a" self.systolicUnit.isHidden = false self.diastolicUnit.isHidden = true self.meanApUnit.isHidden = true } // Read timestamp if timestampPresent { let date = NORCharacteristicReader.readDateTime(ptr: &pointer) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd.MM.yyy, hh:mm" let dateformattedString = dateFormatter.string(from: date) self.timestamp.text = dateformattedString } else { self.timestamp.text = "n/a" } // Read pulse if pulseRatePresent { let pulseValue = NORCharacteristicReader.readSFloatValue(ptr: &pointer) self.pulse.text = String(format: "%.1f", pulseValue) } else { self.pulse.text = "-" } } }) } //MARK: - Segue handling override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { return identifier != "scan" || connectedPeripheral == nil } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "scan" { let nc = segue.destination as! UINavigationController let controller = nc.childViewControllerForStatusBarHidden as! NORScannerViewController controller.filterUUID = bpmServiceUUID controller.delegate = self } } }
bsd-3-clause
b257cd0290ce870d6e1f2b4f1ac2fb2e
47.222591
193
0.620393
5.834003
false
false
false
false
uxmstudio/LANScanner
Pod/Classes/SimplePingHelper.swift
1
2283
// // SimplePingHelper.swift // Pods // // Created by Chris Anderson on 2/14/16. // // import UIKit class SimplePingHelper: NSObject, SimplePingDelegate { fileprivate var address:String fileprivate var simplePing:SimplePing? fileprivate var target:AnyObject fileprivate var selector:Selector static func start(_ address:String, target:AnyObject, selector:Selector) { SimplePingHelper(address: address, target: target, selector: selector).start() } init(address: String, target:AnyObject, selector:Selector) { self.simplePing = SimplePing(hostName:address) self.target = target self.selector = selector self.address = address super.init() self.simplePing!.delegate = self } func start() { self.simplePing?.start() self.perform(#selector(SimplePingHelper.endTime), with: nil, afterDelay: 1) } // MARK: - Helper Methods func killPing() { self.simplePing?.stop() self.simplePing = nil } func successPing() { self.killPing() let _ = self.target.perform(self.selector, with: [ "status": true, "address": self.address ]) } func failPing(_ reason: String) { self.killPing() let _ = self.target.perform(self.selector, with: [ "status": false, "address": self.address, "error": reason ]) } func endTime() { if let _ = self.simplePing { self.failPing("timeout") return } } // MARK: - SimplePing Delegate func simplePing(_ pinger: SimplePing!, didStartWithAddress address: Data!) { self.simplePing?.send(with: nil) } func simplePing(_ pinger: SimplePing!, didFailWithError error: Error!) { self.failPing("didFailWithError") } func simplePing(_ pinger: SimplePing!, didFailToSendPacket packet: Data!, error: Error!) { self.failPing("didFailToSendPacked") } func simplePing(_ pinger: SimplePing!, didReceivePingResponsePacket packet: Data!) { self.successPing() } }
mit
6e4abb6dd55f35336013055d30e463cf
23.815217
94
0.575558
4.476471
false
false
false
false
dshahidehpour/IGListKit
Examples/Examples-iOS/IGListKitExamples/SectionControllers/DisplaySectionController.swift
4
2633
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 import IGListKit class DisplaySectionController: IGListSectionController, IGListSectionType, IGListDisplayDelegate { override init() { super.init() displayDelegate = self inset = UIEdgeInsets(top: 0, left: 0, bottom: 30, right: 0) } func numberOfItems() -> Int { return 4 } func sizeForItem(at index: Int) -> CGSize { return CGSize(width: collectionContext!.containerSize.width, height: 55) } func cellForItem(at index: Int) -> UICollectionViewCell { let cell = collectionContext!.dequeueReusableCell(of: LabelCell.self, for: self, at: index) as! LabelCell let section = collectionContext!.section(for: self) cell.label.text = "Section \(section), cell \(index)" return cell } func didUpdate(to object: Any) {} func didSelectItem(at index: Int) {} // MARK: IGListDisplayDelegate func listAdapter(_ listAdapter: IGListAdapter, willDisplay sectionController: IGListSectionController) { let section = collectionContext!.section(for: self) print("Will display section \(section)") } func listAdapter(_ listAdapter: IGListAdapter, willDisplay sectionController: IGListSectionController, cell: UICollectionViewCell, at index: Int) { let section = collectionContext!.section(for: self) print("Did will display cell \(index) in section \(section)") } func listAdapter(_ listAdapter: IGListAdapter, didEndDisplaying sectionController: IGListSectionController) { let section = collectionContext!.section(for: self) print("Did end displaying section \(section)") } func listAdapter(_ listAdapter: IGListAdapter, didEndDisplaying sectionController: IGListSectionController, cell: UICollectionViewCell, at index: Int) { let section = collectionContext!.section(for: self) print("Did end displaying cell \(index) in section \(section)") } }
bsd-3-clause
ccbc316b918976b90321959255fe632a
38.298507
156
0.716673
5.102713
false
false
false
false
artsy/eigen
ios/Artsy/Views/Core/TextStack.swift
1
2940
import UIKit class TextStack: ORStackView { @discardableResult func addArtistName(_ string: String) -> UILabel { let artistNameLabel = UILabel() artistNameLabel.text = string artistNameLabel.font = UIFont.serifSemiBoldFont(withSize: 16) addSubview(artistNameLabel, withTopMargin: "0", sideMargin: "0") return artistNameLabel } @discardableResult func addArtworkName(_ string: String, date: String?) -> ARArtworkTitleLabel { let title = ARArtworkTitleLabel() title.setTitle(string, date: date) addSubview(title, withTopMargin: "4", sideMargin: "0") return title } @discardableResult func addSmallHeading(_ string: String, sideMargin: String = "0") -> UILabel { let heading = ARSansSerifLabel() heading.font = .sansSerifFont(withSize: 12) heading.text = string addSubview(heading, withTopMargin: "10", sideMargin: sideMargin) return heading } @discardableResult func addBigHeading(_ string: String, sideMargin: String = "0") -> UILabel { let heading = ARSerifLabel() heading.font = .serifFont(withSize: 26) heading.text = string addSubview(heading, withTopMargin: "20", sideMargin:sideMargin) return heading } @discardableResult func addSmallLineBreak(_ sideMargin: String = "0") -> UIView { let line = UIView() line.backgroundColor = .artsyGrayRegular() addSubview(line, withTopMargin: "20", sideMargin: sideMargin) line.constrainHeight("1") return line } @discardableResult func addThickLineBreak(_ sideMargin: String = "0") -> UIView { let line = UIView() line.backgroundColor = .black addSubview(line, withTopMargin: "20", sideMargin: sideMargin) line.constrainHeight("2") return line } @discardableResult func addBodyText(_ string: String, topMargin: String = "20", sideMargin: String = "0") -> UILabel { let serif = ARSerifLabel() serif.font = .serifFont(withSize: 16) serif.numberOfLines = 0 serif.text = string addSubview(serif, withTopMargin: topMargin, sideMargin: sideMargin) return serif } @discardableResult func addBodyMarkdown(_ string: MarkdownString, topMargin: String = "20", sideMargin: String = "0") -> ARTextView { let text = ARTextView() text.plainLinks = true text.setMarkdownString(string) addSubview(text, withTopMargin: topMargin, sideMargin: sideMargin) return text } @discardableResult func addLinkedBodyMarkdown(_ string: MarkdownString, topMargin: String = "20", sideMargin: String = "0") -> ARTextView { let text = ARTextView() text.setMarkdownString(string) addSubview(text, withTopMargin: topMargin, sideMargin: sideMargin) return text } }
mit
5a5b291146eef5a0c8a109948289c634
34.421687
124
0.647959
4.851485
false
false
false
false
yangalex/TimeMatch
TimeMatch/ViewController.swift
1
29320
// // ViewController.swift // TimeMatch // // Created by Alexandre Yang on 7/13/15. // Copyright (c) 2015 Alex Yang. All rights reserved. // import UIKit struct IndexRange { var start: Int var end: Int } let leftEdgeIndexes = [0, 6, 12, 18, 24, 30, 36, 42] let rightEdgeIndexes = [5, 11, 17, 23, 29, 35, 41, 47] let buttonColor = UIColor(red: 180/255, green: 180/255, blue: 180/255, alpha: 1.0) let greenColor = UIColor(red: 46/255, green: 204/255, blue: 113/255, alpha: 1.0) let blueColor = UIColor(red: 86/255, green: 212/255, blue: 243/255, alpha: 1.0) class ViewController: UIViewController { var draggingOn: Bool = false var isOnButton: Bool = false var draggingInitiated: Bool = false var touchBegan: Bool = false var pathSplittable: Bool = false var isMerging: Bool = false var highlightedRange: IndexRange = IndexRange(start: 0, end: 0) var spacing: CGFloat! = 3 var BUTTON_SIZE: CGFloat! var buttonsArray: [TimeButton] = [TimeButton]() var startButton: TimeButton? var endButton: TimeButton? struct Timeslot { var hour: Int var isHalf: Bool init(hour: Int, isHalf: Bool) { if hour > 23 || hour < 0 { self.hour = 0 } else { self.hour = hour } self.isHalf = isHalf } func description() -> String { if isHalf == true { if hour > 9 { return "\(String(hour)):30" } else { return "0\(String(hour)):30" } } else { if hour > 9 { return "\(String(hour)):00" } else { return "0\(String(hour)):00" } } } } override func viewDidLoad() { super.viewDidLoad() loadButtons() } func loadButtons() { // calculate button size // Formula: (screen width - margins - space that spacing take) == space buttons have available to occupy // divide that by 6 and you get size of each individual button BUTTON_SIZE = self.view.frame.width - 16 - spacing*5 BUTTON_SIZE = BUTTON_SIZE/6 spacing = spacing + BUTTON_SIZE // create and fill up array of TimeSlots var timeslots: [Timeslot] = [Timeslot]() for i in 0..<24 { let tempTimeslot = Timeslot(hour: i, isHalf: false) timeslots.append(tempTimeslot) let tempTimeslotHalf = Timeslot(hour: i, isHalf: true) timeslots.append(tempTimeslotHalf) } // Load buttons from timeslots var currentY: CGFloat = UIApplication.sharedApplication().statusBarFrame.height var currentX: CGFloat = 8 var elementsInRow = 0 for timeslot in timeslots { let newButton = buildTimeButton(timeslot.description(), atX: currentX, atY: currentY) self.view.addSubview(newButton) buttonsArray.append(newButton) elementsInRow++ // if row is filled up if elementsInRow == 6 { currentY = currentY + CGFloat(BUTTON_SIZE+10) currentX = 8 elementsInRow = 0 } else { currentX = currentX + spacing } } } func buildTimeButton(withTitle: String, atX x: CGFloat, atY y: CGFloat) -> TimeButton { var newButton = TimeButton(frame: CGRectMake(x, y, CGFloat(BUTTON_SIZE), CGFloat(BUTTON_SIZE))) newButton.spacing = self.spacing newButton.backgroundColor = UIColor.whiteColor() newButton.layer.borderWidth = 1.5 newButton.layer.borderColor = buttonColor.CGColor newButton.layer.cornerRadius = 0.5 * newButton.frame.size.width newButton.setTitle(withTitle, forState: UIControlState.Normal) var fontSize: CGFloat = 0 let screenHeight = UIScreen.mainScreen().bounds.height println(screenHeight) switch screenHeight { case 480: fontSize = 16 case 568: fontSize = 16 case 667: fontSize = 19 case 736: fontSize = 20 default: fontSize = 16 } if fromTimeToIndex(time: withTitle) % 2 == 0 { newButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: fontSize) } else { newButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) } newButton.setTitleColor(buttonColor, forState: UIControlState.Normal) newButton.userInteractionEnabled = false return newButton } func selectTime(sender:TimeButton!) { sender.selected = true if draggingOn { sender.timeState = .Handle } else { sender.timeState = .Single } } func unselectTime(sender: TimeButton!) { sender.leftHandle = nil sender.rightHandle = nil sender.matchingHandle = nil sender.selected = false sender.timeState = .Unselected } func turnToPath(button: TimeButton!, leftHandle: TimeButton!, rightHandle: TimeButton!) { // clear gap rectangles if button.timeState == .Handle { unjoinNeighboringHandles(button) } button.timeState = TimeButton.TimeState.Path // Set left and right handles button.leftHandle = leftHandle button.rightHandle = rightHandle // Customize edges if contains(leftEdgeIndexes, fromTimeToIndex(button)) { button.setBackgroundImage(UIImage(named: "ButtonEdgeLeft"), forState: .Selected) button.layer.borderColor = UIColor.clearColor().CGColor } if contains(rightEdgeIndexes, fromTimeToIndex(button)) { button.setBackgroundImage(UIImage(named: "ButtonEdgeRight"), forState: .Selected) button.layer.borderColor = UIColor.clearColor().CGColor } // Change color if in the middle of a merge if button == endButton { button.backgroundColor = UIColor(red: 137/255, green: 196/255, blue: 244/255, alpha: 1.0) } } // Adds a blue rectangle to the right of the button to fill in gap func joinNeighboringHandles(leftHandle: TimeButton) { if leftHandle.timeState == .Handle { var rightRectangle = UIView(frame: CGRectMake(leftHandle.frame.width, 0, spacing-CGFloat(BUTTON_SIZE), leftHandle.frame.height)) rightRectangle.backgroundColor = blueColor rightRectangle.tag = 15 leftHandle.addSubview(rightRectangle) } } // Removes blue rectangle from UIButton func unjoinNeighboringHandles(leftHandle: TimeButton) { for subview in leftHandle.subviews { if subview.tag == 15 { subview.removeFromSuperview() } } } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = touches.first as! UITouch let viewPoint = touch.locationInView(self.view) // iterate through every button in array and check if touch is inside it for button in buttonsArray { // convert viewPoint to button's coordinate system let buttonPoint = button.convertPoint(viewPoint, fromView: self.view) if button.pointInside(buttonPoint, withEvent: event) { touchBegan = true isOnButton = true // if button is a handle if button.timeState == .Handle { draggingOn = true self.startButton = button.matchingHandle self.endButton = button highlightedRange.start = fromTimeToIndex(button.matchingHandle!) highlightedRange.end = fromTimeToIndex(button) } else if button.timeState == .Path { draggingOn = true pathSplittable = true self.endButton = button } else if button.timeState == .Single { draggingOn = true self.startButton = button self.endButton = button highlightedRange.start = fromTimeToIndex(button) highlightedRange.end = fromTimeToIndex(button) } else { selectTime(button) self.startButton = button self.endButton = button highlightedRange.start = fromTimeToIndex(button) highlightedRange.end = fromTimeToIndex(button) } } } } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { if touchBegan { let touch = touches.first as! UITouch let viewPoint = touch.locationInView(self.view) // if touch was already on top of a button if isOnButton { let endButton = self.endButton! let buttonPoint = endButton.convertPoint(viewPoint, fromView: self.view) // Exited button if !endButton.pointInside(buttonPoint, withEvent: event) { if endButton.timeState == .Handle { draggingInitiated = true } else if endButton.timeState == .Path { draggingInitiated = true } // touched moved away from starting point if endButton == startButton { draggingOn = true startButton?.timeState = .Handle draggingInitiated = true } isOnButton = false } // else if touch was not on top of a button } else { for button in buttonsArray { // convert point let buttonPoint = button.convertPoint(viewPoint, fromView: self.view) // Entered button if button.pointInside(buttonPoint, withEvent: event) { isOnButton = true let pastPosition = self.endButton self.endButton = button // Path moved code if pastPosition!.timeState == .Path && pathSplittable == true { let initialIndex = fromTimeToIndex(pastPosition!) highlightedRange.end = initialIndex let leftHandle = pastPosition!.leftHandle! let rightHandle = pastPosition!.rightHandle! // Check if drag was to the right or left to decide if startButton should be left or right handle if fromTimeToIndex(self.endButton!) > initialIndex { // drag right self.startButton = rightHandle highlightedRange.start = fromTimeToIndex(rightHandle) selectTime(buttonsArray[initialIndex-1]) buttonsArray[initialIndex-1].matchingHandle = leftHandle leftHandle.matchingHandle = buttonsArray[initialIndex-1] highlightPathFrom(buttonsArray[initialIndex-1], toButton: leftHandle) } else if fromTimeToIndex(self.endButton!) < initialIndex { // drag left self.startButton = pastPosition?.leftHandle highlightedRange.start = fromTimeToIndex(self.startButton!) selectTime(buttonsArray[initialIndex+1]) buttonsArray[initialIndex+1].matchingHandle = pastPosition?.rightHandle pastPosition?.rightHandle?.matchingHandle = buttonsArray[initialIndex+1] highlightPathFrom(buttonsArray[initialIndex+1], toButton: pastPosition?.rightHandle) } pathSplittable = false } // user dragged back to starting point if startButton == endButton { draggingOn = false startButton?.timeState = .Single } // merging code // if button was already selected and not within own time cluster if (button.timeState == .Path || button.timeState == .Handle) && !(numBetweenRangeInclusive(fromTimeToIndex(button), startRange: highlightedRange.start, endRange: highlightedRange.end)) { isMerging = true if button.timeState == .Path { if highlightedRange.start < fromTimeToIndex(button) { unhighlightOldPath(fromTimeToIndex(startButton!), endIndex: fromTimeToIndex(button.rightHandle!)) highlightedRange.end = fromTimeToIndex(button.rightHandle!) } else if highlightedRange.start > fromTimeToIndex(button) { unhighlightOldPath(fromTimeToIndex(startButton!), endIndex: fromTimeToIndex(button.leftHandle!)) highlightedRange.end = fromTimeToIndex(button.leftHandle!) } } else if button.timeState == .Handle { unhighlightOldPath(fromTimeToIndex(startButton!), endIndex: fromTimeToIndex(button.matchingHandle!)) highlightedRange.end = fromTimeToIndex(button.matchingHandle!) } } if isMerging { if !numBetweenRange(fromTimeToIndex(button), startRange: highlightedRange.start, endRange: highlightedRange.end) { isMerging = false } else { if button.timeState == .Path { // highlight everything from our initial position to the end of the time cluster's right or left handle if highlightedRange.start < fromTimeToIndex(button) { highlightPathFrom(startButton, toButton: button.rightHandle) button.rightHandle?.matchingHandle = startButton startButton?.matchingHandle = button.rightHandle highlightedRange.end = fromTimeToIndex(button.rightHandle!) } else if highlightedRange.start > fromTimeToIndex(button) { highlightPathFrom(startButton, toButton: button.leftHandle) button.leftHandle?.matchingHandle = startButton startButton?.matchingHandle = button.leftHandle highlightedRange.end = fromTimeToIndex(button.leftHandle!) } } else if button.timeState == .Handle { highlightPathFrom(startButton, toButton: button.matchingHandle) startButton?.matchingHandle = button.matchingHandle button.matchingHandle?.matchingHandle = startButton highlightedRange.end = fromTimeToIndex(button.matchingHandle!) } } } // normal behavior except when merging if !isMerging { selectTime(button) highlightPathFrom(startButton, toButton: endButton) unhighlightOldPath(fromTimeToIndex(startButton!), endIndex: fromTimeToIndex(endButton!)) highlightedRange.end = fromTimeToIndex(button) } break } } } } } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { if touchBegan { if draggingInitiated == false && draggingOn == true { if let endButton = self.endButton { if endButton.timeState == .Handle { deselectHandleHelper(endButton) unselectTime(endButton) } else if endButton.timeState == .Single { unselectTime(endButton) } else if endButton.timeState == .Path { splitPath(from: endButton) unselectTime(endButton) } } } else { // set matching handles if endButton!.timeState != .Path { // necessary for when user lift finger mid-merging if startButton != endButton { self.startButton?.matchingHandle = endButton self.endButton?.matchingHandle = startButton } } } // when path is in middle of merge if endButton?.timeState == .Path { // revert to normal blue color endButton?.backgroundColor = blueColor } highlightedRange.start = 0 highlightedRange.end = 0 endButton = nil draggingInitiated = false self.startButton = nil isOnButton = false draggingOn = false touchBegan = false isMerging = false pathSplittable = false } } func deselectHandleHelper(handleButton: TimeButton) { let handleIndex = fromTimeToIndex(handleButton) let matchingIndex = fromTimeToIndex(handleButton.matchingHandle!) // check if handle is left or right handle if matchingIndex < handleIndex { // right handle if buttonsArray[handleIndex-1].timeState == .Handle { unjoinNeighboringHandles(buttonsArray[matchingIndex]) buttonsArray[handleIndex-1].timeState = .Single } else { buttonsArray[handleIndex-1].timeState = .Handle buttonsArray[handleIndex-1].matchingHandle = handleButton.matchingHandle handleButton.matchingHandle?.matchingHandle = buttonsArray[handleIndex-1] highlightPathFrom(buttonsArray[handleIndex-1], toButton: handleButton.matchingHandle) } } else if matchingIndex > handleIndex { // left handle if buttonsArray[handleIndex+1].timeState == .Handle { unjoinNeighboringHandles(buttonsArray[handleIndex]) buttonsArray[handleIndex+1].timeState = .Single } else { buttonsArray[handleIndex+1].timeState = .Handle buttonsArray[handleIndex+1].matchingHandle = handleButton.matchingHandle handleButton.matchingHandle?.matchingHandle = buttonsArray[handleIndex+1] highlightPathFrom(buttonsArray[handleIndex+1], toButton: handleButton.matchingHandle!) } } } func splitPath(from button: TimeButton) { let buttonIndex = fromTimeToIndex(button) // get left and right handles let leftHandle = button.leftHandle let rightHandle = button.rightHandle // update left side // check if left side is not just a single handle if buttonsArray[buttonIndex-1].timeState == .Handle { buttonsArray[buttonIndex-1].timeState = .Single } else { buttonsArray[buttonIndex-1].timeState = .Handle buttonsArray[buttonIndex-1].matchingHandle = leftHandle leftHandle?.matchingHandle = buttonsArray[buttonIndex-1] highlightPathFrom(buttonsArray[buttonIndex-1], toButton: leftHandle) } // update right side // check if right side is not a handle if buttonsArray[buttonIndex+1].timeState == .Handle { buttonsArray[buttonIndex+1].timeState = .Single } else { buttonsArray[buttonIndex+1].timeState = .Handle buttonsArray[buttonIndex+1].matchingHandle = rightHandle rightHandle?.matchingHandle = buttonsArray[buttonIndex+1] highlightPathFrom(buttonsArray[buttonIndex+1], toButton: rightHandle) } } func highlightPathFrom(startButton: TimeButton!, toButton endButton: TimeButton!) { let startIndex = fromTimeToIndex(startButton) let endIndex = fromTimeToIndex(endButton) // if the startButton is not the same as endButton if startIndex != endIndex { startButton.setTitleColor(buttonColor, forState: .Selected) endButton.setTitleColor(buttonColor, forState: .Selected) // Redesigning handles if endIndex > startIndex { // first check if startButton is at a right edge if contains(rightEdgeIndexes, startIndex) { startButton.setBackgroundImage(UIImage(named: "ButtonEdgeHandle"), forState: .Selected) } else { startButton.setBackgroundImage(UIImage(named: "ButtonHandleLeft"), forState: .Selected) } if !isMerging { // first check if endButton is at a left edge if contains(leftEdgeIndexes, endIndex) { endButton.setBackgroundImage(UIImage(named: "ButtonEdgeHandle"), forState: .Selected) } else { endButton.setBackgroundImage(UIImage(named: "ButtonHandleRight"), forState: .Selected) } } } else if endIndex < startIndex { // first check if startButton is at a left edge if contains(leftEdgeIndexes, startIndex) { startButton.setBackgroundImage(UIImage(named: "ButtonEdgeHandle"), forState: .Selected) } else { startButton.setBackgroundImage(UIImage(named: "ButtonHandleRight"), forState: .Selected) } if !isMerging { // first check if endButton is at a right edge if contains(rightEdgeIndexes, endIndex) { endButton.setBackgroundImage(UIImage(named: "ButtonEdgeHandle"), forState: .Selected) } else { endButton.setBackgroundImage(UIImage(named:"ButtonHandleLeft"), forState: .Selected) } } } } else { // startIndex == endIndex startButton.layer.borderColor = blueColor.CGColor startButton.layer.cornerRadius = 0.5 * startButton.frame.size.width startButton.backgroundColor = blueColor startButton.setBackgroundImage(nil, forState: .Selected) startButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected) } // Making paths if endIndex > startIndex { // Touch is after starting point for i in startIndex+1..<endIndex { turnToPath(buttonsArray[i], leftHandle: startButton, rightHandle: endButton) } } else if endIndex < startIndex { // Touch is behind starting point for i in endIndex+1..<startIndex { turnToPath(buttonsArray[i], leftHandle: endButton, rightHandle: startButton) } } // check neighboring handles if abs(startIndex-endIndex) == 1 { if rowFromIndex(startIndex) == rowFromIndex(endIndex) { if startIndex > endIndex { joinNeighboringHandles(endButton) } else if startIndex < endIndex { joinNeighboringHandles(startButton) } } } else { // clear up extra rectangles if startIndex != 0 { unjoinNeighboringHandles(buttonsArray[startIndex-1]) } unjoinNeighboringHandles(startButton) unjoinNeighboringHandles(endButton) } } func unhighlightOldPath(startIndex: Int, endIndex: Int) { // After startIndex, moving to after startIndex but lower index if highlightedRange.end > startIndex && endIndex > startIndex && endIndex < highlightedRange.end { for i in endIndex+1...highlightedRange.end { unselectTime(buttonsArray[i]) } } // Moving from after startIndex to somewhere before startIndex if highlightedRange.end > startIndex && endIndex < startIndex { for i in startIndex+1...highlightedRange.end { unselectTime(buttonsArray[i]) } } // Moving from before startIndex to somewhere before startIndex but higher index if highlightedRange.end < startIndex && endIndex < startIndex && endIndex > highlightedRange.end { for i in highlightedRange.end..<endIndex { unselectTime(buttonsArray[i]) } } // Move from before startIndex to somewhere after startIndex if highlightedRange.end < startIndex && endIndex > startIndex { for i in highlightedRange.end..<startIndex { unselectTime(buttonsArray[i]) } } // Move from somewhere directly to startbutton if startIndex == endIndex { if highlightedRange.end > startIndex { for i in startIndex+1...highlightedRange.end { unselectTime(buttonsArray[i]) } } else if highlightedRange.end < startIndex { for i in highlightedRange.end..<startIndex { unselectTime(buttonsArray[i]) } } } } func fromTimeToIndex(timeButton: TimeButton) -> Int { let time = timeButton.titleLabel!.text! var timeArray = time.componentsSeparatedByString(":") let hour = Int(timeArray[0].toInt()!) let minute = Int(timeArray[1].toInt()!) if minute != 0 { return hour*2 + 1 } else { return hour*2 } } func fromTimeToIndex(#time: String) -> Int { var timeArray = time.componentsSeparatedByString(":") let hour = Int(timeArray[0].toInt()!) let minute = Int(timeArray[1].toInt()!) if minute != 0 { return hour*2 + 1 } else { return hour*2 } } func numBetweenRange(num: Int, startRange: Int, endRange: Int) -> Bool { if startRange < endRange { return startRange+1..<endRange ~= num } else if startRange > endRange { return endRange+1..<startRange ~= num } else { return false } } func numBetweenRangeInclusive(num: Int, startRange: Int, endRange: Int) -> Bool { if startRange < endRange { return startRange...endRange ~= num } else if startRange > endRange { return endRange...startRange ~= num } else { return false } } func rowFromIndex(index: Int) -> Int { switch index { case 0...5: return 0 case 6...11: return 1 case 12...17: return 2 case 18...23: return 3 case 24...29: return 4 case 30...35: return 5 case 36...41: return 6 case 42...47: return 7 default: return -1 } } }
mit
efed9ca7d5ad0772ffecf70130ef445d
39.949721
212
0.530014
5.559348
false
false
false
false
eaheckert/Tournament
Tournament/Tournament/Model/Tournament.swift
1
2771
// // Tournament.swift // Tournament // // Created by Eugene Heckert on 8/5/15. // Copyright (c) 2015 Eugene Heckert. All rights reserved. // import Foundation import Parse //MARK: Tournament Class class Tournament: PFObject, PFSubclassing { //MARK: Parse Class Variables @NSManaged var createdBy:String @NSManaged var name:String @NSManaged var gameName:String @NSManaged var participantsCount:Int @NSManaged var maxNumberRounds:Int @NSManaged var tournamentMatchesDictAr:Array<AnyObject> @NSManaged var tournamentParticipantsDictAr:Array<AnyObject> //MARK: Model Only Variables var tournamentMatches:Array<Match> = [] var tournamentParticipants:Array<Participant> = [] //MARK: Class Methods //If you override a Parse class it will need this method to be register the class with Parse override class func initialize() { struct Static { static var onceToken : dispatch_once_t = 0; } dispatch_once(&Static.onceToken) { self.registerSubclass() } } static func parseClassName() -> String { return "Tournament" } //MARK: Methods func convertMatches() { // let matchAr = Match.parseMatchFromJson(self.tournamentMatchesDictAr) self.tournamentMatches = [] } func convertParticipants() { print(tournamentParticipantsDictAr, terminator: "") // var partAr: Array<Participant> = Participant.parseParticipantFromJson(self.tournamentParticipantsDictAr) self.tournamentParticipants = [] } func getParticipantById(partId:String!) -> Participant { for part: Participant in tournamentParticipants { if part.participantId == partId { return part } } return Participant() } func saveTournament() { for match: Match in tournamentMatches { for var i = 0; i < tournamentMatchesDictAr.count; i++ { let matchDict = tournamentMatchesDictAr[i] as! NSMutableDictionary if match.matchID == String(stringInterpolationSegment: matchDict["matchID"]!) { matchDict.setValue(match.playerOneID, forKey: "playerOneID") matchDict.setValue(match.playerTwoID, forKey: "playerTwoID") matchDict.setValue(match.winnerID, forKey: "winnerID") matchDict.setValue(match.loserID, forKey: "loserID") } } } self.save() } }
mit
c98353bea97698b697dc9baf9bd10111
25.390476
114
0.585348
4.887125
false
false
false
false
dsoisson/SwiftLearningExercises
Exercise9.playground/Resources/Exercise8_1.playground/Contents.swift
2
6591
import Foundation /*: **Exercise:** Create two classes `Dog` and `Cat`. Each will have properties of `breed`, `color`, `age` and `name`. They also have methods of `barking` (dog's) only, `meowing` (cats only), `eating`, `sleeping`, `playing`, and `chase`. */ /*: **Constraints:** You must also have: * Initializer & Deinitializer * Computed Properties * Property Observers * Method body is up to you, but your method signatures need parameter(s) */ enum DogFoes { case cat case squirrel case intruder } enum MeowReasons { case wantsFood case wantsOutside case wantsInside case wantsAttention } class Dog { var breed: String = "" var color: String = "" var name: String? = "" var birthday: NSDate? var alive: Bool = true var eating: Bool = false var sleeping: Bool = false var playing: Bool = false var barking: Bool = false var age: Int {//read only computed property using birthday and current date guard birthday != nil && alive else{ return 0 } return DateUtils.yearSpan(birthday!, to: NSDate()) } init(breed: String, color: String) { self.breed = breed self.color = color } var energy: Int = 100 { willSet { print("About to set energy to \(newValue)%") } didSet { print("You had \(oldValue)% energy, now you have \(energy)%") if energy <= 0 { print("Too tired. Time to rest.") } } } func bark(kind: DogFoes) -> (String, Bool) { barking = true switch kind { case .cat: return ("Bark, Bark, Bark", barking) case .squirrel: return ("arf", barking) case .intruder: return ("grrrr", barking) } } func eat(inout energy: Int) -> String { switch energy{ case 0..<25: energy = 100 return "Really hungry. Ate 4 cups of food." case 25..<75: energy = 100 return "Sort of hungry. Ate 2 cups of food." case 75..<100: energy = 100 return "Not very hungry but ate anyway." default: sleep() return "Feeling stuffed. Didn't eat." } } func sleep() -> String{ return "Very sleepy. Need to close eyes." } func play() -> (String, Int) { energy = 50 while energy > 10 { chase() energy -= 5 bark(DogFoes.cat) energy -= 10 } return ("I'm tired now", energy) } func chase() -> String{ return "I'm gonna get that cat!!" } deinit { print("no more dog") } } class Cat{ var breed: String = "" var color: String = "" var name: String? = "" var birthday: NSDate? var alive: Bool = true var eating: Bool = false var sleeping: Bool = false var playing: Bool = false var meowing: Bool = false var age: Int {//read only computed property using birthday and current date guard birthday != nil && alive else{ return 0 } return DateUtils.yearSpan(birthday!, to: NSDate()) } init(breed: String, color: String) { self.breed = breed self.color = color } var energy: Int = 100 { willSet { print("About to set energy to \(newValue)%") } didSet { print("You had \(oldValue)% energy, now you have \(energy)%") if energy <= 0 { print("Too tired. Time to rest.") } } } func meow(kind: MeowReasons) -> (String, Bool) { meowing = true switch kind { case .wantsAttention: return ("MEOW!", meowing) case .wantsFood: return ("meow", meowing) case .wantsInside: return ("Meow", meowing) case .wantsOutside: return ("meOWt", meowing) } } func eat(inout energy: Int) -> String { switch energy{ case 0..<25: energy = 100 return "Really hungry. Ate the entire can." case 25..<75: energy = 100 return "Sort of hungry. Ate half the can." case 75..<100: energy = 100 return "Not very hungry. Ate only one bite." default: sleep() return "Feeling stuffed. Didn't eat." } } func sleep() -> String{ return "Very sleepy. Need to close eyes." } func play() -> (String, Int) { energy = 50 while energy > 10 { chase() energy -= 5 } return ("I'm tired now", energy) } func chase() -> String{ return "I'm gonna get that dog!!" } deinit { print("no more cat") } } class Toy { var dogToy: Set = [ "Red Guy", "Rubber Ball", "Chew Bone", "String" ] var catToy: Set = [ "Rubber Ball", "Cat Nip", "String", "Mousy" ] } var activities = [ 1: "Sleeping", 2: "Playing", 3: "Eating", 4: "Chasing", 5: "Barking" ] var myCat = Cat(breed: "Hemmingway", color: "Gray") myCat.name = "Polly" print("My cat \(myCat.name!) has five toes.") myCat.energy = 90 var dogTwo = Dog(breed: "Dauchsund", color: "Gray") dogTwo.name = "Kaycee" var myDog = Dog(breed: "Dauchsund", color: "Black") myDog.birthday = DateUtils.createDate(year: 2008, month: 11, day: 18) myDog.name = "Frannie" print("I love my \(myDog.color) \(myDog.breed), \(myDog.name!). She is \(myDog.age) years old.") myDog.energy = 50 if myCat.energy < myDog.energy { myDog.chase() } else { myCat.chase() } myDog.play() print("Energy Level is \(myDog.energy)") myDog.eat(&myDog.energy) print("Energy Level is \(myDog.energy)") print(myDog.bark(DogFoes.cat).1) dogTwo.barking myDog.barking if dogTwo.barking { activities[5] } else { print("\(dogTwo.name!) is not barking.") } if myDog.barking { "Stop that incessant barking!" myDog.barking = false } if myDog.play().1 < 50 { var energyLevel = myDog.play().1 myDog.eat(&energyLevel) }
mit
7e5d72d1d61b0a6241fefeeb9627e534
20.399351
233
0.508269
3.941986
false
false
false
false
naokits/my-programming-marathon
TinderLikePageBasedApp/TinderLikePageBasedApp/Externals/AHPagingMenuViewController/AHPagingMenuViewController.swift
2
29832
// // AHPagingMenuViewController.swift // VERSION 1.0 - LICENSE MIT // // Menu Slider Page! Enjoy // Swift Version // // Created by André Henrique Silva on 01/04/15. // Bugs? Send -> [email protected] Thank you! // Copyright (c) 2015 André Henrique Silva. All rights reserved. http://andrehenrique.me =D // import UIKit import ObjectiveC @objc protocol AHPagingMenuDelegate { /** Change position number - parameter form: position initial - parameter to: position final */ optional func AHPagingMenuDidChangeMenuPosition(form: NSInteger, to: NSInteger); /** Change position obj - parameter form: obj initial - parameter to: obj final */ optional func AHPagingMenuDidChangeMenuFrom(form: AnyObject, to: AnyObject); } var AHPagingMenuViewControllerKey: UInt8 = 0 extension UIViewController { func setAHPagingController(menuViewController: AHPagingMenuViewController) { self.willChangeValueForKey("AHPagingMenuViewController") objc_setAssociatedObject(self, &AHPagingMenuViewControllerKey, menuViewController, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) self.didChangeValueForKey("AHPagingMenuViewController") } func pagingMenuViewController() -> AHPagingMenuViewController { let controller = objc_getAssociatedObject(self, &AHPagingMenuViewControllerKey) as! AHPagingMenuViewController; return controller; } } class AHPagingMenuViewController: UIViewController, UIScrollViewDelegate { //Privates internal var bounce: Bool! internal var fade: Bool! internal var transformScale: Bool! internal var showArrow: Bool! internal var changeFont: Bool! internal var changeColor: Bool! internal var currentPage: NSInteger! internal var selectedColor: UIColor! internal var dissectedColor: UIColor! internal var selectedFont: UIFont! internal var dissectedFont: UIFont! internal var scaleMax: CGFloat! internal var scaleMin: CGFloat! internal var viewControllers: NSMutableArray? internal var iconsMenu: NSMutableArray? internal var delegate: AHPagingMenuDelegate? internal var NAV_SPACE_VALUE: CGFloat = 15.0 internal var NAV_HEIGHT: CGFloat = 45.0 + (UIApplication.sharedApplication().statusBarFrame.size.height) internal var NAV_TITLE_SIZE: CGFloat = 30.0 //Publics private var navView: UIView? private var navLine: UIView? private var viewContainer: UIScrollView? private var arrowRight: UIImageView? private var arrowLeft: UIImageView? // MARK: inits required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); self.inicializeValues(NSArray(), iconsMenu: NSArray(), position: 0) } init(controllers:NSArray, icons: NSArray) { super.init(nibName: nil, bundle: nil); self.inicializeValues(controllers, iconsMenu: icons , position: 0) } init( controllers:(NSArray), icons: (NSArray), position:(NSInteger)) { super.init(nibName: nil, bundle: nil) self.inicializeValues(controllers, iconsMenu: icons, position: position) } // MARK: Cycle Life override func loadView() { super.loadView() self.view.backgroundColor = UIColor.whiteColor(); let viewConteiner = UIScrollView() viewConteiner.delegate = self viewConteiner.pagingEnabled = true viewConteiner.showsHorizontalScrollIndicator = false viewConteiner.showsVerticalScrollIndicator = false viewConteiner.contentSize = CGSizeMake(0,0) self.view.addSubview(viewConteiner) self.viewContainer = viewConteiner let navView = UIView() navView.backgroundColor = UIColor.whiteColor() navView.clipsToBounds = true self.view.addSubview(navView) self.navView = navView let arrowRight = UIImageView(image: UIImage(named:"arrowRight")) arrowRight.userInteractionEnabled = true arrowRight.addGestureRecognizer(UITapGestureRecognizer(target:self, action:Selector("goNextView"))) arrowRight.image = arrowRight.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.navView?.addSubview(arrowRight) self.arrowRight = arrowRight; let arrowLeft = UIImageView(image: UIImage(named:"arrowLeft")) arrowLeft.userInteractionEnabled = true arrowLeft.addGestureRecognizer(UITapGestureRecognizer(target:self, action:Selector("goPrevieusView"))) arrowLeft.image = arrowLeft.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.navView?.addSubview(arrowLeft) self.arrowLeft = arrowLeft let navLine = UIView() navLine.backgroundColor = UIColor(white: 0.8, alpha: 1.0) self.view.addSubview(navLine) self.navLine = navLine } override func viewDidLoad() { super.viewDidLoad() var count = 0 for controller in self.viewControllers! { self.includeControllerOnInterface(controller as! UIViewController, titleView: self.iconsMenu!.objectAtIndex(count) as! UIView, tag: count) count++ } self.viewContainer?.setContentOffset(CGPointMake(CGFloat(self.currentPage!) * self.viewContainer!.frame.size.width, self.viewContainer!.contentOffset.y), animated: false) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.resetNavBarConfig(); } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() NAV_HEIGHT = 45.0 + UIApplication.sharedApplication().statusBarFrame.size.height self.viewContainer?.frame = CGRectMake(0, NAV_HEIGHT, self.view.frame.size.width, self.view.frame.size.height - NAV_HEIGHT) self.viewContainer?.contentOffset = CGPointMake(CGFloat(self.currentPage) * self.viewContainer!.frame.size.width, self.viewContainer!.contentOffset.y) self.arrowLeft?.center = CGPointMake( NAV_SPACE_VALUE, self.navView!.center.y + (UIApplication.sharedApplication().statusBarFrame.size.height)/2.0) self.arrowRight?.center = CGPointMake( self.view.frame.size.width - NAV_SPACE_VALUE , self.navView!.center.y + (UIApplication.sharedApplication().statusBarFrame.size.height)/2.0) self.navView?.frame = CGRectMake( 0, 0, self.view.frame.size.width, NAV_HEIGHT) self.navLine?.frame = CGRectMake( 0.0, self.navView!.frame.size.height, self.navView!.frame.size.width, 1.0) var count = 0; for controller in self.viewControllers! as NSArray as! [UIViewController] { controller.view.frame = CGRectMake(self.view.frame.size.width * CGFloat(count), 0, self.view.frame.size.width, self.view.frame.size.height - NAV_HEIGHT) let titleView = self.iconsMenu?.objectAtIndex(count) as! UIView let affine = titleView.transform titleView.transform = CGAffineTransformMakeScale(1.0, 1.0) if(titleView.isKindOfClass(UIImageView)) { let icon = titleView as! UIImageView; titleView.frame = CGRectMake( 50.0 * CGFloat(count), 0, ( icon.image != nil ? (NAV_TITLE_SIZE * icon.image!.size.width) / icon.image!.size.height : NAV_TITLE_SIZE ) , NAV_TITLE_SIZE) } else if(titleView.isKindOfClass(UILabel)) { titleView.sizeToFit() } if(self.transformScale!) { titleView.transform = affine } let spacing = (self.view.frame.size.width/2.0) - self.NAV_SPACE_VALUE - titleView.frame.size.width/2.0 - CGFloat( self.showArrow! ? self.arrowLeft!.image!.size.width : 0.0) titleView.center = CGPointMake(self.navView!.center.x + (spacing * CGFloat(count)) - (CGFloat(self.currentPage) * spacing) , self.navView!.center.y + (UIApplication.sharedApplication().statusBarFrame.size.height)/2.0) count++ } self.viewContainer?.contentSize = CGSizeMake(self.view.frame.size.width * CGFloat(count), self.view.frame.size.height - NAV_HEIGHT) } override func shouldAutorotate() -> Bool { return true; } // MARK: Methods Public internal func addNewController(controller:UIViewController, title: AnyObject) { self.viewControllers?.addObject(controller); if title.isKindOfClass(NSString) { let label = UILabel() label.text = title as? String; self.iconsMenu?.addObject(label); self.includeControllerOnInterface(controller, titleView: label, tag: self.iconsMenu!.count - 1) } else if title.isKindOfClass(UIImage) { let image = UIImageView(image: title as? UIImage) image.image = image.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) image.contentMode = UIViewContentMode.ScaleAspectFill self.iconsMenu!.addObject(image) self.includeControllerOnInterface(controller, titleView: image, tag: self.iconsMenu!.count - 1) } else { NSException(name:"ClassRequeredNotFoundException", reason:"Not Allowed Class. NSString or UIImage Please!", userInfo:nil).raise() } self.viewDidLayoutSubviews() self.resetNavBarConfig(); } internal func setPosition(position: NSInteger, animated:Bool) { self.currentPage = position self.viewContainer?.setContentOffset(CGPointMake( CGFloat(self.currentPage!) * self.viewContainer!.frame.size.width, self.viewContainer!.contentOffset.y), animated: animated) } internal func goNextView() { if self.currentPage! < self.viewControllers!.count { self.setPosition(self.currentPage! + 1, animated: true) } } internal func goPrevieusView() { if self.currentPage > 0 { self.setPosition(self.currentPage! - 1, animated: true) } } internal func resetNavBarConfig() { var count = 0; for titleView in self.iconsMenu! as NSArray as! [UIView] { if(titleView.isKindOfClass(UIImageView)) { titleView.tintColor = self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor } else { if( titleView.isKindOfClass(UILabel)) { let titleText = titleView as! UILabel titleText.textColor = self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor titleText.font = self.changeFont! ? ( count == self.currentPage ? self.selectedFont : self.dissectedFont ) : self.selectedFont } } let transform = (self.transformScale! ? ( count == self.currentPage ? self.scaleMax: self.scaleMin): self.scaleMax) titleView.transform = CGAffineTransformMakeScale(transform!, transform!) count++ } self.arrowLeft!.alpha = (self.showArrow! ? (self.currentPage == 0 ? 0.0 : 1.0) :0.0); self.arrowRight!.alpha = (self.showArrow! ? (self.currentPage == self.viewControllers!.count - 1 ? 0.0 : 1.0) :0.0); self.arrowRight!.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor) self.arrowLeft!.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor) } // MARK: Methods Private private func inicializeValues(viewControllers: NSArray!, iconsMenu: NSArray!, position: NSInteger!) { let elementsController = NSMutableArray(); for controller in viewControllers { if controller.isKindOfClass(UIViewController) { let controller_element = controller as! UIViewController controller_element.setAHPagingController(self) elementsController.addObject(controller) } else { NSException(name:"ClassRequeredNotFoundException", reason:"Not Allowed Class. Controller Please", userInfo:nil).raise() } } let iconsController = NSMutableArray(); for icon in iconsMenu { if icon.isKindOfClass(NSString) { let label = UILabel() label.text = icon as? String iconsController.addObject(label) } else if(icon.isKindOfClass(UIImage)) { let imageView = UIImageView(image: icon as? UIImage) imageView.image = imageView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) imageView.contentMode = UIViewContentMode.ScaleAspectFill iconsController.addObject(imageView) } else { NSException(name:"ClassRequeredNotFoundException", reason:"Not Allowed Class. NSString or UIImage Please!", userInfo:nil).raise() } } if(iconsController.count != elementsController.count) { NSException(name:"TitleAndControllersException", reason:"Title and controllers not match", userInfo:nil).raise() } self.bounce = true self.fade = true self.showArrow = true self.transformScale = false self.changeFont = true self.changeColor = true self.selectedColor = UIColor.blackColor() self.dissectedColor = UIColor(red: 0.0 , green: 122.0/255.0, blue: 1.0, alpha: 1.0) self.selectedFont = UIFont(name: "HelveticaNeue-Medium", size: 16)! self.dissectedFont = UIFont(name: "HelveticaNeue", size: 16)! self.currentPage = position self.viewControllers = elementsController self.iconsMenu = iconsController self.scaleMax = 1.0 self.scaleMin = 0.9 } private func includeControllerOnInterface(controller: UIViewController, titleView:UIView, tag:(NSInteger)) { controller.view.clipsToBounds = true; controller.view.frame = CGRectMake(self.viewContainer!.contentSize.width, 0.0, self.view.frame.size.width, self.view.frame.size.height - NAV_HEIGHT) self.viewContainer?.contentSize = CGSizeMake(self.view.frame.size.width + self.viewContainer!.contentSize.width, self.view.frame.size.height - NAV_HEIGHT) self.addChildViewController(controller) controller.didMoveToParentViewController(self) self.viewContainer?.addSubview(controller.view) let tap = UITapGestureRecognizer(target:self, action:Selector("tapOnButton:")) titleView.addGestureRecognizer(tap) titleView.userInteractionEnabled = true; titleView.tag = tag self.navView?.addSubview(titleView); } func tapOnButton(sender: UITapGestureRecognizer) { if sender.view!.tag != self.currentPage { var frame = self.viewContainer!.frame frame.origin.y = 0; frame.origin.x = frame.size.width * CGFloat(sender.view!.tag) self.viewContainer?.scrollRectToVisible(frame, animated:true) } } private func changeColorFrom(fromColor: (UIColor), toColor: UIColor, porcent:(CGFloat)) ->UIColor { var redStart: CGFloat = 0 var greenStart : CGFloat = 0 var blueStart: CGFloat = 0 var alphaStart : CGFloat = 0 fromColor.getRed(&redStart, green: &greenStart, blue: &blueStart, alpha: &alphaStart) var redFinish: CGFloat = 0 var greenFinish: CGFloat = 0 var blueFinish: CGFloat = 0 var alphaFinish: CGFloat = 0 toColor.getRed(&redFinish, green: &greenFinish, blue: &blueFinish, alpha: &alphaFinish) return UIColor(red: (redStart - ((redStart-redFinish) * porcent)) , green: (greenStart - ((greenStart-greenFinish) * porcent)) , blue: (blueStart - ((blueStart-blueFinish) * porcent)) , alpha: (alphaStart - ((alphaStart-alphaFinish) * porcent))); } // MARK: Setters internal func setBounce(bounce: Bool) { self.viewContainer?.bounces = bounce; self.bounce = bounce; } internal func setFade(fade: Bool) { self.fade = fade; } internal func setTransformScale(transformScale: Bool) { self.transformScale = transformScale if (self.isViewLoaded() && self.view.window != nil) { var count = 0 for titleView in self.iconsMenu! as NSArray as! [UIView] { let transform = (self.transformScale! ? ( count == self.currentPage ? self.scaleMax: self.scaleMin): self.scaleMax); titleView.transform = CGAffineTransformMakeScale(transform, transform) count++ } } } internal func setShowArrow(showArrow: Bool) { self.showArrow = showArrow; if (self.isViewLoaded() && self.view.window != nil) { UIView .animateWithDuration(0.3, animations: { () -> Void in self.arrowLeft?.alpha = (self.showArrow! ? (self.currentPage == 0 ? 0.0 : 1.0) : 0.0) self.arrowRight?.alpha = (self.showArrow! ? (self.currentPage == self.viewControllers!.count - 1 ? 0.0 : 1.0) :0.0) self.viewDidLayoutSubviews() }) } } internal func setChangeFont(changeFont:Bool) { self.changeFont = changeFont if (self.isViewLoaded() && self.view.window != nil) { var count = 0 for titleView in self.iconsMenu! as NSArray as! [UIView] { if titleView.isKindOfClass(UILabel) { let title = titleView as! UILabel title.font = self.changeFont! ? ( count == self.currentPage ? self.selectedFont : self.dissectedFont ) : self.selectedFont titleView.sizeToFit() } count++ } } } internal func setChangeColor(changeColor: Bool) { self.changeColor = changeColor; if (self.isViewLoaded() && self.view.window != nil) { var count = 0 for titleView in self.iconsMenu! as NSArray as! [UIView] { if titleView.isKindOfClass(UIImageView) { titleView.tintColor = self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor } else if titleView.isKindOfClass(UILabel) { let title = titleView as! UILabel title.textColor = (self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor) } count++ } self.arrowLeft?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor); self.arrowRight?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor); } } internal func setSelectColor(selectedColor: UIColor) { self.selectedColor = selectedColor if (self.isViewLoaded() && self.view.window != nil) { var count = 0 for titleView in self.iconsMenu! as NSArray as! [UIView] { if titleView.isKindOfClass(UIImageView) { titleView.tintColor = self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor } else if titleView.isKindOfClass(UILabel) { let title = titleView as! UILabel title.textColor = (self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor) } count++ } self.arrowLeft?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor); self.arrowRight?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor); } } internal func setDissectColor(dissectedColor: UIColor) { self.dissectedColor = dissectedColor if (self.isViewLoaded() && self.view.window != nil) { var count = 0 for titleView in self.iconsMenu! as NSArray as! [UIView] { if titleView.isKindOfClass(UIImageView) { titleView.tintColor = self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor } else if titleView.isKindOfClass(UILabel) { let title = titleView as! UILabel title.textColor = (self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor) } count++ } self.arrowLeft?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor); self.arrowRight?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor); } } internal func setSelectFont(selectedFont: UIFont) { self.selectedFont = selectedFont if (self.isViewLoaded() && self.view.window != nil) { var count = 0 for titleView in self.iconsMenu! as NSArray as! [UIView] { if titleView.isKindOfClass(UILabel) { let title = titleView as! UILabel title.font = self.changeFont! ? ( count == self.currentPage ? self.selectedFont : self.dissectedFont ) : self.selectedFont titleView.sizeToFit() } count++ } } } internal func setDissectFont(dissectedFont: UIFont) { self.dissectedFont = selectedFont if (self.isViewLoaded() && self.view.window != nil) { var count = 0 for titleView in self.iconsMenu! as NSArray as! [UIView] { if titleView.isKindOfClass(UILabel) { let title = titleView as! UILabel title.font = self.changeFont! ? ( count == self.currentPage ? self.selectedFont : self.dissectedFont ) : self.selectedFont titleView.sizeToFit() } count++ } } } internal func setContentBackgroundColor(backgroundColor: UIColor) { self.viewContainer?.backgroundColor = backgroundColor } internal func setNavBackgroundColor(backgroundColor: UIColor) { self.navView?.backgroundColor = backgroundColor } internal func setNavLineBackgroundColor(backgroundColor: UIColor) { self.navLine?.backgroundColor = backgroundColor } internal func setScaleMax(scaleMax: CGFloat, scaleMin:CGFloat) { if scaleMax < scaleMin || scaleMin < 0.0 || scaleMax < 0.0 { return; } self.scaleMax = scaleMax; self.scaleMin = scaleMin; if (self.isViewLoaded() && self.transformScale == true && self.view.window != nil) { var count = 0 for titleView in self.iconsMenu! as NSArray as! [UIView] { let transform = (self.transformScale! ? ( count == self.currentPage ? self.scaleMax: self.scaleMin): self.scaleMax); titleView.transform = CGAffineTransformMakeScale(transform,transform) if titleView.isKindOfClass(UILabel) { titleView.sizeToFit() } count++ } } } // MARK: UIScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView) { if scrollView == self.viewContainer { let xPosition = scrollView.contentOffset.x; let fractionalPage = Float(xPosition / scrollView.frame.size.width); let currentPage = Int(round(fractionalPage)); if fractionalPage == Float(currentPage) && currentPage != self.currentPage { self.delegate?.AHPagingMenuDidChangeMenuPosition?(self.currentPage, to: currentPage) self.delegate?.AHPagingMenuDidChangeMenuFrom?(self.viewControllers!.objectAtIndex(self.currentPage), to: self.viewControllers!.objectAtIndex(currentPage)) self.currentPage = currentPage; } let porcent = fabs(fractionalPage - Float(currentPage))/0.5; if self.showArrow! { if currentPage <= 0 { self.arrowLeft?.alpha = 0; self.arrowRight?.alpha = 1.0 - CGFloat(porcent); } else if currentPage >= self.iconsMenu!.count - 1 { self.arrowLeft?.alpha = 1.0 - CGFloat(porcent); self.arrowRight?.alpha = 0.0; } else { self.arrowLeft?.alpha = 1.0 - CGFloat(porcent); self.arrowRight?.alpha = 1.0 - CGFloat(porcent); } } else { self.arrowLeft?.alpha = 0; self.arrowRight?.alpha = 0; } var count = 0; for titleView in self.iconsMenu! as NSArray as! [UIView] { titleView.alpha = CGFloat (( self.fade! ? (count <= (currentPage + 1) && count >= (currentPage - 1) ? 1.3 - porcent : 0.0 ) : (count <= self.currentPage + 1 || count >= self.currentPage - 1 ? 1.0: 0.0))) let spacing = (self.view.frame.size.width/2.0) - self.NAV_SPACE_VALUE - titleView.frame.size.width/2 - (self.showArrow! ? self.arrowLeft!.image!.size.width : 0.0) titleView.center = CGPointMake(self.navView!.center.x + (spacing * CGFloat(count)) - (CGFloat(fractionalPage) * spacing), self.navView!.center.y + (UIApplication.sharedApplication().statusBarFrame.size.height/2.0)) let distance_center = CGFloat(fabs(titleView.center.x - self.navView!.center.x)) if titleView.isKindOfClass(UIImageView) { if( distance_center < spacing) { if self.changeColor! { titleView.tintColor = self.changeColorFrom(self.selectedColor, toColor: self.dissectedColor, porcent: distance_center/spacing) } } } else if titleView.isKindOfClass(UILabel) { let titleText = titleView as! UILabel; if( distance_center < spacing) { if self.changeColor! { titleText.textColor = self.changeColorFrom(self.selectedColor, toColor: self.dissectedColor, porcent: distance_center/spacing) } if self.changeFont! { titleText.font = (distance_center < spacing/2.0 ? self.selectedFont : self.dissectedFont) titleText.sizeToFit() } } } if (self.transformScale! && count <= (currentPage + 1) && count >= (currentPage - 1)) { let transform = CGFloat(self.scaleMax! + ((self.scaleMax! - self.scaleMin!) * (-distance_center/spacing))) titleView.transform = CGAffineTransformMakeScale(transform, transform); } count++; } } } }
mit
a3ae7d4c4b0e88131d9630f24258681c
38.353562
254
0.571271
4.955973
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Event/NotUse/BFEventCommitView.swift
1
1775
// // BFEventCommitView.swift // BeeFun // // Created by WengHengcong on 23/09/2017. // Copyright © 2017 JungleSong. All rights reserved. // import UIKit import YYText /* user pushed to repos ╭┈┈┈╮ | | 76027aa Merge pull request #489 from ahstro/patch-1 ╰┈┈┈╯ 说明: ╭┈┈┈╮ | | 76027aa Merge pull request #489 from ahstro/patch-1 ╰┈┈┈╯ user avatar commit hash commit conent */ // 以上由于头像图不好拿,故略去 class BFEventCommitView: UIView { //数据 var cell: BFEventCell? var layout: BFEventLayout? var commitLabel: YYLabel = YYLabel() override init(frame: CGRect) { var newFrame = frame if frame.size.width == 0 && frame.size.height == 0 { newFrame.size.width = BFEventConstants.PRDETAIL_W newFrame.size.height = 1 } super.init(frame: newFrame) isUserInteractionEnabled = true commitLabel.size = CGSize(width: self.width, height: self.height) // commitLabel.backgroundColor = UIColor.hex("#eaf5ff") commitLabel.numberOfLines = 1 commitLabel.displaysAsynchronously = true commitLabel.ignoreCommonProperties = true commitLabel.fadeOnAsynchronouslyDisplay = false commitLabel.fadeOnHighlight = false self.addSubview(commitLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setLayout(layout: BFEventLayout) { self.layout = layout // commitLabel.layer.contents = nil commitLabel.height = self.layout!.commitHeight commitLabel.textLayout = self.layout?.commitLayout } }
mit
cd7bef190b7a025f4ea6493ff6631673
25.5
79
0.631486
3.837104
false
false
false
false
hstdt/GodEye
Carthage/Checkouts/SwViewCapture/SwViewCapture/UIView+SwCapture.swift
1
2391
// // UIView+SwCapture.swift // SwViewCapture // // Created by chenxing.cx on 16/2/17. // Copyright © 2016年 Startry. All rights reserved. // import UIKit import WebKit import ObjectiveC private var SwViewCaptureKey_IsCapturing: String = "SwViewCapture_AssoKey_isCapturing" public extension UIView { public func swSetFrame(_ frame: CGRect) { // Do nothing, use for swizzling } var isCapturing:Bool! { get { let num = objc_getAssociatedObject(self, &SwViewCaptureKey_IsCapturing) if num == nil { return false } if let numObj = num as? NSNumber { return numObj.boolValue }else { return false } } set(newValue) { let num = NSNumber(value: newValue as Bool) objc_setAssociatedObject(self, &SwViewCaptureKey_IsCapturing, num, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // Ref: chromium source - snapshot_manager, fix wkwebview screenshot bug. // https://chromium.googlesource.com/chromium/src.git/+/46.0.2478.0/ios/chrome/browser/snapshots/snapshot_manager.mm public func swContainsWKWebView() -> Bool { if self.isKind(of: WKWebView.self) { return true } for subView in self.subviews { if (subView.swContainsWKWebView()) { return true } } return false } public func swCapture(_ completionHandler: (_ capturedImage: UIImage?) -> Void) { self.isCapturing = true let bounds = self.bounds UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale) let context = UIGraphicsGetCurrentContext() context?.saveGState() context?.translateBy(x: -self.frame.origin.x, y: -self.frame.origin.y); if (swContainsWKWebView()) { self.drawHierarchy(in: bounds, afterScreenUpdates: true) }else{ self.layer.render(in: context!) } let capturedImage = UIGraphicsGetImageFromCurrentImageContext() context?.restoreGState(); UIGraphicsEndImageContext() self.isCapturing = false completionHandler(capturedImage) } }
mit
8a6494c6ed72707cf3718f5611600d74
28.481481
136
0.59129
4.682353
false
false
false
false
XLabKC/Badger
Badger/Badger/AppDelegate.swift
1
8134
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GPPSignInDelegate { var window: UIWindow? var notificationManager = NotificationManager() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { UINavigationBar.appearance().backgroundColor = UIColor.whiteColor() UINavigationBar.appearance().barStyle = UIBarStyle.Default UINavigationBar.appearance().translucent = false UINavigationBar.appearance().tintColor = Color.colorize(0x929292, alpha: 1.0) // Set the font of all bar buttons to be Open Sans. var attributes: [NSObject: AnyObject] = [:] attributes[NSFontAttributeName] = UIFont(name: "OpenSans", size: 17.0) UIBarButtonItem.appearance().setTitleTextAttributes(attributes, forState: .Normal) // Start listening for user store events. UserStore.sharedInstance().unauthorizedBlock = self.loggedOut UserStore.sharedInstance().initialize() // Setup Google auth object. var signIn = GPPSignIn.sharedInstance() signIn.shouldFetchGooglePlusUser = true signIn.shouldFetchGoogleUserEmail = true signIn.clientID = ApiKeys.getGoogleClientId() signIn.scopes = [] signIn.attemptSSO = true if Firebase(url: Global.FirebaseUrl).authData == nil { self.navigateToLogin() } else { self.navigateToFirstView(launchOptions) } return true } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { // Convert NSData into a hex string. var bytes = [UInt8](count: deviceToken.length, repeatedValue: 0x0) deviceToken.getBytes(&bytes, length:deviceToken.length) var hexBits = "" as String for value in bytes { hexBits += NSString(format: "%2X", value) as String } let hexDeviceToken = hexBits.stringByReplacingOccurrencesOfString("\u{0020}", withString: "0", options: NSStringCompareOptions.CaseInsensitiveSearch) // Save device token. let device = [ "platform": "ios", "token": hexDeviceToken ] let ref = Firebase(url: Global.FirebaseUsersUrl) ref.childByAppendingPath(ref.authData.uid).childByAppendingPath("device").setValue(device) } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { println("Failed to register for remote notifications") } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { return GPPURLHandler.handleURL(url, sourceApplication: sourceApplication, annotation: annotation); } 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 application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { if application.applicationState == .Active { // Application was already in foreground. self.notificationManager.notify(userInfo) } else { // Application was in the background. if let revealVC = RevealManager.sharedInstance().revealVC { if let vc = NotificationManager.createViewControllerFromNotification(userInfo) { revealVC.setFrontViewController(vc, animated: true) } } } } private func loggedOut() { var signIn = GPPSignIn.sharedInstance() signIn.delegate = self if signIn.trySilentAuthentication() { // Google silent authentication is working so no need to redirect to login. return } let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as! UIViewController RevealManager.sharedInstance().removeRevealVC() self.window?.rootViewController?.presentViewController(vc, animated: true, completion: nil) } func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!) { if error != nil { println("Google auth error when trying to reauthenticate.") println("Google auth error \(error) and auth object \(auth)") } else { let ref = Firebase(url: Global.FirebaseUrl) ref.authWithOAuthProvider("google", token: auth.accessToken) { error, authData in if error != nil { println("Firebase auth error \(error) and auth object \(authData)") } } } } private func navigateToLogin() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as! UIViewController self.navigateToViewController(vc, animated: true) } private func navigateToFirstView(launchOptions: [NSObject: AnyObject]?) { if let options = launchOptions { if let note = options[UIApplicationLaunchOptionsRemoteNotificationKey] as? [NSObject : AnyObject] { if let vc = NotificationManager.createViewControllerFromNotification(note) { UserStore.sharedInstance().waitForUser({ _ in let reveal = RevealManager.sharedInstance().initialize(vc) self.navigateToViewController(reveal, animated: true) }) return } } } UserStore.sharedInstance().waitForUser({ _ in let vc = RevealManager.sharedInstance().initialize() self.navigateToViewController(vc, animated: true) }) } private func navigateToViewController(viewController: UIViewController, animated: Bool) { if let root = self.window?.rootViewController { if root.isViewLoaded() { var cur = root while cur.presentedViewController != nil { cur = cur.presentedViewController! } cur.presentViewController(viewController, animated: animated, completion: nil) return } } self.window?.rootViewController = viewController } }
gpl-2.0
a7cf5cbdd2ea6a60008b0c0a75a0c63b
45.215909
285
0.665232
5.740296
false
false
false
false
MadAppGang/SmartLog
iOS/Pods/Dip/Sources/Resolve_swift2.swift
3
5712
// // Dip // // Copyright (c) 2015 Olivier Halligon <[email protected]> // // 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. // #if !swift(>=3.0) extension DependencyContainer { /** Resolve an instance of type `T`. If no matching definition was registered with provided `tag`, container will lookup definition associated with `nil` tag. - parameter tag: The arbitrary tag to use to lookup definition. - throws: `DipError.DefinitionNotFound`, `DipError.AutoInjectionFailed`, `DipError.AmbiguousDefinitions`, `DipError.InvalidType` - returns: An instance of type `T`. **Example**: ```swift let service = try! container.resolve() as Service let service = try! container.resolve(tag: "service") as Service let service: Service = try! container.resolve() ``` - seealso: `register(_:type:tag:factory:)` */ public func resolve<T>(tag tag: DependencyTagConvertible? = nil) throws -> T { return try resolve(tag: tag) { factory in try factory() } } /** Resolve an instance of requested type. Weakly-typed alternative of `resolve(tag:)` - warning: This method does not make any type checks, so there is no guaranty that resulting instance is actually an instance of requested type. That can happen if you register forwarded type that is not implemented by resolved instance. - parameters: - type: Type to resolve - tag: The arbitrary tag to use to lookup definition. - throws: `DipError.DefinitionNotFound`, `DipError.AutoInjectionFailed`, `DipError.AmbiguousDefinitions`, `DipError.InvalidType` - returns: An instance of requested type. **Example**: ```swift let service = try! container.resolve(Service.self) as! Service let service = try! container.resolve(Service.self, tag: "service") as! Service ``` - seealso: `resolve(tag:)`, `register(_:type:tag:factory:)` */ public func resolve(type: Any.Type, tag: DependencyTagConvertible? = nil) throws -> Any { return try resolve(type, tag: tag) { factory in try factory() } } /** Resolve an instance of type `T` using generic builder closure that accepts generic factory and returns created instance. - parameters: - tag: The arbitrary tag to use to lookup definition. - builder: Generic closure that accepts generic factory and returns inctance created by that factory. - throws: `DipError.DefinitionNotFound`, `DipError.AutoInjectionFailed`, `DipError.AmbiguousDefinitions`, `DipError.InvalidType` - returns: An instance of type `T`. - note: You _should not_ call this method directly, instead call any of other `resolve(tag:)` or `resolve(tag:withArguments:)` methods. You _should_ use this method only to resolve dependency with more runtime arguments than _Dip_ supports (currently it's up to six) like in the following example: ```swift public func resolve<T, A, B, C, ...>(tag: Tag? = nil, _ arg1: A, _ arg2: B, _ arg3: C, ...) throws -> T { return try resolve(tag: tag) { factory in factory(arg1, arg2, arg3, ...) } } ``` Though before you do so you should probably review your design and try to reduce the number of dependencies. */ public func resolve<T, U>(tag tag: DependencyTagConvertible? = nil, builder: ((U) throws -> T) throws -> T) throws -> T { return try _resolve(tag: tag, builder: builder) } /** Resolve an instance of provided type using builder closure. Weakly-typed alternative of `resolve(tag:builder:)` - seealso: `resolve(tag:builder:)` */ public func resolve<U>(type: Any.Type, tag: DependencyTagConvertible? = nil, builder: ((U) throws -> Any) throws -> Any) throws -> Any { return try _resolve(type: type, tag: tag, builder: builder) } } /// Resolvable protocol provides some extension points for resolving dependencies with property injection. public protocol Resolvable { /// This method will be called right after instance is created by the container. func resolveDependencies(container: DependencyContainer) /// This method will be called when all dependencies of the instance are resolved. /// When resolving objects graph the last resolved instance will receive this callback first. func didResolveDependencies() } extension Resolvable { func resolveDependencies(container: DependencyContainer) {} func didResolveDependencies() {} } #endif
mit
d089d88ec91c8641f45ad02768dcb7a4
41.311111
140
0.677521
4.522565
false
false
false
false
qutheory/vapor
Sources/Vapor/Utilities/URI.swift
1
6308
import CURLParser public struct URI: ExpressibleByStringInterpolation, CustomStringConvertible { /// A URI's scheme. public struct Scheme: ExpressibleByStringInterpolation { /// HTTP public static let http: Self = "http" /// HTTPS public static let https: Self = "https" /// HTTP over Unix Domain Socket Paths. The socket path should be encoded as the host in the URI, making sure to encode any special characters: /// ``` /// host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) /// ``` /// Do note that URI's initializer will encode the host in this way if you use `init(scheme:host:port:path:query:fragment:)`. public static let httpUnixDomainSocket: Self = "http+unix" /// HTTPS over Unix Domain Socket Paths. The socket path should be encoded as the host in the URI, making sure to encode any special characters: /// ``` /// host.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) /// ``` /// Do note that URI's initializer will encode the host in this way if you use `init(scheme:host:port:path:query:fragment:)`. public static let httpsUnixDomainSocket: Self = "https+unix" public let value: String? public init(stringLiteral value: String) { self.value = value } public init(_ value: String? = nil) { self.value = value } } public var string: String public init(string: String = "/") { self.string = string } public var description: String { return self.string } public init( scheme: String?, host: String? = nil, port: Int? = nil, path: String, query: String? = nil, fragment: String? = nil ) { self.init( scheme: Scheme(scheme), host: host, port: port, path: path, query: query, fragment: fragment ) } public init( scheme: Scheme = Scheme(), host: String? = nil, port: Int? = nil, path: String, query: String? = nil, fragment: String? = nil ) { var string = "" if let scheme = scheme.value { string += scheme + "://" } if let host = host?.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) { string += host } if let port = port { string += ":" + port.description } if path.hasPrefix("/") { string += path } else { string += "/" + path } if let query = query { string += "?" + query } if let fragment = fragment { string += "#" + fragment } self.string = string } public init(stringLiteral value: String) { self.init(string: value) } private enum Component { case scheme, host, port, path, query, fragment, userinfo } public var scheme: String? { get { return self.parse(.scheme) } set { self = .init( scheme: newValue, host: self.host, port: self.port, path: self.path, query: self.query, fragment: self.fragment ) } } public var host: String? { get { return self.parse(.host) } set { self = .init( scheme: self.scheme, host: newValue, port: self.port, path: self.path, query: self.query, fragment: self.fragment ) } } public var port: Int? { get { return self.parse(.port).flatMap(Int.init) } set { self = .init( scheme: self.scheme, host: self.host, port: newValue, path: self.path, query: self.query, fragment: self.fragment ) } } public var path: String { get { return self.parse(.path) ?? "" } set { self = .init( scheme: self.scheme, host: self.host, port: self.port, path: newValue, query: self.query, fragment: self.fragment ) } } public var query: String? { get { return self.parse(.query) } set { self = .init( scheme: self.scheme, host: self.host, port: self.port, path: self.path, query: newValue, fragment: self.fragment ) } } public var fragment: String? { get { return self.parse(.fragment) } set { self = .init( scheme: self.scheme, host: self.host, port: self.port, path: self.path, query: self.query, fragment: newValue ) } } private func parse(_ component: Component) -> String? { var url = urlparser_url() urlparser_parse(self.string, self.string.count, 0, &url) let data: urlparser_field_data switch component { case .scheme: data = url.field_data.0 case .host: data = url.field_data.1 case .port: data = url.field_data.2 case .path: data = url.field_data.3 case .query: data = url.field_data.4 case .fragment: data = url.field_data.5 case .userinfo: data = url.field_data.6 } if data.len == 0 { return nil } let start = self.string.index(self.string.startIndex, offsetBy: numericCast(data.off)) let end = self.string.index(start, offsetBy: numericCast(data.len)) return String(self.string[start..<end]) } }
mit
c76c6b6c66b206ddc1464bfdd5727feb
26.666667
152
0.480818
4.75
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
ResearchUXFactory/String+Utilities.swift
1
5069
// // String+Utilities.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation public struct HtmlRange { let open: Range<String.Index> let close: Range<String.Index> } extension String { public func trim() -> String? { let result = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) guard result != "" else { return nil } return result } public func parseSuffix(prefix: String, separator: String = "") -> String? { guard self.hasPrefix(prefix) else { return nil } let prefixWithSeparator = prefix + separator guard let range = self.range(of: prefixWithSeparator) else { return "" } return self.substring(from: range.upperBound) } public func removingNewlineCharacters() -> String { let set = CharacterSet.newlines // Since there can be two newline characters in a row, but we only want to replace that with a single // space, use the custom reduce to strip out the new line characters and replace with a single space. let result = (self as NSString).components(separatedBy: set).reduce("") { (input, next) -> String in guard let nextTrimmed = next.trim() else { return input } guard input != "" else { return nextTrimmed } return input + " " + nextTrimmed } return result.replacingBreaklineHtmlTags() } public func replacingBreaklineHtmlTags() -> String { guard let trimmedString = trim() else { return "" } guard let range = trimmedString.htmlSearch(tag: "br", start: nil) else { return trimmedString } var result = trimmedString.substring(to: range.open.lowerBound) if range.open.upperBound < trimmedString.endIndex { result.append("\n") let remaining = trimmedString.substring(from: range.open.upperBound) result.append(remaining.replacingBreaklineHtmlTags()) } return result } public func search(_ str: String, range: Range<String.Index>?) -> Range<String.Index>? { return self.range(of: str, options: .caseInsensitive, range: range, locale: nil) } public func htmlSearch(tag: String, start: String.Index?) -> HtmlRange? { guard (start == nil) || (start! < self.endIndex) else { return nil } // Find the next tag open let startRange: Range<String.Index>? = (start != nil) ? start!..<self.endIndex : nil guard let startOpenRange = search("<\(tag)", range: startRange), let endOpenRange = search(">", range: startOpenRange.upperBound..<self.endIndex) else { return nil } // If the end range is the same for the first open and the first end close // then they are the same. let openRange = startOpenRange.lowerBound..<endOpenRange.upperBound if let _ = search("/>", range: openRange) { return HtmlRange(open: openRange, close: openRange) } guard let startCloseRange = search("<\(tag)", range:openRange.upperBound..<self.endIndex), let endCloseRange = search("/>", range: startCloseRange.upperBound..<self.endIndex) else { return nil } return HtmlRange(open: openRange, close: startCloseRange.lowerBound..<endCloseRange.upperBound) } }
bsd-3-clause
f8ac94787ae1dd7231dce8c460e8f751
44.657658
110
0.676204
4.670968
false
false
false
false
josipbernat/Hasher
Pods/CryptoSwift/Sources/CryptoSwift/StreamDecryptor.swift
3
3278
// CryptoSwift // // Copyright (C) 2014-2018 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // final class StreamDecryptor: Cryptor, Updatable { private let blockSize: Int private var worker: CipherModeWorker private let padding: Padding private var accumulated = Array<UInt8>() private var lastBlockRemainder = 0 init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws { self.blockSize = blockSize self.padding = padding self.worker = worker } // MARK: Updatable public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> { accumulated += bytes let toProcess = accumulated.prefix(max(accumulated.count - worker.additionalBufferSize, 0)) if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true { // will truncate suffix if needed try finalizingWorker.willDecryptLast(bytes: accumulated.slice) } var processedBytesCount = 0 var plaintext = Array<UInt8>(reserveCapacity: bytes.count + worker.additionalBufferSize) for chunk in toProcess.batched(by: blockSize) { plaintext += worker.decrypt(block: chunk) processedBytesCount += chunk.count } if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true { plaintext = Array(try finalizingWorker.didDecryptLast(bytes: plaintext.slice)) } // omit unecessary calculation if not needed if padding != .noPadding { lastBlockRemainder = plaintext.count.quotientAndRemainder(dividingBy: blockSize).remainder } if isLast { // CTR doesn't need padding. Really. Add padding to the last block if really want. but... don't. plaintext = padding.remove(from: plaintext, blockSize: blockSize - lastBlockRemainder) } accumulated.removeFirst(processedBytesCount) // super-slow if var finalizingWorker = worker as? FinalizingDecryptModeWorker, isLast == true { plaintext = Array(try finalizingWorker.finalize(decrypt: plaintext.slice)) } return plaintext } public func seek(to position: Int) throws { guard var worker = self.worker as? SeekableModeWorker else { fatalError("Not supported") } try worker.seek(to: position) self.worker = worker } }
mit
e623a4e8f9f9b9d7e43b8eb83b919826
41.012821
217
0.689655
4.854815
false
false
false
false
ArchimboldiMao/remotex-iOS
remotex-iOS/Model/AboutModel.swift
2
1772
// // AboutModel.swift // remotex-iOS // // Created by archimboldi on 14/05/2017. // Copyright © 2017 me.archimboldi. All rights reserved. // import UIKit struct AboutModel { let aboutTitle: String let slogan: String let description: String let author: String let review: String let authorTwitterUsername: String let remoteXiOSGitHub: String let remoteXiOSContributors: String let remoteXWebSite: String let remoteXSlack: String let remoteXEmail: String let linkInfo: String init() { self.aboutTitle = "RemoteX" self.slogan = "快乐工作 认真生活" self.description = "RemoteX 是一个关于远程、兼职、外包、众包等信息的聚合平台,我们将需求从不同的平台汇集到这里,非盈利组织运作。\n欢迎需求方、开发方联系我们。" self.authorTwitterUsername = "@ArchimboldiMao" self.remoteXiOSContributors = "贡献者列表" self.remoteXiOSGitHub = "GitHub" self.author = "RemoteX iOS App 由 \(self.authorTwitterUsername) 创建,并带领 RemoteX iOS 社区共同开发,详细贡献者信息请点击查看\(self.remoteXiOSContributors)。\n欢迎前往社区 \(self.remoteXiOSGitHub) 主页围观源代码。" self.review = "喜欢“RemoteX”吗?\n请前往 \(Constants.AppStore.TitleText) 为我们评分。" self.remoteXWebSite = "https://remotex.ooclab.org" self.remoteXSlack = "https://remotex.slack.com" self.remoteXEmail = "[email protected]" self.linkInfo = "联系方式\n网 站:\(remoteXWebSite)\nSlack:\(remoteXSlack)\n邮 件:\(remoteXEmail)\nQQ: RemoteX 633498747\n微信: lijian_gnu(手动拉入微信群)" } }
apache-2.0
6fba6ba6206a13781ad77d5115390291
33.785714
183
0.685147
2.963489
false
false
false
false
cotkjaer/SilverbackFramework
SilverbackFramework/UIView.swift
1
3312
// // UIView.swift // SilverbackFramework // // Created by Christian Otkjær on 09/06/15. // Copyright (c) 2015 Christian Otkjær. All rights reserved. // import Foundation //MARK: - Nib public extension UIView { public class func loadFromNibNamed(nibName: String, bundle: NSBundle?) -> UIView? { return UINib( nibName: nibName, bundle: bundle ).instantiateWithOwner(nil, options: nil).first as? UIView } } //MARK: - Hierarchy public extension UIView { /** Ascends the super-view hierarchy until a view of the specified type is encountered - parameter type: the (super)type of superview to look for - returns: the first superview encountered that is of the specified type */ func closestSuperViewOfType<T where T: UIView>(type: T.Type) -> T? { var views : [UIView] = [] for var view = superview; view != nil; view = view?.superview { views.append(view!) } let ts = views.filter { $0 is T } return ts.first as? T } /** does a breadth-first search of the subviews hierarchy - parameter type: the (super)type of subviews to look for - returns: an array of subviews of the specified type */ func closestSubViewsOfType<T where T: UIView>(type: T.Type) -> [T] { var views = subviews while !views.isEmpty { let ts = views.mapFilter({ $0 as? T}) if !ts.isEmpty { return ts } views = views.reduce([], combine: { (subs, view) -> [UIView] in return subs + view.subviews }) } return [] } } //MARK: - Animations public extension UIView { func bounce() { let options : UIViewAnimationOptions = [.BeginFromCurrentState, .AllowUserInteraction] transform = CGAffineTransformMakeScale(0.9, 0.9) UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 2, options: options, animations: { self.transform = CGAffineTransformMakeScale(1, 1) }, completion: nil) } func attachPopUpAnimation() { let animation = CAKeyframeAnimation(keyPath: "transform") let scale1 = CATransform3DMakeScale(0.5, 0.5, 1) let scale2 = CATransform3DMakeScale(1.2, 1.2, 1); let scale3 = CATransform3DMakeScale(0.9, 0.9, 1); let scale4 = CATransform3DMakeScale(1.0, 1.0, 1); let frameValues = [ NSValue(CATransform3D: scale1), NSValue(CATransform3D: scale2), NSValue(CATransform3D: scale3), NSValue(CATransform3D: scale4), ] animation.values = frameValues let frameTimes : [NSNumber] = [ 0, 0.5, 0.9, 1.0 ] animation.keyTimes = frameTimes animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false animation.duration = 0.2 self.layer.addAnimation(animation, forKey: "popup") } }
mit
969a1fbe3dc22f5b913b8a9acec3a7e5
24.859375
94
0.555891
4.590846
false
false
false
false
openHPI/xikolo-ios
Common/Extensions/UIColor+hex.swift
1
1049
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import UIKit public extension UIColor { // Taken from https://gist.github.com/yannickl/16f0ed38f0698d9a8ae7 convenience init(hexString: String) { let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines) let scanner = Scanner(string: hexString) if hexString.hasPrefix("#") { scanner.scanLocation = 1 } var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var color: UInt32 = 0 if scanner.scanHexInt32(&color) { let mask = 0x000000FF let redValue = Int(color >> 16) & mask let greenValue = Int(color >> 8) & mask let blueValue = Int(color) & mask red = CGFloat(redValue) / 255.0 green = CGFloat(greenValue) / 255.0 blue = CGFloat(blueValue) / 255.0 } self.init(red: red, green: green, blue: blue, alpha: 1) } }
gpl-3.0
c4fec0fd4f1dc5fc994a608f61302c75
26.578947
81
0.581107
3.867159
false
false
false
false
coylums/arcturus
arcturus/arcturus/DataServices/LogFileDataService.swift
1
2966
// // LogFileDataService.swift // Arcturus // // Created by William Woolard on 8/2/14. // Copyright (c) 2014 coylums. All rights reserved. // import Foundation class LogFileDataService: LogBookDataProtocol { class func getLogBookEntries() -> Array<LogEntry> { // Empty array to add LogEntry objects var logArray: Array<LogEntry> = []; var filePath = NSBundle.mainBundle().pathForResource("logbook", ofType:"json") var error: NSError? = nil // Load local JSON data var jsonData: NSData? = NSData.dataWithContentsOfFile(filePath, options: nil, error: &error) let json = JSONValue(jsonData) let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate let managedObjectContext = appDelegate.managedObjectContext for (index, element) in enumerate(json.array!) { let logEntry: LogEntry = NSEntityDescription.insertNewObjectForEntityForName("LogEntry", inManagedObjectContext: managedObjectContext) as LogEntry if var dateValue = json[index]["Date"].string{ logEntry.date = DateHelper.parse(dateValue) } if var latitudeValue = json[index]["Latitude"].string{ logEntry.latitude = latitudeValue.bridgeToObjectiveC().floatValue } if var longitudeValue = json[index]["Longitude"].string{ logEntry.longitude = longitudeValue.bridgeToObjectiveC().floatValue } if var courseValue = json[index]["Course"].string{ logEntry.course = courseValue.toInt()! } if var recordedByValue = json[index]["RecordedBy"].string{ logEntry.recordedBy = recordedByValue } if var personAtHelmValue = json[index]["PersonAtHelm"].string{ logEntry.personAtHelm = personAtHelmValue } if var windValue = json[index]["Wind"].string{ logEntry.wind = windValue } if var barometerValue = json[index]["Barometer"].string{ logEntry.barometer = barometerValue.toInt()! } if var conditionsValue = json[index]["Conditions"].string{ logEntry.conditions = conditionsValue } if var skyValue = json[index]["Sky"].string{ logEntry.sky = skyValue } if var tempValue = json[index]["Temp"].string{ if(tempValue != nil || tempValue != "null") { logEntry.temp = tempValue.toInt()! } } if var commentsValue = json[index]["Comments"].string{ logEntry.comments = commentsValue } logArray.append(logEntry) } return logArray } }
mit
a0d90dd90c9792731b93970e010bf1ba
24.144068
158
0.565745
5.185315
false
false
false
false