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
antonio081014/LeetCode-CodeBase
Swift/longest-word-in-dictionary-through-deleting.swift
2
2324
/** * https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/ * * */ // Date: Mon Feb 22 09:49:12 PST 2021 class Solution { /// Sorting, then comparing. func findLongestWord(_ s: String, _ d: [String]) -> String { let d = d.sorted { $0.count == $1.count ? $0 < $1 : $0.count > $1.count } let s = Array(s) for text in d { var sindex = 0 var dindex = 0 let text = Array(text) while sindex < s.count, dindex < text.count { if text[dindex] == s[sindex] { dindex += 1 } sindex += 1 } if dindex == text.count { return String(text) } } return "" } } class Solution { /// Comparing directly. func findLongestWord(_ s: String, _ d: [String]) -> String { let s = Array(s) var result = "" for text in d { var sindex = 0 var dindex = 0 let text = Array(text) while sindex < s.count, dindex < text.count { if text[dindex] == s[sindex] { dindex += 1 } sindex += 1 } if dindex == text.count { let substring = String(text) if substring.count > result.count || (substring.count == result.count && substring < result) { result = substring } } } return result } } /// Refactor. class Solution { func findLongestWord(_ s: String, _ d: [String]) -> String { var result = "" let s = Array(s) for text in d { if isSubstring(s, text) { if text.count > result.count || (text.count == result.count && text < result) { result = text } } } return result } private func isSubstring(_ main: [Character], _ sub: String) -> Bool { var mindex = 0 var sindex = 0 let sList = Array(sub) while mindex < main.count, sindex < sList.count { if main[mindex] == sList[sindex] { sindex += 1 } mindex += 1 } return sindex == sList.count } }
mit
a740e4d8b82c3c79e472d10f50f5abfc
27.353659
110
0.450947
4.041739
false
false
false
false
darthpelo/SurviveAmsterdam
mobile/Pods/QuadratTouch/Source/Shared/Endpoints/Specials.swift
3
2267
// // Specials.swift // Quadrat // // Created by Constantine Fry on 06/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation public class Specials: Endpoint { override var endpoint: String { return "specials" } /** https://developer.foursquare.com/docs/specials/specials */ public func get(specialId: String, venueId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { var allParameters = [Parameter.venueId:venueId] allParameters += parameters return self.getWithPath(specialId, parameters: allParameters, completionHandler: completionHandler) } // MARK: - General /** https://developer.foursquare.com/docs/specials/add */ public func add(parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = "add" return self.postWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/specials/list */ public func all(parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = "list" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/specials/search */ public func search(ll: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = "search" var allParameters = [Parameter.ll:ll] allParameters += parameters return self.getWithPath(path, parameters: allParameters, completionHandler: completionHandler) } // MARK: - Actions /** https://developer.foursquare.com/docs/specials/flag */ public func flag(specialId:String, venueId: String, problem: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = "add" var allParameters = ["ID": specialId, Parameter.venueId:venueId, Parameter.problem:problem] allParameters += allParameters return self.postWithPath(path, parameters: allParameters, completionHandler: completionHandler) } }
mit
efb68b2fc5db7ba9d9baf757c7ddb161
39.482143
112
0.67446
4.742678
false
false
false
false
hooman/swift
test/IRGen/generic_casts.swift
4
6080
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -enable-objc-interop -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: CPU=x86_64 import Foundation import gizmo // -- Protocol records for cast-to ObjC protocols // CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ = internal constant // CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section {{"__DATA,__objc_protolist,coalesced,no_dead_strip"|"objc_protolist"|".objc_protolist\$B"}} // CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL__TtP13generic_casts10ObjCProto1_ to i8*), section {{"__DATA,__objc_protorefs,coalesced,no_dead_strip"|"objc_protorefs"|".objc_protorefs\$B"}} // CHECK: @_PROTOCOL_NSRuncing = internal constant // CHECK: @"\01l_OBJC_LABEL_PROTOCOL_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section {{"__DATA,__objc_protolist,coalesced,no_dead_strip"|"objc_protolist"|".objc_protolist\$B"}} // CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" = weak hidden global i8* bitcast ({{.*}} @_PROTOCOL_NSRuncing to i8*), section {{"__DATA,__objc_protorefs,coalesced,no_dead_strip"|"objc_protorefs"|".objc_protorefs\$B"}} // CHECK: @_PROTOCOLS__TtC13generic_casts10ObjCClass2 = internal constant { i64, [1 x i8*] } { // CHECK: i64 1, // CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto2_ // CHECK: } // CHECK: @_DATA__TtC13generic_casts10ObjCClass2 = internal constant {{.*}} @_PROTOCOLS__TtC13generic_casts10ObjCClass2 // CHECK: @_PROTOCOL_PROTOCOLS__TtP13generic_casts10ObjCProto2_ = internal constant { i64, [1 x i8*] } { // CHECK: i64 1, // CHECK: @_PROTOCOL__TtP13generic_casts10ObjCProto1_ // CHECK: } // CHECK: define hidden swiftcc i64 @"$s13generic_casts8allToIntySixlF"(%swift.opaque* noalias nocapture %0, %swift.type* %T) func allToInt<T>(_ x: T) -> Int { return x as! Int // CHECK: [[INT_TEMP:%.*]] = alloca %TSi, // CHECK: [[TYPE_ADDR:%.*]] = bitcast %swift.type* %T to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[TYPE_ADDR]], i64 -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable* // CHECK: [[SIZE_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8 // CHECK: [[SIZE:%.*]] = load i64, i64* [[SIZE_ADDR]] // CHECK: [[T_ALLOCA:%.*]] = alloca i8, {{.*}} [[SIZE]], align 16 // CHECK: [[T_TMP:%.*]] = bitcast i8* [[T_ALLOCA]] to %swift.opaque* // CHECK: [[TEMP:%.*]] = call %swift.opaque* {{.*}}(%swift.opaque* noalias [[T_TMP]], %swift.opaque* noalias %0, %swift.type* %T) // CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque* // CHECK: call i1 @swift_dynamicCast(%swift.opaque* [[T0]], %swift.opaque* [[T_TMP]], %swift.type* %T, %swift.type* @"$sSiN", i64 7) // CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0 // CHECK: [[INT_RESULT:%.*]] = load i64, i64* [[T0]], // CHECK: ret i64 [[INT_RESULT]] } // CHECK: define hidden swiftcc void @"$s13generic_casts8intToAllyxSilF"(%swift.opaque* noalias nocapture sret({{.*}}) %0, i64 %1, %swift.type* %T) {{.*}} { func intToAll<T>(_ x: Int) -> T { // CHECK: [[INT_TEMP:%.*]] = alloca %TSi, // CHECK: [[T0:%.*]] = getelementptr inbounds %TSi, %TSi* [[INT_TEMP]], i32 0, i32 0 // CHECK: store i64 %1, i64* [[T0]], // CHECK: [[T0:%.*]] = bitcast %TSi* [[INT_TEMP]] to %swift.opaque* // CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[T0]], %swift.type* @"$sSiN", %swift.type* %T, i64 7) return x as! T } // CHECK: define hidden swiftcc i64 @"$s13generic_casts8anyToIntySiypF"(%Any* noalias nocapture dereferenceable({{.*}}) %0) {{.*}} { func anyToInt(_ x: Any) -> Int { return x as! Int } @objc protocol ObjCProto1 { static func forClass() static func forInstance() var prop: NSObject { get } } @objc protocol ObjCProto2 : ObjCProto1 {} @objc class ObjCClass {} // CHECK: define hidden swiftcc %objc_object* @"$s13generic_casts9protoCastyAA10ObjCProto1_So9NSRuncingpAA0E6CClassCF"(%T13generic_casts9ObjCClassC* %0) {{.*}} { func protoCast(_ x: ObjCClass) -> ObjCProto1 & NSRuncing { // CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP13generic_casts10ObjCProto1_" // CHECK: load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$_NSRuncing" // CHECK: call %objc_object* @swift_dynamicCastObjCProtocolUnconditional(%objc_object* {{%.*}}, i64 2, i8** {{%.*}}) return x as! ObjCProto1 & NSRuncing } @objc class ObjCClass2 : NSObject, ObjCProto2 { class func forClass() {} class func forInstance() {} var prop: NSObject { return self } } // <rdar://problem/15313840> // Class existential to opaque archetype cast // CHECK: define hidden swiftcc void @"$s13generic_casts33classExistentialToOpaqueArchetypeyxAA10ObjCProto1_plF"(%swift.opaque* noalias nocapture sret({{.*}}) %0, %objc_object* %1, %swift.type* %T) func classExistentialToOpaqueArchetype<T>(_ x: ObjCProto1) -> T { var x = x // CHECK: [[X:%.*]] = alloca %T13generic_casts10ObjCProto1P // CHECK: [[LOCAL:%.*]] = alloca %T13generic_casts10ObjCProto1P // CHECK: [[LOCAL_OPAQUE:%.*]] = bitcast %T13generic_casts10ObjCProto1P* [[LOCAL]] to %swift.opaque* // CHECK: [[PROTO_TYPE:%.*]] = call {{.*}}@"$s13generic_casts10ObjCProto1_pMD" // CHECK: call i1 @swift_dynamicCast(%swift.opaque* %0, %swift.opaque* [[LOCAL_OPAQUE]], %swift.type* [[PROTO_TYPE]], %swift.type* %T, i64 7) return x as! T } protocol P {} protocol Q {} // CHECK: define hidden swiftcc void @"$s13generic_casts19compositionToMemberyAA1P_pAaC_AA1QpF{{.*}}"(%T13generic_casts1PP* noalias nocapture sret({{.*}}) %0, %T13generic_casts1P_AA1Qp* noalias nocapture dereferenceable({{.*}}) %1) {{.*}} { func compositionToMember(_ a: P & Q) -> P { return a }
apache-2.0
064c6dab0c0e494971ba989141622d32
53.285714
270
0.65625
3.251337
false
false
false
false
AliSoftware/SwiftGen
SwiftGen.playground/Pages/XCAssets-Demo.xcplaygroundpage/Sources/Implementation Details.swift
1
5849
#if os(macOS) import AppKit #elseif os(iOS) import ARKit import UIKit #elseif os(tvOS) || os(watchOS) import UIKit #endif // Extra for playgrounds public var bundle: Bundle! // MARK: - Implementation Details public struct ARResourceGroupAsset { public fileprivate(set) var name: String #if os(iOS) @available(iOS 11.3, *) public var referenceImages: Set<ARReferenceImage> { return ARReferenceImage.referenceImages(in: self) } @available(iOS 12.0, *) public var referenceObjects: Set<ARReferenceObject> { return ARReferenceObject.referenceObjects(in: self) } #endif // Extra for playgrounds public init(name: String) { self.name = name } } #if os(iOS) @available(iOS 11.3, *) public extension ARReferenceImage { static func referenceImages(in asset: ARResourceGroupAsset) -> Set<ARReferenceImage> { return referenceImages(inGroupNamed: asset.name, bundle: bundle) ?? Set() } } @available(iOS 12.0, *) public extension ARReferenceObject { static func referenceObjects(in asset: ARResourceGroupAsset) -> Set<ARReferenceObject> { return referenceObjects(inGroupNamed: asset.name, bundle: bundle) ?? Set() } } #endif public final class ColorAsset { public fileprivate(set) var name: String #if os(macOS) public typealias Color = NSColor #elseif os(iOS) || os(tvOS) || os(watchOS) public typealias Color = UIColor #endif @available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *) public private(set) lazy var color: Color = { guard let color = Color(asset: self) else { fatalError("Unable to load color asset named \(name).") } return color }() #if os(iOS) || os(tvOS) @available(iOS 11.0, tvOS 11.0, *) public func color(compatibleWith traitCollection: UITraitCollection) -> Color { guard let color = Color(named: name, in: bundle, compatibleWith: traitCollection) else { fatalError("Unable to load color asset named \(name).") } return color } #endif // Extra for playgrounds public init(name: String) { self.name = name } } public extension ColorAsset.Color { @available(iOS 11.0, tvOS 11.0, watchOS 4.0, macOS 10.13, *) convenience init?(asset: ColorAsset) { #if os(iOS) || os(tvOS) self.init(named: asset.name, in: bundle, compatibleWith: nil) #elseif os(macOS) self.init(named: NSColor.Name(asset.name), bundle: bundle) #elseif os(watchOS) self.init(named: asset.name) #endif } } public struct DataAsset { public fileprivate(set) var name: String @available(iOS 9.0, tvOS 9.0, watchOS 6.0, macOS 10.11, *) public var data: NSDataAsset { guard let data = NSDataAsset(asset: self) else { fatalError("Unable to load data asset named \(name).") } return data } // Extra for playgrounds public init(name: String) { self.name = name } } @available(iOS 9.0, tvOS 9.0, watchOS 6.0, macOS 10.11, *) public extension NSDataAsset { convenience init?(asset: DataAsset) { #if os(iOS) || os(tvOS) || os(watchOS) self.init(name: asset.name, bundle: bundle) #elseif os(macOS) self.init(name: NSDataAsset.Name(asset.name), bundle: bundle) #endif } } public struct ImageAsset { public fileprivate(set) var name: String #if os(macOS) public typealias Image = NSImage #elseif os(iOS) || os(tvOS) || os(watchOS) public typealias Image = UIImage #endif @available(iOS 8.0, tvOS 9.0, watchOS 2.0, macOS 10.7, *) public var image: Image { #if os(iOS) || os(tvOS) let image = Image(named: name, in: bundle, compatibleWith: nil) #elseif os(macOS) let name = NSImage.Name(self.name) let image = (bundle == .main) ? NSImage(named: name) : bundle.image(forResource: name) #elseif os(watchOS) let image = Image(named: name) #endif guard let result = image else { fatalError("Unable to load image asset named \(name).") } return result } #if os(iOS) || os(tvOS) @available(iOS 8.0, tvOS 9.0, *) public func image(compatibleWith traitCollection: UITraitCollection) -> Image { guard let result = Image(named: name, in: bundle, compatibleWith: traitCollection) else { fatalError("Unable to load image asset named \(name).") } return result } #endif // Extra for playgrounds public init(name: String) { self.name = name } } public extension ImageAsset.Image { @available(iOS 8.0, tvOS 9.0, watchOS 2.0, *) @available(macOS, deprecated, message: "This initializer is unsafe on macOS, please use the ImageAsset.image property") convenience init?(asset: ImageAsset) { #if os(iOS) || os(tvOS) self.init(named: asset.name, in: bundle, compatibleWith: nil) #elseif os(macOS) self.init(named: NSImage.Name(asset.name)) #elseif os(watchOS) self.init(named: asset.name) #endif } } public struct SymbolAsset { public fileprivate(set) var name: String #if os(iOS) || os(tvOS) || os(watchOS) @available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) public typealias Configuration = UIImage.Configuration public typealias Image = UIImage @available(iOS 12.0, tvOS 12.0, watchOS 5.0, *) public var image: Image { #if os(iOS) || os(tvOS) let image = Image(named: name, in: bundle, compatibleWith: nil) #elseif os(watchOS) let image = Image(named: name) #endif guard let result = image else { fatalError("Unable to load symbol asset named \(name).") } return result } @available(iOS 13.0, tvOS 13.0, watchOS 6.0, *) public func image(with configuration: Configuration) -> Image { guard let result = Image(named: name, in: bundle, with: configuration) else { fatalError("Unable to load symbol asset named \(name).") } return result } #endif // Extra for playgrounds public init(name: String) { self.name = name } }
mit
41d5210cd659cdec3ad76ea581649aae
26.078704
93
0.6702
3.608267
false
false
false
false
lorentey/swift
test/Parse/diagnostic_missing_func_keyword.swift
25
3052
// RUN: %target-typecheck-verify-swift // https://bugs.swift.org/browse/SR-10477 protocol Brew { // expected-note {{in declaration of 'Brew'}} tripel() -> Int // expected-error {{expected 'func' keyword in instance method declaration}} {{3-3=func }} quadrupel: Int { get } // expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} static + (lhs: Self, rhs: Self) -> Self // expected-error {{expected 'func' keyword in operator function declaration}} {{10-10=func }} * (lhs: Self, rhs: Self) -> Self // expected-error {{expected 'func' keyword in operator function declaration}} {{3-3=func }} // expected-error @-1 {{operator '*' declared in protocol must be 'static'}} {{3-3=static }} ipa: Int { get }; apa: Float { get } // expected-error @-1 {{expected 'var' keyword in property declaration}} {{3-3=var }} // expected-error @-2 {{expected 'var' keyword in property declaration}} {{21-21=var }} stout: Int { get } porter: Float { get } // expected-error @-1 {{expected 'var' keyword in property declaration}} {{3-3=var }} // expected-error @-2 {{expected declaration}} // expected-error @-3 {{consecutive declarations on a line must be separated by ';'}} } infix operator %% struct Bar { fisr = 0x5F3759DF // expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} %%<T: Brew> (lhs: T, rhs: T) -> T { // expected-error {{expected 'func' keyword in operator function declaration}} {{3-3=func }} // expected-error @-1 {{operator '%%' declared in type 'Bar' must be 'static'}} // expected-error @-2 {{member operator '%%' must have at least one argument of type 'Bar'}} lhs + lhs + rhs + rhs } _: Int = 42 // expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} // expected-error @-1 {{property declaration does not bind any variables}} (light, dark) = (100, 200)// expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} a, b: Int // expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} } class Baz { instanceMethod() {} // expected-error {{expected 'func' keyword in instance method declaration}} {{3-3=func }} static staticMethod() {} // expected-error {{expected 'func' keyword in static method declaration}} {{10-10=func }} instanceProperty: Int { 0 } // expected-error {{expected 'var' keyword in property declaration}} {{3-3=var }} static staticProperty: Int { 0 } // expected-error {{expected 'var' keyword in static property declaration}} {{10-10=var }} } class C1 { class classMethod() {} // expected-error {{expected '{' in class}} } class C2 { class classProperty: Int { 0 } // expected-error {{inheritance from non-protocol, non-class type 'Int'}} // expected-note @-1 {{in declaration of 'classProperty'}} // expected-error @-2 {{expected declaration}} }
apache-2.0
56bac2cb85583ca1f7691d5c0a78f4d4
47.444444
136
0.62156
3.943152
false
false
false
false
YoungGary/30daysSwiftDemo
day13/day13/day13/ViewController.swift
1
2973
// // ViewController.swift // day13 // // Created by YOUNG on 2016/10/9. // Copyright © 2016年 Young. All rights reserved. // import UIKit class ViewController: UITableViewController { let dataCount : Int = 9 override func viewDidLoad() { super.viewDidLoad() tableView.registerClass(FirstTableViewCell.self, forCellReuseIdentifier: "first") tableView.backgroundColor = UIColor.blackColor() tableView.tableFooterView = UIView() tableView.separatorStyle = UITableViewCellSeparatorStyle.None } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) animationCell() } func randomCellColor(index : Int) -> UIColor{ let itemCount = dataCount - 1 let color = (CGFloat(index) / CGFloat(itemCount)) * 0.6 return UIColor(red: color, green: 0.0, blue: 1.0, alpha: 1.0) } func animationCell(){ self.tableView.reloadData() let cells = tableView.visibleCells let tableHeight = tableView.bounds.height for index in cells { let cell : UITableViewCell = index as UITableViewCell cell.transform = CGAffineTransformMakeTranslation(0, tableHeight) } var index = 0 for a in cells { let cell: UITableViewCell = a as UITableViewCell UIView.animateWithDuration(1.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { cell.transform = CGAffineTransformMakeTranslation(0, 0); }, completion: nil) index += 1 } } } extension ViewController{ override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataCount } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 60 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("first", forIndexPath: indexPath) cell.textLabel?.text = "第\(indexPath.row)行" cell.selectionStyle = UITableViewCellSelectionStyle.None cell.textLabel?.textColor = UIColor.whiteColor() cell.textLabel?.backgroundColor = UIColor.clearColor() return cell } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.backgroundColor = randomCellColor(indexPath.row) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("pushpush", sender: nil) } }
mit
bb4005dd1f48189ab756cbd99ce09f16
31.593407
154
0.640593
5.533582
false
false
false
false
denmanboy/IQKeyboardManager
KeyboardTextFieldDemo/IQKeyboardManager Swift/ViewController.swift
18
1903
// // ViewController.swift // swift test // // Created by Iftekhar on 22/09/14. // Copyright (c) 2014 Iftekhar. All rights reserved. // import UIKit class ViewController: UITableViewController { @IBAction func sharedClicked (sender : UIBarButtonItem!) { let shareString : String = "IQKeyboardManager is really great control for iOS developer to manage keyboard-textField." let shareImage : UIImage = UIImage(named: "IQKeyboardManagerScreenshot")! let youtubeUrl : NSURL = NSURL(string: "http://youtu.be/6nhLw6hju2A")! var activityItems = [NSObject]() activityItems.append(shareString) activityItems.append(shareImage) activityItems.append(youtubeUrl) var excludedActivities = [NSString]() activityItems.append(UIActivityTypePrint) activityItems.append(UIActivityTypeCopyToPasteboard) activityItems.append(UIActivityTypeAssignToContact) activityItems.append(UIActivityTypeSaveToCameraRoll) let controller = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) controller.excludedActivityTypes = excludedActivities; presentViewController(controller, animated: true) { () -> Void in } } override func viewDidLoad() { super.viewDidLoad() IQKeyboardManager.sharedManager().toolbarManageBehaviour = IQAutoToolbarManageBehaviour.ByPosition // Do any additional setup after loading the view, typically from a nib. } override func shouldAutorotate() -> Bool { return false } // override func supportedInterfaceOrientations() -> Int { // return UIInterfaceOrientationMask.Portrait // } override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation { return UIInterfaceOrientation.Portrait } }
mit
dedba0b42027327de9a17eb1455bf0c3
34.240741
126
0.700473
5.646884
false
false
false
false
sivakumarscorpian/INTPushnotification1
REIOSSDK/REiosNetwork.swift
1
7501
// // ServerCommunication.swift // INTPushNotification // // Created by Sivakumar on 22/8/17. // Copyright © 2017 Interakt. All rights reserved. // import UIKit import Alamofire import CryptoSwift enum REiosHTTPMethod:String { case get = "GET" case post = "POST" } class REiosNetwork: NSObject { class func getDataFromServer(url: String, headers: [String:String], params:[String:Any],successHandler: @escaping (_ returnData: [String:Any]) -> (Void), failureHandler: @escaping (_ error: String) -> (Void)) { // url let url : URL = URL(string: url )! // prepare json data let json = params let jsonData = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) // create post request var request = URLRequest(url: url) request.httpMethod = "POST" request.allHTTPHeaderFields = headers // insert json data to the request request.httpBody = jsonData let task = URLSession.shared.dataTask(with: request) { data, response, error in if (error != nil) { print(error?.localizedDescription ?? "No data") failureHandler((error?.localizedDescription)!) } if (data != nil) && error == nil { do { let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any] successHandler(json) } catch { failureHandler(error.localizedDescription) } } }; task.resume() } // Get url private class func getUrl(str:String) -> String? { if REiosDataManager.shared.getDynamicBaseUrl() == "" { return REiosUrls.baseUrl+str } else { return REiosDataManager.shared.getDynamicBaseUrl()+str } } // Get header private class func getHeader() -> [String:String] { let header: [String:String] = [ "Accept": "application/json", "Token" : self.hmacGen() ] return header } // Build request private class func buildRequestWith(path:String?, params:[String:Any]?,method: REiosHTTPMethod) -> URLRequest? { guard let _path = path else { return nil } // url let url : URL = URL(string: getUrl(str: _path)!)! guard let _params = params else { return nil } // prepare json data let jsonData = try? JSONSerialization.data(withJSONObject: _params, options: .prettyPrinted) // create post request var request = URLRequest(url: url) request.httpMethod = REiosHTTPMethod.post.rawValue request.allHTTPHeaderFields = getHeader() // insert json data to the request request.httpBody = jsonData return request } private class func hmacGen() -> String { // let sz: UInt32 = 99999 // let ms: UInt64 = UInt64(arc4random_uniform(sz)) // let ls: UInt64 = UInt64(arc4random_uniform(sz)) // let digits: UInt64 = UInt64(sz) + ls // // print(String(format:"18 digits: %018llu", digits)) // Print with leading 0s. var key = "D9ENR3JNZS657NP" var msg = String(arc4random_uniform(99999)) var keyBuff = [UInt8]() keyBuff += key.utf8 var msgBuff = [UInt8]() msgBuff += msg.utf8 let hmac = try! HMAC(key: keyBuff, variant: .sha256).authenticate(msgBuff) let longstring = hmac.toBase64()!+":"+msg let data = (longstring).data(using: String.Encoding.utf8) let base64 = data!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) print(base64) return base64 } // Requesting server for data class func getDataFromServer7(path:String, params:[String:Any]?,method: REiosHTTPMethod, successHandler: @escaping (_ returnData: [String:Any]) -> (Void), failureHandler: @escaping (_ error: String) -> (Void)) { guard let request = buildRequestWith(path: path, params: params, method: method) else { return } print("request \(request)") let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let httpResponse = response as? HTTPURLResponse else { failureHandler((error?.localizedDescription)!) return } if error == nil { if data != nil { do { let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any] switch httpResponse.statusCode { case 200: successHandler(json) case 201: successHandler(json) case 400: failureHandler(json["message"] as! String) case 500: failureHandler(json["message"] as! String) default: print("default") } } catch { failureHandler("Parser error") } } else { failureHandler("Data is nil") } } else { failureHandler((error?.localizedDescription)!) } }; task.resume() } // Requesting data from Local class func fetchDataFromLocalPath(fileName:String, successHandler: @escaping (_ returnData: Data) -> (Void), failureHandler: @escaping (_ error: String) -> (Void)) { // Getting bundle let podBundle = Bundle(for: REiosRatingControl.self) let bundleURL = podBundle.url(forResource: "REIOSSDK", withExtension: "bundle") let bundle = Bundle(url: bundleURL!) // Load Button Images // let filledStar = UIImage(named: "Rating-filled", in: bundle, compatibleWith: self.traitCollection) guard let path = bundle?.path(forResource: fileName, ofType: "json") else {return} let url = URL(fileURLWithPath: path) do { URLSession.shared.dataTask(with: url, completionHandler: { (returnData, response, error) in if (error != nil) { failureHandler((error?.localizedDescription)!) } if let data = returnData { successHandler(data) } }).resume() } } } class REiosReachability { static func isInternetReachable() ->Bool { return NetworkReachabilityManager()!.isReachable } }
mit
ea4501fb67012b916f965121a90b5ce1
32.936652
215
0.513333
5.28914
false
false
false
false
Snail93/iOSDemos
SnailSwiftDemos/SnailSwiftDemos/Skills/ViewControllers/TDTouchViewController.swift
2
5981
// // TDTouchViewController.swift // SnailSwiftDemos // // Created by Jian Wu on 2016/11/16. // Copyright © 2016年 Snail. All rights reserved. // import UIKit /* 当App未打开的情况下,用3dtouch进入App,在AppDelegate中走的方法是application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) 当App打开的情况下,用3dTouch进入App,走的方法是application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) */ //MARK: - 动态设置3DTouch func config3DTouch() { if #available(iOS 9.0, *){ let homeIcon = UIApplicationShortcutIcon.init(templateImageName: "right") let homeItem = UIApplicationShortcutItem.init(type: "GoHome", localizedTitle: "回家", localizedSubtitle: "", icon: homeIcon, userInfo: nil) UIApplication.shared.shortcutItems?.append(homeItem) let companyIcon = UIApplicationShortcutIcon.init(templateImageName: "right") let companyItem = UIApplicationShortcutItem.init(type: "GoCompany", localizedTitle: "去公司", localizedSubtitle: "", icon: companyIcon, userInfo: nil) UIApplication.shared.shortcutItems?.append(companyItem) let eatIcon = UIApplicationShortcutIcon.init(templateImageName: "right") let eatItem = UIApplicationShortcutItem.init(type: "Eat", localizedTitle: "吃饭", localizedSubtitle: "", icon: eatIcon, userInfo: nil) UIApplication.shared.shortcutItems?.append(eatItem) let sleepIcon = UIApplicationShortcutIcon.init(templateImageName: "right") let sleepItem = UIApplicationShortcutItem.init(type: "Sleep", localizedTitle: "睡觉", localizedSubtitle: "", icon: sleepIcon, userInfo: nil) UIApplication.shared.shortcutItems?.append(sleepItem) } } class TDTouchViewController: CustomViewController,UIViewControllerPreviewingDelegate,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var aTableView: UITableView! var selectedIndexPath : IndexPath! var sourceRect : CGRect! let data = ["Hello","World","Snail","WuJian"] var childVC : TouchChildController! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if #available(iOS 9.0, *) { if self.traitCollection.forceTouchCapability == .available { //TODO:注册3DTouch,并且设置代理 self.registerForPreviewing(with: self, sourceView: self.view) } }else { // Fallback on earlier versions print("不可用或者不支持3DTouch") } aTableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") aTableView.separatorStyle = .none } //MARK: - UITableViewDelegate methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = data[indexPath.row] cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 40 } //MARK: - UIViewControllerPreviewingDelegate methods 预览显示 func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { //获取用户手势点所在Cell的下表,同时判断手势点是否超出tableView的响应范围 if !self.getShouldShowRectAndIndexPathWithLocation(location){ return nil } if #available(iOS 9.0, *) { previewingContext.sourceRect = sourceRect childVC = TouchChildController() //TODO:Frame得给一下 childVC.view.frame = self.view.frame childVC.navTitleLabel.text = data[selectedIndexPath.row] return childVC } else { return nil } } //MARK: - 提交显示 func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { // self.navigationController?.pushViewController(childVC, animated: false) childVC.navTitleLabel.text = data[selectedIndexPath.row] self.show(childVC, sender: self) } //MARK: - 获取手势点所在Cell的下标,同时判断手势点是否超出TableView的范围 func getShouldShowRectAndIndexPathWithLocation(_ location : CGPoint) -> Bool { let tableLocation = self.view.convert(location, to: self.aTableView) selectedIndexPath = self.aTableView.indexPathForRow(at: tableLocation) if selectedIndexPath != nil{ sourceRect = CGRect(x: 0,y: CGFloat(selectedIndexPath.row * 40) + 64,width: Width , height: 40) print(sourceRect) return true }else{ return false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
cc4c4f8b66524d9f38bec2faadb783fc
38.136986
175
0.671159
5.097235
false
false
false
false
sekouperry/news-pro
codecanyon-11884937-wp-news-pro/Code_Documentation/Code/WPNews2/WPNews2 WatchKit Extension/MINewsString+RemoveHTMLCharacters.swift
1
5246
// // MINewsString+RemoveHTMLCharacters.swift // WPNews2 WatchKit Extension // // Created by Istvan Szabo on 2015. 06. 15.. // Copyright (c) 2015. Istvan Szabo. All rights reserved. // import Foundation import WatchKit extension String { func stringByDecodingNewsHTMLEntities() -> String? { var r: NSRange let pattern = "<[^>]+>" var s = self.stringByDecodingNewsHTMLEscapeCharacters() r = (s as NSString).rangeOfString(pattern, options: NSStringCompareOptions.RegularExpressionSearch) while (r.location != NSNotFound) { s = (s as NSString).stringByReplacingCharactersInRange(r, withString: " ") r = (s as NSString).rangeOfString(pattern, options: NSStringCompareOptions.RegularExpressionSearch) } return s.stringByReplacingOccurrencesOfString(" ", withString: " ") } func stringByDecodingNewsHTMLEscapeCharacters() -> String { var s = self.stringByReplacingOccurrencesOfString("&quot;", withString: "\"") s = s.stringByReplacingOccurrencesOfString("&apos;", withString: "'") s = s.stringByReplacingOccurrencesOfString("&amp;", withString: "&") s = s.stringByReplacingOccurrencesOfString("&lt;", withString: "<") s = s.stringByReplacingOccurrencesOfString("&gt;", withString: ">") s = s.stringByReplacingOccurrencesOfString("&#39;", withString: "'") s = s.stringByReplacingOccurrencesOfString("&ldquot;", withString: "\"") s = s.stringByReplacingOccurrencesOfString("&rdquot;", withString: "\"") s = s.stringByReplacingOccurrencesOfString("&#8217;", withString: "'") s = s.stringByReplacingOccurrencesOfString("&#8220;", withString: "\"") s = s.stringByReplacingOccurrencesOfString("&#8221;", withString: "\"") s = s.stringByReplacingOccurrencesOfString("&#8216;", withString: "'") s = s.stringByReplacingOccurrencesOfString("&#8211;", withString: "-") s = s.stringByReplacingOccurrencesOfString("&nbsp;", withString: " ") s = s.stringByReplacingOccurrencesOfString("&euro;", withString: "€") s = s.stringByReplacingOccurrencesOfString("&pound;", withString: "£") s = s.stringByReplacingOccurrencesOfString("&laquo;", withString: "«") s = s.stringByReplacingOccurrencesOfString("&raquo;", withString: "»") s = s.stringByReplacingOccurrencesOfString("&bull;", withString: "•") s = s.stringByReplacingOccurrencesOfString("&dagger;", withString: "†") s = s.stringByReplacingOccurrencesOfString("&copy;", withString: "©") s = s.stringByReplacingOccurrencesOfString("&reg;", withString: "®") s = s.stringByReplacingOccurrencesOfString("&trade;", withString: "™") s = s.stringByReplacingOccurrencesOfString("&deg;", withString: "°") s = s.stringByReplacingOccurrencesOfString("&permil;", withString: "‰") s = s.stringByReplacingOccurrencesOfString("&micro;", withString: "µ") s = s.stringByReplacingOccurrencesOfString("&middot;", withString: "·") s = s.stringByReplacingOccurrencesOfString("&ndash;", withString: "–") s = s.stringByReplacingOccurrencesOfString("&mdash;", withString: "—") s = s.stringByReplacingOccurrencesOfString("&#8212;", withString: "—") s = s.stringByReplacingOccurrencesOfString("&#8470;", withString: "№") s = s.stringByReplacingOccurrencesOfString("&#36;;", withString: "$") s = s.stringByReplacingOccurrencesOfString("&#37;", withString: "%") //Hungarian (add other language support) s = s.stringByReplacingOccurrencesOfString("&Aacute;", withString: "Á") s = s.stringByReplacingOccurrencesOfString("&aacute;", withString: "á") s = s.stringByReplacingOccurrencesOfString("&Eacute;", withString: "É") s = s.stringByReplacingOccurrencesOfString("&eacute;", withString: "é") s = s.stringByReplacingOccurrencesOfString("&Iacute;", withString: "Í") s = s.stringByReplacingOccurrencesOfString("&iacute;", withString: "í") s = s.stringByReplacingOccurrencesOfString("&Oacute;", withString: "Ó") s = s.stringByReplacingOccurrencesOfString("&oacute;", withString: "ó") s = s.stringByReplacingOccurrencesOfString("&#336;", withString: "Ő") s = s.stringByReplacingOccurrencesOfString("&#337;", withString: "ő") s = s.stringByReplacingOccurrencesOfString("&Uacute;", withString: "Ú") s = s.stringByReplacingOccurrencesOfString("&uacute;", withString: "ú") s = s.stringByReplacingOccurrencesOfString("&Uuml;", withString: "Ü") s = s.stringByReplacingOccurrencesOfString("&uuml;", withString: "ü") s = s.stringByReplacingOccurrencesOfString("&#368;", withString: "Ű") s = s.stringByReplacingOccurrencesOfString("&#369;", withString: "ű") return s } } /* http://www.thesauruslex.com/typo/eng/enghtml.htm Support for additional languages Add hungarian Ő and ő caracters support s = s.stringByReplacingOccurrencesOfString("&#336;", withString: "Ő") s = s.stringByReplacingOccurrencesOfString("&#337;", withString: "ő") */
apache-2.0
4fce0116e70aba35f074530ffcc68eb9
53.177083
111
0.668462
5.189621
false
false
false
false
jkolb/Asheron
Sources/Asheron/DatFile.swift
1
12194
/* The MIT License (MIT) Copyright (c) 2020 Justin Kolb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public final class DatFile { public struct Header : Packable { static let diskSize = 1024 var ignore0: [UInt8] = [] var magic: [UInt8] = [] var blockSize: Int = 0 var fileSize: UInt32 = 0 var dataSet: UInt32 = 0 // 1 = portal DATFILE_TYPE var dataSubset: UInt32 = 0 // Hires? var firstFree: UInt32 = 0 var finalFree: UInt32 = 0 var freeBlocks: UInt32 = 0 var btreeRoot: Int = 0 var youngLRU: UInt32 = 0 var oldLRU: UInt32 = 0 var useLRU: Bool = false var padding: [UInt8] = [] // 3 var masterMapId: UInt32 = 0 var engPackVNum: UInt32 = 0 var gamePackVNum: UInt32 = 0 var idVNum: [UInt8] = [] // 16 var ignore1: [UInt8] = [] public init() {} public init(from dataStream: DataStream) { self.ignore0 = [UInt8](from: dataStream, count: 320) self.magic = [UInt8](from: dataStream, count: 4) precondition(magic == [0x42, 0x54, 0x00, 0x00]) // BT\0\0 self.blockSize = numericCast(UInt32(from: dataStream)) precondition(blockSize > MemoryLayout<Int32>.size) self.fileSize = UInt32(from: dataStream) self.dataSet = UInt32(from: dataStream) self.dataSubset = UInt32(from: dataStream) self.firstFree = UInt32(from: dataStream) self.finalFree = UInt32(from: dataStream) self.freeBlocks = UInt32(from: dataStream) self.btreeRoot = numericCast(UInt32(from: dataStream)) self.youngLRU = UInt32(from: dataStream) self.oldLRU = UInt32(from: dataStream) self.useLRU = UInt8(from: dataStream) != 0 self.padding = [UInt8](from: dataStream, count: 3) self.masterMapId = UInt32(from: dataStream) self.engPackVNum = UInt32(from: dataStream) self.gamePackVNum = UInt32(from: dataStream) self.idVNum = [UInt8](from: dataStream, count: 20) self.ignore1 = [UInt8](from: dataStream, count: 624) precondition(dataStream.remainingCount == 0) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public struct Node : Packable { public static let diskSize = (nextNodeCount * 4) + 4 + (entryCount * Entry.byteCount) public static let entryCount = 61 public static var nextNodeCount = entryCount + 1 public struct Entry : Packable { public static let byteCount = 24 public var comp_resv_ver: UInt32 // 1_111111111111111_1111111111111111 public var identifier: Identifier public var offset: Int public var length: Int public var date: UInt32 public var iter: UInt32 public init(from dataStream: DataStream) { self.comp_resv_ver = UInt32(from: dataStream) self.identifier = Identifier(from: dataStream) self.offset = numericCast(Int32(from: dataStream)) self.length = numericCast(Int32(from: dataStream)) self.date = UInt32(from: dataStream) self.iter = UInt32(from: dataStream) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } public var nextNode: [Int] public var numEntries: Int public var entry: [Entry] public init(nextNode: [Int], numEntries: Int, entry: [Entry]) { precondition(nextNode.count == Node.nextNodeCount) precondition(entry.count == Node.entryCount) precondition(numEntries <= Node.entryCount) self.nextNode = nextNode self.numEntries = numEntries self.entry = entry } public var isLeaf: Bool { return nextNode[0] == 0 } public init(from dataStream: DataStream) { self.nextNode = [Int32](from: dataStream, count: Node.nextNodeCount).map({ numericCast($0) }) self.numEntries = numericCast(Int32(from: dataStream)) self.entry = [Entry](from: dataStream, count: Node.entryCount) } @inlinable public func encode(to dataStream: DataStream) { fatalError("Not implemented") } } private let fileHandle: FileHandle private var header: Header public init(url: URL) throws { self.fileHandle = try FileHandle(forUpdating: url) self.header = Self.readHeader(fileHandle: fileHandle) } public func readRegion(id: Identifier) -> Region { let data = readData(id: id) let dataStream = DataStream(data: data) return Region(from: dataStream, id: id) } public func readSetup(id: Identifier) -> Setup { let data = readData(id: id) let dataStream = DataStream(data: data) return Setup(from: dataStream, id: id) } public func readSurface(id: Identifier) -> Surface { let data = readData(id: id) let dataStream = DataStream(data: data) return Surface(from: dataStream, id: id) } public func readSurfaceTexture(id: Identifier) -> SurfaceTexture { let data = readData(id: id) let dataStream = DataStream(data: data) return SurfaceTexture(from: dataStream, id: id) } public func readTexture(id: Identifier) -> Texture { let data = readData(id: id) let dataStream = DataStream(data: data) return Texture(from: dataStream, id: id) } public func readPalette(id: Identifier) -> Palette { let data = readData(id: id) let dataStream = DataStream(data: data) return Palette(from: dataStream, id: id) } public func readGraphicsObject(id: Identifier) -> GraphicsObject { let data = readData(id: id) let dataStream = DataStream(data: data) return GraphicsObject(from: dataStream, id: id) } public func readWave(id: Identifier) -> Wave { let data = readData(id: id) let dataStream = DataStream(data: data) return Wave(from: dataStream, id: id) } public func readData(id: Identifier) -> Data { guard let entry = findEntry(for: id) else { fatalError("Missing identifier: \(id)") } return readEntry(entry) } public func allIdentifiers() -> [Identifier] { return identifiers(matching: { _ in true }) } public func identifiers(for dbType: DBType) -> [Identifier] { return identifiers(matching: { dbType.matches(id: $0) }) } public func identifiers(matching filter: (Identifier) -> Bool) -> [Identifier] { let node = readNode(fileOffset: header.btreeRoot) return identifiersInNode(node, matching: filter) } private func identifiersInNode(_ node: Node, matching filter: (Identifier) -> Bool) -> [Identifier] { var identifiers = [Identifier]() for index in 0..<node.numEntries { let entry = node.entry[index] if filter(entry.identifier) { identifiers.append(entry.identifier) } } if !node.isLeaf { for index in 0...node.numEntries { let nodeOffset = node.nextNode[index] let nextNode = readNode(fileOffset: nodeOffset) let nextIdentifiers = identifiersInNode(nextNode, matching: filter) identifiers.append(contentsOf: nextIdentifiers) } } return identifiers.sorted() } public func findEntry(for identifier: Identifier) -> Node.Entry? { var nodeOffset = header.btreeRoot nextLevel: while nodeOffset > 0 { let node = readNode(fileOffset: nodeOffset) precondition(node.numEntries > 0) for index in 0..<node.numEntries { let entry = node.entry[index] if entry.identifier == identifier { return entry } else if entry.identifier > identifier { nodeOffset = node.isLeaf ? 0 : node.nextNode[index] continue nextLevel } } nodeOffset = node.isLeaf ? 0 : node.nextNode[node.numEntries] } return nil } public func readEntry(_ entry: Node.Entry) -> Data { return readBlocks(fileHandle: fileHandle, fileOffset: entry.offset, length: entry.length) } public func readNode(fileOffset: Int) -> Node { let data = readBlocks(fileHandle: fileHandle, fileOffset: fileOffset, length: Node.diskSize) let dataStream = DataStream(data: data) let node = Node(from: dataStream) return node } public static func readHeader(fileHandle: FileHandle) -> Header { let data = readBytes(fileHandle: fileHandle, fileOffset: 0, length: Header.diskSize) let dataStream = DataStream(data: data) let header = Header(from: dataStream) return header } public func readBlocks(fileHandle: FileHandle, fileOffset: Int, length: Int) -> Data { precondition(length > 0) let dataStream = DataStream(count: length) var nextOffset = fileOffset while nextOffset > 0 { precondition(nextOffset >= Header.diskSize) precondition((nextOffset - Header.diskSize) % header.blockSize == 0) let block = Self.readBytes(fileHandle: fileHandle, fileOffset: nextOffset, length: header.blockSize) let blockStream = DataStream(data: block) nextOffset = numericCast(Int32(from: blockStream)) precondition(nextOffset >= 0) dataStream.putRemainingData(blockStream) precondition(dataStream.remainingCount >= 0) } precondition(dataStream.remainingCount == 0) return dataStream.data } public func writeBlocks(data: Data, fileOffset: Int) { fatalError() } public static func readBytes(fileHandle: FileHandle, fileOffset: Int, length: Int) -> Data { precondition(fileOffset >= 0) precondition(length > 0) let data = try! fileHandle.readDataUp(toLength: length, at: numericCast(fileOffset)) precondition(data.count == length) return data } public func writeBytes(data: Data, fileOffset: Int) { fatalError() } } extension FileHandle { @inlinable public func readDataUp(toLength length: Int, at offset: UInt64) throws -> Data { try seek(toOffset: offset) return try __readDataUp(toLength: length) } }
mit
9ed466a6149819a08f1f25b1441afd6f
36.52
112
0.601607
4.629461
false
false
false
false
ChrisStayte/Pokedex
Pokedex/csv.swift
1
2669
// // csv.swift // Pokedex // // Created by ChrisStayte on 1/23/16. // Copyright © 2016 ChrisStayte. All rights reserved. // import Foundation public class CSV { public var headers: [String] = [] public var rows: [Dictionary<String, String>] = [] public var columns = Dictionary<String, [String]>() var delimiter = NSCharacterSet(charactersInString: ",") public init(content: String?, delimiter: NSCharacterSet, encoding: UInt) throws{ if let csvStringToParse = content{ self.delimiter = delimiter let newline = NSCharacterSet.newlineCharacterSet() var lines: [String] = [] csvStringToParse.stringByTrimmingCharactersInSet(newline).enumerateLines { line, stop in lines.append(line) } self.headers = self.parseHeaders(fromLines: lines) self.rows = self.parseRows(fromLines: lines) self.columns = self.parseColumns(fromLines: lines) } } public convenience init(contentsOfURL url: String) throws { let comma = NSCharacterSet(charactersInString: ",") let csvString: String? do { csvString = try String(contentsOfFile: url, encoding: NSUTF8StringEncoding) } catch _ { csvString = nil }; try self.init(content: csvString,delimiter:comma, encoding:NSUTF8StringEncoding) } func parseHeaders(fromLines lines: [String]) -> [String] { return lines[0].componentsSeparatedByCharactersInSet(self.delimiter) } func parseRows(fromLines lines: [String]) -> [Dictionary<String, String>] { var rows: [Dictionary<String, String>] = [] for (lineNumber, line) in lines.enumerate() { if lineNumber == 0 { continue } var row = Dictionary<String, String>() let values = line.componentsSeparatedByCharactersInSet(self.delimiter) for (index, header) in self.headers.enumerate() { if index < values.count { row[header] = values[index] } else { row[header] = "" } } rows.append(row) } return rows } func parseColumns(fromLines lines: [String]) -> Dictionary<String, [String]> { var columns = Dictionary<String, [String]>() for header in self.headers { let column = self.rows.map { row in row[header] != nil ? row[header]! : "" } columns[header] = column } return columns } }
mit
65f6e8cc53ef5c2aed610e350257d2bf
32.3625
121
0.570465
4.877514
false
false
false
false
polydice/ICInputAccessory
Source/OptionPickerControl/Option.swift
1
2565
// // Option.swift // ICInputAccessory // // Created by Ben on 22/11/2017. // Copyright © 2017 bcylin. // // 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 /// The protocol defines the required variables to be displayed in a `UIPickerView` via `OptionPickerControl`. public protocol OptionDescriptive: Equatable { /// The text for the row in the `UIPickerView`. var title: String { get } /// The text for a placeholder row when the picker selection is optional. static var titleForOptionalValue: String { get } } /// An option struct that carries the `OptionDescriptive` public struct Option<T: OptionDescriptive>: Equatable { // MARK: - Initialization /// Returns an option that displays the optional value of an `OptionDescriptive` type. public static var optional: Option<T> { return Option<T>() } /// Returns an initialized option with an instance of an `OptionDescriptive` type. public init(_ value: T) { self.value = value } // MARK: - Properties /// Conformance to `OptionDescriptive`. public var title: String { return value?.title ?? T.titleForOptionalValue } /// The `OptionDescriptive` value of the option. Returns `nil` when it's the `optional` placeholder. public let value: T? // MARK: - Private private init() { self.value = nil } // MARK: - Equatable /// Returns true when two options' values are equal. public static func == (lhs: Option<T>, rhs: Option<T>) -> Bool { return lhs.value == rhs.value } }
mit
d4c04c37b01b517389040edc27d86cf2
32.736842
110
0.716849
4.238017
false
false
false
false
antelope-app/Antelope
Antelope-ios/Antelope/TutorialStepOne.swift
1
1084
// // TutorialStepOne.swift // AdShield // // Created by Jae Lee on 9/2/15. // Copyright © 2015 AdShield. All rights reserved. // import UIKit class TutorialStepOne: TutorialStep { @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var headline: UITextView! @IBOutlet weak var subheader: UITextView! override func viewDidLoad() { super.viewDidLoad() let buttonOptions: [String: String] = ["color": "white"] nextButton = self.borderButtonStyle(nextButton, options: buttonOptions) headline.textColor = colorKit.white subheader = self.paragraphStyle(subheader) subheader.textColor = colorKit.white self.view.backgroundColor = self.colorKit.magenta self.constrainButton(nextButton) self.constrainHeader(headline) self.view.layoutSubviews() } @IBAction func nextStep(sender: UIButton) { delegate.nextStep(1) } override func viewDidAppear(animated: Bool) { } func initialize() { } }
gpl-2.0
ddb465fb523782a5c880af0e11124ea2
22.543478
79
0.634349
4.608511
false
false
false
false
sochalewski/TinySwift
TinySwift/Bool.swift
1
1286
// // Bool.swift // TinySwift // // Created by Piotr Sochalewski on 02.12.2016. // Copyright © 2016 Piotr Sochalewski. All rights reserved. // import Foundation #if !os(watchOS) import GameplayKit #endif public extension Bool { /** Creates an instance initialized to the specified integer value. - parameter integer: The integer value. */ init<T: BinaryInteger>(_ integer: T) { self = integer != 0 } /// Generates and returns a new random Boolean value. @available(swift, deprecated: 4.2, message: "Deprecated in favor of Bool.random().") static var random: Bool { #if !os(watchOS) if #available(iOS 9.0, tvOS 9.0, *) { return GKRandomSource.sharedRandom().nextBool() } #endif return arc4random_uniform(2) == 0 } /** Performs a logical NOT operation on a Boolean value. The logical NOT operator (`!`) inverts a Boolean value. If the value is `true`, the result of the operation is `false`; if the value is `false`, the result is `true`. var bool = true bool.toggle() print(bool) // Prints false */ @available(swift, obsoleted: 4.2) mutating func toggle() { self = !self } }
mit
8bbe59866264443f9fc244eda06da272
25.22449
171
0.598444
4.066456
false
false
false
false
liuxianghong/SmartLight
Code/SmartLight/SmartLight/Api/DeviceSession.swift
1
12446
// // DeviceSession.swift // SmartLight // // Created by 刘向宏 on 2017/4/19. // Copyright © 2017年 刘向宏. All rights reserved. // import UIKit enum SessionComand { case power case level case color case colorTemp case state case discovery case associate case reset } enum SessionError: Int { case success // 成功 case timeout // 超时 case unknown } class DeviceSession: NSObject { fileprivate var device: BLEDevice! fileprivate var command: SessionComand! fileprivate let interval = Foundation.TimeInterval(0.01) fileprivate var stepTimer: DispatchSource! fileprivate var elapsed = Foundation.TimeInterval(0) fileprivate var timeout = Foundation.TimeInterval(0) fileprivate var expiredTimer: DispatchSource! fileprivate var expired = Foundation.TimeInterval(0) fileprivate var resendCount = UInt32(0) fileprivate var resendLimit = UInt32(0) fileprivate var completion: ((SessionError, BLEDevice?) -> Void)? fileprivate var requstId = NSNumber(value: 0) fileprivate let meshServiceApi = MeshServiceApi.sharedInstance() as! MeshServiceApi fileprivate let powerModelApi = PowerModelApi.sharedInstance() as! PowerModelApi fileprivate let lightModelApi = LightModelApi.sharedInstance() as! LightModelApi fileprivate let configModelApi = ConfigModelApi.sharedInstance() as! ConfigModelApi @discardableResult class func request(_ device: BLEDevice , command: SessionComand , timeout: Foundation.TimeInterval = 0 , resend: UInt32 = 0 , expired: Foundation.TimeInterval = 3 , completion: ((SessionError, BLEDevice?) -> Void)?) -> DeviceSession { let session = DeviceSession() session.device = device session.command = command session.timeout = timeout session.expired = expired session.resendLimit = resend session.completion = { (error, message) -> Void in completion?(error, message) session.stop() } NotificationCenter.default.addObserver(session , selector: #selector(deviceDidRecvMsg(_:)) , name: BLEManager.NOTICE_RECV_MESSAGE , object: BLEManager.shareManager ) // 消息超时时间大于0才打开定时器,否则不需要此操作 if timeout > 0 { session.startStepTimer() } // 函数超时时间不为0才打开定时器,否则不需要此操作 if expired > 0 { session.startExpiredTimer() } // 发送命令 session.send() return session } func deviceDidRecvMsg(_ sender: Notification) { guard let message = sender.userInfo?["recvMsg"] as? [String: Any] , let cmd = message["cmd"] as? NoticeCmd else { return } switch command! { case .discovery: discoveryRecvHandle(cmd: cmd, message: message) case .associate: guard let meshRequestId = message["meshRequestId"] as? NSNumber , meshRequestId == self.requstId else { return } associateRecvHandle(cmd: cmd, message: message) case .reset: resetRecvHandle(cmd: cmd, message: message) case .power: guard let meshRequestId = message["meshRequestId"] as? NSNumber , meshRequestId == self.requstId else { return } powerRecvHandle(cmd: cmd, message: message) case .colorTemp: guard let meshRequestId = message["meshRequestId"] as? NSNumber , meshRequestId == self.requstId else { return } lightStateRecvHandle(cmd: cmd, message: message) case .level: guard let meshRequestId = message["meshRequestId"] as? NSNumber , meshRequestId == self.requstId else { return } lightStateRecvHandle(cmd: cmd, message: message) case .state: guard let meshRequestId = message["meshRequestId"] as? NSNumber , meshRequestId == self.requstId else { return } lightStateRecvHandle(cmd: cmd, message: message) case .color: guard let meshRequestId = message["meshRequestId"] as? NSNumber , meshRequestId == self.requstId else { return } lightStateRecvHandle(cmd: cmd, message: message) } } fileprivate func send() { switch command! { case .discovery: meshServiceApi.setDeviceDiscoveryFilterEnabled(true) case .associate: let uuid = CBUUID(string: device.uuid!) let hash = self.meshServiceApi.getDeviceHash(from: uuid) requstId = meshServiceApi.associateDevice(hash , authorisationCode: nil) case .reset: configModelApi.resetDevice(self.device.deviceId as NSNumber) case .power: requstId = powerModelApi.setPowerState(device.deviceId as NSNumber , state: device.power ? 1 : 0 , acknowledged: true) case .colorTemp: requstId = lightModelApi.setColorTemperature(device.deviceId as NSNumber , temperature: device.temperature as NSNumber , duration: 0) case .level: requstId = lightModelApi.setLevel(device.deviceId as NSNumber , level: device.level as NSNumber , acknowledged: true) case .state: requstId = lightModelApi.getState(device.deviceId as NSNumber) case .color: requstId = lightModelApi.setRgb(device.deviceId as NSNumber , red: Int(device.color.red * 255) as NSNumber , green: Int(device.color.green * 255) as NSNumber , blue: Int(device.color.blue * 255) as NSNumber , level: device.level as NSNumber , duration: 0 , acknowledged: true) } } func stop() { NotificationCenter.default.removeObserver(self) self.stopStepTimer() self.stopExpiredTimer() self.elapsed = 0 self.resendLimit = 0 self.completion = nil switch command! { case .discovery: meshServiceApi.setDeviceDiscoveryFilterEnabled(false) case .reset: break default: if requstId != 0 { meshServiceApi.killTransaction(requstId) } } } fileprivate func discoveryRecvHandle(cmd: NoticeCmd, message: [String: Any]) { switch cmd { case .discover: if let uuid = message["uuid"] as? CBUUID { device.uuid = uuid.uuidString self.completion?(.success, self.device) } default: break } } fileprivate func associateRecvHandle(cmd: NoticeCmd, message: [String: Any]) { switch cmd { case .associate: if let deviceId = message["deviceId"] as? Int { requstId = 0 self.device.deviceId = Int32(deviceId) self.completion?(.success, self.device) } case .associating: break default: self.completion?(.timeout, self.device) } } fileprivate func resetRecvHandle(cmd: NoticeCmd, message: [String: Any]) { switch cmd { case .reset: if let deviceId = message["deviceId"] as? Int32, device.deviceId == deviceId { self.completion?(.success, self.device) } case .appearanceating: if let deviceHash = message["deviceHash"] as? NSData { let data = meshServiceApi.getDeviceHash(from: CBUUID(string: device.uuid!))! if data.hashValue == deviceHash.hashValue { self.completion?(.success, self.device) } } default: break } } fileprivate func powerRecvHandle(cmd: NoticeCmd, message: [String: Any]) { switch cmd { case .powerState: if let state = message["state"] as? Int , let deviceId = message["deviceId"] as? Int32 , device.deviceId == deviceId { requstId = 0 device.power = (state == 1) self.device.linkState = .linked self.completion?(.success, self.device) } default: self.completion?(.timeout, self.device) } } fileprivate func lightStateRecvHandle(cmd: NoticeCmd, message: [String: Any]) { if device.isInvalid { self.completion?(.unknown, nil) return } switch cmd { case .lightState: if let state = message["state"] as? Int , let deviceId = message["deviceId"] as? Int32 , device.deviceId == deviceId , let red = message["red"] as? UInt8 , let green = message["green"] as? UInt8 , let blue = message["blue"] as? UInt8 , let level = message["level"] as? UInt8 , let colorTemperature = message["colorTemperature"] as? UInt8 { requstId = 0 device.power = (state == 1) device.temperature = colorTemperature device.level = level device.color = UIColor(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: 1) self.device.linkState = .linked self.completion?(.success, self.device) } default: self.completion?(.timeout, self.device) } } fileprivate func startStepTimer() { guard stepTimer == nil else {return} stepTimer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: 0), queue: DispatchQueue.main) /*Migrator FIXME: Use DispatchSourceTimer to avoid the cast*/ as! DispatchSource guard let timer = stepTimer else {return} let interval = UInt64(self.interval * 1000) * NSEC_PER_MSEC let start = DispatchTime.now() + Double(Int64(interval)) / Double(NSEC_PER_SEC) timer.scheduleRepeating(deadline: start, interval: .milliseconds(Int(self.interval * 1000)), leeway: .milliseconds(0)) timer.setEventHandler { [weak self]() -> Void in self?.stepTimerTrigger() } timer.resume() } fileprivate func stopStepTimer() { guard let timer = stepTimer else {return} timer.cancel() stepTimer = nil } fileprivate func stepTimerTrigger() { elapsed += interval if elapsed >= timeout { if resendCount >= resendLimit && expiredTimer == nil { completion?(.timeout, self.device) } else { elapsed = 0 if resendCount < resendLimit { self.send() resendCount += 1 } } } } fileprivate func startExpiredTimer() { guard expiredTimer == nil else {return} expiredTimer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: 0), queue: DispatchQueue.main) /*Migrator FIXME: Use DispatchSourceTimer to avoid the cast*/ as! DispatchSource guard let timer = expiredTimer else {return} let interval = UInt64(self.expired * 1000) * NSEC_PER_MSEC let start = DispatchTime.now() + Double(Int64(interval)) / Double(NSEC_PER_SEC) timer.scheduleRepeating(deadline: start, interval: .milliseconds(Int(self.interval * 1000)), leeway: .milliseconds(0)) timer.setEventHandler { [weak self]() -> Void in self?.completion?(.timeout, self?.device) } timer.resume() } fileprivate func stopExpiredTimer() { guard let timer = expiredTimer else {return} timer.cancel() expiredTimer = nil } }
apache-2.0
5b9bcdd19b3e434dacd60d901e9a79bb
34.718841
208
0.568206
4.840141
false
false
false
false
chrisvire/ipatool
IpaTool/ITCMSDecoder.swift
1
1671
// // ITCMSDecoder.swift // ipatool // // Created by Stefan on 20/11/14. // Copyright (c) 2014 Stefan van den Oord. All rights reserved. // import Foundation class ITCMSDecoder { var cmsDecoder:CMSDecoder? private var _decodedString:String? private var _decodedData:NSData? init() { var d: Unmanaged<CMSDecoder>? = nil var status = CMSDecoderCreate(&d) assert(status == noErr) cmsDecoder = d!.takeRetainedValue() } func decodeData(data:NSData) { let l = data.length var bytes = UnsafeMutablePointer<Void>.alloc(l) data.getBytes(bytes, length:l) var status = CMSDecoderUpdateMessage(cmsDecoder, bytes, Int(l)) assert(status == noErr) status = CMSDecoderFinalizeMessage(cmsDecoder) assert(status == noErr) decodeString() } func decodeString() { var data:Unmanaged<CFData>? = nil var status = CMSDecoderCopyContent(cmsDecoder, &data) assert(status == noErr) if let d = data { _decodedData = d.takeRetainedValue() _decodedString = NSString(data:_decodedData!, encoding: NSUTF8StringEncoding) as String? } } func decodedString() -> String? { if (_decodedString != nil) { return _decodedString } if (cmsDecoder == nil) { return nil } decodeString() return _decodedString } func provisioningProfile() -> ITProvisioningProfile? { if let d = _decodedData { return ITProvisioningProfile(d) } else { return nil } } }
mit
b7ca764fec51ce0e283e64b7a4d4b0ba
23.940299
100
0.583483
4.351563
false
false
false
false
divadretlaw/very
Sources/very/Subcommands/DotFiles.swift
1
1774
// // DotFiles.swift // very // // Created by David Walter on 14.03.21. // import ArgumentParser import Foundation import Shell extension Very { struct DotFiles: ParsableCommand { @OptionGroup var options: Options static var configuration = CommandConfiguration( commandName: "dotfiles", abstract: "Init and update dotFiles in your home directory" ) @Option(name: .customLong("init")) var origin: String? @Option var home: String? func run() throws { try options.load() let home = home ?? "~" if let origin = origin { Log.message(Log.Icon.notes, "Intializing dotfiles") let initScript = """ cd \(home) git init git config --local status.showUntrackedFiles no git remote add origin \(origin) git branch -M main git pull origin main git branch --set-upstream-to=origin/main main """ Shell.run(initScript) let updateScript = """ cd \(home) git fetch git pull brew install git-secret git secret reveal -f """ Shell.run(updateScript) } else { Log.message(Log.Icon.notes, "Updating dotfiles") let script = """ cd \(home) git fetch git pull --rebase git secret reveal -f """ Shell.run(script) } } } }
apache-2.0
0ac074277ad66db043209d3b6b6bfb60
26.292308
71
0.450958
5.375758
false
false
false
false
benlangmuir/swift
test/IRGen/objc_async_metadata.swift
9
1668
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -disable-availability-checking %s -emit-ir | %FileCheck %s // REQUIRES: OS=macosx // REQUIRES: concurrency // REQUIRES: objc_interop import Foundation // CHECK: [[ENCODE_ASYNC_STRING:@.*]] = private unnamed_addr constant [28 x i8] c"v24@0:8@?<v@?@\22NSString\22>16\00" // CHECK: [[ENCODE_ASYNC_THROWS_STRING:@.*]] = private unnamed_addr constant [38 x i8] c"v24@0:8@?<v@?@\22NSString\22@\22NSError\22>16\00" // CHECK: @_INSTANCE_METHODS__TtC19objc_async_metadata7MyClass = internal constant // CHECK-SAME: methodWithCompletionHandler: // CHECK-SAME: [[ENCODE_ASYNC_STRING]] // CHECK-SAME: throwingMethodWithCompletionHandler: // CHECK-SAME: [[ENCODE_ASYNC_THROWS_STRING]] class MyClass: NSObject { @objc func method() async -> String { "" } @objc func throwingMethod() async throws -> String { "" } } // CHECK: [[ENCODE_ASYNC_STRING_PROTO:@.*]] = private unnamed_addr constant [15 x i8] c"v32@0:8@16@?24\00" // CHECK-LABEL: @_PROTOCOL_INSTANCE_METHODS__TtP19objc_async_metadata7MyProto_ = weak hidden constant // CHECK-SAME: _selector_data(myProtoRequirement:completionHandler:) // CHECK-SAME: [15 x i8]* [[ENCODE_ASYNC_STRING_PROTO]] // CHECK: [[ENCODE_ASYNC_STRING_PROTO_TYPE:@.*]] = private unnamed_addr constant [41 x i8] c"v32@0:8@\22NSString\2216@?<v@?@\22NSString\22>24\00" // CHECK-LABEL: @_PROTOCOL_METHOD_TYPES__TtP19objc_async_metadata7MyProto_ = weak hidden constant // CHECK-SAME: [41 x i8]* [[ENCODE_ASYNC_STRING_PROTO_TYPE]] @objc protocol MyProto { @objc func myProtoRequirement(_ x: String) async -> String }
apache-2.0
b37e860fd20de58cd9ca7d9da63229f1
45.333333
145
0.705635
3.153119
false
false
false
false
silence0201/Swift-Study
Swifter/13Typealias.playground/Contents.swift
1
695
//: Playground - noun: a place where people can play import UIKit typealias Location = CGPoint typealias Distance = Double func distance(from location: Location, to anotherLocation: Location) -> Distance { let dx = Distance(location.x - anotherLocation.x) let dy = Distance(location.y - anotherLocation.y) return sqrt(dx * dx + dy * dy) } let origin: Location = Location(x: 0, y: 0) let point: Location = Location(x: 1, y: 1) let d = distance(from: origin, to: point) class Person<T> {} typealias WorkId = String typealias Worker = Person<WorkId> //class Person<T> {} typealias WorkerGeneric<T> = Person<T> let w1 = Worker() let w2 = WorkerGeneric<WorkId>()
mit
a047dc4b0b39817dab34c02cefae4683
21.419355
57
0.68777
3.406863
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/Sections/Network/CookieManager.swift
1
1366
// // CookieManager.swift // HiPDA // // Created by leizh007 on 2017/3/30. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation import RxSwift /// 处理Cookie相关 class CookieManager { static let shared = CookieManager() private let disposeBag = DisposeBag() private init() { EventBus.shared.activeAccount.asObservable() .subscribe(onNext: { [unowned self] loginResult in guard let loginResult = loginResult, case .success(let account) = loginResult else { return } let cookies = self.currentCookies() self.set(cookies: cookies, for: account) }) .disposed(by: disposeBag) } fileprivate var cookieCache = [Account: [HTTPCookie]]() /// 清除所有cookie func clear() { HTTPCookieStorage.shared.removeCookies(since: Date(timeIntervalSince1970: 0)) } func cookies(for account: Account) -> [HTTPCookie]? { return cookieCache[account] } func set(cookies: [HTTPCookie]?, for account: Account) { cookieCache[account] = cookies clear() cookies?.forEach { HTTPCookieStorage.shared.setCookie($0) } } func currentCookies() -> [HTTPCookie]? { return HTTPCookieStorage.shared.cookies } }
mit
e88fee9f0696c9a63ca9091ea840f17b
26.489796
100
0.602821
4.70979
false
false
false
false
trolmark/FunctionalDataStructures
FunctionalDataStructures.playground/Pages/Queue.xcplaygroundpage/Contents.swift
1
2311
//: [Previous](@previous) import Foundation struct BatchedQueue<Elem> : Queue { typealias Element = Elem fileprivate var f : [Elem] = [] fileprivate var r : [Elem] = [] func isEmpty() -> Bool { return f.isEmpty } func head() -> Elem? { return f.first } func tail() -> BatchedQueue<Elem> { let newF = Array(f.dropFirst()) return checkF(f: newF, r: r) } func snoc(elem: Elem) -> BatchedQueue<Elem> { let newR = [elem] + r return checkF(f: f, r: newR) } } private extension BatchedQueue { /* Elements are added to r and removed from f , so they must somehow migrate from one list to the other. This is accomplished by reversing R and installing the result as the new F whenever F would otherwise become empty, simultaneously setting the new R to [ ] */ func checkF(f:[Elem], r:[Elem]) -> BatchedQueue<Elem> { if f.isEmpty { return BatchedQueue(f: r.reversed(), r: []) } else { return BatchedQueue(f: f, r: r) } } } struct LazyQueue<Elem> : Queue { var f : [Elem] = [] var r : [Elem] = [] var lenF : Int = 0 var lenR : Int = 0 typealias Element = Elem func isEmpty() -> Bool { return (lenF == 0) } func head() -> Elem? { return f.first } func tail() -> LazyQueue<Elem> { let newF = Array(f.dropFirst()) return check(lenF: lenF - 1, fStream: newF, lenR: lenR, rStream: r) } func snoc(elem: Elem) -> LazyQueue<Elem> { let newR = [elem] + r return check(lenF: lenF, fStream: f, lenR: lenR + 1, rStream: newR) } } private extension LazyQueue { func check(lenF:Int, fStream:[Elem],lenR:Int, rStream:[Elem]) -> LazyQueue<Elem> { if lenR <= lenF { return LazyQueue(f: fStream, r: rStream, lenF: lenF, lenR: lenR) } else { return LazyQueue(f: fStream + rStream.reversed(), r: [], lenF: lenF + lenR, lenR: 0) } } } let queue = BatchedQueue<Int>() print(queue .snoc(elem: 1) .snoc(elem: 2) .snoc(elem: 7) .tail() .head()!) //: [Next](@next)
gpl-3.0
1e027ad64deb65e038d14af246fa9ecf
22.343434
101
0.526612
3.475188
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Tool/Sources/ToolKit/General/TextRegex.swift
1
605
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public enum TextRegex: String { case cardholderName = "^.{2,26}$" // 2-26 characters as defined in `ISO/IEC 7813`: https://en.wikipedia.org/wiki/ISO/IEC_7813#Track_1 case cvv = "^[0-9]{3,4}$" case cardExpirationDate = "^((0[1-9])|(1[0-2]))/[2-9][0-9]$" case walletIdentifier = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" case email = "^[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}$" case notEmpty = "^.+$" case noSpecialCharacters = "^[a-zA-Z0-9]*$" }
lgpl-3.0
9d1152a246a671ba7897694af0959f60
45.461538
137
0.581126
2.506224
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureWalletConnect/Sources/FeatureWalletConnectData/Handlers/SwitchRequestHandler.swift
1
2299
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BigInt import DIKit import EthereumKit import FeatureWalletConnectDomain import MoneyKit import WalletConnectSwift final class SwitchRequestHandler: RequestHandler { private enum Method: String { case sendRawTransaction = "wallet_switchEthereumChain" } private let enabledCurrenciesService: EnabledCurrenciesServiceAPI private let getSession: (WCURL) -> Session? private let responseEvent: (WalletConnectResponseEvent) -> Void private let sessionEvent: (WalletConnectSessionEvent) -> Void init( enabledCurrenciesService: EnabledCurrenciesServiceAPI = resolve(), getSession: @escaping (WCURL) -> Session?, responseEvent: @escaping (WalletConnectResponseEvent) -> Void, sessionEvent: @escaping (WalletConnectSessionEvent) -> Void ) { self.enabledCurrenciesService = enabledCurrenciesService self.getSession = getSession self.responseEvent = responseEvent self.sessionEvent = sessionEvent } func canHandle(request: Request) -> Bool { Method(rawValue: request.method) != nil } func handle(request: Request) { guard let session = getSession(request.url) else { responseEvent(.invalid(request)) return } guard let payload = try? request.parameter(of: ChainIdPayload.self, at: 0) else { // Invalid Payload. responseEvent(.invalid(request)) return } guard let chainID = BigUInt(payload.chainId.withoutHex, radix: 16) else { // Invalid value. responseEvent(.invalid(request)) return } guard let network: EVMNetwork = EVMNetwork(chainID: chainID) else { // Chain not recognised. responseEvent(.invalid(request)) return } guard enabledCurrenciesService.allEnabledCryptoCurrencies.contains(network.cryptoCurrency) else { // Chain recognised, but currently disabled. responseEvent(.invalid(request)) return } sessionEvent(.shouldChangeChainID(session, request, network)) } } private struct ChainIdPayload: Decodable { let chainId: String }
lgpl-3.0
1eb6fd39e22c5698161a0e27d44d5e02
32.304348
105
0.664056
5.106667
false
false
false
false
adamnemecek/AudioKit
Sources/AudioKit/Audio Files/AVAudioPCMBuffer+Processing.swift
1
9353
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import Accelerate import AVFoundation extension AVAudioPCMBuffer { /// Read the contents of the url into this buffer public convenience init?(url: URL) throws { guard let file = try? AVAudioFile(forReading: url) else { return nil } try self.init(file: file) } /// Read entire file and return a new AVAudioPCMBuffer with its contents public convenience init?(file: AVAudioFile) throws { file.framePosition = 0 self.init(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length)) try file.read(into: self) } } extension AVAudioPCMBuffer { /// Returns audio data as an `Array` of `Float` Arrays. /// /// If stereo: /// - `floatChannelData?[0]` will contain an Array of left channel samples as `Float` /// - `floatChannelData?[1]` will contains an Array of right channel samples as `Float` public func toFloatChannelData() -> FloatChannelData? { // Do we have PCM channel data? guard let pcmFloatChannelData = floatChannelData else { return nil } let channelCount = Int(format.channelCount) let frameLength = Int(self.frameLength) let stride = self.stride // Preallocate our Array so we're not constantly thrashing while resizing as we append. var result = Array(repeating: [Float](zeros: frameLength), count: channelCount) // Loop across our channels... for channel in 0 ..< channelCount { // Make sure we go through all of the frames... for sampleIndex in 0 ..< frameLength { result[channel][sampleIndex] = pcmFloatChannelData[channel][sampleIndex * stride] } } return result } } extension AVAudioPCMBuffer { /// Local maximum containing the time, frame position and amplitude public struct Peak { /// Initialize the peak, to be able to use outside of AudioKit public init() {} internal static let min: Float = -10_000.0 /// Time of the peak public var time: Double = 0 /// Frame position of the peak public var framePosition: Int = 0 /// Peak amplitude public var amplitude: Float = 1 } /// Find peak in the buffer /// - Returns: A Peak struct containing the time, frame position and peak amplitude public func peak() -> Peak? { guard frameLength > 0 else { return nil } guard let floatData = floatChannelData else { return nil } var value = Peak() var position = 0 var peakValue: Float = Peak.min let chunkLength = 512 let channelCount = Int(format.channelCount) while true { if position + chunkLength >= frameLength { break } for channel in 0 ..< channelCount { var block = Array(repeating: Float(0), count: chunkLength) // fill the block with frameLength samples for i in 0 ..< block.count { if i + position >= frameLength { break } block[i] = floatData[channel][i + position] } // scan the block let blockPeak = getPeakAmplitude(from: block) if blockPeak > peakValue { value.framePosition = position value.time = Double(position) / Double(format.sampleRate) peakValue = blockPeak } position += block.count } } value.amplitude = peakValue return value } // Returns the highest level in the given array private func getPeakAmplitude(from buffer: [Float]) -> Float { // create variable with very small value to hold the peak value var peak: Float = Peak.min for i in 0 ..< buffer.count { // store the absolute value of the sample let absSample = abs(buffer[i]) peak = max(peak, absSample) } return peak } /// - Returns: A normalized buffer public func normalize() -> AVAudioPCMBuffer? { guard let floatData = floatChannelData else { return self } let normalizedBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) let length: AVAudioFrameCount = frameLength let channelCount = Int(format.channelCount) guard let peak: AVAudioPCMBuffer.Peak = peak() else { Log("Failed getting peak amplitude, returning original buffer") return self } let gainFactor: Float = 1 / peak.amplitude // i is the index in the buffer for i in 0 ..< Int(length) { // n is the channel for n in 0 ..< channelCount { let sample = floatData[n][i] * gainFactor normalizedBuffer?.floatChannelData?[n][i] = sample } } normalizedBuffer?.frameLength = length return normalizedBuffer } /// - Returns: A reversed buffer public func reverse() -> AVAudioPCMBuffer? { let reversedBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) var j: Int = 0 let length: AVAudioFrameCount = frameLength let channelCount = Int(format.channelCount) // i represents the normal buffer read in reverse for i in (0 ..< Int(length)).reversed() { // n is the channel for n in 0 ..< channelCount { // we write the reverseBuffer via the j index reversedBuffer?.floatChannelData?[n][j] = floatChannelData?[n][i] ?? 0.0 } j += 1 } reversedBuffer?.frameLength = length return reversedBuffer } /// - Returns: A new buffer from this one that has fades applied to it. Pass 0 for either parameter /// if you only want one of them. The ramp is exponential by default. public func fade(inTime: Double, outTime: Double, linearRamp: Bool = false) -> AVAudioPCMBuffer? { guard let floatData = floatChannelData, inTime > 0 || outTime > 0 else { Log("Error fading buffer, returning original...") return self } let fadeBuffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) let length: UInt32 = frameLength let sampleRate = format.sampleRate let channelCount = Int(format.channelCount) // initial starting point for the gain, if there is a fade in, start it at .01 otherwise at 1 var gain: Double = inTime > 0 ? 0.01 : 1 let sampleTime: Double = 1.0 / sampleRate var fadeInPower: Double = 1 var fadeOutPower: Double = 1 if linearRamp { gain = inTime > 0 ? 0 : 1 fadeInPower = sampleTime / inTime } else { fadeInPower = exp(log(10) * sampleTime / inTime) } if linearRamp { fadeOutPower = sampleTime / outTime } else { fadeOutPower = exp(-log(25) * sampleTime / outTime) } // where in the buffer to end the fade in let fadeInSamples = Int(sampleRate * inTime) // where in the buffer to start the fade out let fadeOutSamples = Int(Double(length) - (sampleRate * outTime)) // i is the index in the buffer for i in 0 ..< Int(length) { // n is the channel for n in 0 ..< channelCount { if i < fadeInSamples, inTime > 0 { if linearRamp { gain *= fadeInPower } else { gain += fadeInPower } } else if i > fadeOutSamples, outTime > 0 { if linearRamp { gain -= fadeOutPower } else { gain *= fadeOutPower } } else { gain = 1.0 } // sanity check if gain > 1 { gain = 1 } else if gain < 0 { gain = 0 } let sample = floatData[n][i] * Float(gain) fadeBuffer?.floatChannelData?[n][i] = sample } } // update this fadeBuffer?.frameLength = length // set the buffer now to be the faded one return fadeBuffer } } extension AVAudioPCMBuffer { var rms: Float { guard let data = floatChannelData else { return 0 } let channelCount = Int(format.channelCount) var rms: Float = 0.0 for i in 0 ..< channelCount { var channelRms: Float = 0.0 vDSP_rmsqv(data[i], 1, &channelRms, vDSP_Length(frameLength)) rms += abs(channelRms) } let value = (rms / Float(channelCount)) return value } }
mit
2b6da515aadc6c24e9c5cdfec0ae42d1
33.010909
103
0.549022
5.088683
false
false
false
false
elpassion/el-space-ios
ELSpace/Screens/Hub/Activity/Type/Activity/ActivityTypeViewModel.swift
1
2064
import UIKit import RxSwift import RxCocoa protocol ActivityTypeViewModeling: class { var type: ReportType { get } var imageSelected: UIImage? { get } var imageUnselected: UIImage? { get } var title: String { get } var isUserInteractionEnabled: Bool { get } var isSelected: BehaviorRelay<Bool> { get } } class ActivityTypeViewModel: ActivityTypeViewModeling { init(type: ReportType, isUserInteractionEnabled: Bool) { self.type = type imageSelected = type.imageSelected imageUnselected = type.imageUnselected title = type.title.uppercased() self.isUserInteractionEnabled = isUserInteractionEnabled } let type: ReportType let imageSelected: UIImage? let imageUnselected: UIImage? let title: String let isUserInteractionEnabled: Bool var isSelected = BehaviorRelay(value: false) } private extension ReportType { var imageSelected: UIImage? { switch self { case .normal: return UIImage(named: "time_report_selected") case .paidVacations: return UIImage(named: "vacation_selected") case .unpaidDayOff: return UIImage(named: "day_off_selected") case .sickLeave: return UIImage(named: "sick_leave_selected") case .conference: return UIImage(named: "conference_selected") } } var imageUnselected: UIImage? { switch self { case .normal: return UIImage(named: "time_report_unselected") case .paidVacations: return UIImage(named: "vacation_unselected") case .unpaidDayOff: return UIImage(named: "day_off_unselected") case .sickLeave: return UIImage(named: "sick_leave_unselected") case .conference: return UIImage(named: "conference_unselected") } } var title: String { switch self { case .normal: return "time report" case .paidVacations: return "vacation" case .unpaidDayOff: return "day off" case .sickLeave: return "sick leave" case .conference: return "conference" } } }
gpl-3.0
8acfc2acc09e4c6961ee977298a2e384
30.272727
73
0.670058
4.35443
false
false
false
false
iosyaowei/Weibo
WeiBo/Classes/Utils(工具)/Emoticon/View/YWEmoticonLayout.swift
1
555
// // YWEmoticonLayout.swift // 表情键盘 // // Created by 姚巍 on 16/11/6. // Copyright © 2016年 Guangxi City Network Technology Co.,Ltd. All rights reserved. // import UIKit class YWEmoticonLayout: UICollectionViewFlowLayout { override func prepare() { super.prepare() guard let collectionView = collectionView else { return } itemSize = collectionView.bounds.size // minimumLineSpacing = 0 // minimumInteritemSpacing = 0 scrollDirection = .horizontal } }
mit
1c5232e4c64c62eddc933fd3495c894d
22.478261
83
0.633333
4.5
false
false
false
false
eBay/NMessenger
nMessenger/Source/MessageNodes/ContentNodes/ImageContent/ImageContentNode.swift
2
4984
// // Copyright (c) 2016 eBay Software Foundation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit import AsyncDisplayKit //MARK: ImageContentNode /** ImageContentNode for NMessenger. Extends ContentNode. Defines content that is an image. */ open class ImageContentNode: ContentNode { // MARK: Public Variables /** UIImage as the image of the cell*/ open var image: UIImage? { get { return imageMessageNode.image } set { imageMessageNode.image = newValue } } // MARK: Private Variables /** ASImageNode as the content of the cell*/ open fileprivate(set) var imageMessageNode:ASImageNode = ASImageNode() // MARK: Initialisers /** Initialiser for the cell. - parameter image: Must be UIImage. Sets image for cell. Calls helper method to setup cell */ public init(image: UIImage, bubbleConfiguration: BubbleConfigurationProtocol? = nil) { super.init(bubbleConfiguration: bubbleConfiguration) self.setupImageNode(image) } // MARK: Initialiser helper method /** Override updateBubbleConfig to set bubble mask */ open override func updateBubbleConfig(_ newValue: BubbleConfigurationProtocol) { var maskedBubbleConfig = newValue maskedBubbleConfig.isMasked = true super.updateBubbleConfig(maskedBubbleConfig) } /** Sets the image to be display in the cell. Clips and rounds the corners. - parameter image: Must be UIImage. Sets image for cell. */ fileprivate func setupImageNode(_ image: UIImage) { imageMessageNode.image = image imageMessageNode.clipsToBounds = true imageMessageNode.contentMode = UIViewContentMode.scaleAspectFill self.imageMessageNode.accessibilityIdentifier = "imageNode" self.imageMessageNode.isAccessibilityElement = true self.addSubnode(imageMessageNode) } // MARK: Override AsycDisaplyKit Methods /** Overriding layoutSpecThatFits to specifiy relatiohsips between elements in the cell */ override open func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let width = constrainedSize.max.width self.imageMessageNode.style.width = ASDimension(unit: .points, value: width) self.imageMessageNode.style.height = ASDimension(unit: .points, value: width/4*3) let absLayout = ASAbsoluteLayoutSpec() absLayout.sizing = .sizeToFit absLayout.children = [self.imageMessageNode] return absLayout } // MARK: UILongPressGestureRecognizer Selector Methods /** Overriding canBecomeFirstResponder to make cell first responder */ override open func canBecomeFirstResponder() -> Bool { return true } /** Override method from superclass */ open override func messageNodeLongPressSelector(_ recognizer: UITapGestureRecognizer) { if recognizer.state == UIGestureRecognizerState.began { let touchLocation = recognizer.location(in: view) if self.imageMessageNode.frame.contains(touchLocation) { view.becomeFirstResponder() delay(0.1, closure: { let menuController = UIMenuController.shared menuController.menuItems = [UIMenuItem(title: "Copy", action: #selector(ImageContentNode.copySelector))] menuController.setTargetRect(self.imageMessageNode.frame, in: self.view) menuController.setMenuVisible(true, animated:true) }) } } } /** Copy Selector for UIMenuController Puts the node's image on UIPasteboard */ open func copySelector() { if let image = self.image { UIPasteboard.general.image = image } } }
mit
8a28af05ed618622f8a0b9614b5974c3
37.9375
463
0.675762
5.246316
false
true
false
false
amdaza/Scoop-iOS-Client
ScoopClient/AnonymousTableViewController.swift
1
1839
// // ScoopsTableViewController.swift // ScoopClient // // Created by Home on 30/10/16. // Copyright © 2016 Alicia. All rights reserved. // import UIKit class AnonymousTableViewController: ScoopsTableViewController { @IBAction func backButton(_ sender: AnyObject) { let storyBoardA = UIStoryboard(name: "Main", bundle: Bundle.main) if let navController = storyBoardA.instantiateViewController(withIdentifier: "firstView") as? UINavigationController { self.present(navController, animated: true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return super.tableView(withCellName: "anonymousCell", tableView, cellForRowAt: indexPath) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = model?[indexPath.row] performSegue(withIdentifier: "postDetail", sender: item) } // 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. if segue.identifier == "postDetail" { let vc = segue.destination as? PostViewController vc?.model = sender as? ScoopRecord } } }
gpl-3.0
e4985d806803e372560c30f6500d12a4
30.152542
126
0.649619
5.281609
false
false
false
false
scoremedia/Fisticuffs
Tests/FisticuffsTests/ComputedSpec.swift
1
5562
// The MIT License (MIT) // // Copyright (c) 2015 theScore Inc. // // 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 import Quick import Nimble @testable import Fisticuffs class ComputedSpec: QuickSpec { override func spec() { describe("Computed") { it("should derive its value from the provided block") { let a = Observable(11) let b = Observable(42) let sum = Computed { a.value + b.value } expect(sum.value) == 53 } it("should update its value when any dependencies change") { let a = Observable(11) let b = Observable(42) let sum = Computed { a.value + b.value } a.value = 42 expect(sum.value) == 84 } it("should allow for Observable and Computed dependencies") { let a = Observable(11) let b = Observable(42) let sum = Computed { a.value + b.value } let display = Computed { "Sum: \(sum.value)" } a.value = 42 expect(display.value) == "Sum: 84" } context("coalescing updates") { it("should coalesce updates") { var numberOfTimesComputed = 0 let a = Observable(11) let b = Observable(42) let sum = Computed { a.value + b.value } let display: Computed<String> = Computed { numberOfTimesComputed += 1 return "Sum: \(sum.value)" } a.value = 2 b.value = 3 expect(display.value).toEventually(equal("Sum: 5")) // once for init() & once for updating a/b expect(numberOfTimesComputed) == 2 } it("should immediately recompute if `.value` is accessed & it is dirty") { let a = Observable(5) let result = Computed { a.value } a.value = 11 expect(result.value) == 11 } it("should avoid sending multiple updates when recomputed early due to accessing `value`") { let a = Observable(5) let result = Computed { a.value } var notificationCount = 0 let opts = SubscriptionOptions(notifyOnSubscription: false, when: .afterChange) _ = result.subscribe(opts) { notificationCount += 1 } a.value = 11 expect(result.value) == 11 // let runloop finish so that coalesced update happens RunLoop.main.run(until: Date()) expect(notificationCount) == 1 } it("should not recurse infinitely if the value is accessed in the subscription block") { let a = Observable(5) let result = Computed { a.value } _ = result.subscribe { [weak result] in _ = result?.value // trigger "side effects" in getter } a.value = 11 expect(result.value) == 11 // this test will blow the stack here if it fails } } it("should not collect dependencies for any Subscribables read in its subscriptions") { let shouldNotDependOn = Observable(false) let a = Observable(11) let computed = Computed { a.value } // attempt to introduce a (false) dependency on `shouldNotDependOn` _ = computed.subscribe { _, _ in _ = shouldNotDependOn.value // trigger "side effects" in getter } a.value = 5 // trigger the subscription block var fired = false _ = computed.subscribe(SubscriptionOptions(notifyOnSubscription: false, when: .afterChange)) { _, _ in fired = true } // if a dependency was added, this'll cause `fired` to be set to `true` shouldNotDependOn.value = true expect(fired) == false } } } }
mit
743bd030691199453704d28cf38a968f
38.728571
133
0.523373
5.169145
false
false
false
false
fhchina/ReactiveCocoa
ReactiveCocoa/Swift/Scheduler.swift
70
10349
// // Scheduler.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-06-02. // Copyright (c) 2014 GitHub. All rights reserved. // /// Represents a serial queue of work items. public protocol SchedulerType { /// Enqueues an action on the scheduler. /// /// When the work is executed depends on the scheduler in use. /// /// Optionally returns a disposable that can be used to cancel the work /// before it begins. func schedule(action: () -> ()) -> Disposable? } /// A particular kind of scheduler that supports enqueuing actions at future /// dates. public protocol DateSchedulerType: SchedulerType { /// The current date, as determined by this scheduler. /// /// This can be implemented to deterministic return a known date (e.g., for /// testing purposes). var currentDate: NSDate { get } /// Schedules an action for execution at or after the given date. /// /// Optionally returns a disposable that can be used to cancel the work /// before it begins. func scheduleAfter(date: NSDate, action: () -> ()) -> Disposable? /// Schedules a recurring action at the given interval, beginning at the /// given start time. /// /// Optionally returns a disposable that can be used to cancel the work /// before it begins. func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway: NSTimeInterval, action: () -> ()) -> Disposable? } /// A scheduler that performs all work synchronously. public final class ImmediateScheduler: SchedulerType { public init() {} public func schedule(action: () -> ()) -> Disposable? { action() return nil } } /// A scheduler that performs all work on the main thread, as soon as possible. /// /// If the caller is already running on the main thread when an action is /// scheduled, it may be run synchronously. However, ordering between actions /// will always be preserved. public final class UIScheduler: SchedulerType { private var queueLength: Int32 = 0 public init() {} public func schedule(action: () -> ()) -> Disposable? { let disposable = SimpleDisposable() let actionAndDecrement: () -> () = { if !disposable.disposed { action() } withUnsafeMutablePointer(&self.queueLength, OSAtomicDecrement32) } let queued = withUnsafeMutablePointer(&queueLength, OSAtomicIncrement32) // If we're already running on the main thread, and there isn't work // already enqueued, we can skip scheduling and just execute directly. if NSThread.isMainThread() && queued == 1 { actionAndDecrement() } else { dispatch_async(dispatch_get_main_queue(), actionAndDecrement) } return disposable } } /// A scheduler backed by a serial GCD queue. public final class QueueScheduler: DateSchedulerType { internal let queue: dispatch_queue_t /// A singleton QueueScheduler that always targets the main thread's GCD /// queue. /// /// Unlike UIScheduler, this scheduler supports scheduling for a future /// date, and will always schedule asynchronously (even if already running /// on the main thread). public static let mainQueueScheduler = QueueScheduler(queue: dispatch_get_main_queue(), name: "org.reactivecocoa.ReactiveCocoa.QueueScheduler.mainQueueScheduler") public var currentDate: NSDate { return NSDate() } /// Initializes a scheduler that will target the given queue with its work. /// /// Even if the queue is concurrent, all work items enqueued with the /// QueueScheduler will be serial with respect to each other. public init(queue: dispatch_queue_t, name: String = "org.reactivecocoa.ReactiveCocoa.QueueScheduler") { self.queue = dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL) dispatch_set_target_queue(self.queue, queue) } /// Initializes a scheduler that will target the global queue with the given /// priority. public convenience init(priority: CLong = DISPATCH_QUEUE_PRIORITY_DEFAULT, name: String = "org.reactivecocoa.ReactiveCocoa.QueueScheduler") { self.init(queue: dispatch_get_global_queue(priority, 0), name: name) } public func schedule(action: () -> ()) -> Disposable? { let d = SimpleDisposable() dispatch_async(queue) { if !d.disposed { action() } } return d } private func wallTimeWithDate(date: NSDate) -> dispatch_time_t { var seconds = 0.0 let frac = modf(date.timeIntervalSince1970, &seconds) let nsec: Double = frac * Double(NSEC_PER_SEC) var walltime = timespec(tv_sec: CLong(seconds), tv_nsec: CLong(nsec)) return dispatch_walltime(&walltime, 0) } public func scheduleAfter(date: NSDate, action: () -> ()) -> Disposable? { let d = SimpleDisposable() dispatch_after(wallTimeWithDate(date), queue) { if !d.disposed { action() } } return d } /// Schedules a recurring action at the given interval, beginning at the /// given start time, and with a reasonable default leeway. /// /// Optionally returns a disposable that can be used to cancel the work /// before it begins. public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, action: () -> ()) -> Disposable? { // Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of // at least 10% of the timer interval. return scheduleAfter(date, repeatingEvery: repeatingEvery, withLeeway: repeatingEvery * 0.1, action: action) } public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway leeway: NSTimeInterval, action: () -> ()) -> Disposable? { precondition(repeatingEvery >= 0) precondition(leeway >= 0) let nsecInterval = repeatingEvery * Double(NSEC_PER_SEC) let nsecLeeway = leeway * Double(NSEC_PER_SEC) let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) dispatch_source_set_timer(timer, wallTimeWithDate(date), UInt64(nsecInterval), UInt64(nsecLeeway)) dispatch_source_set_event_handler(timer, action) dispatch_resume(timer) return ActionDisposable { dispatch_source_cancel(timer) } } } /// A scheduler that implements virtualized time, for use in testing. public final class TestScheduler: DateSchedulerType { private final class ScheduledAction { let date: NSDate let action: () -> () init(date: NSDate, action: () -> ()) { self.date = date self.action = action } func less(rhs: ScheduledAction) -> Bool { return date.compare(rhs.date) == .OrderedAscending } } private let lock = NSRecursiveLock() private var _currentDate: NSDate /// The virtual date that the scheduler is currently at. public var currentDate: NSDate { let d: NSDate lock.lock() d = _currentDate lock.unlock() return d } private var scheduledActions: [ScheduledAction] = [] /// Initializes a TestScheduler with the given start date. public init(startDate: NSDate = NSDate(timeIntervalSinceReferenceDate: 0)) { lock.name = "org.reactivecocoa.ReactiveCocoa.TestScheduler" _currentDate = startDate } private func schedule(action: ScheduledAction) -> Disposable { lock.lock() scheduledActions.append(action) scheduledActions.sort { $0.less($1) } lock.unlock() return ActionDisposable { self.lock.lock() self.scheduledActions = self.scheduledActions.filter { $0 !== action } self.lock.unlock() } } public func schedule(action: () -> ()) -> Disposable? { return schedule(ScheduledAction(date: currentDate, action: action)) } /// Schedules an action for execution at or after the given interval /// (counted from `currentDate`). /// /// Optionally returns a disposable that can be used to cancel the work /// before it begins. public func scheduleAfter(interval: NSTimeInterval, action: () -> ()) -> Disposable? { return scheduleAfter(currentDate.dateByAddingTimeInterval(interval), action: action) } public func scheduleAfter(date: NSDate, action: () -> ()) -> Disposable? { return schedule(ScheduledAction(date: date, action: action)) } private func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, disposable: SerialDisposable, action: () -> ()) { precondition(repeatingEvery >= 0) disposable.innerDisposable = scheduleAfter(date) { [unowned self] in action() self.scheduleAfter(date.dateByAddingTimeInterval(repeatingEvery), repeatingEvery: repeatingEvery, disposable: disposable, action: action) } } /// Schedules a recurring action at the given interval, beginning at the /// given interval (counted from `currentDate`). /// /// Optionally returns a disposable that can be used to cancel the work /// before it begins. public func scheduleAfter(interval: NSTimeInterval, repeatingEvery: NSTimeInterval, withLeeway leeway: NSTimeInterval = 0, action: () -> ()) -> Disposable? { return scheduleAfter(currentDate.dateByAddingTimeInterval(interval), repeatingEvery: repeatingEvery, withLeeway: leeway, action: action) } public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway: NSTimeInterval = 0, action: () -> ()) -> Disposable? { let disposable = SerialDisposable() scheduleAfter(date, repeatingEvery: repeatingEvery, disposable: disposable, action: action) return disposable } /// Advances the virtualized clock by an extremely tiny interval, dequeuing /// and executing any actions along the way. /// /// This is intended to be used as a way to execute actions that have been /// scheduled to run as soon as possible. public func advance() { advanceByInterval(DBL_EPSILON) } /// Advances the virtualized clock by the given interval, dequeuing and /// executing any actions along the way. public func advanceByInterval(interval: NSTimeInterval) { lock.lock() advanceToDate(currentDate.dateByAddingTimeInterval(interval)) lock.unlock() } /// Advances the virtualized clock to the given future date, dequeuing and /// executing any actions up until that point. public func advanceToDate(newDate: NSDate) { lock.lock() assert(currentDate.compare(newDate) != .OrderedDescending) _currentDate = newDate while scheduledActions.count > 0 { if newDate.compare(scheduledActions[0].date) == .OrderedAscending { break } let scheduledAction = scheduledActions[0] scheduledActions.removeAtIndex(0) scheduledAction.action() } lock.unlock() } /// Dequeues and executes all scheduled actions, leaving the scheduler's /// date at `NSDate.distantFuture()`. public func run() { advanceToDate(NSDate.distantFuture() as! NSDate) } }
mit
6fc197cbad02fbda64436c9b78048f9d
31.75
163
0.723258
4.060024
false
false
false
false
Senspark/ee-x
src/ios/ee/store/StoreUnityPurchasing.swift
1
17495
// // StoreUnityPurchasing.swift // Pods // // Created by eps on 6/29/20. // import StoreKit internal typealias UnityPurchasingCallback = (_ subject: String, _ payload: String, _ receipt: String, _ transactionId: String) -> Void internal class StoreUnityPurchasing: NSObject, SKProductsRequestDelegate, SKPaymentTransactionObserver { private let _queue = SKPaymentQueue.default() private var _messageCallback: UnityPurchasingCallback? private var _validProducts: [String: SKProduct] = [:] private var _productIds: Set<String>? private var _request: SKProductsRequest? private var _pendingTransactions: [String: SKPaymentTransaction] = [:] private var _finishedTransactions: Set<String> = [] private var _receiptRefresher: StoreReceiptRefresher? private var _refreshRequest: SKReceiptRefreshRequest? private var _simulateAskToBuyEnabled = false private var _delayInSeconds = 2 var messageCallback: UnityPurchasingCallback? { get { return _messageCallback } set(value) { _messageCallback = value } } var simulateAskToBuyEnabled: Bool { get { return _simulateAskToBuyEnabled } set(value) { _simulateAskToBuyEnabled = value } } func getAppReceipt() -> String { let bundle = Bundle.main if let receipUrl = bundle.appStoreReceiptURL { if FileManager.default.fileExists(atPath: receipUrl.path) { do { let receipt = try Data(contentsOf: receipUrl) let result = receipt.base64EncodedString() return result } catch { print("\(#function): \(error.localizedDescription)") } } } print("No App Receipt found") return "" } var canMakePayments: Bool { return SKPaymentQueue.canMakePayments() } private func unitySendMessage(_ subject: String, _ payload: String) { _messageCallback?(subject, payload, "", "") } private func unitySendMessage(_ subject: String, _ payload: String, _ receipt: String) { _messageCallback?(subject, payload, receipt, "") } private func unitySendMessage(_ subject: String, _ payload: String, _ receipt: String, _ transactionId: String) { _messageCallback?(subject, payload, receipt, transactionId) } func refreshReceipt() { let refresher = StoreReceiptRefresher { success in print("\(#function): RefreshReceipt status \(success)") if success { self.unitySendMessage("onAppReceiptRefreshed", self.getAppReceipt()) } else { self.unitySendMessage("onAppReceiptRefreshFailed", "") } } let request = SKReceiptRefreshRequest() request.delegate = refresher request.start() _receiptRefresher = refresher _refreshRequest = request } /// Handle a new or restored purchase transaction by informing Unity. private func onTransactionSucceeded(_ transaction: SKPaymentTransaction) { let transactionId = transaction.transactionIdentifier ?? UUID().uuidString // This transaction was marked as finished, but was not cleared from the queue. // Try to clear it now, then pass the error up the stack as a DuplicateTransaction if _finishedTransactions.contains(transactionId) { _queue.finishTransaction(transaction) let productId = transaction.payment.productIdentifier print("\(#function): DuplicateTransaction error with product \(productId) and transactionId \(transactionId)") onPurchaseFailed(productId, "DuplicateTransaction", "", "Duplicate transaction occurred") return } // Item was successfully purchased or restored. if _pendingTransactions.index(forKey: transactionId) == nil { _pendingTransactions[transactionId] = transaction } unitySendMessage("OnPurchaseSucceeded", transaction.payment.productIdentifier, getAppReceipt(), transactionId) } /// Called back by managed code when the tranaction has been logged. func finishTransaction(_ transactionId: String) { if let transaction = _pendingTransactions[transactionId] { print("\(#function): Finishing transaction \(transactionId)") _queue.finishTransaction(transaction) _pendingTransactions.removeValue(forKey: transactionId) _finishedTransactions.insert(transactionId) } else { print("\(#function): Transaction \(transactionId) not pending, nothing to finish here") } } /// Request information about our products from Apple. func requestProducts(_ paramIds: Set<String>) { _productIds = paramIds print("\(#function): Requesting \(paramIds.count) products") // Start an immediate poll. initiateProductPoll(0) } /// Execute a product metadata retrieval request via GCD. private func initiateProductPoll(_ delayInSeconds: Int) { Thread.runOnMainThreadDelayed(Float(delayInSeconds)) { print("\(#function): Requesting product data...") let request = SKProductsRequest(productIdentifiers: self._productIds ?? []) request.delegate = self request.start() self._request = request } } func purchaseProduct(_ productDefinition: StoreProductDefinition) { if let requestedProduct = _validProducts[productDefinition.storeSpecificId] { print("\(#function): PurchaseProduct: \(requestedProduct.productIdentifier)") if canMakePayments { let payment = SKMutablePayment(product: requestedProduct) // Modify payment request for testing ask-to-buy. if _simulateAskToBuyEnabled { print("\(#function): Queueing payment request with simulatesAskToBuyInSandbox enabled") payment.simulatesAskToBuyInSandbox = true } _queue.add(payment) } else { print("\(#function): PurchaseProduct: IAP Disabled") onPurchaseFailed(productDefinition.storeSpecificId, "PurchasingUnavailable", "SKErrorPaymentNotAllowed", "User is not authorized to make payments") } } else { onPurchaseFailed(productDefinition.storeSpecificId, "ItemUnavailable", "", "Unity IAP could not find requested product") } } /// Initiate a request to Apple to restore previously made purchases. func restorePurchases() { print("\(#function): RestorePurchases") _queue.restoreCompletedTransactions() } /// A transaction observer should be added at startup (by managed code) /// and maintained for the life of the app, since transactions can /// be delivered at any time. func addTransactionObserver() { // Detect whether an existing transaction observer is in place. // An existing observer will have processed any transactions already pending, // so when we add our own storekit will not call our updatedTransactions handler. // We workaround this by explicitly processing any existing transactions if they exist. let processExistingTransactions = _queue.transactions.count > 0 _queue.add(self) if processExistingTransactions { paymentQueue(_queue, updatedTransactions: _queue.transactions) } } /// Store Kit returns a response from an SKProductsRequest. internal func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { print("\(#function): Received \(response.products.count) products") // Add the retrieved products to our set of valid products. let fetchedProducts = Dictionary(uniqueKeysWithValues: zip(response.products.map { $0.productIdentifier }, response.products)) fetchedProducts.forEach { _validProducts[$0] = $1 } let productJson = serializeProductMetadata(response.products) unitySendMessage("OnProductsRetrieved", productJson, getAppReceipt()) } /// A product metadata retrieval request failed. /// We handle it by retrying at an exponentially increasing interval. func request(_ request: SKRequest, didFailWithError error: Error) { _delayInSeconds = min(60, 2 * _delayInSeconds) print(""" \(#function): SKProductRequest::didFailWithError: \(error.localizedDescription). Unity Purchasing will retry in \(_delayInSeconds) seconds """) initiateProductPoll(_delayInSeconds) } func requestDidFinish(_ request: SKRequest) { _request = nil } func onPurchaseFailed(_ productId: String, _ reason: String, _ errorCode: String, _ errorDescription: String) { unitySendMessage("OnPurchaseFailed", EEJsonUtils.convertDictionary(toString: [ "productId": productId, "reason": reason, "storeSpecificErrorCode": errorCode, "message": errorDescription ])) } func purchaseErrorCodeToReason(_ errorCode: Int) -> String { switch errorCode { case SKError.paymentCancelled.rawValue: return "UserCancelled" case SKError.paymentInvalid.rawValue: return "PaymentDeclined" case SKError.paymentNotAllowed.rawValue: return "PurchasingUnavailable" default: return "Unknown" } } func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { print("\(#function): UpdatedTransactions") for transaction in transactions { let productIdentifier = transaction.payment.productIdentifier if _validProducts[productIdentifier] == nil { // FIXME: workaround to fix confliction with soomla. print("\(#function): Ignore invalid product \(productIdentifier)") continue } switch transaction.transactionState { case SKPaymentTransactionState.purchasing: // Item is still in the process of being purchased. break case SKPaymentTransactionState.purchased: onTransactionSucceeded(transaction) case SKPaymentTransactionState.restored: onTransactionSucceeded(transaction) case SKPaymentTransactionState.deferred: print("\(#function): PurchaseDeferred") unitySendMessage("onProductPurchaseDeferred", productIdentifier) case SKPaymentTransactionState.failed: // Purchase was either cancelled by user or an error occurred. let errorCode = (transaction.error as NSError?)?.code ?? -1 print("\(#function): PurchaseFailed: \(errorCode)") let reason = purchaseErrorCodeToReason(errorCode) let errorCodeString = storeKitErrorCodeNames[errorCode] ?? "SKErrorUnknown" let errorDescription = "APPLE_\(transaction.error?.localizedDescription ?? "")" onPurchaseFailed(productIdentifier, reason, errorCodeString, errorDescription) // Finished transactions should be removed from the payment queue. _queue.finishTransaction(transaction) break @unknown default: fatalError() } } } /// Called when one or more transactions have been removed from the queue. func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) { // Nothing to do here. } /// Called when SKPaymentQueue has finished sending restored transactions. func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { print("\(#function): PaymentQueueRestoreCompletedTransactionsFinished") unitySendMessage("onTransactionsRestoredSuccess", "") } /// Called if an error occurred while restoring transactions. func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { print("\(#function): restoreCompletedTransactionsFailedWithError") // Restore was cancelled or an error occurred, so notify user. unitySendMessage("onTransactionsRestoredFail", error.localizedDescription) } func decodeProductDefinition(_ hash: [String: Any]) -> StoreProductDefinition { let product = StoreProductDefinition(hash["id"] as? String ?? "", hash["storeSpecificId"] as? String ?? "", hash["type"] as? Int ?? 0) return product } func deserializeProductDefinitions(_ json: String) -> [StoreProductDefinition] { let hashes = EEJsonUtils.convertString(toArray: json) as? [[String: Any]] ?? [] var result: [StoreProductDefinition] = [] for hash in hashes { result.append(decodeProductDefinition(hash)) } return result } func deserializeProductDefinition(_ json: String) -> StoreProductDefinition { let hash = EEJsonUtils.convertString(toDictionary: json) as? [String: Any] ?? [:] return decodeProductDefinition(hash) } func serializeProductMetadata(_ appleProducts: [SKProduct]) -> String { var hashes: [[String: Any]] = [] for product in appleProducts { var hash: [String: Any] = [:] hash["storeSpecificId"] = product.productIdentifier var metadata: [String: Any] = [:] metadata["localizedPrice"] = product.price metadata["isoCurrencyCode"] = product.priceLocale.currencyCode if let introductoryPrice = product.introductoryPrice { metadata["introductoryPrice"] = introductoryPrice.price metadata["introductoryPriceLocale"] = introductoryPrice.priceLocale.currencyCode metadata["introductoryPriceNumberOfPeriods"] = introductoryPrice.numberOfPeriods metadata["numberOfUnits"] = introductoryPrice.subscriptionPeriod.numberOfUnits metadata["unit"] = introductoryPrice.subscriptionPeriod.unit } else { metadata["introductoryPrice"] = "" metadata["introductoryPriceLocale"] = "" metadata["introductoryPriceNumberOfPeriods"] = "" metadata["numberOfUnits"] = "" metadata["unit"] = "" } if let subscriptionPeriod = product.subscriptionPeriod { metadata["subscriptionNumberOfUnits"] = subscriptionPeriod.numberOfUnits metadata["subscriptionPeriodUnit"] = subscriptionPeriod.unit.rawValue } else { metadata["subscriptionNumberOfUnits"] = "" metadata["subscriptionPeriodUnit"] = "" } let numberFormatter = NumberFormatter() numberFormatter.formatterBehavior = NumberFormatter.Behavior.behavior10_4 numberFormatter.numberStyle = NumberFormatter.Style.currency numberFormatter.locale = product.priceLocale if let formattedString = numberFormatter.string(from: product.price) { metadata["localizedPriceString"] = formattedString } else { print("\(#function): Unable to format a localized price") metadata["localizedPriceString"] = "" } metadata["localizedTitle"] = product.localizedTitle metadata["localizedDescription"] = product.localizedDescription hash["metadata"] = metadata hashes.append(hash) } return EEJsonUtils.convertArray(toString: hashes) } private var storeKitErrorCodeNames: [Int: String] { return [ SKError.unknown.rawValue: "SKErrorUnknown", SKError.clientInvalid.rawValue: "SKErrorClientInvalid", SKError.paymentCancelled.rawValue: "SKErrorPaymentCancelled", SKError.paymentInvalid.rawValue: "SKErrorPaymentInvalid", SKError.paymentNotAllowed.rawValue: "SKErrorPaymentNotAllowed", SKError.storeProductNotAvailable.rawValue: "SKErrorStoreProductNotAvailable", SKError.cloudServicePermissionDenied.rawValue: "SKErrorCloudServicePermissionDenied", SKError.cloudServiceNetworkConnectionFailed.rawValue: "SKErrorCloudServiceNetworkConnectionFailed", SKError.cloudServiceRevoked.rawValue: "SKErrorCloudServiceRevoked" ] } }
mit
fb69b9fe9848a80ad6f564fac6056e3e
43.858974
122
0.621949
5.839453
false
false
false
false
halonsoluis/MiniRev
MiniRev/MiniRev/RateConfig.swift
1
872
// // RateConfig.swift // MiniRev // // Created by Hugo Alonso on 3/18/16. // Copyright © 2016 halonso. All rights reserved. // import Foundation enum RateConfig: String { case App_Store_Rate_URL = "App_Store_Rate_URL", App_Store_URL = "App_Store_URL", AskRateInEveryVersion = "AskRateInEveryVersion", debugMode = "debugMode", shouldAskMoreThanOnce = "shouldAskMoreThanOnce" private static let configFile = "RateConfig" static let data = DataManager(configFile: configFile).data func obtainData() -> String { guard let data = self.dynamicType.data, let value = data[self.rawValue] else { if let value = DataManager(configFile: self.dynamicType.configFile, defaults: true).data?[self.rawValue] { return value } return "" } return value } }
mit
0217ce1ab94f14f2d69ee1f9d78b54e9
27.096774
118
0.636051
4.032407
false
true
false
false
recurly/recurly-client-ios
ContainerApp/ContentView.swift
1
9169
// // ContentView.swift // ContainerApp // // Created by Carlos Landaverde on 14/01/22. // import SwiftUI import RecurlySDK_iOS struct ContentView: View { @State private var currentStatusLabel = "Logs here" // Apple Payment handler instance let paymentHandler = REApplePaymentHandler() var body: some View { ScrollView { /// Components UI VStack(alignment: .center, spacing: 20) { VStack(alignment: .leading) { RECardNumberTextField(placeholder: " Card number") .padding(.bottom, 30) HStack(spacing: 15) { REExpDateTextField(placeholder: "MM/YY") RECVVTextField(placeholder: "CVV") }.padding(.bottom, 3) }.padding(.horizontal, 51) .padding(.vertical, 10) Button { getToken { myToken in print(myToken) currentStatusLabel = myToken } } label: { Text("Subscribe") .fontWeight(.bold) } } /// Inline payment UI VStack(alignment: .center) { RECreditCardInputUI(cardNumberPlaceholder: "Card number", expDatePlaceholder: "MM/YY", cvvPlaceholder: "CVV") .padding(10) Button { getToken { myToken in print("Token: \(myToken)") currentStatusLabel = myToken } } label: { Text("Subscribe") .fontWeight(.bold) }.padding(.bottom, 50) }.padding(.vertical, 50) /// Apple Pay VStack(alignment: .center) { Group { REApplePayButton(action: { getTokenApplePayment { myToken in print("Apple Pay Token: \(myToken)") } }) .padding() .preferredColorScheme(.light) } .previewLayout(.sizeThatFits) } /// Show the current status message or token VStack { Text("Current Status: \(currentStatusLabel)") .lineLimit(nil) } .padding([.top, .bottom], 16) } } // Get token from UI components private func getToken(completion: @escaping (String) ->()) { let billingInfo = REBillingInfo(firstName: "John", lastName: "Doe", address1: "123 Main St", address2: "", company: "CH2", country: "USA", city: "Miami", state: "Florida", postalCode: "33101", phone: "555-555-5555", vatNumber: "", taxIdentifier: "", taxIdentifierType: "") RETokenizationManager.shared.setBillingInfo(billingInfo: billingInfo) RETokenizationManager.shared.getTokenId { tokenId, error in if let errorResponse = error { print(errorResponse.error.message ?? "") currentStatusLabel = errorResponse.error.message ?? "" return } completion(tokenId ?? "") } } // Get token from ApplePay button private func getTokenApplePayment(completion: @escaping (String) -> ()) { // Test items var items = [REApplePayItem]() items.append(REApplePayItem(amountLabel: "Foo", amount: NSDecimalNumber(string: "3.80"))) items.append(REApplePayItem(amountLabel: "Bar", amount: NSDecimalNumber(string: "0.99"))) items.append(REApplePayItem(amountLabel: "Tax", amount: NSDecimalNumber(string: "1.53"))) // Using 'var' instance to change some default properties values var applePayInfo = REApplePayInfo(purchaseItems: items) // Set your verified Apple merchant id here applePayInfo.merchantIdentifier = "merchant.YOUR.ID" applePayInfo.countryCode = "US" applePayInfo.currencyCode = "USD" /// Starting the Apple Pay flow self.paymentHandler.startApplePayment(with: applePayInfo) { (success, token, billingInfo) in if success { /// Token object 'PKPaymentToken' returned by Apple Pay guard let token = token else { return } /// Billing info guard let billingInfo = billingInfo else { return } /// Decode ApplePaymentData from Token let decoder = JSONDecoder() var applePaymentData = REApplePaymentData() do { // This only works with a Sandbox Apple Pay enviroment in real device let applePaymentDataBody = try decoder.decode(REApplePaymentDataBody.self, from: token.paymentData) applePaymentData = REApplePaymentData(paymentData: applePaymentDataBody) } catch { print("Apple Payment Data Error") // Creating a Simulated Data for Apple Pay let paymentDataBody = REApplePaymentDataBody(version: "EC_v1", data: "test", signature: "test", header: REApplePaymentDataHeader(ephemeralPublicKey: "test_public_key", publicKeyHash: "test_public_hash", transactionId: "abc123")) applePaymentData = REApplePaymentData(paymentData: paymentDataBody) } let displayName = token.paymentMethod.displayName ?? "unknown" let network = token.paymentMethod.network?.rawValue ?? "unknown" let type = token.paymentMethod.type.rawValue // Creating Apple Payment Method let applePaymentMethod = REApplePaymentMethod(paymentMethod: REApplePaymentMethodBody(displayName: displayName, network: network, type: "\(type)")) // Creating Billing Info let billingData = REBillingInfo(firstName: billingInfo.name?.givenName ?? String(), lastName: billingInfo.name?.familyName ?? String(), address1: billingInfo.postalAddress?.street ?? String(), address2: "", country: billingInfo.postalAddress?.country ?? String(), city: billingInfo.postalAddress?.city ?? String(), state: billingInfo.postalAddress?.state ?? String(), postalCode: billingInfo.postalAddress?.postalCode ?? String(), taxIdentifier: "", taxIdentifierType: "") RETokenizationManager.shared.setBillingInfo(billingInfo: billingData) RETokenizationManager.shared.setApplePaymentData(applePaymentData: applePaymentData) RETokenizationManager.shared.setApplePaymentMethod(applePaymentMethod: applePaymentMethod) // This method is used to send ApplePay data for Tokenization RETokenizationManager.shared.getApplePayTokenId { tokenId, error in if let errorResponse = error { print(errorResponse.error.message ?? "") currentStatusLabel = errorResponse.error.message ?? "" return } self.currentStatusLabel = tokenId ?? "" completion(tokenId ?? "") } } else { print("Apple Payment Failed") completion("") } } } } // MARK: - UI Preview struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
mit
54d93cbbfb914488f719bb3b1155a463
41.059633
248
0.463627
6.336558
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/BackerDashboardProjects/Views/Cells/BackerDashboardEmptyStateCell.swift
1
3997
import KsApi import Library import Prelude import UIKit internal final class BackerDashboardEmptyStateCell: UITableViewCell, ValueCell { @IBOutlet private var filledHeartIconImageView: UIImageView! @IBOutlet private var messageLabel: UILabel! @IBOutlet private var titleLabel: UILabel! @IBOutlet private var iconImageView: UIImageView! private var isAnimating: Bool = false private let duration = 0.4 private let hiddenHeartAlpha = CGFloat(0.0) private let visibleHeartAlpha = CGFloat(1.0) private let shrunkHeartTransform = CGAffineTransform(scaleX: 0.7, y: 0.7) private let expandedHearTransform = CGAffineTransform(scaleX: 1.0, y: 1.0) internal func configureWith(value: ProfileProjectsType) { switch value { case .backed: self.messageLabel.text = Strings.Pledge_to_your_favorites_then_view_all_the_projects() self.titleLabel.text = Strings.Explore_creative_projects() _ = self.iconImageView |> UIImageView.lens.image .~ UIImage( named: "icon--eye", in: .framework, compatibleWith: nil ) _ = self.filledHeartIconImageView |> UIImageView.lens.isHidden .~ true case .saved: self.messageLabel.text = Strings.Tap_the_heart_on_a_project_to_get_notified() self.titleLabel.text = Strings.No_saved_projects() NotificationCenter.default.addObserver( self, selector: #selector(self.animateToFilledHeart), name: .ksr_savedProjectEmptyStateTapped, object: nil ) self.animateToFilledHeart() } } @objc internal func animateToFilledHeart() { guard self.isAnimating == false else { return } UIView.animate( withDuration: self.duration, delay: 1.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .curveEaseInOut, animations: { [weak self] in guard let _self = self else { return } _self.isAnimating = true _self.filledHeartIconImageView.alpha = _self.hiddenHeartAlpha _self.iconImageView.alpha = _self.hiddenHeartAlpha _self.iconImageView.transform = _self.shrunkHeartTransform _self.filledHeartIconImageView.transform = _self.expandedHearTransform _self.filledHeartIconImageView.alpha = _self.visibleHeartAlpha }, completion: { [weak self] _ in guard let _self = self else { return } _self.animateToOutlineHeart() } ) } internal func animateToOutlineHeart() { UIView.animate( withDuration: self.duration, delay: 0.6, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .curveEaseInOut, animations: { [weak self] in guard let _self = self else { return } _self.filledHeartIconImageView.alpha = _self.hiddenHeartAlpha _self.iconImageView.alpha = _self.hiddenHeartAlpha _self.filledHeartIconImageView.transform = _self.shrunkHeartTransform _self.iconImageView.transform = _self.expandedHearTransform _self.iconImageView.alpha = _self.visibleHeartAlpha }, completion: { [weak self] _ in guard let _self = self else { return } _self.isAnimating = false } ) } internal override func bindStyles() { super.bindStyles() _ = self |> baseTableViewCellStyle() |> UITableViewCell.lens.contentView.layoutMargins %~~ { _, cell in cell.traitCollection.isRegularRegular ? .init(topBottom: Styles.grid(4), leftRight: Styles.grid(20)) : .init(topBottom: Styles.grid(10), leftRight: Styles.grid(3)) } _ = self.messageLabel |> UILabel.lens.textColor .~ .ksr_support_400 |> UILabel.lens.font .~ UIFont.ksr_body(size: 15.0) _ = self.titleLabel |> UILabel.lens.textColor .~ .ksr_support_700 |> UILabel.lens.font .~ UIFont.ksr_headline(size: 21.0) _ = self.iconImageView |> UIImageView.lens.tintColor .~ .ksr_support_700 } }
apache-2.0
d79722d244d5a15b55370d45592352ce
32.033058
92
0.66675
4.274866
false
false
false
false
remobjects/ElementsSamples
Silver/Island/GUI/Basic Windows GUI App/Program.swift
1
3677
import rtl class Program { static let szTitle: LPCWSTR = "RemObjects Elements — Island Windows Sample" static let szWindowClass: LPCWSTR = "IslandWindowsSample" static var button: HWND = nil @CallingConvention(CallingConvention.Stdcall) static func WndProc(_ hWnd: HWND, _ message: UINT, _ wParam: WPARAM, _ lParam: LPARAM) -> Integer { switch message { case WM_COMMAND: if wParam == BN_CLICKED && lParam == button as! rtl.LPARAM { MessageBox(hWnd, "You clicked, hello there!", szTitle, 0) } case WM_CLOSE: PostQuitMessage(0) default: } return DefWindowProc(hWnd, message, wParam, lParam) } static func SetupWindow() -> Bool { // // Set up and Register the Windows Class // var windowClass: WNDCLASSEX windowClass.cbSize = sizeOf(WNDCLASSEX) windowClass.style = CS_HREDRAW | CS_VREDRAW windowClass.lpfnWndProc = WndProc windowClass.cbClsExtra = 0 windowClass.cbWndExtra = 0 windowClass.hInstance = rtl.GetModuleHandleW(nil) windowClass.hIcon = LoadIcon(windowClass.hInstance, IDI_APPLICATION as! LPCWSTR) windowClass.hCursor = LoadCursor(nil, IDC_ARROW as! LPCWSTR) windowClass.hbrBackground = (COLOR_WINDOW + 1) as! HBRUSH windowClass.lpszMenuName = nil windowClass.lpszClassName = szWindowClass if RegisterClassEx(&windowClass) == 0 { MessageBox(nil, "Call to RegisterClassEx failed", szTitle, 0) return false } // // Create the Window // var window = CreateWindowExW(0, szWindowClass, szTitle, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 400, 300, nil, nil, windowClass.hInstance, nil) if window == nil { MessageBox(nil, "Call to CreateWindowExW failed", szTitle, 0) return false } // // Add a button to it // button = CreateWindowEx(0, "BUTTON", // Predefined class Unicode assumed "Click Me", // Button text WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles 130, // x position 70, // y position 100, // Button width 25, // Button height window, // Parent window nil, // No menu. windowClass.hInstance, nil) // Pointer not needed. // // Show the Window // ShowWindow(window, SW_SHOW) UpdateWindow(window) return true } } if !Program.SetupWindow() { return -1 } // // Finally, run the main Windows message loop // var msg: MSG = `default`(MSG) while GetMessage((&msg), nil, 0, 0) { TranslateMessage(&msg) DispatchMessage(&msg) } return msg.wParam
mit
07d72b49f9591e892a4eb16cb1b20fa6
31.715596
103
0.463654
4.512285
false
false
false
false
WhisperSystems/Signal-iOS
Signal/src/ViewControllers/ConversationView/Cells/MediaAlbumCellView.swift
1
10667
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation @objc(OWSMediaAlbumCellView) public class MediaAlbumCellView: UIStackView { private let items: [ConversationMediaAlbumItem] @objc public let itemViews: [ConversationMediaView] @objc public var moreItemsView: ConversationMediaView? private static let kSpacingPts: CGFloat = 2 private static let kMaxItems = 5 @available(*, unavailable, message: "use other init() instead.") required public init(coder aDecoder: NSCoder) { notImplemented() } @objc public required init(mediaCache: NSCache<NSString, AnyObject>, items: [ConversationMediaAlbumItem], isOutgoing: Bool, maxMessageWidth: CGFloat) { self.items = items self.itemViews = MediaAlbumCellView.itemsToDisplay(forItems: items).map { ConversationMediaView(mediaCache: mediaCache, attachment: $0.attachment, isOutgoing: isOutgoing, maxMessageWidth: maxMessageWidth) } super.init(frame: .zero) // UIStackView's backgroundColor property has no effect. addBackgroundView(withBackgroundColor: Theme.backgroundColor) createContents(maxMessageWidth: maxMessageWidth) } private func createContents(maxMessageWidth: CGFloat) { switch itemViews.count { case 0: owsFailDebug("No item views.") return case 1: // X guard let itemView = itemViews.first else { owsFailDebug("Missing item view.") return } addSubview(itemView) itemView.autoPinEdgesToSuperviewEdges() case 2: // X X // side-by-side. let imageSize = (maxMessageWidth - MediaAlbumCellView.kSpacingPts) / 2 autoSet(viewSize: imageSize, ofViews: itemViews) for itemView in itemViews { addArrangedSubview(itemView) } self.axis = .horizontal self.spacing = MediaAlbumCellView.kSpacingPts case 3: // x // X x // Big on left, 2 small on right. let smallImageSize = (maxMessageWidth - MediaAlbumCellView.kSpacingPts * 2) / 3 let bigImageSize = smallImageSize * 2 + MediaAlbumCellView.kSpacingPts guard let leftItemView = itemViews.first else { owsFailDebug("Missing view") return } autoSet(viewSize: bigImageSize, ofViews: [leftItemView]) addArrangedSubview(leftItemView) let rightViews = Array(itemViews[1..<3]) addArrangedSubview(newRow(rowViews: rightViews, axis: .vertical, viewSize: smallImageSize)) self.axis = .horizontal self.spacing = MediaAlbumCellView.kSpacingPts case 4: // X X // X X // Square let imageSize = (maxMessageWidth - MediaAlbumCellView.kSpacingPts) / 2 let topViews = Array(itemViews[0..<2]) addArrangedSubview(newRow(rowViews: topViews, axis: .horizontal, viewSize: imageSize)) let bottomViews = Array(itemViews[2..<4]) addArrangedSubview(newRow(rowViews: bottomViews, axis: .horizontal, viewSize: imageSize)) self.axis = .vertical self.spacing = MediaAlbumCellView.kSpacingPts default: // X X // xxx // 2 big on top, 3 small on bottom. let bigImageSize = (maxMessageWidth - MediaAlbumCellView.kSpacingPts) / 2 let smallImageSize = (maxMessageWidth - MediaAlbumCellView.kSpacingPts * 2) / 3 let topViews = Array(itemViews[0..<2]) addArrangedSubview(newRow(rowViews: topViews, axis: .horizontal, viewSize: bigImageSize)) let bottomViews = Array(itemViews[2..<5]) addArrangedSubview(newRow(rowViews: bottomViews, axis: .horizontal, viewSize: smallImageSize)) self.axis = .vertical self.spacing = MediaAlbumCellView.kSpacingPts if items.count > MediaAlbumCellView.kMaxItems { guard let lastView = bottomViews.last else { owsFailDebug("Missing lastView") return } moreItemsView = lastView let tintView = UIView() tintView.backgroundColor = UIColor(white: 0, alpha: 0.4) lastView.addSubview(tintView) tintView.autoPinEdgesToSuperviewEdges() let moreCount = max(1, items.count - MediaAlbumCellView.kMaxItems) let moreCountText = OWSFormat.formatInt(Int32(moreCount)) let moreText = String(format: NSLocalizedString("MEDIA_GALLERY_MORE_ITEMS_FORMAT", comment: "Format for the 'more items' indicator for media galleries. Embeds {{the number of additional items}}."), moreCountText) let moreLabel = UILabel() moreLabel.text = moreText moreLabel.textColor = UIColor.ows_white // We don't want to use dynamic text here. moreLabel.font = UIFont.systemFont(ofSize: 24) lastView.addSubview(moreLabel) moreLabel.autoCenterInSuperview() } } for itemView in itemViews { guard moreItemsView != itemView else { // Don't display the caption indicator on // the "more" item, if any. continue } guard let index = itemViews.firstIndex(of: itemView) else { owsFailDebug("Couldn't determine index of item view.") continue } let item = items[index] guard let caption = item.caption else { continue } guard caption.count > 0 else { continue } guard let icon = UIImage(named: "media_album_caption") else { owsFailDebug("Couldn't load icon.") continue } let iconView = UIImageView(image: icon) itemView.addSubview(iconView) itemView.layoutMargins = .zero iconView.autoPinTopToSuperviewMargin(withInset: 6) iconView.autoPinLeadingToSuperviewMargin(withInset: 6) } } private func autoSet(viewSize: CGFloat, ofViews views: [ConversationMediaView]) { for itemView in views { itemView.autoSetDimensions(to: CGSize(width: viewSize, height: viewSize)) } } private func newRow(rowViews: [ConversationMediaView], axis: NSLayoutConstraint.Axis, viewSize: CGFloat) -> UIStackView { autoSet(viewSize: viewSize, ofViews: rowViews) return newRow(rowViews: rowViews, axis: axis) } private func newRow(rowViews: [ConversationMediaView], axis: NSLayoutConstraint.Axis) -> UIStackView { let stackView = UIStackView(arrangedSubviews: rowViews) stackView.axis = axis stackView.spacing = MediaAlbumCellView.kSpacingPts return stackView } @objc public func loadMedia() { for itemView in itemViews { itemView.loadMedia() } } @objc public func unloadMedia() { for itemView in itemViews { itemView.unloadMedia() } } private class func itemsToDisplay(forItems items: [ConversationMediaAlbumItem]) -> [ConversationMediaAlbumItem] { // TODO: Unless design changes, we want to display // items which are still downloading and invalid // items. let validItems = items guard validItems.count < kMaxItems else { return Array(validItems[0..<kMaxItems]) } return validItems } @objc public class func layoutSize(forMaxMessageWidth maxMessageWidth: CGFloat, items: [ConversationMediaAlbumItem]) -> CGSize { let itemCount = itemsToDisplay(forItems: items).count switch itemCount { case 0, 1, 4: // X // // or // // XX // XX // Square return CGSize(width: maxMessageWidth, height: maxMessageWidth) case 2: // X X // side-by-side. let imageSize = (maxMessageWidth - kSpacingPts) / 2 return CGSize(width: maxMessageWidth, height: imageSize) case 3: // x // X x // Big on left, 2 small on right. let smallImageSize = (maxMessageWidth - kSpacingPts * 2) / 3 let bigImageSize = smallImageSize * 2 + kSpacingPts return CGSize(width: maxMessageWidth, height: bigImageSize) default: // X X // xxx // 2 big on top, 3 small on bottom. let bigImageSize = (maxMessageWidth - kSpacingPts) / 2 let smallImageSize = (maxMessageWidth - kSpacingPts * 2) / 3 return CGSize(width: maxMessageWidth, height: bigImageSize + smallImageSize + kSpacingPts) } } @objc public func mediaView(forLocation location: CGPoint) -> ConversationMediaView? { var bestMediaView: ConversationMediaView? var bestDistance: CGFloat = 0 for itemView in itemViews { let itemCenter = convert(itemView.center, from: itemView.superview) let distance = CGPointDistance(location, itemCenter) if bestMediaView != nil && distance > bestDistance { continue } bestMediaView = itemView bestDistance = distance } return bestMediaView } @objc public func isMoreItemsView(mediaView: ConversationMediaView) -> Bool { return moreItemsView == mediaView } }
gpl-3.0
a031cce4c25996e61490fa6bf66a4685
36.297203
193
0.552358
5.384654
false
false
false
false
shahmishal/swift
test/IRGen/associated_types.swift
1
4564
// RUN: %target-swift-frontend -emit-ir -primary-file %s | %FileCheck %s -DINT=i%target-ptrsize // REQUIRES: CPU=i386 || CPU=x86_64 protocol Runcer { associatedtype Runcee } protocol Runcible { associatedtype RuncerType : Runcer associatedtype AltRuncerType : Runcer } struct Mince {} struct Quince : Runcer { typealias Runcee = Mince } struct Spoon : Runcible { typealias RuncerType = Quince typealias AltRuncerType = Quince } struct Owl<T : Runcible, U> { // CHECK: define hidden swiftcc void @"$s16associated_types3OwlV3eat{{[_0-9a-zA-Z]*}}F"(%swift.opaque* func eat(_ what: T.RuncerType.Runcee, and: T.RuncerType, with: T) { } } class Pussycat<T : Runcible, U> { init() {} // CHECK: define hidden swiftcc void @"$s16associated_types8PussycatC3eat{{[_0-9a-zA-Z]*}}F"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %T16associated_types8PussycatC* swiftself) func eat(_ what: T.RuncerType.Runcee, and: T.RuncerType, with: T) { } } func owl() -> Owl<Spoon, Int> { return Owl() } func owl2() { Owl<Spoon, Int>().eat(Mince(), and: Quince(), with: Spoon()) } func pussycat() -> Pussycat<Spoon, Int> { return Pussycat() } func pussycat2() { Pussycat<Spoon, Int>().eat(Mince(), and: Quince(), with: Spoon()) } protocol Speedy { static func accelerate() } protocol FastRuncer { associatedtype Runcee : Speedy } protocol FastRuncible { associatedtype RuncerType : FastRuncer } // This is a complex example demonstrating the need to pull conformance // information for archetypes from all paths to that archetype, not just // its parent relationships. func testFastRuncible<T: Runcible, U: FastRuncible>(_ t: T, u: U) where T.RuncerType == U.RuncerType { U.RuncerType.Runcee.accelerate() } // CHECK: define hidden swiftcc void @"$s16associated_types16testFastRuncible_1uyx_q_tAA0E0RzAA0dE0R_10RuncerTypeQy_AFRtzr0_lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.Runcible, i8** %U.FastRuncible) {{.*}} { // 1. Get the type metadata for U.RuncerType.Runcee. // 1a. Get the type metadata for U.RuncerType. // Note that we actually look things up in T, which is going to prove unfortunate. // CHECK: [[T2:%.*]] = call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %T.Runcible, %swift.type* %T, %swift.protocol_requirement* getelementptr{{.*}}i32 12), i32 -1), %swift.protocol_requirement* getelementptr inbounds (<{{.*}}>, <{{.*}}>* @"$s16associated_types8RuncibleMp", i32 0, i32 14)) [[NOUNWIND_READNONE:#.*]] // CHECK-NEXT: %T.RuncerType = extractvalue %swift.metadata_response [[T2]], 0 // 2. Get the witness table for U.RuncerType.Runcee : Speedy // 2a. Get the protocol witness table for U.RuncerType : FastRuncer. // CHECK-NEXT: %T.RuncerType.FastRuncer = call swiftcc i8** @swift_getAssociatedConformanceWitness(i8** %U.FastRuncible, %swift.type* %U, %swift.type* %T.RuncerType // 1c. Get the type metadata for U.RuncerType.Runcee. // CHECK-NEXT: [[T2:%.*]] = call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %T.RuncerType.FastRuncer, %swift.type* %T.RuncerType, {{.*}}, %swift.protocol_requirement* getelementptr inbounds (<{{.*}}>, <{{.*}}>* @"$s16associated_types10FastRuncerMp", i32 0, i32 10)) // CHECK-NEXT: %T.RuncerType.Runcee = extractvalue %swift.metadata_response [[T2]], 0 // 2b. Get the witness table for U.RuncerType.Runcee : Speedy. // CHECK-NEXT: %T.RuncerType.Runcee.Speedy = call swiftcc i8** @swift_getAssociatedConformanceWitness(i8** %T.RuncerType.FastRuncer, %swift.type* %T.RuncerType, %swift.type* %T.RuncerType.Runcee // 3. Perform the actual call. // CHECK-NEXT: [[T0_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.RuncerType.Runcee.Speedy, i32 1 // CHECK-NEXT: [[T0:%.*]] = load i8*, i8** [[T0_GEP]] // CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to void (%swift.type*, %swift.type*, i8**)* // CHECK-NEXT: call swiftcc void [[T1]](%swift.type* swiftself %T.RuncerType.Runcee, %swift.type* %T.RuncerType.Runcee, i8** %T.RuncerType.Runcee.Speedy) public protocol P0 { associatedtype ErrorType : Swift.Error } public struct P0Impl : P0 { public typealias ErrorType = Swift.Error } // CHECK: define{{.*}} swiftcc i8** @"$s16associated_types6P0ImplVAA0C0AA9ErrorTypeAaDP_s0E0PWT"(%swift.type* %P0Impl.ErrorType, %swift.type* %P0Impl, i8** %P0Impl.P0) // CHECK: ret i8** @"$ss5ErrorWS" // CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone }
apache-2.0
3ec417f6067eed29ac0438981c07831f
42.056604
355
0.698291
3.358352
false
false
false
false
guoc/spi
SPiKeyboard/TastyImitationKeyboard/KeyboardLayout.swift
1
45271
// // KeyboardLayout.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/25/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit // TODO: need to rename, consolidate, and define terms class LayoutConstants: NSObject { class var landscapeRatio: CGFloat { get { return 2 }} // side edges increase on 6 in portrait class var sideEdgesPortraitArray: [CGFloat] { get { return [3, 4] }} class var sideEdgesPortraitWidthThreshholds: [CGFloat] { get { return [400] }} class var sideEdgesLandscape: CGFloat { get { return 3 }} // top edges decrease on various devices in portrait class var topEdgePortraitArray: [CGFloat] { get { return [12, 10, 8] }} class var topEdgePortraitWidthThreshholds: [CGFloat] { get { return [350, 400] }} class var topEdgeLandscape: CGFloat { get { return 6 }} // keyboard area shrinks in size in landscape on 6 and 6+ class var keyboardShrunkSizeArray: [CGFloat] { get { return [522, 524] }} class var keyboardShrunkSizeWidthThreshholds: [CGFloat] { get { return [700] }} class var keyboardShrunkSizeBaseWidthThreshhold: CGFloat { get { return 600 }} // row gaps are weird on 6 in portrait class var rowGapPortraitArray: [CGFloat] { get { return [15, 11, 10] }} class var rowGapPortraitThreshholds: [CGFloat] { get { return [350, 400] }} class var rowGapPortraitLastRow: CGFloat { get { return 9 }} class var rowGapPortraitLastRowIndex: Int { get { return 1 }} class var rowGapLandscape: CGFloat { get { return 7 }} // key gaps have weird and inconsistent rules class var keyGapPortraitNormal: CGFloat { get { return 6 }} class var keyGapPortraitSmall: CGFloat { get { return 5 }} class var keyGapPortraitNormalThreshhold: CGFloat { get { return 350 }} class var keyGapPortraitUncompressThreshhold: CGFloat { get { return 350 }} class var keyGapLandscapeNormal: CGFloat { get { return 6 }} class var keyGapLandscapeSmall: CGFloat { get { return 5 }} // TODO: 5.5 row gap on 5L // TODO: wider row gap on 6L class var keyCompressedThreshhold: Int { get { return 11 }} // rows with two special keys on the side and characters in the middle (usually 3rd row) // TODO: these are not pixel-perfect, but should be correct within a few pixels // TODO: are there any "hidden constants" that would allow us to get rid of the multiplier? see: popup dimensions class var flexibleEndRowTotalWidthToKeyWidthMPortrait: CGFloat { get { return 1 }} class var flexibleEndRowTotalWidthToKeyWidthCPortrait: CGFloat { get { return -14 }} class var flexibleEndRowTotalWidthToKeyWidthMLandscape: CGFloat { get { return 0.9231 }} class var flexibleEndRowTotalWidthToKeyWidthCLandscape: CGFloat { get { return -9.4615 }} class var flexibleEndRowMinimumStandardCharacterWidth: CGFloat { get { return 7 }} class var lastRowKeyGapPortrait: CGFloat { get { return 6 }} class var lastRowKeyGapLandscapeArray: [CGFloat] { get { return [8, 7, 5] }} class var lastRowKeyGapLandscapeWidthThreshholds: [CGFloat] { get { return [500, 700] }} // TODO: approxmiate, but close enough class var lastRowPortraitFirstTwoButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.24 }} class var lastRowLandscapeFirstTwoButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.19 }} class var lastRowPortraitLastButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.24 }} class var lastRowLandscapeLastButtonAreaWidthToKeyboardAreaWidth: CGFloat { get { return 0.19 }} class var micButtonPortraitWidthRatioToOtherSpecialButtons: CGFloat { get { return 0.765 }} // TODO: not exactly precise class var popupGap: CGFloat { get { return 8 }} class var popupWidthIncrement: CGFloat { get { return 26 }} class var popupTotalHeightArray: [CGFloat] { get { return [102, 108] }} class var popupTotalHeightDeviceWidthThreshholds: [CGFloat] { get { return [350] }} class func sideEdgesPortrait(_ width: CGFloat) -> CGFloat { return self.findThreshhold(self.sideEdgesPortraitArray, threshholds: self.sideEdgesPortraitWidthThreshholds, measurement: width) } class func topEdgePortrait(_ width: CGFloat) -> CGFloat { return self.findThreshhold(self.topEdgePortraitArray, threshholds: self.topEdgePortraitWidthThreshholds, measurement: width) } class func rowGapPortrait(_ width: CGFloat) -> CGFloat { return self.findThreshhold(self.rowGapPortraitArray, threshholds: self.rowGapPortraitThreshholds, measurement: width) } class func rowGapPortraitLastRow(_ width: CGFloat) -> CGFloat { let index = self.findThreshholdIndex(self.rowGapPortraitThreshholds, measurement: width) if index == self.rowGapPortraitLastRowIndex { return self.rowGapPortraitLastRow } else { return self.rowGapPortraitArray[index] } } class func keyGapPortrait(_ width: CGFloat, rowCharacterCount: Int) -> CGFloat { let compressed = (rowCharacterCount >= self.keyCompressedThreshhold) if compressed { if width >= self.keyGapPortraitUncompressThreshhold { return self.keyGapPortraitNormal } else { return self.keyGapPortraitSmall } } else { return self.keyGapPortraitNormal } } class func keyGapLandscape(_ width: CGFloat, rowCharacterCount: Int) -> CGFloat { let compressed = (rowCharacterCount >= self.keyCompressedThreshhold) let shrunk = self.keyboardIsShrunk(width) if compressed || shrunk { return self.keyGapLandscapeSmall } else { return self.keyGapLandscapeNormal } } class func lastRowKeyGapLandscape(_ width: CGFloat) -> CGFloat { return self.findThreshhold(self.lastRowKeyGapLandscapeArray, threshholds: self.lastRowKeyGapLandscapeWidthThreshholds, measurement: width) } class func keyboardIsShrunk(_ width: CGFloat) -> Bool { let isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad return (isPad ? false : width >= self.keyboardShrunkSizeBaseWidthThreshhold) } class func keyboardShrunkSize(_ width: CGFloat) -> CGFloat { let isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad if isPad { return width } if width >= self.keyboardShrunkSizeBaseWidthThreshhold { return self.findThreshhold(self.keyboardShrunkSizeArray, threshholds: self.keyboardShrunkSizeWidthThreshholds, measurement: width) } else { return width } } class func popupTotalHeight(_ deviceWidth: CGFloat) -> CGFloat { return self.findThreshhold(self.popupTotalHeightArray, threshholds: self.popupTotalHeightDeviceWidthThreshholds, measurement: deviceWidth) } class func findThreshhold(_ elements: [CGFloat], threshholds: [CGFloat], measurement: CGFloat) -> CGFloat { assert(elements.count == threshholds.count + 1, "elements and threshholds do not match") return elements[self.findThreshholdIndex(threshholds, measurement: measurement)] } class func findThreshholdIndex(_ threshholds: [CGFloat], measurement: CGFloat) -> Int { for (i, threshhold) in Array(threshholds.reversed()).enumerated() { if measurement >= threshhold { let actualIndex = threshholds.count - i return actualIndex } } return 0 } } class GlobalColors: NSObject { class var lightModeRegularKey: UIColor { get { return UIColor.white }} class var darkModeRegularKey: UIColor { get { return UIColor.white.withAlphaComponent(CGFloat(0.3)) }} class var darkModeSolidColorRegularKey: UIColor { get { return UIColor(red: CGFloat(83)/CGFloat(255), green: CGFloat(83)/CGFloat(255), blue: CGFloat(83)/CGFloat(255), alpha: 1) }} class var lightModeSpecialKey: UIColor { get { return GlobalColors.lightModeSolidColorSpecialKey }} class var lightModeSolidColorSpecialKey: UIColor { get { return UIColor(red: CGFloat(167)/CGFloat(255), green: CGFloat(176)/CGFloat(255), blue: CGFloat(187)/CGFloat(255), alpha: 1) }} class var darkModeSpecialKey: UIColor { get { return UIColor.gray.withAlphaComponent(CGFloat(0.3)) }} class var darkModeSolidColorSpecialKey: UIColor { get { return UIColor(red: CGFloat(45)/CGFloat(255), green: CGFloat(45)/CGFloat(255), blue: CGFloat(45)/CGFloat(255), alpha: 1) }} class var darkModeShiftKeyDown: UIColor { get { return UIColor(red: CGFloat(214)/CGFloat(255), green: CGFloat(220)/CGFloat(255), blue: CGFloat(208)/CGFloat(255), alpha: 1) }} class var lightModePopup: UIColor { get { return GlobalColors.lightModeRegularKey }} class var darkModePopup: UIColor { get { return UIColor.gray }} class var darkModeSolidColorPopup: UIColor { get { return GlobalColors.darkModeSolidColorRegularKey }} class var lightModeUnderColor: UIColor { get { return UIColor(hue: (220/360.0), saturation: 0.04, brightness: 0.56, alpha: 1) }} class var darkModeUnderColor: UIColor { get { return UIColor(red: CGFloat(38.6)/CGFloat(255), green: CGFloat(18)/CGFloat(255), blue: CGFloat(39.3)/CGFloat(255), alpha: 0.4) }} class var lightModeTextColor: UIColor { get { return UIColor.black }} class var darkModeTextColor: UIColor { get { return UIColor.white }} class var lightModeBorderColor: UIColor { get { return UIColor(hue: (214/360.0), saturation: 0.04, brightness: 0.65, alpha: 1.0) }} class var darkModeBorderColor: UIColor { get { return UIColor.clear }} class func regularKey(_ darkMode: Bool, solidColorMode: Bool) -> UIColor { if darkMode { if solidColorMode { return self.darkModeSolidColorRegularKey } else { return self.darkModeRegularKey } } else { return self.lightModeRegularKey } } class func popup(_ darkMode: Bool, solidColorMode: Bool) -> UIColor { if darkMode { if solidColorMode { return self.darkModeSolidColorPopup } else { return self.darkModePopup } } else { return self.lightModePopup } } class func specialKey(_ darkMode: Bool, solidColorMode: Bool) -> UIColor { if darkMode { if solidColorMode { return self.darkModeSolidColorSpecialKey } else { return self.darkModeSpecialKey } } else { if solidColorMode { return self.lightModeSolidColorSpecialKey } else { return self.lightModeSpecialKey } } } } //"darkShadowColor": UIColor(hue: (220/360.0), saturation: 0.04, brightness: 0.56, alpha: 1), //"blueColor": UIColor(hue: (211/360.0), saturation: 1.0, brightness: 1.0, alpha: 1), //"blueShadowColor": UIColor(hue: (216/360.0), saturation: 0.05, brightness: 0.43, alpha: 1), extension CGRect: Hashable { public var hashValue: Int { get { return (origin.x.hashValue ^ origin.y.hashValue ^ size.width.hashValue ^ size.height.hashValue) } } } extension CGSize: Hashable { public var hashValue: Int { get { return (width.hashValue ^ height.hashValue) } } } // handles the layout for the keyboard, including key spacing and arrangement class KeyboardLayout: NSObject, KeyboardKeyProtocol { class var shouldPoolKeys: Bool { get { return true }} var layoutConstants: LayoutConstants.Type var globalColors: GlobalColors.Type unowned var model: Keyboard unowned var superview: UIView var modelToView: [Key:KeyboardKey] = [:] var viewToModel: [KeyboardKey:Key] = [:] var keyPool: [KeyboardKey] = [] var nonPooledMap: [String:KeyboardKey] = [:] var sizeToKeyMap: [CGSize:[KeyboardKey]] = [:] var shapePool: [String:Shape] = [:] var darkMode: Bool var solidColorMode: Bool var initialized: Bool required init(model: Keyboard, superview: UIView, layoutConstants: LayoutConstants.Type, globalColors: GlobalColors.Type, darkMode: Bool, solidColorMode: Bool) { self.layoutConstants = layoutConstants self.globalColors = globalColors self.initialized = false self.model = model self.superview = superview self.darkMode = darkMode self.solidColorMode = solidColorMode } // TODO: remove this method func initialize() { assert(!self.initialized, "already initialized") self.initialized = true } func viewForKey(_ model: Key) -> KeyboardKey? { return self.modelToView[model] } func keyForView(_ key: KeyboardKey) -> Key? { return self.viewToModel[key] } ////////////////////////////////////////////// // CALL THESE FOR LAYOUT/APPEARANCE CHANGES // ////////////////////////////////////////////// func layoutKeys(_ pageNum: Int, uppercase: Bool, characterUppercase: Bool, shiftState: ShiftState) { CATransaction.begin() CATransaction.setDisableActions(true) // pre-allocate all keys if no cache if !type(of: self).shouldPoolKeys { if self.keyPool.isEmpty { for p in 0..<self.model.pages.count { self.positionKeys(p) } self.updateKeyAppearance() self.updateKeyCaps(true, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: shiftState) } } self.positionKeys(pageNum) // reset state for (p, page) in self.model.pages.enumerated() { for (_, row) in page.rows.enumerated() { for (_, key) in row.enumerated() { if let keyView = self.modelToView[key] { keyView.hidePopup() keyView.isHighlighted = false keyView.isHidden = (p != pageNum) } } } } if type(of: self).shouldPoolKeys { self.updateKeyAppearance() self.updateKeyCaps(true, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: shiftState) } CATransaction.commit() } func positionKeys(_ pageNum: Int) { CATransaction.begin() CATransaction.setDisableActions(true) let setupKey = { (view: KeyboardKey, model: Key, frame: CGRect) -> Void in view.frame = frame self.modelToView[model] = view self.viewToModel[view] = model } if var keyMap = self.generateKeyFrames(self.model, bounds: self.superview.bounds, page: pageNum) { if type(of: self).shouldPoolKeys { self.modelToView.removeAll(keepingCapacity: true) self.viewToModel.removeAll(keepingCapacity: true) self.resetKeyPool() var foundCachedKeys = [Key]() // pass 1: reuse any keys that match the required size for (key, frame) in keyMap { if let keyView = self.pooledKey(key: key, model: self.model, frame: frame) { foundCachedKeys.append(key) setupKey(keyView, key, frame) } } for key in foundCachedKeys { keyMap.removeValue(forKey: key) } // pass 2: fill in the blanks for (key, frame) in keyMap { let keyView = self.generateKey() setupKey(keyView, key, frame) } } else { for (key, frame) in keyMap { if let keyView = self.pooledKey(key: key, model: self.model, frame: frame) { setupKey(keyView, key, frame) } } } } CATransaction.commit() } func updateKeyAppearance() { CATransaction.begin() CATransaction.setDisableActions(true) for (key, view) in self.modelToView { self.setAppearanceForKey(view, model: key, darkMode: self.darkMode, solidColorMode: self.solidColorMode) } CATransaction.commit() } // on fullReset, we update the keys with shapes, images, etc. as if from scratch; otherwise, just update the text // WARNING: if key cache is disabled, DO NOT CALL WITH fullReset MORE THAN ONCE func updateKeyCaps(_ fullReset: Bool, uppercase: Bool, characterUppercase: Bool, shiftState: ShiftState) { CATransaction.begin() CATransaction.setDisableActions(true) if fullReset { for (_, key) in self.modelToView { key.shape = nil if let imageKey = key as? ImageKey { // TODO: imageKey.image = nil } } } for (model, key) in self.modelToView { self.updateKeyCap(key, model: model, fullReset: fullReset, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: shiftState) } CATransaction.commit() } func updateKeyCap(_ key: KeyboardKey, model: Key, fullReset: Bool, uppercase: Bool, characterUppercase: Bool, shiftState: ShiftState) { if fullReset { // font size switch model.type { case Key.KeyType.modeChange, Key.KeyType.space, Key.KeyType.return: key.label.adjustsFontSizeToFitWidth = true key.label.font = key.label.font.withSize(16) default: key.label.font = key.label.font.withSize(22) } // label inset switch model.type { case Key.KeyType.modeChange: key.labelInset = 3 default: key.labelInset = 0 } // shapes switch model.type { case Key.KeyType.shift: if key.shape == nil { let shiftShape = self.getShape(ShiftShape) key.shape = shiftShape } case Key.KeyType.backspace: if key.shape == nil { let backspaceShape = self.getShape(BackspaceShape) key.shape = backspaceShape } case Key.KeyType.keyboardChange: if key.shape == nil { let globeShape = self.getShape(GlobeShape) key.shape = globeShape } default: break } // images if model.type == Key.KeyType.settings { if let imageKey = key as? ImageKey { if imageKey.image == nil { let gearImage = UIImage(named: "gear") let settingsImageView = UIImageView(image: gearImage) imageKey.image = settingsImageView } } } } if model.type == Key.KeyType.shift { if key.shape == nil { let shiftShape = self.getShape(ShiftShape) key.shape = shiftShape } switch shiftState { case .disabled: key.isHighlighted = false case .enabled: key.isHighlighted = true case .locked: key.isHighlighted = true } (key.shape as? ShiftShape)?.withLock = (shiftState == .locked) } self.updateKeyCapText(key, model: model, uppercase: uppercase, characterUppercase: characterUppercase) } func updateKeyCapText(_ key: KeyboardKey, model: Key, uppercase: Bool, characterUppercase: Bool) { if model.type == .character { key.text = model.keyCapForCase(characterUppercase) } else { key.text = model.keyCapForCase(uppercase) } } /////////////// // END CALLS // /////////////// func setAppearanceForKey(_ key: KeyboardKey, model: Key, darkMode: Bool, solidColorMode: Bool) { if model.type == Key.KeyType.other { self.setAppearanceForOtherKey(key, model: model, darkMode: darkMode, solidColorMode: solidColorMode) } switch model.type { case Key.KeyType.character, Key.KeyType.specialCharacter, Key.KeyType.period: key.color = self.self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode) if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { key.downColor = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) } else { key.downColor = nil } key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor) key.downTextColor = nil case Key.KeyType.space: key.color = self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode) key.downColor = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor) key.downTextColor = nil case Key.KeyType.shift: key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) key.downColor = (darkMode ? self.globalColors.darkModeShiftKeyDown : self.globalColors.lightModeRegularKey) key.textColor = self.globalColors.darkModeTextColor key.downTextColor = self.globalColors.lightModeTextColor case Key.KeyType.backspace: key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) // TODO: actually a bit different key.downColor = self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode) key.textColor = self.globalColors.darkModeTextColor key.downTextColor = (darkMode ? nil : self.globalColors.lightModeTextColor) case Key.KeyType.modeChange: key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) key.downColor = nil key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor) key.downTextColor = nil case Key.KeyType.return, Key.KeyType.keyboardChange, Key.KeyType.settings: key.color = self.globalColors.specialKey(darkMode, solidColorMode: solidColorMode) // TODO: actually a bit different key.downColor = self.globalColors.regularKey(darkMode, solidColorMode: solidColorMode) key.textColor = (darkMode ? self.globalColors.darkModeTextColor : self.globalColors.lightModeTextColor) key.downTextColor = nil default: break } key.popupColor = self.globalColors.popup(darkMode, solidColorMode: solidColorMode) key.underColor = (self.darkMode ? self.globalColors.darkModeUnderColor : self.globalColors.lightModeUnderColor) key.borderColor = (self.darkMode ? self.globalColors.darkModeBorderColor : self.globalColors.lightModeBorderColor) } func setAppearanceForOtherKey(_ key: KeyboardKey, model: Key, darkMode: Bool, solidColorMode: Bool) { /* override this to handle special keys */ } // TODO: avoid array copies // TODO: sizes stored not rounded? /////////////////////////// // KEY POOLING FUNCTIONS // /////////////////////////// // if pool is disabled, always returns a unique key view for the corresponding key model func pooledKey(key aKey: Key, model: Keyboard, frame: CGRect) -> KeyboardKey? { if !type(of: self).shouldPoolKeys { var p: Int! var r: Int! var k: Int! // TODO: O(N^2) in terms of total # of keys since pooledKey is called for each key, but probably doesn't matter var foundKey: Bool = false for (pp, page) in model.pages.enumerated() { for (rr, row) in page.rows.enumerated() { for (kk, key) in row.enumerated() { if key == aKey { p = pp r = rr k = kk foundKey = true } if foundKey { break } } if foundKey { break } } if foundKey { break } } let id = "p\(p)r\(r)k\(k)" if let key = self.nonPooledMap[id] { return key } else { let key = generateKey() self.nonPooledMap[id] = key return key } } else { if var keyArray = self.sizeToKeyMap[frame.size] { if let key = keyArray.last { if keyArray.count == 1 { self.sizeToKeyMap.removeValue(forKey: frame.size) } else { keyArray.removeLast() self.sizeToKeyMap[frame.size] = keyArray } return key } else { return nil } } else { return nil } } } func createNewKey() -> KeyboardKey { return ImageKey(vibrancy: nil) } // if pool is disabled, always generates a new key func generateKey() -> KeyboardKey { let createAndSetupNewKey = { () -> KeyboardKey in let keyView = self.createNewKey() keyView.isEnabled = true keyView.delegate = self self.superview.addSubview(keyView) self.keyPool.append(keyView) return keyView } if type(of: self).shouldPoolKeys { if !self.sizeToKeyMap.isEmpty { var (size, keyArray) = self.sizeToKeyMap[self.sizeToKeyMap.startIndex] if let key = keyArray.last { if keyArray.count == 1 { self.sizeToKeyMap.removeValue(forKey: size) } else { keyArray.removeLast() self.sizeToKeyMap[size] = keyArray } return key } else { return createAndSetupNewKey() } } else { return createAndSetupNewKey() } } else { return createAndSetupNewKey() } } // if pool is disabled, doesn't do anything func resetKeyPool() { if type(of: self).shouldPoolKeys { self.sizeToKeyMap.removeAll(keepingCapacity: true) for key in self.keyPool { if var keyArray = self.sizeToKeyMap[key.frame.size] { keyArray.append(key) self.sizeToKeyMap[key.frame.size] = keyArray } else { var keyArray = [KeyboardKey]() keyArray.append(key) self.sizeToKeyMap[key.frame.size] = keyArray } key.isHidden = true } } } // TODO: no support for more than one of the same shape // if pool disabled, always returns new shape func getShape(_ shapeClass: Shape.Type) -> Shape { let className = NSStringFromClass(shapeClass) if type(of: self).shouldPoolKeys { if let shape = self.shapePool[className] { return shape } else { let shape = shapeClass.init(frame: CGRect.zero) self.shapePool[className] = shape return shape } } else { return shapeClass.init(frame: CGRect.zero) } } ////////////////////// // LAYOUT FUNCTIONS // ////////////////////// func rounded(_ measurement: CGFloat) -> CGFloat { return round(measurement * UIScreen.main.scale) / UIScreen.main.scale } func generateKeyFrames(_ model: Keyboard, bounds: CGRect, page pageToLayout: Int) -> [Key:CGRect]? { if bounds.height == 0 || bounds.width == 0 { return nil } var keyMap = [Key:CGRect]() let isLandscape: Bool = { let boundsRatio = bounds.width / bounds.height return (boundsRatio >= self.layoutConstants.landscapeRatio) }() var sideEdges = (isLandscape ? self.layoutConstants.sideEdgesLandscape : self.layoutConstants.sideEdgesPortrait(bounds.width)) let bottomEdge = sideEdges let normalKeyboardSize = bounds.width - CGFloat(2) * sideEdges let shrunkKeyboardSize = self.layoutConstants.keyboardShrunkSize(normalKeyboardSize) sideEdges += ((normalKeyboardSize - shrunkKeyboardSize) / CGFloat(2)) let topEdge: CGFloat = (isLandscape ? self.layoutConstants.topEdgeLandscape : self.layoutConstants.topEdgePortrait(bounds.width)) let rowGap: CGFloat = (isLandscape ? self.layoutConstants.rowGapLandscape : self.layoutConstants.rowGapPortrait(bounds.width)) let lastRowGap: CGFloat = (isLandscape ? rowGap : self.layoutConstants.rowGapPortraitLastRow(bounds.width)) // TODO swift2 delete // let flexibleEndRowM = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMPortrait) // let flexibleEndRowC = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCPortrait) let lastRowLeftSideRatio = (isLandscape ? self.layoutConstants.lastRowLandscapeFirstTwoButtonAreaWidthToKeyboardAreaWidth : self.layoutConstants.lastRowPortraitFirstTwoButtonAreaWidthToKeyboardAreaWidth) let lastRowRightSideRatio = (isLandscape ? self.layoutConstants.lastRowLandscapeLastButtonAreaWidthToKeyboardAreaWidth : self.layoutConstants.lastRowPortraitLastButtonAreaWidthToKeyboardAreaWidth) let lastRowKeyGap = (isLandscape ? self.layoutConstants.lastRowKeyGapLandscape(bounds.width) : self.layoutConstants.lastRowKeyGapPortrait) for (p, page) in model.pages.enumerated() { if p != pageToLayout { continue } let numRows = page.rows.count let mostKeysInRow: Int = { var currentMax: Int = 0 for (_, row) in page.rows.enumerated() { currentMax = max(currentMax, row.count) } return currentMax }() let rowGapTotal = CGFloat(numRows - 1 - 1) * rowGap + lastRowGap let keyGap: CGFloat = (isLandscape ? self.layoutConstants.keyGapLandscape(bounds.width, rowCharacterCount: mostKeysInRow) : self.layoutConstants.keyGapPortrait(bounds.width, rowCharacterCount: mostKeysInRow)) let keyHeight: CGFloat = { let totalGaps = bottomEdge + topEdge + rowGapTotal let returnHeight = (bounds.height - totalGaps) / CGFloat(numRows) return self.rounded(returnHeight) }() let letterKeyWidth: CGFloat = { let totalGaps = (sideEdges * CGFloat(2)) + (keyGap * CGFloat(mostKeysInRow - 1)) let returnWidth = (bounds.width - totalGaps) / CGFloat(mostKeysInRow) return self.rounded(returnWidth) }() let processRow = { (row: [Key], frames: [CGRect], map: inout [Key:CGRect]) -> Void in assert(row.count == frames.count, "row and frames don't match") for (k, key) in row.enumerated() { map[key] = frames[k] } } for (r, row) in page.rows.enumerated() { let rowGapCurrentTotal = (r == page.rows.count - 1 ? rowGapTotal : CGFloat(r) * rowGap) let frame = CGRect(x: rounded(sideEdges), y: rounded(topEdge + (CGFloat(r) * keyHeight) + rowGapCurrentTotal), width: rounded(bounds.width - CGFloat(2) * sideEdges), height: rounded(keyHeight)) var frames: [CGRect]! // basic character row: only typable characters if self.characterRowHeuristic(row) { frames = self.layoutCharacterRow(row, keyWidth: letterKeyWidth, gapWidth: keyGap, frame: frame) } // character row with side buttons: shift, backspace, etc. else if self.doubleSidedRowHeuristic(row) { frames = self.layoutCharacterWithSidesRow(row, frame: frame, isLandscape: isLandscape, keyWidth: letterKeyWidth, keyGap: keyGap) } // bottom row with things like space, return, etc. else { frames = self.layoutSpecialKeysRow(row, keyWidth: letterKeyWidth, gapWidth: lastRowKeyGap, leftSideRatio: lastRowLeftSideRatio, rightSideRatio: lastRowRightSideRatio, micButtonRatio: self.layoutConstants.micButtonPortraitWidthRatioToOtherSpecialButtons, isLandscape: isLandscape, frame: frame) } processRow(row, frames, &keyMap) } } return keyMap } func characterRowHeuristic(_ row: [Key]) -> Bool { return (row.count >= 1 && row[0].isCharacter) } func doubleSidedRowHeuristic(_ row: [Key]) -> Bool { return (row.count >= 3 && !row[0].isCharacter && row[1].isCharacter) } func layoutCharacterRow(_ row: [Key], keyWidth: CGFloat, gapWidth: CGFloat, frame: CGRect) -> [CGRect] { var frames = [CGRect]() let keySpace = CGFloat(row.count) * keyWidth + CGFloat(row.count - 1) * gapWidth var actualGapWidth = gapWidth var sideSpace = (frame.width - keySpace) / CGFloat(2) // TODO: port this to the other layout functions // avoiding rounding errors if sideSpace < 0 { sideSpace = 0 actualGapWidth = (frame.width - (CGFloat(row.count) * keyWidth)) / CGFloat(row.count - 1) } var currentOrigin = frame.origin.x + sideSpace for (_, _) in row.enumerated() { let roundedOrigin = rounded(currentOrigin) // avoiding rounding errors if roundedOrigin + keyWidth > frame.origin.x + frame.width { frames.append(CGRect(x: rounded(frame.origin.x + frame.width - keyWidth), y: frame.origin.y, width: keyWidth, height: frame.height)) } else { frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: keyWidth, height: frame.height)) } currentOrigin += (keyWidth + actualGapWidth) } return frames } // TODO: pass in actual widths instead func layoutCharacterWithSidesRow(_ row: [Key], frame: CGRect, isLandscape: Bool, keyWidth: CGFloat, keyGap: CGFloat) -> [CGRect] { var frames = [CGRect]() let standardFullKeyCount = Int(self.layoutConstants.keyCompressedThreshhold) - 1 let standardGap = (isLandscape ? self.layoutConstants.keyGapLandscape : self.layoutConstants.keyGapPortrait)(frame.width, standardFullKeyCount) let sideEdges = (isLandscape ? self.layoutConstants.sideEdgesLandscape : self.layoutConstants.sideEdgesPortrait(frame.width)) var standardKeyWidth = (frame.width - sideEdges - (standardGap * CGFloat(standardFullKeyCount - 1)) - sideEdges) standardKeyWidth /= CGFloat(standardFullKeyCount) let standardKeyCount = self.layoutConstants.flexibleEndRowMinimumStandardCharacterWidth let standardWidth = CGFloat(standardKeyWidth * standardKeyCount + standardGap * (standardKeyCount - 1)) let currentWidth = CGFloat(row.count - 2) * keyWidth + CGFloat(row.count - 3) * keyGap let isStandardWidth = (currentWidth < standardWidth) let actualWidth = (isStandardWidth ? standardWidth : currentWidth) let actualGap = (isStandardWidth ? standardGap : keyGap) let actualKeyWidth = (actualWidth - CGFloat(row.count - 3) * actualGap) / CGFloat(row.count - 2) let sideSpace = (frame.width - actualWidth) / CGFloat(2) let m = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMPortrait) let c = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCPortrait) var specialCharacterWidth = sideSpace * m + c specialCharacterWidth = max(specialCharacterWidth, keyWidth) specialCharacterWidth = rounded(specialCharacterWidth) let specialCharacterGap = sideSpace - specialCharacterWidth var currentOrigin = frame.origin.x for (k, _) in row.enumerated() { if k == 0 { frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: specialCharacterWidth, height: frame.height)) currentOrigin += (specialCharacterWidth + specialCharacterGap) } else if k == row.count - 1 { currentOrigin += specialCharacterGap frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: specialCharacterWidth, height: frame.height)) currentOrigin += specialCharacterWidth } else { frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: actualKeyWidth, height: frame.height)) if k == row.count - 2 { currentOrigin += (actualKeyWidth) } else { currentOrigin += (actualKeyWidth + keyGap) } } } return frames } func layoutSpecialKeysRow(_ row: [Key], keyWidth: CGFloat, gapWidth: CGFloat, leftSideRatio: CGFloat, rightSideRatio: CGFloat, micButtonRatio: CGFloat, isLandscape: Bool, frame: CGRect) -> [CGRect] { var frames = [CGRect]() var keysBeforeSpace = 0 var keysAfterSpace = 0 var reachedSpace = false for (_, key) in row.enumerated() { if key.type == Key.KeyType.space { reachedSpace = true } else { if !reachedSpace { keysBeforeSpace += 1 } else { keysAfterSpace += 1 } } } assert(keysBeforeSpace <= 3, "invalid number of keys before space (only max 3 currently supported)") assert(keysAfterSpace == 1, "invalid number of keys after space (only default 1 currently supported)") let hasButtonInMicButtonPosition = (keysBeforeSpace == 3) var leftSideAreaWidth = frame.width * leftSideRatio let rightSideAreaWidth = frame.width * rightSideRatio var leftButtonWidth = (leftSideAreaWidth - (gapWidth * CGFloat(2 - 1))) / CGFloat(2) leftButtonWidth = rounded(leftButtonWidth) var rightButtonWidth = (rightSideAreaWidth - (gapWidth * CGFloat(keysAfterSpace - 1))) / CGFloat(keysAfterSpace) rightButtonWidth = rounded(rightButtonWidth) let micButtonWidth = (isLandscape ? leftButtonWidth : leftButtonWidth * micButtonRatio) // special case for mic button if hasButtonInMicButtonPosition { leftSideAreaWidth = leftSideAreaWidth + gapWidth + micButtonWidth } var spaceWidth = frame.width - leftSideAreaWidth - rightSideAreaWidth - gapWidth * CGFloat(2) spaceWidth = rounded(spaceWidth) var currentOrigin = frame.origin.x var beforeSpace: Bool = true for (k, key) in row.enumerated() { if key.type == Key.KeyType.space { frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: spaceWidth, height: frame.height)) currentOrigin += (spaceWidth + gapWidth) beforeSpace = false } else if beforeSpace { if hasButtonInMicButtonPosition && k == 2 { //mic button position frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: micButtonWidth, height: frame.height)) currentOrigin += (micButtonWidth + gapWidth) } else { frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: leftButtonWidth, height: frame.height)) currentOrigin += (leftButtonWidth + gapWidth) } } else { frames.append(CGRect(x: rounded(currentOrigin), y: frame.origin.y, width: rightButtonWidth, height: frame.height)) currentOrigin += (rightButtonWidth + gapWidth) } } return frames } //////////////// // END LAYOUT // //////////////// func frameForPopup(_ key: KeyboardKey, direction: Direction) -> CGRect { let actualScreenWidth = (UIScreen.main.nativeBounds.size.width / UIScreen.main.nativeScale) let totalHeight = self.layoutConstants.popupTotalHeight(actualScreenWidth) let popupWidth = key.bounds.width + self.layoutConstants.popupWidthIncrement let popupHeight = totalHeight - self.layoutConstants.popupGap - key.bounds.height // let popupCenterY = 0 // TODO swift2 delete return CGRect(x: (key.bounds.width - popupWidth) / CGFloat(2), y: -popupHeight - self.layoutConstants.popupGap, width: popupWidth, height: popupHeight) } func willShowPopup(_ key: KeyboardKey, direction: Direction) { // TODO: actual numbers, not standins if let popup = key.popup { // TODO: total hack let actualSuperview = (self.superview.superview != nil ? self.superview.superview! : self.superview) var localFrame = actualSuperview.convert(popup.frame, from: popup.superview) if localFrame.origin.y < 3 { localFrame.origin.y = 3 key.background.attached = Direction.down key.connector?.startDir = Direction.down key.background.hideDirectionIsOpposite = true } else { // TODO: this needs to be reset somewhere key.background.hideDirectionIsOpposite = false } if localFrame.origin.x < 3 { localFrame.origin.x = key.frame.origin.x } if localFrame.origin.x + localFrame.width > superview.bounds.width - 3 { localFrame.origin.x = key.frame.origin.x + key.frame.width - localFrame.width } popup.frame = actualSuperview.convert(localFrame, to: popup.superview) } } func willHidePopup(_ key: KeyboardKey) { } }
bsd-3-clause
060f1caede2317fe09e96d74bbaa2517
41.992403
313
0.586799
5.316618
false
false
false
false
Verchen/Swift-Project
JinRong/JinRong/Classes/Main(主控制器)/MainController.swift
1
2365
// // MainController.swift // JinRong // // Created by 乔伟成 on 2017/7/12. // Copyright © 2017年 乔伟成. All rights reserved. // import UIKit class MainController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() setupChildVC() } func setupChildVC() -> Void { let borrowVC = BorrowController() borrowVC.title = "借款" borrowVC.tabBarItem.image = UIImage(named: "tabbar_home_normal") borrowVC.tabBarItem.selectedImage = UIImage(named: "tabbar_home_select")?.withRenderingMode(.alwaysOriginal) borrowVC.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.theme], for: .selected) let nav1 = BaseNavigationController(rootViewController: borrowVC) self.addChildViewController(nav1) let authVC = AuthController() authVC.title = "认证" authVC.tabBarItem.image = UIImage(named: "tabbar_auth_normal") authVC.tabBarItem.selectedImage = UIImage(named: "tabbar_auth_select")?.withRenderingMode(.alwaysOriginal) authVC.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.theme], for: .selected) let nav2 = BaseNavigationController(rootViewController: authVC) self.addChildViewController(nav2) let billVC = BillController() billVC.title = "账单" billVC.tabBarItem.image = UIImage(named: "tabbar_zhangdan_normal") billVC.tabBarItem.selectedImage = UIImage(named: "tabbar_zhangdan_select")?.withRenderingMode(.alwaysOriginal) billVC.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.theme], for: .selected) let nav3 = BaseNavigationController(rootViewController: billVC) self.addChildViewController(nav3) let profileVC = ProfileController() profileVC.title = "我的" profileVC.tabBarItem.image = UIImage(named: "tabbar_wo_normal") profileVC.tabBarItem.selectedImage = UIImage(named: "tabbar_wo_select")?.withRenderingMode(.alwaysOriginal) profileVC.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.theme], for: .selected) let nav4 = BaseNavigationController(rootViewController: profileVC) self.addChildViewController(nav4) } }
mit
8146c7afecef15d4679aebf27712cfaf
41.436364
118
0.700514
4.792608
false
false
false
false
AdySan/HomeKit-Demo
BetterHomeKit/ActionSetsViewController.swift
4
12480
// // ActionSetViewController.swift // BetterHomeKit // // Created by Khaos Tian on 8/6/14. // Copyright (c) 2014 Oltica. All rights reserved. // import UIKit import HomeKit class ActionSetsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { weak var pendingTrigger:HMTrigger? var pendingCharacteristic: Characteristic? var actionSets = [HMActionSet]() @IBOutlet weak var actionSetsTableview: UITableView! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateActionSets() } func updateActionSets () { actionSets.removeAll(keepCapacity: false) if let currentHome = Core.sharedInstance.currentHome { actionSets += currentHome.actionSets as! [HMActionSet] } actionSetsTableview.reloadData() } @IBAction func addActionSet(sender: AnyObject) { let alert:UIAlertController = UIAlertController(title: "Add Action Set", message: "Add Action Set to current Home", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Add", style: UIAlertActionStyle.Default, handler: { [weak self] (action:UIAlertAction!) in let textField = alert.textFields?[0] as! UITextField if let strongSelf = self { Core.sharedInstance.currentHome?.addActionSetWithName(textField.text){ [weak self] (actionSet: HMActionSet!, error: NSError!) in if error != nil { NSLog("Failed to add action set, Error: \(error)") } else { self?.updateActionSets() } } } })) self.presentViewController(alert, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetailedActionSet" { let actionVC = segue.destinationViewController as! ActionSetViewController actionVC.currentActionSet = sender as? HMActionSet } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return actionSets.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ActionSetCell", forIndexPath: indexPath) as! UITableViewCell let actionSet = actionSets[indexPath.row] cell.textLabel?.text = actionSet.name cell.detailTextLabel?.text = "Actions:\(actionSet.actions.count)" return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let actionSet = actionSets[indexPath.row] if let pendingTrigger = pendingTrigger { pendingTrigger.addActionSet(actionSet) { [weak self] error in if error != nil { NSLog("Failed adding action set to trigger, error:\(error)") } else { self?.navigationController?.popViewControllerAnimated(true) } } } else if let pendingChar = pendingCharacteristic?.toHMCharacteristic() { let object = pendingChar var charDesc = object.characteristicType charDesc = HomeKitUUIDs[object.characteristicType] switch (object.metadata.format as NSString) { case HMCharacteristicMetadataFormatBool: let alert:UIAlertController = UIAlertController(title: "Target \(charDesc)", message: "Please choose the target state for this action", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "On", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) in let writeAction = HMCharacteristicWriteAction(characteristic: object, targetValue: true) actionSet.addAction(writeAction) { error in if error != nil { NSLog("Failed adding action to action set, error: \(error)") } else { self.navigationController?.popViewControllerAnimated(true) } } })) alert.addAction(UIAlertAction(title: "Off", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) in let writeAction = HMCharacteristicWriteAction(characteristic: object, targetValue: false) actionSet.addAction(writeAction) { error in if error != nil { NSLog("Failed adding action to action set, error: \(error)") } else { self.navigationController?.popViewControllerAnimated(true) } } })) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(alert, animated: true, completion: nil) }) case HMCharacteristicMetadataFormatInt,HMCharacteristicMetadataFormatFloat,HMCharacteristicMetadataFormatUInt8,HMCharacteristicMetadataFormatUInt16,HMCharacteristicMetadataFormatUInt32,HMCharacteristicMetadataFormatUInt64: let alert:UIAlertController = UIAlertController(title: "Target \(charDesc)", message: "Enter the target state for this action from \(object.metadata.minimumValue) to \(object.metadata.maximumValue). Unit is \(object.metadata.units)", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) in let textField = alert.textFields?[0] as! UITextField let f = NSNumberFormatter() f.numberStyle = NSNumberFormatterStyle.DecimalStyle let writeAction = HMCharacteristicWriteAction(characteristic: object, targetValue: f.numberFromString(textField.text)) actionSet.addAction(writeAction) { error in if error != nil { NSLog("Failed adding action to action set, error: \(error)") } else { self.navigationController?.popViewControllerAnimated(true) } } })) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(alert, animated: true, completion: nil) }) case HMCharacteristicMetadataFormatString: let alert:UIAlertController = UIAlertController(title: "Target \(charDesc)", message: "Enter the target \(charDesc) from \(object.metadata.minimumValue) to \(object.metadata.maximumValue). Unit is \(object.metadata.units)", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) in let textField = alert.textFields?[0] as! UITextField let writeAction = HMCharacteristicWriteAction(characteristic: object, targetValue: textField.text) actionSet.addAction(writeAction) { error in if error != nil { NSLog("Failed adding action to action set, error: \(error)") } else { self.navigationController?.popViewControllerAnimated(true) } } })) dispatch_async(dispatch_get_main_queue(), { self.presentViewController(alert, animated: true, completion: nil) }) default: NSLog("Unsupported") } } else { self.performSegueWithIdentifier("showDetailedActionSet", sender: actionSet) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { var options = [UITableViewRowAction]() let actionSet = actionSets[indexPath.row] as HMActionSet let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) in Core.sharedInstance.currentHome?.removeActionSet(actionSet) { error in if error != nil { NSLog("Failed removing action set, error: \(error)") } else { self.updateActionSets() } } tableView.setEditing(false, animated: true) } ) options.append(deleteAction) let renameAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Rename", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) in let alert:UIAlertController = UIAlertController(title: "Rename Action Set", message: "Update the name of the Action Set", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler(nil) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Rename", style: UIAlertActionStyle.Default, handler: { (action:UIAlertAction!) in let textField = alert.textFields?[0] as! UITextField actionSet.updateName(textField.text) { error in if let error = error { println("Error:\(error)") }else{ let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.textLabel?.text = actionSet.name } } })) self.presentViewController(alert, animated: true, completion: nil) tableView.setEditing(false, animated: true) } ) renameAction.backgroundColor = UIColor.orangeColor() options.append(renameAction) return options } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { } }
mit
c63cf3da80048d25c463f51c6cee3e81
47.75
273
0.564984
6.075949
false
false
false
false
neoneye/SwiftyFORM
Source/FormItems/SliderFormItem.swift
1
1420
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import Foundation public class SliderFormItem: FormItem { override func accept(visitor: FormItemVisitor) { visitor.visit(object: self) } public var minimumValue: Float = 0.0 @discardableResult public func minimumValue(_ minimumValue: Float) -> Self { self.minimumValue = minimumValue return self } public var maximumValue: Float = 1.0 @discardableResult public func maximumValue(_ maximumValue: Float) -> Self { self.maximumValue = maximumValue return self } typealias SyncBlock = (_ value: Float, _ animated: Bool) -> Void var syncCellWithValue: SyncBlock = { (value: Float, animated: Bool) in SwiftyFormLog("sync is not overridden") } internal var innerValue: Float = 0.0 public var value: Float { get { return self.innerValue } set { self.setValue(newValue, animated: false) } } @discardableResult public func value(_ value: Float) -> Self { setValue(value, animated: false) return self } public func setValue(_ value: Float, animated: Bool) { innerValue = value syncCellWithValue(value, animated) } public typealias SliderDidChangeBlock = (_ value: Float) -> Void public var sliderDidChangeBlock: SliderDidChangeBlock = { (value: Float) in SwiftyFormLog("not overridden") } public func sliderDidChange(_ value: Float) { innerValue = value sliderDidChangeBlock(value) } }
mit
b41f90a5ceb2acbe3ea608e309533029
22.666667
76
0.723239
3.669251
false
false
false
false
cclovett/iRemeber
iRemeber/Pods/Core/Sources/Core/WorkingDirectory.swift
2
1329
#if !COCOAPODS import libc #endif /// This function will attempt to get the current /// working directory of the application public func workingDirectory() -> String { let fileBasedWorkDir: String? #if Xcode // attempt to find working directory through #file let file = #file if file.contains(".build") { // most dependencies are in `./.build/` fileBasedWorkDir = file.components(separatedBy: "/.build").first } else if file.contains("Packages") { // when editing a dependency, it is in `./Packages/` fileBasedWorkDir = file.components(separatedBy: "/Packages").first } else { // when dealing with current repository, file is in `./Sources/` fileBasedWorkDir = file.components(separatedBy: "/Sources").first } #else fileBasedWorkDir = nil #endif let workDir: String if let fileBasedWorkDir = fileBasedWorkDir { workDir = fileBasedWorkDir } else { // get actual working directory let cwd = getcwd(nil, Int(PATH_MAX)) defer { free(cwd) } if let cwd = cwd, let string = String(validatingUTF8: cwd) { workDir = string } else { workDir = "./" } } return workDir.finished(with: "/") }
mit
cf5e9e2590dd4e3a36ab5c0d0e379316
27.891304
74
0.593679
4.43
false
false
false
false
fgengine/quickly
Quickly/ViewControllers/QNibViewController.swift
1
5918
// // Quickly // open class QNibViewController : QViewController, IQInputContentViewController, IQStackContentViewController, IQPageContentViewController, IQGroupContentViewController, IQModalContentViewController, IQDialogContentViewController, IQHamburgerContentViewController, IQJalousieContentViewController, IQLoadingViewDelegate { @IBOutlet public var rootView: UIView! { willSet { guard let rootView = self.rootView else { return } rootView.removeFromSuperview() } didSet { guard let rootView = self.rootView else { return } rootView.translatesAutoresizingMaskIntoConstraints = false rootView.frame = self.view.bounds self.view.addSubview(rootView) self._updateConstraints(self.view, rootView: rootView) } } public var loadingView: QLoadingViewType? { willSet { guard let loadingView = self.loadingView else { return } loadingView.removeFromSuperview() loadingView.delegate = nil } didSet { guard let loadingView = self.loadingView else { return } loadingView.translatesAutoresizingMaskIntoConstraints = false loadingView.delegate = self } } private var _rootConstraints: [NSLayoutConstraint] = [] { willSet { self.view.removeConstraints(self._rootConstraints) } didSet { self.view.addConstraints(self._rootConstraints) } } private var _loadingConstraints: [NSLayoutConstraint] = [] { willSet { self.view.removeConstraints(self._loadingConstraints) } didSet { self.view.addConstraints(self._loadingConstraints) } } open func nibName() -> String { return String(describing: self.classForCoder) } open func nibBundle() -> Bundle { return Bundle.main } open override func didLoad() { let nib = UINib(nibName: self.nibName(), bundle: self.nibBundle()) _ = nib.instantiate(withOwner: self, options: nil) } open override func didChangeContentEdgeInsets() { super.didChangeContentEdgeInsets() if let rootView = self.rootView { self._updateConstraints(self.view, rootView: rootView) } } open func isLoading() -> Bool { guard let loadingView = self.loadingView else { return false } return loadingView.isAnimating() } open func startLoading() { guard let loadingView = self.loadingView else { return } loadingView.start() } open func stopLoading() { guard let loadingView = self.loadingView else { return } loadingView.stop() } // MARK: IQContentViewController public var contentOffset: CGPoint { get { return CGPoint.zero } } public var contentSize: CGSize { get { guard self.isLoaded == true else { return CGSize.zero } return self.view.bounds.size } } open func notifyBeginUpdateContent() { if let viewController = self.contentOwnerViewController { viewController.beginUpdateContent() } } open func notifyUpdateContent() { if let viewController = self.contentOwnerViewController { viewController.updateContent() } } open func notifyFinishUpdateContent(velocity: CGPoint) -> CGPoint? { if let viewController = self.contentOwnerViewController { return viewController.finishUpdateContent(velocity: velocity) } return nil } open func notifyEndUpdateContent() { if let viewController = self.contentOwnerViewController { viewController.endUpdateContent() } } // MARK: IQModalContentViewController open func modalShouldInteractive() -> Bool { return true } // MARK: IQDialogContentViewController open func dialogDidPressedOutside() { } // MARK: IQHamburgerContentViewController open func hamburgerShouldInteractive() -> Bool { return true } // MARK: IQJalousieContentViewController open func jalousieShouldInteractive() -> Bool { return true } // MARK: IQLoadingViewDelegate open func willShow(loadingView: QLoadingViewType) { self.view.addSubview(loadingView) self._updateConstraints(self.view, loadingView: loadingView) } open func didHide(loadingView: QLoadingViewType) { loadingView.removeFromSuperview() } } // MARK: Private private extension QNibViewController { func _updateConstraints(_ view: UIView, rootView: UIView) { let edgeInsets = self.inheritedEdgeInsets self._rootConstraints = [ rootView.topLayout == view.topLayout.offset(edgeInsets.top), rootView.leadingLayout == view.leadingLayout.offset(edgeInsets.left), rootView.trailingLayout == view.trailingLayout.offset(-edgeInsets.right), rootView.bottomLayout == view.bottomLayout.offset(-edgeInsets.bottom) ] } func _updateConstraints(_ view: UIView, loadingView: QLoadingViewType) { self._loadingConstraints = [ loadingView.topLayout == view.topLayout, loadingView.leadingLayout == view.leadingLayout, loadingView.trailingLayout == view.trailingLayout, loadingView.bottomLayout == view.bottomLayout ] } } // MARK: IQContainerSpec extension QNibViewController : IQContainerSpec { open var containerSize: CGSize { get { return self.view.bounds.size } } open var containerLeftInset: CGFloat { get { return self.inheritedEdgeInsets.left } } open var containerRightInset: CGFloat { get { return self.inheritedEdgeInsets.right } } }
mit
c1e646a251d457003c772deb94602d8e
29.984293
319
0.644474
5.350814
false
false
false
false
ps2/rileylink_ios
MinimedKit/Messages/MeterMessage.swift
1
1133
// // MeterMessageBody.swift // RileyLink // // Created by Pete Schwamb on 3/10/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // public struct MeterMessage: MessageBody, DictionaryRepresentable { public static let length = 7 public let glucose: Int public let ackFlag: Bool let rxData: Data public init?(rxData: Data) { self.rxData = rxData if rxData.count == type(of: self).length, let packetType = PacketType(rawValue: rxData[0]), packetType == .meter { let flags = ((rxData[4]) & 0b110) >> 1 ackFlag = flags == 0x03 glucose = Int((rxData[4]) & 0b1) << 8 + Int(rxData[4]) } else { ackFlag = false glucose = 0 return nil } } public var txData: Data { return rxData } public var dictionaryRepresentation: [String: Any] { return [ "glucose": glucose, "ackFlag": ackFlag, ] } public var description: String { return "Meter(\(glucose), \(ackFlag))" } }
mit
b221d818c929db6060a0b4c36cd4bb82
22.583333
82
0.536219
4.192593
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/App/Preferences.swift
1
4321
/** * Copyright © 2019 Aga Khan Foundation * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ import Foundation import OAuthSwift struct UserInfo { private static let defaults = UserDefaults.standard // Add new keys to store to UserDefaults here private static let pedometerKey = "UserInfo.Keys.Pedometer" private static let profileStatsRangeKey = "UserInfo.Keys.ProfileStatsRange" private static let teamLeaderStatsRangeKey = "UserInfo.Keys.TeamLeaderboardStatsRange" private static let OnboardingCompleteKey: String = "UserInfo.Keys.OnboardingComplete" private static let AKFIDKey: String = "UserInfo.Keys.AKFID" private static let AKFProfileCreatedKey: String = "UserInfo.Keys.AKFProfileCreated" private static let staging: String = "UserInfo.Keys.staging" private static let fitbitAuthObjKey: String = "UserInfo.Keys.fitbitAuthObj" private static let waitingDateKey: String = "UserInfo.Keys.waitingDate" enum Pedometer: String { case healthKit = "UserInfo.Pedometer.HealthKit" case fitbit = "UserInfo.Pedometer.Fitbit" } static var pedometerSource: Pedometer? { get { guard let pedometerRaw = defaults.string(forKey: pedometerKey) else { return nil } return Pedometer(rawValue: pedometerRaw) } set { if let newValue = newValue { defaults.set(newValue.rawValue, forKey: pedometerKey) } else { defaults.removeObject(forKey: pedometerKey) } } } static var profileStatsRange: Int { get { return defaults.integer(forKey: profileStatsRangeKey) } // 0 returned by default if none set set { defaults.set(newValue, forKey: profileStatsRangeKey) } } static var teamLeaderStatsRange: Int { get { return defaults.integer(forKey: teamLeaderStatsRangeKey) } set { defaults.set(newValue, forKey: teamLeaderStatsRangeKey) } } public static var onboardingComplete: Bool { get { return defaults.bool(forKey: OnboardingCompleteKey) } set { defaults.set(newValue, forKey: OnboardingCompleteKey) } } public static var AKFID: String? { get { return defaults.string(forKey: AKFIDKey) } set { defaults.set(newValue, forKey: AKFIDKey) } } public static var AKFProfileCreated: Bool { get { return defaults.bool(forKey: AKFProfileCreatedKey) } set { defaults.set(newValue, forKey: AKFProfileCreatedKey) } } public static var fitbitAuthObj: OAuthSwiftCredential? { get { return defaults.retrieve(OAuthSwiftCredential.self, fromKey: fitbitAuthObjKey) } set { defaults.save(newValue, forKey: fitbitAuthObjKey) } } public static var isStaging: Bool { get { return defaults.bool(forKey: staging) } set { defaults.set(newValue, forKey: staging) } } public static var waitingDate: Date? { get { return defaults.value(forKey: waitingDateKey) as? Date} set { return defaults.set(newValue, forKey: waitingDateKey)} } }
bsd-3-clause
8d4bd9aa9d614747ed09f998dec0553e
37.918919
102
0.737037
4.28997
false
false
false
false
bitrise-samples/fastlane
BitriseFastlaneSample/BitriseFastlaneSample/MasterViewController.swift
1
9257
// // MasterViewController.swift // BitriseFastlaneSample // // Created by Viktor Benei on 15/01/16. // Copyright © 2016 bitrise. All rights reserved. // import UIKit import CoreData class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate { var detailViewController: DetailViewController? = nil var managedObjectContext: NSManagedObjectContext? = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(MasterViewController.insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { let context = self.fetchedResultsController.managedObjectContext let entity = self.fetchedResultsController.fetchRequest.entity! let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. newManagedObject.setValue(NSDate(), forKey: "timeStamp") // Save the context. do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = self.fetchedResultsController.objectAtIndexPath(indexPath) let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath) 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 true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let context = self.fetchedResultsController.managedObjectContext context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject) do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } } } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let object = self.fetchedResultsController.objectAtIndexPath(indexPath) cell.textLabel!.text = object.valueForKey("timeStamp")!.description } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() // Edit the entity name as appropriate. let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Edit the sort key as appropriate. let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master") aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController do { try _fetchedResultsController!.performFetch() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //print("Unresolved error \(error), \(error.userInfo)") abort() } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController? = nil func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } /* // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) { // In the simplest, most efficient, case, reload the table view. self.tableView.reloadData() } */ }
mit
3e980e2f24c14bf4290e375a60c81f25
45.28
360
0.689715
6.296599
false
false
false
false
blcsntb/Utilities
Utilities/Classes/CustomViewProtocol.swift
1
698
import UIKit public protocol CustomViewProtocol { var viewIndex: Int { get set } } extension CustomViewProtocol where Self: UIView { public func setup() { self.subviews.last?.removeFromSuperview() self.addSubview(nibView) } private var nibView: UIView { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: className, bundle: bundle) let views = nib.instantiate(withOwner: self, options: nil) let nibView = views[viewIndex] as! UIView self.layoutIfNeeded() nibView.frame = bounds nibView.autoresizingMask = [.flexibleWidth, .flexibleHeight] return nibView } }
mit
9066c44dbf705f9417c5a5bb08c0e04b
26.92
68
0.63467
4.716216
false
false
false
false
Wei-Xia/TVMLKitchen
Sources/Recipes/Recipe.swift
1
3387
// // Recipe.swift // TVMLKitchen // // Created by toshi0383 on 12/28/15. // Copyright © 2015 toshi0383. All rights reserved. // // MARK: RecipeType public protocol RecipeType { /// Theme associatedtype Theme var theme: Theme {get} /// Presentation type is defined in the recipe to keep things consistent. var presentationType: PresentationType {get} /// Template part of TVML which is used to format full page xmlString. /// - SeeAlso: RecipeType.xmlString var template: String {get} /// XML string representation of whole TVML page. /// Uses RecipeType.template for template part by default. var xmlString: String {get} } public protocol TemplateRecipeType: RecipeType { /// File name of this TemplateRecipe. /// Defaults to name of the class. (No need to implement) var templateFileName: String {get} /// Custom pairs of replacement strings. /// /// e.g. /// /// ["title": "Sherlock Holmes: A Game of Shadows (2011)"] /// will modifies this `<title>{{title}}</title>` /// to this `<title>Sherlock Holmes: A Game of Shadows (2011)</title>` var replacementDictionary: [String: String] {get} /// The Bundle in which the corresponding Template file. /// Defaults to the bundle of this class/struct/enum. static var bundle: NSBundle {get} } public protocol SearchRecipeType: TemplateRecipeType { /// Filter text and pass the result to callback. /// - parameter text: keyword /// - parameter callback: pass the result template xmlString. /// - SeeAlso: SampleRecipe.MySearchRecipe.swift, SearchResult.xml func filterSearchText(text: String, callback: (String -> Void)) } // MARK: - Default Implementations extension RecipeType { public var theme: ThemeType { return EmptyTheme() } public var presentationType: PresentationType { return .Default } } extension TemplateRecipeType { public static var bundle: NSBundle { return Kitchen.bundle() } public var replacementDictionary: [String: String] { return [:] } public var base: String { let url = Kitchen.bundle().URLForResource("Base", withExtension: "xml")! // swiftlint:disable:next force_try let xml = try! String(contentsOfURL: url) return xml } public var template: String { let url = Self.bundle.URLForResource(templateFileName, withExtension: "xml")! // swiftlint:disable:next force_try let xml = try! String(contentsOfURL: url) return xml } public var templateFileName: String { return String(self.dynamicType) .componentsSeparatedByString(".") .last! } } extension TemplateRecipeType where Self.Theme: ThemeType { public var xmlString: String { // Start with Base var result = base // Replace template part. result = result .stringByReplacingOccurrencesOfString("{{template}}", withString: template) .stringByReplacingOccurrencesOfString("{{style}}", withString: theme.style) // Replace user-defined variables. for (k, v) in replacementDictionary { result = result.stringByReplacingOccurrencesOfString( "{{\(k)}}", withString: v ) } return result } }
mit
c87c01f5148c58e8aab2a27a957be8ca
27.216667
87
0.643532
4.651099
false
false
false
false
Eonil/EditorLegacy
Modules/EditorWorkspaceNavigationFeature/EditorWorkspaceNavigationFeature/Internals/WorkspaceSerialisation.swift
1
7040
// // WorkspaceSerialisation.swift // EditorWorkspaceNavigationFeature // // Created by Hoon H. on 2015/02/21. // Copyright (c) 2015 Eonil. All rights reserved. // import Foundation import Standards import EditorCommon //extension WorkspaceRepository { // init(workspaceAtURL u:NSURL) { // // } //} // //extension WorkspaceRepository { // func writeToWorkspaceAtURL(u:NSURL) { // // } //} private let CONF_FILE_NAME = ".eonil.editor.workspace.configuration" class WorkspaceSerialisation { static func configurationFileURLForWorkspaceAtURL(u:NSURL) -> NSURL { return u.URLByAppendingPathComponent(CONF_FILE_NAME) } /// This will creates a new repository if there's no existing configuration. static func readRepositoryConfiguration(fromWorkspaceAtURL u:NSURL) -> WorkspaceRepository { precondition(u.existingAsDirectoryFile, "No directory at the URL `\(u)`.") let confFileURL = configurationFileURLForWorkspaceAtURL(u) precondition(confFileURL.existingAsDataFile, "No file at the URL `\(confFileURL)`.") let data = NSData(contentsOfURL: confFileURL)! let rep = deserialise(data) Debug.log("Workspace configuration read from `\(u)`.") return rep } static func writeRepositoryConfiguration(repository:WorkspaceRepository, toWorkspaceAtURL u:NSURL) { let confFileURL = configurationFileURLForWorkspaceAtURL(u) let data = serialise(repository) let ok = data.writeToURL(confFileURL, atomically: true) precondition(ok) Debug.log("Workspace configuration written to `\(u)`.") } static func serialise(repository:WorkspaceRepository) -> NSData { return JSON.serialise(repository.json)! } static func deserialise(data:NSData) -> WorkspaceRepository { let j = JSON.deserialise(data) return WorkspaceRepository.objectify(j, errorTrap: { s in fatalError(s) })! } } extension WorkspaceRepository { static func objectify(json: JSON.Value?, @noescape errorTrap:(String)->()) -> WorkspaceRepository? { if json == nil { errorTrap("JSON value for `\(self.dynamicType)` is `nil`."); return nil } if json!.object == nil { errorTrap("JSON value for `\(self.dynamicType)` is not an JSON object."); return nil } let o = json!.object! let root = o["root"]?.object if root == nil { errorTrap("JSON object for `\(self.dynamicType)` has no proper `root` value."); return nil } let name = root!["name"]?.string if name == nil { errorTrap("JSON object for `root` field of `\(self.dynamicType)` has no proper `name` value."); return nil } let o1 = self.init(name: name!) o1.root.reconfigure(o["root"]!, errorTrap: errorTrap) return o1 } var json:JSON.Value { get { let o = [ "version" : JSON.Value.String("0.0.0"), "root" : self.root.json, ] as JSON.Object return JSON.Value.Object(o) } } } extension WorkspaceNode { /// Erases all existing state and reset to data restored from supplied JSON data. private func reconfigure(json: JSON.Value?, @noescape errorTrap:(String)->()) { func inner(@noescape errorTrap:(String)->()) -> ()? { if json == nil { errorTrap("JSON value for `\(self.dynamicType)` is `nil`."); return nil } if json!.object == nil { errorTrap("JSON value for `\(self.dynamicType)` is not an JSON string."); return nil } let o = json!.object! // let name = o["name"]?.string let comment = o["comment"]?.string let flags = WorkspaceNodeFlags(json: o["flags"], errorTrap: errorTrap) let subnodes = o["subnodes"]?.array // if name == nil { errorTrap("JSON object for `\(self.dynamicType)` is not have `name` string field."); return nil } if flags == nil { errorTrap("A JSON object for `\(self.dynamicType)`'s child has no proper `flags` value."); return nil } if subnodes == nil { errorTrap("JSON object for `\(self.dynamicType)` is not have `subnodes` array field."); return nil } // self.rename(name!) self.comment = comment // `comment` can be `nil`. if flags!.isOpenFolder { self.setExpanded() } self.deleteAllChildNodes() for j in subnodes! { if j.object == nil { errorTrap("One of more item is not JSON object value in array of JSON object for `\(self.dynamicType)`."); return nil } let o1 = j.object! let name = o1["name"]?.string let kind = WorkspaceNodeKind(json: o1["kind"], errorTrap: errorTrap) if name == nil { errorTrap("A JSON object for `\(self.dynamicType)`'s child has no `name` string field."); return nil } if kind == nil { errorTrap("A JSON object for `\(self.dynamicType)`'s child has no proper `kind` value."); return nil } let sn = self.createChildNodeAtLastAsKind(kind!, withName: name!) sn.reconfigure(j, errorTrap: errorTrap) } return nil } inner(errorTrap) } var json:JSON.Value { get { let ns = children.map({ n in n.json }) let ns1 = JSON.Value.Array(ns) let o = [ "name" : JSON.Value.String(name), "comment" : comment == nil ? JSON.Value.Null : JSON.Value.String(comment!), "kind" : kind.json, "flags" : flags.json, "subnodes" : ns1, ] as JSON.Object return JSON.Value.Object(o) } } } extension WorkspaceNodeKind { init?(json: JSON.Value?, @noescape errorTrap:(String)->()) { if json == nil { errorTrap("JSON value for `\(self.dynamicType)` is `nil`."); return nil } if json!.string == nil { errorTrap("JSON value for `\(self.dynamicType)` is not an JSON string."); return nil } switch json!.string! { case "file": self = File case "folder": self = Folder default: errorTrap("JSON value for `\(self.dynamicType)` is an unknown value `\(json!.string!)`.") return nil } } var json:JSON.Value { get { switch self { case .File: return JSON.Value.String("file") case .Folder: return JSON.Value.String("folder") } } } } extension WorkspaceNodeFlags { init?(json:JSON.Value?, @noescape errorTrap:(String)->()) { if json == nil { errorTrap("JSON value for `\(self.dynamicType)` is `nil`."); return nil } if json!.object == nil { errorTrap("JSON value for `\(self.dynamicType)` is not an JSON object."); return nil } // let _lazy = json!.object!["lazySubtree"]?.boolean // let _subws = json!.object!["subworkspace"]?.boolean let _open = json!.object!["isOpenFolder"]?.boolean // if _lazy == nil { errorTrap("JSON object for `WorkspaceNodeFlags` has no proper `lazySubtree` value."); return nil } // if _subws == nil { errorTrap("JSON object for `WorkspaceNodeFlags` has no proper `subworkspace` value."); return nil } if _open == nil { errorTrap("JSON object for `WorkspaceNodeFlags` has no proper `isOpenFolder` value."); return nil } self.isOpenFolder = _open! // self.subworkspace = _subws! } var json:JSON.Value { get { let o = [ // "lazySubtree" : JSON.Value.Boolean(lazySubtree), "isOpenFolder" : JSON.Value.Boolean(isOpenFolder), // "subworkspace" : JSON.Value.Boolean(subworkspace), ] as JSON.Object return JSON.Value.Object(o) } } }
mit
ac1adbe063d60301526e830fcaec8937
27.617886
145
0.665625
3.268338
false
false
false
false
robtimp/xswift
exercises/circular-buffer/Tests/CircularBufferTests/CircularBufferTests.swift
2
5075
import XCTest @testable import CircularBuffer class CircularBufferTests: XCTestCase { func testReadEmptyBufferThrowsBufferEmptyException() { var buffer = CircularBuffer<Int>(capacity: 1) XCTAssertThrowsError(try buffer.read()) { error in XCTAssertEqual(error as? CircularBufferError, .bufferEmpty) } } func testWriteAndReadBackOneItem() { var buffer = CircularBuffer<Int>(capacity: 1) try? buffer.write(1) XCTAssertEqual(try? buffer.read(), 1) XCTAssertThrowsError(try buffer.read()) { error in XCTAssertEqual(error as? CircularBufferError, .bufferEmpty) } } func testWriteAndReadBackMultipleItems() { var buffer = CircularBuffer<Int>(capacity: 2) try? buffer.write(1) try? buffer.write(2) XCTAssertEqual(try? buffer.read(), 1) XCTAssertEqual(try? buffer.read(), 2) XCTAssertThrowsError(try buffer.read()) { error in XCTAssertEqual(error as? CircularBufferError, .bufferEmpty) } } func testClearingBuffer() { var buffer = CircularBuffer<Int>(capacity: 3) (1...3).forEach { try? buffer.write($0) } buffer.clear() XCTAssertThrowsError(try buffer.read()) { error in XCTAssertEqual(error as? CircularBufferError, .bufferEmpty) } try? buffer.write(1) try? buffer.write(2) XCTAssertEqual(try? buffer.read(), 1) try? buffer.write(3) XCTAssertEqual(try? buffer.read(), 2) } func testAlternateWriteAndRead() { var buffer = CircularBuffer<Int>(capacity: 2) try? buffer.write(1) XCTAssertEqual(try? buffer.read(), 1) try? buffer.write(2) XCTAssertEqual(try? buffer.read(), 2) } func testReadsBackOldestItem() { var buffer = CircularBuffer<Int>(capacity: 3) try? buffer.write(1) try? buffer.write(2) XCTAssertEqual(try? buffer.read(), 1) try? buffer.write(3) XCTAssertEqual(try? buffer.read(), 2) XCTAssertEqual(try? buffer.read(), 3) } func testWritingToAFullBufferThrowsAnException() { var buffer = CircularBuffer<String>(capacity: 2) try? buffer.write("1") try? buffer.write("2") XCTAssertThrowsError(try buffer.write("A")) { error in XCTAssertEqual(error as? CircularBufferError, .bufferFull) } } func testOverwritingOldestItemInAFullBuffer() { var buffer = CircularBuffer<String>(capacity: 2) try? buffer.write("1") try? buffer.write("2") buffer.overwrite("A") XCTAssertEqual(try? buffer.read(), "2") XCTAssertEqual(try? buffer.read(), "A") XCTAssertThrowsError(try buffer.read()) { error in XCTAssertEqual(error as? CircularBufferError, .bufferEmpty) } } func testForcedWritesToNonFullBufferShouldBehaveLikeWrites() { var buffer = CircularBuffer<String>(capacity: 2) buffer.overwrite("1") buffer.overwrite("2") XCTAssertEqual(try? buffer.read(), "1") XCTAssertEqual(try? buffer.read(), "2") XCTAssertThrowsError(try buffer.read()) { error in XCTAssertEqual(error as? CircularBufferError, .bufferEmpty) } } func testAlternateReadAndWriteIntoBufferOverflow() { var buffer = CircularBuffer<Int>(capacity: 5) (1...3).forEach { try? buffer.write($0) } _ = try? buffer.read() _ = try? buffer.read() _ = try? buffer.write(4) _ = try? buffer.read() (5...8).forEach { try? buffer.write($0) } buffer.overwrite(9) buffer.overwrite(10) (6...8).forEach { XCTAssertEqual(try? buffer.read(), $0) } XCTAssertEqual(try? buffer.read(), 9) XCTAssertEqual(try? buffer.read(), 10) XCTAssertThrowsError(try buffer.read()) { error in XCTAssertEqual(error as? CircularBufferError, .bufferEmpty) } } static var allTests: [(String, (CircularBufferTests) -> () throws -> Void)] { return [ ("testReadEmptyBufferThrowsBufferEmptyException", testReadEmptyBufferThrowsBufferEmptyException), ("testWriteAndReadBackOneItem", testWriteAndReadBackOneItem), ("testWriteAndReadBackMultipleItems", testWriteAndReadBackMultipleItems), ("testClearingBuffer", testClearingBuffer), ("testAlternateWriteAndRead", testAlternateWriteAndRead), ("testReadsBackOldestItem", testReadsBackOldestItem), ("testWritingToAFullBufferThrowsAnException", testWritingToAFullBufferThrowsAnException), ("testOverwritingOldestItemInAFullBuffer", testOverwritingOldestItemInAFullBuffer), ("testForcedWritesToNonFullBufferShouldBehaveLikeWrites", testForcedWritesToNonFullBufferShouldBehaveLikeWrites), ("testAlternateReadAndWriteIntoBufferOverflow", testAlternateReadAndWriteIntoBufferOverflow), ] } }
mit
c6321cd8d95ca1905b4506389bb5728f
36.873134
125
0.635862
4.393939
false
true
false
false
bitjammer/swift
validation-test/compiler_crashers_fixed/27135-swift-patternbindingdecl-setpattern.swift
65
2460
// 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 // RUN: not %target-swift-frontend %s -typecheck {{{ let : T:a<T where f enum b {struct A enum B}protocol a{ let a=f:A{var" let a { let c{ class d{{ }typealias d {func f g class A { struct d<S where B{ let : N < where h:a var f _}}}} struct S<T where g:d {{{ class B{ var b{ <f {let:d { class b:d{ " { var b{ let : d:A struct d:d { B{ struct B<T where " {{a enum B<T where f: T> : a{var b=Swift.h =1 func f g < where " "" {}struct B<T where f: d< where B : T.h =1 < where h:A func f g:a func let a = " " class d func g a<T {var b { class B<f=1 var b{ var f= let : d:P { class A class A class A{ class A { }}protocol a= func aA} "" class b<f= struct B<T> : { B<T where B{var b:e}}struct S<f:P { let a = " { func foo}typealias d<T where f func aA} struct S<T where " { let : T:e let:d{var" var b { " func a <T {let:d< {func a{{let:A }}} < where h: d B{{ " " " " func a=1 class A var b{ { where =1 class b<T where a = f: a= protocol B:a = " [ 1 {{{ protocol B{ let a func < where h: { class A {}} protocol a{var b {b{{ protocol B:a func struct S<T where =f: { { enum :a<T where g:e let:d struct S<T { func A protocol B{var f= let c{ enum B:P { enum S<T where B : d where a func let a = " {var b:d where g:a<{{var"""" class B<f:A struct S<h {var b {}typealias d< where h: d where f class d<T where g:d<T where g struct B{{ enum b { protocol B{ protocol a class A class B{ class A { { let a<T where B{ let : d:P { struct A enum S<f:d:e}}struct S<T where h:e class d let a func class A<T where f=Swift.E let a = f:d { func g a enum B<T where B : a{ func g a<T where g:d where g:d func a class a<T where " [ 1 class A {var b:d {b<T:a{ }protocol B} class d{} _}}typealias d let a {var f=1 let c{var b { class A { func aA}}}typealias d func f g:a=f:P {{ class A { protocol B} func foo}} let c<f=1 class A class {{ let : T:A{func g a{struct B{ <T { class A { class d<T where g:a var b<T where g func f g:a protocol a<T where g:d<T where h:A class A{ { class d<S where f: {{ protocol a{ class a<T.e}}}} let a{ { enum S<f class a{let:T {b {{ func g a var b:T>: T func foo} let a{ let : d:d enum B{var b{a{struct S<T:A<T <T
apache-2.0
be5b695c51565a61829f91f0b3bd722c
14.769231
79
0.630488
2.338403
false
false
false
false
iHunterX/SocketIODemo
DemoSocketIO/Utils/CustomTextField/iHBorderColorTextField.swift
1
4907
// // iH2TextField.swift // DemoSocketIO // // Created by Đinh Xuân Lộc on 10/21/16. // Copyright © 2016 Loc Dinh Xuan. All rights reserved. // import UIKit @IBDesignable open class iHBorderColorTextField: TextFieldEffects { /** The color of the placeholder text. This property applies a color to the complete placeholder string. The default value for this property is a black color. */ @IBInspectable dynamic open var placeholderColor: UIColor = .black { didSet { updatePlaceholder() } } override open var backgroundColor: UIColor? { set { backgroundLayerColor = newValue } get { return backgroundLayerColor } } /** The scale of the placeholder font. This property determines the size of the placeholder label relative to the font size of the text field. */ @IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.65 { didSet { updatePlaceholder() } } override open var placeholder: String? { didSet { updatePlaceholder() } } override open var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: CGFloat = 1 private let placeholderInsets = CGPoint(x: 6, y: 6) private let textFieldInsets = CGPoint(x: 6, y: 6) private let borderLayer = CALayer() private var backgroundLayerColor: UIColor? // MARK: - TextFieldsEffects override open func drawViewsForRect(_ rect: CGRect) { let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = frame.insetBy(dx: placeholderInsets.x, dy: placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font!) updateBorder() updatePlaceholder() layer.addSublayer(borderLayer) addSubview(placeholderLabel) } override open func animateViewsForTextEntry() { borderLayer.borderColor = textColor?.cgColor borderLayer.shadowOffset = CGSize.zero borderLayer.borderWidth = borderThickness borderLayer.shadowColor = textColor?.cgColor borderLayer.shadowOpacity = 0.5 borderLayer.shadowRadius = 1 animationCompletionHandler?(.textEntry) } override open func animateViewsForTextDisplay() { borderLayer.borderColor = nil borderLayer.shadowOffset = CGSize.zero borderLayer.borderWidth = 0 borderLayer.shadowColor = nil borderLayer.shadowOpacity = 0 borderLayer.shadowRadius = 0 animationCompletionHandler?(.textDisplay) } // MARK: - Private open override func updateBorder() { borderLayer.frame = rectForBorder(frame) borderLayer.backgroundColor = backgroundColor?.cgColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder { animateViewsForTextEntry() } } private func placeholderFontFromFont(_ font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale) return smallerFont } private func rectForBorder(_ bounds: CGRect) -> CGRect { let newRect = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y) return newRect } private func layoutPlaceholderInTextRect() { let textRect = self.textRect(forBounds: bounds) var originX = textRect.origin.x switch textAlignment { case .center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height, width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height) } // MARK: - Overrides override open func editingRect(forBounds bounds: CGRect) -> CGRect { let newBounds = rectForBorder(bounds) return newBounds.insetBy(dx: textFieldInsets.x, dy: 0) } override open func textRect(forBounds bounds: CGRect) -> CGRect { let newBounds = rectForBorder(bounds) return newBounds.insetBy(dx: textFieldInsets.x, dy: 0) } }
gpl-3.0
cb83b561996cd8dbfadbdfc383841e1e
30.025316
133
0.626275
5.428571
false
false
false
false
tmn/swift-http-server
Sources/HTTP/Server.swift
1
2298
import func libc.accept import func libc.close import func libc.send import func libc.strlen import struct libc.sockaddr import struct libc.socklen_t import class utils.Socket public enum Action { case Send(Response) } extension Action { func response() -> Response { switch self { case .Send(let res): return res } } } public class Server { var serverSocket: Socket var routes = [String: Any]() var router = Router() public typealias Handler = (Request, Response) -> Action public init() { serverSocket = Socket(serverSocket: -1) serverSocket.connect() } public func addRoute(route: String, _ callback: () -> Void) { routes[route] = callback } public func start() { while true { #if os(Linux) var sockAddr: sockaddr = sockaddr() #else var sockAddr: sockaddr = sockaddr(sa_len: 0, sa_family: 0, sa_data: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)) #endif var sockLen: socklen_t = 0 let sockClient = accept(serverSocket.sock, &sockAddr, &sockLen) let request = Request(socket: Socket(serverSocket: sockClient)) handleRequest(sockClient, request: request) close(sockClient) } } private func handleRequest(socket: Int32, request: Request) { print("Path: \(request.path), method: \(request.method)") if let route = router.findRoute(request.path, method: request.method) { let res: Response = route.handler( ( request, Response() ) ).response() sendMessage(socket, message: res.headers()) sendMessage(socket, message: res.body) } } func sendMessage(socket: Int32, message: String) { send(socket,[UInt8](message.utf8), Int(strlen(message)), 0) } public func post(path: String, _ handler: Handler) { router.addRoute(Route(method: HTTPMethod.POST, path: path, handler: handler)) } public func get(path: String, _ handler: Handler) { router.addRoute(Route(method: HTTPMethod.GET, path: path, handler: handler)) } }
bsd-3-clause
5a00183234a33c9ff1b0a4f12200460a
27.02439
123
0.573977
4.208791
false
false
false
false
hejunbinlan/Operations
examples/Permissions/Pods/YapDatabaseExtensions/framework/YapDatabaseExtensions/Common/YapDatabaseExtensions.swift
1
14961
// // Created by Daniel Thorpe on 08/04/2015. // import YapDatabase /** This is a struct used as a namespace for new types to avoid any possible future clashes with `YapDatabase` types. */ public struct YapDB { /** Helper function for evaluating the path to a database for easy use in the YapDatabase constructor. :param: directory a NSSearchPathDirectory value, use .DocumentDirectory for production. :param: name a String, the name of the sqlite file. :param: suffix a String, will be appended to the name of the file. :returns: a String */ public static func pathToDatabase(directory: NSSearchPathDirectory, name: String, suffix: String? = .None) -> String { let paths = NSSearchPathForDirectoriesInDomains(directory, .UserDomainMask, true) let directory: String = paths.first ?? NSTemporaryDirectory() let filename: String = { if let suffix = suffix { return "\(name)-\(suffix).sqlite" } return "\(name).sqlite" }() return (directory as NSString).stringByAppendingPathComponent(filename) } /// Type of closure which can perform operations on newly created/opened database instances. public typealias DatabaseOperationsBlock = (YapDatabase) -> Void /** Conveniently create or read a YapDatabase with the given name in the application's documents directory. Optionally, pass a block which receives the database instance, which is called before being returned. This block allows for things like registering extensions. Typical usage in a production environment would be to use this inside a singleton pattern, eg extension YapDB { public static var userDefaults: YapDatabase { get { struct DatabaseSingleton { static func database() -> YapDatabase { return YapDB.databaseNamed("User Defaults") } static let instance = DatabaseSingleton.database() } return DatabaseSingleton.instance } } } which would allow the following behavior in your app: let userDefaultDatabase = YapDB.userDefaults Note that you can only use this convenience if you use the default serializers and sanitizers etc. :param: name a String, which will be the name of the SQLite database in the documents folder. :param: operations a DatabaseOperationsBlock closure, which receives the database, but is executed before the database is returned. :returns: the YapDatabase instance. */ public static func databaseNamed(name: String, operations: DatabaseOperationsBlock? = .None) -> YapDatabase { let db = YapDatabase(path: pathToDatabase(.DocumentDirectory, name: name, suffix: .None)) operations?(db) return db } /** Conveniently create an empty database for testing purposes in the app's Caches directory. This function should only be used in unit tests, as it will delete any previously existing SQLite file with the same path. It should only be used like this inside your test case. func test_MyUnitTest() { let db = YapDB.testDatabaseForFile(__FILE__, test: __FUNCTION__) // etc etc } func test_GivenInitialData_MyUnitTest(initialDataImport: YapDB.DatabaseOperationsBlock) { let db = YapDB.testDatabaseForFile(__FILE__, test: __FUNCTION__, operations: initialDataImport) // etc etc } :param: file a String, which should be the swift special macro __FILE__ :param: test a String, which should be the swift special macro __FUNCTION__ :param: operations a DatabaseOperationsBlock closure, which receives the database, but is executed before the database is returned. This is very useful if you want to populate the database with some objects before running the test. :returns: the YapDatabase instance. */ public static func testDatabaseForFile(file: String, test: String, operations: DatabaseOperationsBlock? = .None) -> YapDatabase { let path = pathToDatabase(.CachesDirectory, name: (file as NSString).lastPathComponent, suffix: test.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "()"))) assert(!path.isEmpty, "Path should not be empty.") do { try NSFileManager.defaultManager().removeItemAtPath(path) } catch { } let db = YapDatabase(path: path) operations?(db) return db } } extension YapDB { /** A database index value type. :param: collection A String :param: key A String */ public struct Index { public let collection: String public let key: String public init(collection: String, key: String) { self.collection = collection self.key = key } } } // MARK: - Identifiable /** A generic protocol which is used to return a unique identifier for the type. To use `String` type identifiers, use the aliased Identifier type. */ public protocol Identifiable { typealias IdentifierType: CustomStringConvertible var identifier: IdentifierType { get } } /** A typealias of String, which implements the Printable protocol. When implementing the Identifiable protocol, use Identifier for your String identifiers. extension Person: Identifiable { let identifier: Identifier } */ public typealias Identifier = String extension Identifier: CustomStringConvertible { public var description: String { return self } } // MARK: - Persistable /** Types which implement Persistable can be used in the functions defined in this framework. It assumes that all instances of a type are stored in the same YapDatabase collection. */ public protocol Persistable: Identifiable { /// The YapDatabase collection name the type is stored in. static var collection: String { get } } /** A simple function which generates a String key from a Persistable instance. Note that it is preferable to use this exclusively to ensure a consistent key structure. :param: persistable A Persistable type instance :returns: A String */ public func keyForPersistable<P: Persistable>(persistable: P) -> String { return "\(persistable.identifier)" } /** A simple function which generates a YapDB.Index from a Persistable instance. All write(_:) store objects in the database using this function. :param: persistable A Persistable type instance :returns: A YapDB.Index */ public func indexForPersistable<P: Persistable>(persistable: P) -> YapDB.Index { return YapDB.Index(collection: persistable.dynamicType.collection, key: keyForPersistable(persistable)) } /** A generic protocol which extends Persistable. It allows types to expose their own metadata object type for use in YapDatabase. The object metadata must conform to NSCoding. */ public protocol ObjectMetadataPersistable: Persistable { typealias MetadataType: NSCoding /// The metadata object for this Persistable type. var metadata: MetadataType { get } } /** A generic protocol which extends Persistable. It allows types to expose their own metadata value type for use in YapDatabase. The metadata value must conform to Saveable. */ public protocol ValueMetadataPersistable: Persistable { typealias MetadataType: Saveable /// The metadata value for this Persistable type. var metadata: MetadataType { get } } // MARK: - Archiver & Saveable /** A generic protocol which acts as an archiver for value types. */ public protocol Archiver { typealias ValueType /// The value type which is being encoded/decoded var value: ValueType { get } /// Required initializer receiving the wrapped value type. init(_: ValueType) } /** A generic protocol which can be implemented to vends another object capable of archiving the receiver. */ public protocol Saveable { typealias ArchiverType: Archiver var archive: ArchiverType { get } } /// Default implementations of archiving/unarchiving. extension Archiver where ValueType: Saveable, ValueType.ArchiverType == Self { /// Simple helper to unarchive any object, has a default implementation public static func unarchive(object: AnyObject?) -> ValueType? { return (object as? Self)?.value } /// Simple helper to unarchive objects, has a default implementation public static func unarchive(objects: [AnyObject]) -> [ValueType] { return objects.reduce([ValueType]()) { (var acc, object) -> [ValueType] in if let value = unarchive(object) { acc.append(value) } return acc } } /// Simple helper to archive a value, has a default implementation public static func archive(value: ValueType?) -> Self? { return value?.archive } /// Simple helper to archive a values, has a default implementation public static func archive(values: [ValueType]) -> [Self] { return values.map { $0.archive } } } /// Default implementations of archiving/unarchiving. extension Saveable where ArchiverType: NSCoding, ArchiverType.ValueType == Self { public static func unarchive(object: AnyObject?) -> Self? { return ArchiverType.unarchive(object) } public static func unarchive(objects: [AnyObject]) -> [Self] { return ArchiverType.unarchive(objects) } public static func archive(value: Self?) -> AnyObject? { return ArchiverType.archive(value) } public static func archive(values: [Self]) -> [AnyObject] { return values.map { $0.archive } } /// The archive(r) public var archive: ArchiverType { return ArchiverType(self) } public init?(_ object: AnyObject?) { if let tmp = ArchiverType.unarchive(object) { self = tmp } else { return nil } } } extension SequenceType where Generator.Element: Archiver { public var values: [Generator.Element.ValueType] { return map { $0.value } } } extension SequenceType where Generator.Element: Saveable { public var archives: [Generator.Element.ArchiverType] { return map { $0.archive } } } extension SequenceType where Generator.Element: Hashable { public func unique() -> [Generator.Element] { return Array(Set(self)) } } extension YapDatabaseConnection { /** Synchronously reads from the database on the connection. The closure receives the read transaction, and the function returns the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. :param: block A closure which receives YapDatabaseReadTransaction and returns T :returns: An instance of T */ public func read<T>(block: (YapDatabaseReadTransaction) -> T) -> T { var result: T! = .None readWithBlock { result = block($0) } return result } /** Synchronously writes to the database on the connection. The closure receives the read write transaction, and the function returns the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. :param: block A closure which receives YapDatabaseReadWriteTransaction and returns T :returns: An instance of T */ public func write<T>(block: (YapDatabaseReadWriteTransaction) -> T) -> T { var result: T! = .None readWriteWithBlock { result = block($0) } return result } /** Asynchronously reads from the database on the connection. The closure receives the read transaction, and completion block receives the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. :param: block A closure which receives YapDatabaseReadTransaction and returns T :param: queue A dispatch_queue_t, defaults to main queue, can be ommitted in most cases. :param: completion A closure which receives T and returns Void. */ public func asyncRead<T>(block: (YapDatabaseReadTransaction) -> T, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (T) -> Void) { var result: T! = .None asyncReadWithBlock({ result = block($0) }, completionQueue: queue) { completion(result) } } /** Asynchronously writes to the database on the connection. The closure receives the read write transaction, and completion block receives the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. :param: block A closure which receives YapDatabaseReadWriteTransaction and returns T :param: queue A dispatch_queue_t, defaults to main queue, can be ommitted in most cases. :param: completion A closure which receives T and returns Void. */ public func asyncWrite<T>(block: (YapDatabaseReadWriteTransaction) -> T, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (T) -> Void) { var result: T! = .None asyncReadWriteWithBlock({ result = block($0) }, completionQueue: queue) { completion(result) } } } // MARK: Hashable etc extension YapDB.Index: CustomStringConvertible, Hashable { public var description: String { return "\(collection):\(key)" } public var hashValue: Int { return description.hashValue } } public func == (a: YapDB.Index, b: YapDB.Index) -> Bool { return (a.collection == b.collection) && (a.key == b.key) } // MARK: Saveable extension YapDB.Index: Saveable { public typealias Archiver = YapDBIndexArchiver public var archive: Archiver { return Archiver(self) } } // MARK: Archivers public final class YapDBIndexArchiver: NSObject, NSCoding, Archiver { public let value: YapDB.Index public init(_ v: YapDB.Index) { value = v } public required init(coder aDecoder: NSCoder) { let collection = aDecoder.decodeObjectForKey("collection") as! String let key = aDecoder.decodeObjectForKey("key") as! String value = YapDB.Index(collection: collection, key: key) } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(value.collection, forKey: "collection") aCoder.encodeObject(value.key, forKey: "key") } }
mit
8d10211e82c42754997f91ac4a02e8d9
31.383117
183
0.683845
4.812158
false
false
false
false
GeoThings/LakestoneCore
Source/AnyFileOrDirectory.swift
2
2685
// // AnyFileOrDirectory.swift // LakestoneCore // // Created by Taras Vozniuk on 9/29/16. // Copyright © 2016 GeoThings. All rights reserved. // // -------------------------------------------------------- // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #if !COOPER import Foundation #endif public protocol AnyFileOrDirectory { var path: String { get } var url: URL { get } var exists: Bool { get } var isDirectory: Bool { get } var name: String { get } var size: Int64 { get } var lastModificationDateº: Date? { get } func remove() throws var parentDirectoryº: Directory? { get } // copy the file or directory with subdirectories to new destination; overwrite existing or throw exception // returns new location func copy(to destination: AnyFileOrDirectory, overwrites: Bool) throws -> AnyFileOrDirectory // move the file or directory with subdirectories to new destination; overwrite existing or throw exception // returns new location func move(to destination: AnyFileOrDirectory, overwrites: Bool) throws -> AnyFileOrDirectory } #if !COOPER extension AnyFileOrDirectory { public var exists: Bool { return FileManager.default.fileExists(atPath: self.path) } public var isDirectory: Bool { var isDirectoryPath: ObjCBool = ObjCBool(false) let doesFileExists = FileManager.default.fileExists(atPath: self.path, isDirectory: &isDirectoryPath) #if os(Linux) return doesFileExists && Bool(isDirectoryPath) #else return doesFileExists && isDirectoryPath.boolValue #endif } public var lastModificationDateº: Date? { guard let fileAttributes = try? FileManager.default.attributesOfItem(atPath: self.path) else { return nil } return fileAttributes[FileAttributeKey.modificationDate] as? Date } } #endif public func FileOrDirectory(with path: String) -> AnyFileOrDirectory { let file = File(path: path) if (file.isDirectory) { return Directory(path: path) } else { return file } } public func FileOrDirectory(with fileURL: URL) -> AnyFileOrDirectory { let file = File(fileURL: fileURL) if (file.isDirectory) { return Directory(directoryURL: fileURL) } else { return file } }
apache-2.0
199c21e4a1f23f9aa8e908caba395860
26.927083
108
0.721
4.037651
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch7/7.3.2continue语句2.playground/section-1.swift
1
264
// Playground - noun: a place where people can play label1: for var x = 0; x < 5; x++ { label2: for var y = 5; y > 0; y-- { if y == x { //continue label1 } println("(x,y) = (\(x),\(y))") } } println("Game Over!")
gpl-2.0
1d1457b60130140d4f3c7fc73e8357a5
19.307692
51
0.439394
3.142857
false
false
false
false
getsocial-im/getsocial-ios-sdk
example/GetSocialDemo/Views/Communities/Polls/Vote/VoteOptionTableViewCell.swift
1
1873
// // VoteOptionTableViewCell.swift // GetSocialDemo // // Created by Gábor Vass on 03/05/2021. // Copyright © 2021 GrambleWorld. All rights reserved. // import Foundation import UIKit import GetSocialSDK class VoteOptionTableViewCell: UITableViewCell { let optionId = UILabel() let optionText = UILabel() let imageURL = UILabel() let videoURL = UILabel() let voteCount = UILabel() public required init?(coder: NSCoder) { super.init(coder: coder) addUIElements() } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addUIElements() } func update(_ option: PollOption, selected: Bool) { self.optionId.text = "Id: \(option.optionId)" self.optionText.text = "Text: \(option.text ?? "")" self.imageURL.text = "Image URL: \(option.attachment?.imageUrl ?? "")" self.videoURL.text = "Video URL: \(option.attachment?.videoUrl ?? "")" self.voteCount.text = "Vote count: \(option.voteCount)" self.accessoryType = selected ? .checkmark : .none } private func addUIElements() { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.spacing = 4 self.contentView.addSubview(stackView) stackView.addArrangedSubview(self.optionId) stackView.addArrangedSubview(self.optionText) stackView.addArrangedSubview(self.imageURL) stackView.addArrangedSubview(self.videoURL) stackView.addArrangedSubview(self.voteCount) NSLayoutConstraint.activate([ stackView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor), stackView.topAnchor.constraint(equalTo: self.contentView.topAnchor), stackView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor) ]) } }
apache-2.0
37f4b9f08cd4dd2e52f4d8df2c88404d
29.177419
81
0.755211
3.980851
false
false
false
false
pascalbros/PAPermissions
Example/PAPermissionsApp/PACustomPermissionsCheck.swift
1
583
// // PACustomPermissionsCheck.swift // PAPermissionsApp // // Created by Pasquale Ambrosini on 06/09/16. // Copyright © 2016 Pasquale Ambrosini. All rights reserved. // import UIKit import PAPermissions class PACustomPermissionsCheck: PAPermissionsCheck { override init() { super.init() self.status = .disabled self.canBeDisabled = true } open override func checkStatus() { self.updateStatus() } open override func defaultAction() { if self.status == .enabled { self.status = .disabled }else{ self.status = .enabled } self.updateStatus() } }
mit
492a4854f7f7b74273d6b0d7481abd3d
17.1875
61
0.702749
3.325714
false
true
false
false
hebertialmeida/ModelGen
Sources/ModelGenKit/Utils.swift
1
3514
// // Utils.swift // ModelGen // // Created by Heberti Almeida on 2017-05-10. // Copyright © 2017 ModelGen. All rights reserved. // import Foundation import Commander import PathKit // MARK: - Global var jsonAbsolutePath = Path() var currentFile = Path() // MARK: - Validators func checkPath(type: String, assertion: @escaping (Path) -> Bool) -> ((Path) throws -> Path) { return { (path: Path) throws -> Path in guard assertion(path) else { throw ArgumentError.invalidType(value: path.description, type: type, argument: nil) } return path } } public let pathExists = checkPath(type: "path") { $0.exists } let fileExists = checkPath(type: "file") { $0.isFile } let dirExists = checkPath(type: "directory") { $0.isDirectory } let pathsExist = { (paths: [Path]) throws -> [Path] in try paths.map(pathExists) } let filesExist = { (paths: [Path]) throws -> [Path] in try paths.map(fileExists) } let dirsExist = { (paths: [Path]) throws -> [Path] in try paths.map(dirExists) } // MARK: - Path as Input Argument extension Path: ArgumentConvertible { public init(parser: ArgumentParser) throws { guard let path = parser.shift() else { throw ArgumentError.missingValue(argument: nil) } self = Path(path) } } // MARK: - Output (Path or Console) Argument public enum OutputDestination: ArgumentConvertible { case console case file(path: Path) public init(parser: ArgumentParser) throws { guard let path = parser.shift() else { throw ArgumentError.missingValue(argument: nil) } self = .file(path: Path(path)) } public var description: String { switch self { case .console: return "(stdout)" case .file(let path): return path.description } } func write(content: String, onlyIfChanged: Bool = false) { switch self { case .console: print(content) case .file(let path): do { if try onlyIfChanged && path.exists && path.read(.utf8) == content { return print("☑️ Unchanged: \(path)") } try path.write(content) print("✅ Generated: \(path)") } catch let error { printError(error.localizedDescription, showFile: true) } } } } /// Validate a template path /// /// - Parameter template: String template path /// - Returns: Typed valid Path /// - Throws: TemplateError func validate(_ template: String) throws -> Path { guard !template.isEmpty else { throw TemplateError.noTemplateProvided } let templatePath = Path(template) guard templatePath.isFile else { throw TemplateError.templatePathNotFound(path: templatePath) } return templatePath } // MARK: - Decode from dictionary extension Decodable { public init(from: Any) throws { let data = try JSONSerialization.data(withJSONObject: from, options: .prettyPrinted) let decoder = JSONDecoder() self = try decoder.decode(Self.self, from: data) } } // MARK: - Remove duplicated ocurrencies from Array // https://stackoverflow.com/a/35014912/976628 extension Array where Element: Equatable { func removeDuplicates() -> [Element] { var result = [Element]() for value in self { if result.contains(value) == false { result.append(value) } } return result } }
mit
4491d71d55da9ac21898dca72493b2e6
27.282258
122
0.616766
4.150296
false
false
false
false
jokechat/swift3-novel
swift_novels/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationCubeTransition.swift
8
3123
// // NVActivityIndicatorAnimationCubeTransition.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/24/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationCubeTransition: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let squareSize = size.width / 5 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let deltaX = size.width - squareSize let deltaY = size.height - squareSize let duration: CFTimeInterval = 1.6 let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0, -0.8] let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.25, 0.5, 0.75, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction] scaleAnimation.values = [1, 0.5, 1, 0.5, 1] scaleAnimation.duration = duration // Translate animation let translateAnimation = CAKeyframeAnimation(keyPath: "transform.translation") translateAnimation.keyTimes = scaleAnimation.keyTimes translateAnimation.timingFunctions = scaleAnimation.timingFunctions translateAnimation.values = [ NSValue(cgSize: CGSize(width: 0, height: 0)), NSValue(cgSize: CGSize(width: deltaX, height: 0)), NSValue(cgSize: CGSize(width: deltaX, height: deltaY)), NSValue(cgSize: CGSize(width: 0, height: deltaY)), NSValue(cgSize: CGSize(width: 0, height: 0)) ] translateAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = scaleAnimation.timingFunctions rotateAnimation.values = [0, CGFloat(-M_PI_2), CGFloat(-M_PI), CGFloat(-1.5 * M_PI), CGFloat(-2 * M_PI)] rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, translateAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false // Draw squares for i in 0 ..< 2 { let square = NVActivityIndicatorShape.rectangle.layerWith(size: CGSize(width: squareSize, height: squareSize), color: color) let frame = CGRect(x: x, y: y, width: squareSize, height: squareSize) animation.beginTime = beginTime + beginTimes[i] square.frame = frame square.add(animation, forKey: "animation") layer.addSublayer(square) } } }
apache-2.0
48a20e3096fd4356ecef750a1fdade21
41.780822
136
0.648415
5.144975
false
false
false
false
WeHUD/app
weHub-ios/Gzone_App/Gzone_App/ForgotPassViewController.swift
1
1241
// // ForgotPassViewController.swift // Gzone_App // // Created by Tracy Sablon on 05/03/2017. // Copyright © 2017 Tracy Sablon. All rights reserved. // import UIKit class ForgotPassViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var mailTxtField: UITextField! @IBOutlet weak var SendMailBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() SendMailBtn.layer.cornerRadius = 15; SendMailBtn.layer.borderWidth = 0.0; SendMailBtn.layer.borderColor = UIColor.white.cgColor SendMailBtn.backgroundColor = (UIColor(red: 78/255.0, green: 14/255.0, blue: 15/255.0, alpha: 1.0)) self.mailTxtField.delegate = self //extension Utils self.view.closeTextField() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.mailTxtField.resignFirstResponder() return true } @IBAction func closeForgotPass(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } }
bsd-3-clause
b4f323be07b27472d39c690211d3d75f
25.382979
107
0.651613
4.444444
false
false
false
false
DikeyKing/WeCenterMobile-iOS
WeCenterMobile/Model/Manager/DataManager.swift
1
4756
// // DataManager.swift // WeCenterMobile // // Created by Darren Liu on 14/10/7. // Copyright (c) 2014年 ifLab. All rights reserved. // import CoreData import Foundation class DataManager: NSObject { required init?(name: String?) { super.init() managedObjectModel = NSManagedObjectModel(contentsOfURL: NSBundle.mainBundle().URLForResource("WeCenterMobile", withExtension: "momd")!) if managedObjectModel == nil { return nil } if name != nil { let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) let directory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last as! NSURL let url = directory.URLByAppendingPathComponent(name! + ".sqlite") var error: NSError? = nil if persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data." dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." dict[NSUnderlyingErrorKey] = error error = NSError( domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: dict as [NSObject: AnyObject]) NSLog("Unresolved error \(error), \(error!.userInfo)") return nil } managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext!.persistentStoreCoordinator = persistentStoreCoordinator } } private static var _defaultManager: DataManager! = nil private static var _temporaryManager: DataManager! = nil static var defaultManager: DataManager! { // for creating cached objects get { if _defaultManager == nil { _defaultManager = DataManager(name: "WeCenterMobile") } return _defaultManager } set { _defaultManager = newValue } } static var temporaryManager: DataManager! { // for creating temporary objects get { if _temporaryManager == nil { _temporaryManager = DataManager(name: nil) } return _temporaryManager } set { _temporaryManager = newValue } } func create(entityName: String) -> DataObject { let entity = managedObjectModel.entitiesByName[entityName] as! NSEntityDescription return DataObject(entity: entity, insertIntoManagedObjectContext: managedObjectContext) } func fetch(entityName: String, ID: NSNumber, error: NSErrorPointer) -> DataObject? { let request = NSFetchRequest(entityName: entityName) request.predicate = NSPredicate(format: "id = %@", ID) request.fetchLimit = 1 let results = managedObjectContext?.executeFetchRequest(request, error: error) if results != nil && results!.count != 0 { return results![0] as? DataObject } else { if error != nil && error.memory == nil { error.memory = NSError() // Needs specification } return nil } } func fetchAll(entityName: String, error: NSErrorPointer) -> [DataObject] { let request = NSFetchRequest(entityName: entityName) let results = managedObjectContext?.executeFetchRequest(request, error: error) if results != nil { return results as! [DataObject] } else { if error != nil && error.memory == nil { error.memory = NSError() // Needs specification } return [] } } func autoGenerate(entityName: String, ID: NSNumber) -> DataObject { var object = fetch(entityName, ID: ID, error: nil) if object == nil { object = create(entityName) object!.setValue(ID, forKey: "id") } return object! } func deleteAllObjectsWithEntityName(entityName: String) { managedObjectContext?.msr_deleteAllObjectsWithEntityName(entityName) } func saveChanges(error: NSErrorPointer) { if managedObjectContext?.hasChanges ?? false { managedObjectContext?.save(error) } } var managedObjectModel: NSManagedObjectModel! var managedObjectContext: NSManagedObjectContext? }
gpl-2.0
5ed9e3ea887afa509d6503e7ad033ea6
41.446429
155
0.62621
5.707083
false
false
false
false
ios-ximen/DYZB
斗鱼直播/Pods/Kingfisher/Sources/ImageDownloader.swift
41
24876
// // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang <[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 os(macOS) import AppKit #else import UIKit #endif /// Progress update block of downloader. public typealias ImageDownloaderProgressBlock = DownloadProgressBlock /// Completion block of downloader. public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> ()) /// Download task. public struct RetrieveImageDownloadTask { let internalTask: URLSessionDataTask /// Downloader by which this task is intialized. public private(set) weak var ownerDownloader: ImageDownloader? /** Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error. */ public func cancel() { ownerDownloader?.cancelDownloadingTask(self) } /// The original request URL of this download task. public var url: URL? { return internalTask.originalRequest?.url } /// The relative priority of this download task. /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task. /// The value for it is between 0.0~1.0. Default priority is value of 0.5. /// See documentation on `priority` of `NSURLSessionTask` for more about it. public var priority: Float { get { return internalTask.priority } set { internalTask.priority = newValue } } } ///The code of errors which `ImageDownloader` might encountered. public enum KingfisherError: Int { /// badData: The downloaded data is not an image or the data is corrupted. case badData = 10000 /// notModified: The remote server responsed a 304 code. No image data downloaded. case notModified = 10001 /// The HTTP status code in response is not valid. If an invalid /// code error received, you could check the value under `KingfisherErrorStatusCodeKey` /// in `userInfo` to see the code. case invalidStatusCode = 10002 /// notCached: The image rquested is not in cache but .onlyFromCache is activated. case notCached = 10003 /// The URL is invalid. case invalidURL = 20000 /// The downloading task is cancelled before started. case downloadCancelledBeforeStarting = 30000 } /// Key will be used in the `userInfo` of `.invalidStatusCode` public let KingfisherErrorStatusCodeKey = "statusCode" /// Protocol of `ImageDownloader`. public protocol ImageDownloaderDelegate: class { /** Called when the `ImageDownloader` object successfully downloaded an image from specified URL. - parameter downloader: The `ImageDownloader` object finishes the downloading. - parameter image: Downloaded image. - parameter url: URL of the original request URL. - parameter response: The response object of the downloading process. */ func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) /** Called when the `ImageDownloader` object starts to download an image from specified URL. - parameter downloader: The `ImageDownloader` object starts the downloading. - parameter url: URL of the original request. - parameter response: The request object of the downloading process. */ func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) /** Check if a received HTTP status code is valid or not. By default, a status code between 200 to 400 (excluded) is considered as valid. If an invalid code is received, the downloader will raise an .invalidStatusCode error. It has a `userInfo` which includes this statusCode and localizedString error message. - parameter code: The received HTTP status code. - parameter downloader: The `ImageDownloader` object asking for validate status code. - returns: Whether this HTTP status code is valid or not. - Note: If the default 200 to 400 valid code does not suit your need, you can implement this method to change that behavior. */ func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool } extension ImageDownloaderDelegate { public func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {} public func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) {} public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool { return (200..<400).contains(code) } } /// Protocol indicates that an authentication challenge could be handled. public protocol AuthenticationChallengeResponsable: class { /** Called when an session level authentication challenge is received. This method provide a chance to handle and response to the authentication challenge before downloading could start. - parameter downloader: The downloader which receives this challenge. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call. - Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`. */ func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) } extension AuthenticationChallengeResponsable { func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) { let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) completionHandler(.useCredential, credential) return } } completionHandler(.performDefaultHandling, nil) } } /// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server. open class ImageDownloader { class ImageFetchLoad { var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]() var responseData = NSMutableData() var downloadTaskCount = 0 var downloadTask: RetrieveImageDownloadTask? var cancelSemaphore: DispatchSemaphore? } // MARK: - Public property /// The duration before the download is timeout. Default is 15 seconds. open var downloadTimeout: TimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. /// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. /// If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead. open var trustedHosts: Set<String>? /// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. /// You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly. open var sessionConfiguration = URLSessionConfiguration.ephemeral { didSet { session?.invalidateAndCancel() session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: OperationQueue.main) } } /// Whether the download requests should use pipeling or not. Default is false. open var requestsUsePipelining = false fileprivate let sessionHandler: ImageDownloaderSessionHandler fileprivate var session: URLSession? /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. open weak var delegate: ImageDownloaderDelegate? /// A responder for authentication challenge. /// Downloader will forward the received authentication challenge for the downloading session to this responder. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable? // MARK: - Internal property let barrierQueue: DispatchQueue let processQueue: DispatchQueue let cancelQueue: DispatchQueue typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) var fetchLoads = [URL: ImageFetchLoad]() // MARK: - Public method /// The default downloader. public static let `default` = ImageDownloader(name: "default") /** Init a downloader with name. - parameter name: The name for the downloader. It should not be empty. - returns: The downloader object. */ public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.") } barrierQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Barrier.\(name)", attributes: .concurrent) processQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process.\(name)", attributes: .concurrent) cancelQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Cancel.\(name)") sessionHandler = ImageDownloaderSessionHandler() // Provide a default implement for challenge responder. authenticationChallengeResponder = sessionHandler session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main) } deinit { session?.invalidateAndCancel() } func fetchLoad(for url: URL) -> ImageFetchLoad? { var fetchLoad: ImageFetchLoad? barrierQueue.sync(flags: .barrier) { fetchLoad = fetchLoads[url] } return fetchLoad } /** Download an image with a URL and option. - parameter url: Target URL. - parameter retrieveImageTask: The task to cooporate with cache. Pass `nil` if you are not trying to use downloader and cache. - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`. - parameter progressBlock: Called when the download progress updated. - parameter completionHandler: Called when the download progress finishes. - returns: A downloading task. You could call `cancel` on it to stop the downloading process. */ @discardableResult open func downloadImage(with url: URL, retrieveImageTask: RetrieveImageTask? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: ImageDownloaderProgressBlock? = nil, completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask? { if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) return nil } let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout) request.httpShouldUsePipelining = requestsUsePipelining if let modifier = options?.modifier { guard let r = modifier.modified(for: request) else { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) return nil } request = r } // There is a possiblility that request modifier changed the url to `nil` or empty. guard let url = request.url, !url.absoluteString.isEmpty else { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), nil, nil) return nil } var downloadTask: RetrieveImageDownloadTask? setup(progressBlock: progressBlock, with: completionHandler, for: url, options: options) {(session, fetchLoad) -> Void in if fetchLoad.downloadTask == nil { let dataTask = session.dataTask(with: request) fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self) dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority dataTask.resume() self.delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request) // Hold self while the task is executing. self.sessionHandler.downloadHolder = self } fetchLoad.downloadTaskCount += 1 downloadTask = fetchLoad.downloadTask retrieveImageTask?.downloadTask = downloadTask } return downloadTask } } // MARK: - Download method extension ImageDownloader { // A single key may have multiple callbacks. Only download once. func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, options: KingfisherOptionsInfo?, started: @escaping ((URLSession, ImageFetchLoad) -> Void)) { func prepareFetchLoad() { barrierQueue.sync(flags: .barrier) { let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad() let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler) loadObjectForURL.contents.append((callbackPair, options ?? KingfisherEmptyOptionsInfo)) fetchLoads[url] = loadObjectForURL if let session = session { started(session, loadObjectForURL) } } } if let fetchLoad = fetchLoad(for: url), fetchLoad.downloadTaskCount == 0 { if fetchLoad.cancelSemaphore == nil { fetchLoad.cancelSemaphore = DispatchSemaphore(value: 0) } cancelQueue.async { _ = fetchLoad.cancelSemaphore?.wait(timeout: .distantFuture) fetchLoad.cancelSemaphore = nil prepareFetchLoad() } } else { prepareFetchLoad() } } func cancelDownloadingTask(_ task: RetrieveImageDownloadTask) { barrierQueue.sync(flags: .barrier) { if let URL = task.internalTask.originalRequest?.url, let imageFetchLoad = self.fetchLoads[URL] { imageFetchLoad.downloadTaskCount -= 1 if imageFetchLoad.downloadTaskCount == 0 { task.internalTask.cancel() } } } } func clean(for url: URL) { barrierQueue.sync(flags: .barrier) { fetchLoads.removeValue(forKey: url) return } } } // MARK: - NSURLSessionDataDelegate /// Delegate class for `NSURLSessionTaskDelegate`. /// The session object will hold its delegate until it gets invalidated. /// If we use `ImageDownloader` as the session delegate, it will not be released. /// So we need an additional handler to break the retain cycle. // See https://github.com/onevcat/Kingfisher/issues/235 class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponsable { // The holder will keep downloader not released while a data task is being executed. // It will be set when the task started, and reset when the task finished. var downloadHolder: ImageDownloader? func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { guard let downloader = downloadHolder else { completionHandler(.cancel) return } if let statusCode = (response as? HTTPURLResponse)?.statusCode, let url = dataTask.originalRequest?.url, !(downloader.delegate ?? downloader).isValidStatusCode(statusCode, for: downloader) { let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidStatusCode.rawValue, userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)]) callCompletionHandlerFailure(error: error, url: url) } completionHandler(.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { guard let downloader = downloadHolder else { return } if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) { fetchLoad.responseData.append(data) if let expectedLength = dataTask.response?.expectedContentLength { for content in fetchLoad.contents { DispatchQueue.main.async { content.callback.progressBlock?(Int64(fetchLoad.responseData.length), expectedLength) } } } } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let url = task.originalRequest?.url else { return } guard error == nil else { callCompletionHandlerFailure(error: error!, url: url) return } processImage(for: task, url: url) } /** This method is exposed since the compiler requests. Do not call it. */ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let downloader = downloadHolder else { return } downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler) } private func cleanFetchLoad(for url: URL) { guard let downloader = downloadHolder else { return } downloader.clean(for: url) if downloader.fetchLoads.isEmpty { downloadHolder = nil } } private func callCompletionHandlerFailure(error: Error, url: URL) { guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else { return } // We need to clean the fetch load first, before actually calling completion handler. cleanFetchLoad(for: url) var leftSignal: Int repeat { leftSignal = fetchLoad.cancelSemaphore?.signal() ?? 0 } while leftSignal != 0 for content in fetchLoad.contents { content.options.callbackDispatchQueue.safeAsync { content.callback.completionHandler?(nil, error as NSError, url, nil) } } } private func processImage(for task: URLSessionTask, url: URL) { guard let downloader = downloadHolder else { return } // We are on main queue when receiving this. downloader.processQueue.async { guard let fetchLoad = downloader.fetchLoad(for: url) else { return } self.cleanFetchLoad(for: url) let data = fetchLoad.responseData as Data // Cache the processed images. So we do not need to re-process the image if using the same processor. // Key is the identifier of processor. var imageCache: [String: Image] = [:] for content in fetchLoad.contents { let options = content.options let completionHandler = content.callback.completionHandler let callbackQueue = options.callbackDispatchQueue let processor = options.processor var image = imageCache[processor.identifier] if image == nil { image = processor.process(item: .data(data), options: options) // Add the processed image to cache. // If `image` is nil, nothing will happen (since the key is not existing before). imageCache[processor.identifier] = image } if let image = image { downloader.delegate?.imageDownloader(downloader, didDownload: image, for: url, with: task.response) if options.backgroundDecode { let decodedImage = image.kf.decoded(scale: options.scaleFactor) callbackQueue.safeAsync { completionHandler?(decodedImage, nil, url, data) } } else { callbackQueue.safeAsync { completionHandler?(image, nil, url, data) } } } else { if let res = task.response as? HTTPURLResponse , res.statusCode == 304 { let notModified = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil) completionHandler?(nil, notModified, url, nil) continue } let badData = NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil) callbackQueue.safeAsync { completionHandler?(nil, badData, url, nil) } } } } } } // Placeholder. For retrieving extension methods of ImageDownloaderDelegate extension ImageDownloader: ImageDownloaderDelegate {} // MARK: - Deprecated extension ImageDownloader { @available(*, deprecated, message: "`requestsUsePipeling` is deprecated. Use `requestsUsePipelining` instead", renamed: "requestsUsePipelining") open var requestsUsePipeling: Bool { get { return requestsUsePipelining } set { requestsUsePipelining = newValue } } }
mit
37bca413c8ab276cd2c7cbf00b848db5
42.718805
227
0.656818
5.644656
false
false
false
false
Lisergishnu/TetraVex
TetraVex/TVHighScoreViewController.swift
1
2528
// // TVHighScoreViewController.swift // TetraVex // // Created by Alessandro Vinciguerra on 08/08/2017. // // Copyright © 2017 Arc676/Alessandro Vinciguerra // // 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 (version 3) // // 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 Cocoa class TVHighScoreViewController : NSViewController, NSTableViewDelegate, NSTableViewDataSource { @IBOutlet weak var tableView: NSTableView! var selectedSize: String = "2x2" var scores: TVHighScores? var dates: [NSDate]? var dateFmt: DateFormatter? override func viewDidLoad() { scores = TVHighScores.read() reload() dateFmt = DateFormatter() dateFmt?.timeZone = TimeZone.current dateFmt?.dateFormat = "yyyy-MM-dd HH:mm:ss" tableView.delegate = self tableView.dataSource = self } func reload() { dates = Array((scores?.scores![selectedSize]!.keys)!).sorted(by: { date1, date2 in return scores!.scores![selectedSize]![date1]! < scores!.scores![selectedSize]![date2]! }) tableView.reloadData() } func numberOfRows(in tableView: NSTableView) -> Int { return dates!.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { if (tableColumn?.identifier)!.rawValue == "Date-Time" { return dateFmt?.string(from: dates![row] as Date) } else { return TVHighScores.timeToString(scores!.scores![selectedSize]![dates![row]]!) } } @IBAction func deleteScores(_ sender: Any) { let alert = NSAlert() alert.messageText = "Are you sure you want to delete your high scores? This cannot be undone." alert.addButton(withTitle: "No") alert.addButton(withTitle: "Yes") if alert.runModal() == NSApplication.ModalResponse.alertSecondButtonReturn { scores?.scores = TVHighScores.emptyScores scores?.save() reload() } } @IBAction func sizeChooser(_ sender: NSPopUpButton) { selectedSize = sender.titleOfSelectedItem! reload() } }
gpl-3.0
44038714954e948c9e387975d1efee8e
30.197531
106
0.692125
4.163097
false
false
false
false
net-a-porter-mobile/NSURLSession-Mock
Pod/Classes/NSURLSession/MockSessionDataTask.swift
1
1918
// // MockSessionDataTask.swift // Pods // // Created by Sam Dean on 19/01/2016. // // import Foundation private var globalTaskIdentifier: Int = 100000 // Some number bigger than the session would naturally create /** Internal implementation of `NSURLSessionDataTask` with read-write properties. And, curiously, added the properties that `NSURLSessionDataTask` says it has but doesn't actually have. Not sure what's going on there. */ class MockSessionDataTask: URLSessionDataTask { let onResume: (_ task: MockSessionDataTask)->() init(onResume: @escaping (_ task: MockSessionDataTask)->()) { self.onResume = onResume } var _taskIdentifier: Int = { globalTaskIdentifier += 1 return globalTaskIdentifier }() override var taskIdentifier: Int { return _taskIdentifier } var _originalRequest: URLRequest? override var originalRequest: URLRequest? { return _originalRequest } var _currentRequest: URLRequest? override var currentRequest: URLRequest? { return _currentRequest } var _state: URLSessionTask.State = .suspended override var state: URLSessionTask.State { return _state } override func resume() { self.onResume(self) } private var _taskDescription: String? override var taskDescription: String? { get { return _taskDescription } set { _taskDescription = newValue } } private var _response: URLResponse? override var response: URLResponse? { get { return _response } set { _response = newValue } } override func cancel() { self._state = .canceling } override var countOfBytesExpectedToSend: Int64 { return 0 } override var countOfBytesExpectedToReceive: Int64 { return NSURLSessionTransferSizeUnknown } }
mit
8c2575d7830ad412f4e1b400e2172f7c
23.589744
135
0.649635
5.101064
false
false
false
false
alexito4/RACPhotos
Pod/Classes/RAC_PHPhotoLibrary.swift
1
6843
// // RAC_PHPhotoLibrary.swift // Originally build for BWallpapers. // http://alejandromp.com/bwallpapers/ // // Created by Alejandro Martinez on 21/6/15. // Copyright (c) 2015 Alejandro Martinez. All rights reserved. // import Foundation import Photos import ReactiveCocoa public enum RACPhotosError: ErrorType { case NotAuthorized(status: PHAuthorizationStatus) case CollectionCreationFailed case CollectionNotFound case PhotoSaveFailed public var nsError: NSError { return NSError(domain: "RACPhotosError", code: 0, userInfo: nil) } } // Sends next event and inmediatly completes the Signal. // Usefoul for Signals that only have one event. extension Observer { public func sendNextAndComplete(value: Value) { sendNext(value) sendCompleted() } } // MARK: Authorization extension PHPhotoLibrary { /// Returns a SignalProducer that will send 1 event with the `PHAuthorizationStatus` when started. /// It checks for the current `authorizationStatus` and only calls the system API if it's not determined. public class func requestAuthorization() -> SignalProducer<PHAuthorizationStatus, RACPhotosError> { return SignalProducer({ (observer, disposable) in let status = PHPhotoLibrary.authorizationStatus() switch status { case .NotDetermined: PHPhotoLibrary.requestAuthorization({ (status) -> Void in switch (status) { case .Authorized: observer.sendNextAndComplete(status) default: observer.sendFailed(RACPhotosError.NotAuthorized(status: status)) } }) case .Restricted, .Denied: observer.sendFailed(RACPhotosError.NotAuthorized(status: status)) case .Authorized: observer.sendNextAndComplete(status) } }) } } // MARK: Images extension PHPhotoLibrary { /// Calls `saveImage` using the `sharedPhotoLibrary` by default. public class func saveImage(image: UIImage, toCollection album: PHAssetCollection) -> SignalProducer<Void, RACPhotosError> { return PHPhotoLibrary.sharedPhotoLibrary().saveImage(image, toCollection: album) } /** Saves the given `image` to the `collection` when started. :param: image Image to be saved. :param: album Collection where to save the image. :returns: SignalProducer with a Void event type. */ public func saveImage(image: UIImage, toCollection album: PHAssetCollection) -> SignalProducer<Void, RACPhotosError> { return SignalProducer { observer, disposable in self.performChanges({ () -> Void in let request = PHAssetChangeRequest.creationRequestForAssetFromImage(image) let asset = request.placeholderForCreatedAsset let albumRequest = PHAssetCollectionChangeRequest(forAssetCollection: album) if let asset = asset, albumRequest = albumRequest { albumRequest.addAssets([asset]) } }, completionHandler: { (completed, error) -> Void in if completed { observer.sendNextAndComplete(Void()) } else { observer.sendFailed(RACPhotosError.PhotoSaveFailed) } }) } } } // MARK: Collections extension PHPhotoLibrary { public typealias CollectionIdentifier = String /** Creates a new collection. :param: title :returns: SignalProducer that will send 1 next event with the identifier of the created collection. */ public func createCollectionWithTitle(title: String) -> SignalProducer<CollectionIdentifier, RACPhotosError> { return SignalProducer { observer, disposable in var identifier: String? self.performChanges({ () -> Void in let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(title) identifier = request.placeholderForCreatedAssetCollection.localIdentifier }, completionHandler: { (completed, error) -> Void in if completed { if let identifier = identifier { observer.sendNextAndComplete(identifier) } else { observer.sendFailed(RACPhotosError.CollectionCreationFailed) } } else { observer.sendFailed(RACPhotosError.CollectionCreationFailed) } }) } } } extension PHAssetCollection { /// Calls `createCollectionWithTitle` using the `sharedPhotoLibrary` by default. public class func createCollectionWithTitle(title: String) -> SignalProducer<String, RACPhotosError> { return PHPhotoLibrary.sharedPhotoLibrary().createCollectionWithTitle(title) } /// Returns a SignalProducer that will send 1 next event with a `PHAssetCollection` that has the given identifier. public class func fetchCollectionWithIdentifier(identifier: String) -> SignalProducer<PHAssetCollection, RACPhotosError> { return SignalProducer { observer, disposable in let result = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers([identifier], options: nil) let album = result.firstObject as? PHAssetCollection if let album = album { observer.sendNextAndComplete(album) } else { observer.sendFailed(RACPhotosError.CollectionNotFound) } } } /// Returns a SignalProducer that will send 1 next event with a `PHAssetCollection` that has the given `title`. public class func fetchCollectionWithTitle(title: String) -> SignalProducer<PHAssetCollection, RACPhotosError> { return SignalProducer { observer, disposable in let options = PHFetchOptions() options.predicate = NSPredicate(format: "title == %@", title) let result = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.Any, options: options) let album = result.firstObject as? PHAssetCollection if let album = album { observer.sendNextAndComplete(album) } else { observer.sendFailed(RACPhotosError.CollectionNotFound) } } } }
mit
62750190a0bfddc85c16f73fc7f5f9a6
35.015789
158
0.619319
5.794242
false
false
false
false
codeforgreenville/trolley-tracker-ios-client
TrolleyTracker/Helpers/GeographyHelpers.swift
1
1203
// // GeographyHelpers.swift // TrolleyTracker // // Created by Austin on 3/23/17. // Copyright © 2017 Code For Greenville. All rights reserved. // import MapKit extension CLLocationCoordinate2D { func distance(from otherCoordinate: CLLocationCoordinate2D) -> CLLocationDistance { let pointA = CLLocation(latitude: latitude, longitude: longitude) let pointB = CLLocation(latitude: otherCoordinate.latitude, longitude: otherCoordinate.longitude) return pointA.distance(from: pointB) } } extension MKMapItem { static func openMapsFromCurrentLocation(toCoordinate coordinate: CLLocationCoordinate2D, named name: String) { let placeMark = MKPlacemark(coordinate: coordinate, addressDictionary: nil) let currentLocation = MKMapItem.forCurrentLocation() let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeWalking] let mapItem = MKMapItem(placemark: placeMark) mapItem.name = name MKMapItem.openMaps(with: [currentLocation, mapItem], launchOptions: launchOptions) } }
mit
e4b892fb154a08ee82b575fd39efb3d9
32.388889
100
0.674709
5.390135
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Chat/New Chat/ChatItems/MessageReplyThreadChatItem.swift
1
1178
// // MessageReplyThreadChatItem.swift // Rocket.Chat // // Created by Rafael Kellermann Streit on 17/04/19. // Copyright © 2019 Rocket.Chat. All rights reserved. // import Foundation import DifferenceKit import RocketChatViewController final class MessageReplyThreadChatItem: BaseMessageChatItem, ChatItem, Differentiable { var isSequential: Bool = false var relatedReuseIdentifier: String { return ThreadReplyCollapsedCell.identifier } init(user: UnmanagedUser?, message: UnmanagedMessage?, sequential: Bool = false) { super.init(user: user, message: message) isSequential = sequential } internal var threadName: String? { guard !isSequential, let message = message else { return nil } return message.mainThreadMessage } var differenceIdentifier: String { return message?.identifier ?? "" } func isContentEqual(to source: MessageReplyThreadChatItem) -> Bool { guard let message = message, let sourceMessage = source.message else { return false } return message == sourceMessage } }
mit
85e4ae232ac8e844730d7ffce5ba9228
24.042553
87
0.660153
4.843621
false
false
false
false
bluezald/DesignPatterns
DesignPatterns/DesignPatterns/CommandPattern.swift
1
1766
// // CommandPattern.swift // DesignPatterns // // Created by Vincent Bacalso on 10/10/2016. // Copyright © 2016 bluezald. All rights reserved. // import UIKit /** Intent Encapsulate a request as an object, thereby letting you parametrize clients with different requests, queue or log requests, and support undoable operations. Promote "invocation of a method on an object" to full object status An object-oriented callback The Command Pattern allows requests to be encapsulated as objects, thereby allowing clients to be paramterized with different requests */ class CommandPattern: NSObject { func demo() { let podBayDoors = "Pod Bay Doors" let doorModule = HAL9000DoorsOperations(doors:podBayDoors) print(doorModule.open()) print(doorModule.close()) } } protocol DoorCommand { func execute() -> String } class OpenCommand: DoorCommand { let doors: String required init(doors: String) { self.doors = doors } func execute() -> String { return "Opened \(doors)" } } class CloseCommand: DoorCommand { let doors: String required init(doors: String) { self.doors = doors } func execute() -> String { return "Closed \(doors)" } } class HAL9000DoorsOperations { let openCommand: DoorCommand let closeCommand: DoorCommand init(doors: String) { self.openCommand = OpenCommand(doors: doors) self.closeCommand = CloseCommand(doors: doors) } func close() -> String { return closeCommand.execute() } func open() -> String { return openCommand.execute() } } /** Examples: The 'check' at a Diner */
mit
9a7a372226e4e111b343541eb5a256c3
17.978495
69
0.637394
4.020501
false
false
false
false
AlexLittlejohn/ALCameraViewController
ALCameraViewController/ViewController/CameraViewController.swift
1
21746
// // CameraViewController.swift // CameraViewController // // Created by Alex Littlejohn. // Copyright (c) 2016 zero. All rights reserved. // import UIKit import AVFoundation import Photos public typealias CameraViewCompletion = (UIImage?, PHAsset?) -> Void public extension CameraViewController { /// Provides an image picker wrapped inside a UINavigationController instance class func imagePickerViewController(croppingParameters: CroppingParameters, completion: @escaping CameraViewCompletion) -> UINavigationController { let imagePicker = PhotoLibraryViewController() let navigationController = UINavigationController(rootViewController: imagePicker) navigationController.navigationBar.barTintColor = UIColor.black navigationController.navigationBar.barStyle = UIBarStyle.black navigationController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve imagePicker.onSelectionComplete = { [weak imagePicker] asset in if let asset = asset { let confirmController = ConfirmViewController(asset: asset, croppingParameters: croppingParameters) confirmController.onComplete = { [weak imagePicker] image, asset in if let image = image, let asset = asset { completion(image, asset) } else { imagePicker?.dismiss(animated: true, completion: nil) } } confirmController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve imagePicker?.present(confirmController, animated: true, completion: nil) } else { completion(nil, nil) } } return navigationController } } open class CameraViewController: UIViewController { var didUpdateViews = false var croppingParameters: CroppingParameters var animationRunning = false let allowVolumeButtonCapture: Bool var lastInterfaceOrientation : UIInterfaceOrientation? open var onCompletion: CameraViewCompletion? var volumeControl: VolumeControl? var animationDuration: TimeInterval = 0.5 var animationSpring: CGFloat = 0.5 var rotateAnimation: UIView.AnimationOptions = .curveLinear var cameraButtonEdgeConstraint: NSLayoutConstraint? var cameraButtonGravityConstraint: NSLayoutConstraint? var closeButtonEdgeConstraint: NSLayoutConstraint? var closeButtonGravityConstraint: NSLayoutConstraint? var containerButtonsEdgeOneConstraint: NSLayoutConstraint? var containerButtonsEdgeTwoConstraint: NSLayoutConstraint? var containerButtonsGravityConstraint: NSLayoutConstraint? var swapButtonEdgeOneConstraint: NSLayoutConstraint? var swapButtonEdgeTwoConstraint: NSLayoutConstraint? var swapButtonGravityConstraint: NSLayoutConstraint? var libraryButtonEdgeOneConstraint: NSLayoutConstraint? var libraryButtonEdgeTwoConstraint: NSLayoutConstraint? var libraryButtonGravityConstraint: NSLayoutConstraint? var flashButtonEdgeConstraint: NSLayoutConstraint? var flashButtonGravityConstraint: NSLayoutConstraint? let cameraView : CameraView = { let cameraView = CameraView() cameraView.translatesAutoresizingMaskIntoConstraints = false return cameraView }() let cameraButton : UIButton = { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64)) button.translatesAutoresizingMaskIntoConstraints = false button.isEnabled = false button.setImage(UIImage(named: "cameraButton", in: CameraGlobals.shared.bundle, compatibleWith: nil), for: .normal) button.setImage(UIImage(named: "cameraButtonHighlighted", in: CameraGlobals.shared.bundle, compatibleWith: nil), for: .highlighted) return button }() let closeButton : UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setImage(UIImage(named: "closeButton", in: CameraGlobals.shared.bundle, compatibleWith: nil), for: .normal) return button }() let swapButton : UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setImage(UIImage(named: "swapButton", in: CameraGlobals.shared.bundle, compatibleWith: nil), for: .normal) return button }() let libraryButton : UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setImage(UIImage(named: "libraryButton", in: CameraGlobals.shared.bundle, compatibleWith: nil), for: .normal) return button }() let flashButton : UIButton = { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) button.translatesAutoresizingMaskIntoConstraints = false button.setImage(UIImage(named: "flashAutoIcon", in: CameraGlobals.shared.bundle, compatibleWith: nil), for: .normal) return button }() let containerSwapLibraryButton : UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() private let allowsLibraryAccess: Bool public init(croppingParameters: CroppingParameters = CroppingParameters(), allowsLibraryAccess: Bool = true, allowsSwapCameraOrientation: Bool = true, allowVolumeButtonCapture: Bool = true, completion: @escaping CameraViewCompletion) { self.croppingParameters = croppingParameters self.allowsLibraryAccess = allowsLibraryAccess self.allowVolumeButtonCapture = allowVolumeButtonCapture super.init(nibName: nil, bundle: nil) onCompletion = completion libraryButton.isEnabled = allowsLibraryAccess libraryButton.isHidden = !allowsLibraryAccess swapButton.isEnabled = allowsSwapCameraOrientation swapButton.isHidden = !allowsSwapCameraOrientation } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override var prefersStatusBarHidden: Bool { return true } open override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return UIStatusBarAnimation.slide } /** * Configure the background of the superview to black * and add the views on this superview. Then, request * the update of constraints for this superview. */ open override func loadView() { super.loadView() view.backgroundColor = UIColor.black [cameraView, cameraButton, closeButton, flashButton, containerSwapLibraryButton].forEach({ view.addSubview($0) }) [swapButton, libraryButton].forEach({ containerSwapLibraryButton.addSubview($0) }) view.setNeedsUpdateConstraints() } /** * Setup the constraints when the app is starting or rotating * the screen. * To avoid the override/conflict of stable constraint, these * stable constraint are one time configurable. * Any other dynamic constraint are configurable when the * device is rotating, based on the device orientation. */ override open func updateViewConstraints() { if !didUpdateViews { configCameraViewConstraints() didUpdateViews = true } let statusBarOrientation = UIApplication.shared.statusBarOrientation let portrait = statusBarOrientation.isPortrait configCameraButtonEdgeConstraint(statusBarOrientation) configCameraButtonGravityConstraint(portrait) removeCloseButtonConstraints() configCloseButtonEdgeConstraint(statusBarOrientation) configCloseButtonGravityConstraint(statusBarOrientation) removeContainerConstraints() configContainerEdgeConstraint(statusBarOrientation) configContainerGravityConstraint(statusBarOrientation) removeSwapButtonConstraints() configSwapButtonEdgeConstraint(statusBarOrientation) configSwapButtonGravityConstraint(portrait) removeLibraryButtonConstraints() configLibraryEdgeButtonConstraint(statusBarOrientation) configLibraryGravityButtonConstraint(portrait) configFlashEdgeButtonConstraint(statusBarOrientation) configFlashGravityButtonConstraint(statusBarOrientation) rotate(actualInterfaceOrientation: statusBarOrientation) super.updateViewConstraints() } /** * Add observer to check when the camera has started, * enable the volume buttons to take the picture, * configure the actions of the buttons on the screen, * check the permissions of access of the camera and * the photo library. * Configure the camera focus when the application * start, to avoid any bluried image. */ open override func viewDidLoad() { super.viewDidLoad() setupActions() checkPermissions() cameraView.configureZoom() } /** * Start the session of the camera. */ open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) cameraView.startSession() addCameraObserver() addRotateObserver() if allowVolumeButtonCapture { setupVolumeControl() } } /** * Enable the button to take the picture when the * camera is ready. */ open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if cameraView.session?.isRunning == true { notifyCameraReady() } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) volumeControl = nil } /** * This method will disable the rotation of the */ override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) lastInterfaceOrientation = UIApplication.shared.statusBarOrientation if animationRunning { return } CATransaction.begin() CATransaction.setDisableActions(true) coordinator.animate(alongsideTransition: { [weak self] animation in self?.view.setNeedsUpdateConstraints() }, completion: { _ in CATransaction.commit() }) } /** * Observer the camera status, when it is ready, * it calls the method cameraReady to enable the * button to take the picture. */ private func addCameraObserver() { NotificationCenter.default.addObserver( self, selector: #selector(notifyCameraReady), name: NSNotification.Name.AVCaptureSessionDidStartRunning, object: nil) } /** * Observer the device orientation to update the * orientation of CameraView. */ private func addRotateObserver() { NotificationCenter.default.addObserver( self, selector: #selector(rotateCameraView), name: UIDevice.orientationDidChangeNotification, object: nil) } @objc internal func notifyCameraReady() { cameraButton.isEnabled = true } /** * Attach the take of picture for any volume button. */ private func setupVolumeControl() { volumeControl = VolumeControl(view: view) { [weak self] _ in guard let enabled = self?.cameraButton.isEnabled, enabled else { return } self?.capturePhoto() } } /** * Configure the action for every button on this * layout. */ private func setupActions() { cameraButton.action = { [weak self] in self?.capturePhoto() } swapButton.action = { [weak self] in self?.swapCamera() } libraryButton.action = { [weak self] in self?.showLibrary() } closeButton.action = { [weak self] in self?.close() } flashButton.action = { [weak self] in self?.toggleFlash() } } /** * Toggle the buttons status, based on the actual * state of the camera. */ private func toggleButtons(enabled: Bool) { [cameraButton, closeButton, swapButton, libraryButton].forEach({ $0.isEnabled = enabled }) } @objc func rotateCameraView() { cameraView.rotatePreview() } /** * This method will rotate the buttons based on * the last and actual orientation of the device. */ internal func rotate(actualInterfaceOrientation: UIInterfaceOrientation) { if lastInterfaceOrientation != nil { let lastTransform = CGAffineTransform(rotationAngle: radians(currentRotation( lastInterfaceOrientation!, newOrientation: actualInterfaceOrientation))) setTransform(transform: lastTransform) } let transform = CGAffineTransform(rotationAngle: 0) animationRunning = true /** * Dispatch delay to avoid any conflict between the CATransaction of rotation of the screen * and CATransaction of animation of buttons. */ let duration = animationDuration let spring = animationSpring let options = rotateAnimation let time: DispatchTime = DispatchTime.now() + Double(1 * UInt64(NSEC_PER_SEC)/10) DispatchQueue.main.asyncAfter(deadline: time) { [weak self] in guard let _ = self else { return } CATransaction.begin() CATransaction.setDisableActions(false) CATransaction.commit() UIView.animate( withDuration: duration, delay: 0.1, usingSpringWithDamping: spring, initialSpringVelocity: 0, options: options, animations: { [weak self] in self?.setTransform(transform: transform) }, completion: { [weak self] _ in self?.animationRunning = false }) } } func setTransform(transform: CGAffineTransform) { closeButton.transform = transform swapButton.transform = transform libraryButton.transform = transform flashButton.transform = transform } /** * Validate the permissions of the camera and * library, if the user do not accept these * permissions, it shows an view that notifies * the user that it not allow the permissions. */ private func checkPermissions() { if AVCaptureDevice.authorizationStatus(for: AVMediaType.video) != .authorized { AVCaptureDevice.requestAccess(for: AVMediaType.video) { granted in DispatchQueue.main.async() { [weak self] in if !granted { self?.showNoPermissionsView() } } } } } /** * Generate the view of no permission. */ private func showNoPermissionsView(library: Bool = false) { let permissionsView = PermissionsView(frame: view.bounds) let title: String let desc: String if library { title = localizedString("permissions.library.title") desc = localizedString("permissions.library.description") } else { title = localizedString("permissions.title") desc = localizedString("permissions.description") } permissionsView.configureInView(view, title: title, description: desc, completion: { [weak self] in self?.close() }) } /** * This method will be called when the user * try to take the picture. * It will lock any button while the shot is * taken, then, realease the buttons and save * the picture on the device. */ internal func capturePhoto() { guard let output = cameraView.imageOutput, let connection = output.connection(with: AVMediaType.video) else { return } if connection.isEnabled { toggleButtons(enabled: false) cameraView.capturePhoto { [weak self] image in guard let image = image else { self?.toggleButtons(enabled: true) return } self?.saveImage(image: image) } } } internal func saveImage(image: UIImage) { let spinner = showSpinner() cameraView.preview.isHidden = true if allowsLibraryAccess { _ = SingleImageSaver() .setImage(image) .onSuccess { [weak self] asset in self?.layoutCameraResult(asset: asset) self?.hideSpinner(spinner) } .onFailure { [weak self] error in self?.toggleButtons(enabled: true) self?.showNoPermissionsView(library: true) self?.cameraView.preview.isHidden = false self?.hideSpinner(spinner) } .save() } else { layoutCameraResult(uiImage: image) hideSpinner(spinner) } } internal func close() { onCompletion?(nil, nil) onCompletion = nil } internal func showLibrary() { let imagePicker = CameraViewController.imagePickerViewController(croppingParameters: croppingParameters) { [weak self] image, asset in defer { self?.cameraView.startSession() self?.dismiss(animated: true, completion: nil) } guard let image = image, let asset = asset else { return } self?.onCompletion?(image, asset) } present(imagePicker, animated: true) { [weak self] in self?.cameraView.stopSession() } } internal func toggleFlash() { cameraView.cycleFlash() guard let device = cameraView.device else { return } let image = UIImage(named: flashImage(device.flashMode), in: CameraGlobals.shared.bundle, compatibleWith: nil) flashButton.setImage(image, for: .normal) } internal func swapCamera() { cameraView.swapCameraInput() flashButton.isHidden = cameraView.currentPosition == AVCaptureDevice.Position.front } internal func layoutCameraResult(uiImage: UIImage) { cameraView.stopSession() startConfirmController(uiImage: uiImage) toggleButtons(enabled: true) } internal func layoutCameraResult(asset: PHAsset) { cameraView.stopSession() startConfirmController(asset: asset) toggleButtons(enabled: true) } private func startConfirmController(uiImage: UIImage) { let confirmViewController = ConfirmViewController(image: uiImage, croppingParameters: croppingParameters) confirmViewController.onComplete = { [weak self] image, asset in defer { self?.cameraView.startSession() self?.dismiss(animated: true, completion: nil) } guard let image = image else { return } self?.onCompletion?(image, asset) self?.onCompletion = nil } confirmViewController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve present(confirmViewController, animated: true, completion: nil) } private func startConfirmController(asset: PHAsset) { let confirmViewController = ConfirmViewController(asset: asset, croppingParameters: croppingParameters) confirmViewController.onComplete = { [weak self] image, asset in defer { self?.cameraView.startSession() self?.dismiss(animated: true, completion: nil) } guard let image = image, let asset = asset else { return } self?.onCompletion?(image, asset) self?.onCompletion = nil } confirmViewController.modalTransitionStyle = UIModalTransitionStyle.crossDissolve present(confirmViewController, animated: true, completion: nil) } private func showSpinner() -> UIActivityIndicatorView { let spinner = UIActivityIndicatorView() spinner.style = .white spinner.center = view.center spinner.startAnimating() view.addSubview(spinner) view.bringSubviewToFront(spinner) return spinner } private func hideSpinner(_ spinner: UIActivityIndicatorView) { spinner.stopAnimating() spinner.removeFromSuperview() } }
mit
07442f4f89b7c262bd7765013611e85a
33.51746
152
0.623103
5.721126
false
false
false
false
frootloops/swift
test/SILGen/source_location.swift
1
1407
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -Xllvm -sil-print-debuginfo -emit-silgen -enable-sil-ownership %s | %FileCheck %s func printSourceLocation(file: String = #file, line: Int = #line) {} #sourceLocation(file: "caller.swift", line: 10000) _ = printSourceLocation() // CHECK: [[CALLER_FILE_VAL:%.*]] = string_literal utf16 "caller.swift", // CHECK: [[CALLER_FILE:%.*]] = apply {{.*}}([[CALLER_FILE_VAL]], // CHECK: [[CALLER_LINE_VAL:%.*]] = integer_literal $Builtin.Int{{[0-9]+}}, 10000, // CHECK: [[CALLER_LINE:%.*]] = apply {{.*}}([[CALLER_LINE_VAL]], // CHECK: [[PRINT_SOURCE_LOCATION:%.*]] = function_ref @_T015source_location19printSourceLocationySS4file_Si4linetF // CHECK: apply [[PRINT_SOURCE_LOCATION]]([[CALLER_FILE]], [[CALLER_LINE]]) #sourceLocation(file: "inplace.swift", line: 20000) let FILE = #file, LINE = #line // CHECK: [[FILE_ADDR:%.*]] = global_addr @_T015source_location4FILESSv // CHECK: [[INPLACE_FILE_VAL:%.*]] = string_literal utf16 "inplace.swift", // CHECK: [[INPLACE_FILE:%.*]] = apply {{.*}}([[INPLACE_FILE_VAL]], // CHECK: store [[INPLACE_FILE]] to [init] [[FILE_ADDR]] // CHECK: [[LINE_ADDR:%.*]] = global_addr @_T015source_location4LINESiv // CHECK: [[INPLACE_LINE_VAL:%.*]] = integer_literal $Builtin.Int{{[0-9]+}}, 20000, // CHECK: [[INPLACE_LINE:%.*]] = apply {{.*}}([[INPLACE_LINE_VAL]], // CHECK: store [[INPLACE_LINE]] to [trivial] [[LINE_ADDR]]
apache-2.0
1aa94f3c8bc3f53c4eb5b3db3646cb10
60.173913
138
0.645345
3.227064
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/NCTextFieldTableViewCell.swift
2
1934
// // NCTextFieldTableViewCell.swift // Neocom // // Created by Artem Shimanski on 15.02.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit class NCTextFieldTableViewCell: NCTableViewCell { @IBOutlet weak var textField: UITextField! @IBOutlet weak var doneButton: UIButton? var handlers: [UIControlEvents: NCActionHandler<UITextField>] = [:] override func prepareForReuse() { super.prepareForReuse() handlers = [:] } } class NCTextFieldRow: TreeRow { var text: String? let placeholder: String? init(prototype: Prototype = Prototype.NCTextFieldTableViewCell.default, text: String? = nil, placeholder: String? = nil) { self.text = text self.placeholder = placeholder super.init(prototype: prototype) } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCTextFieldTableViewCell else {return} cell.textField.text = text let textField = cell.textField cell.doneButton?.alpha = 0.0 cell.handlers[.editingChanged] = NCActionHandler(cell.textField, for: [.editingChanged], handler: { [weak self] _ in self?.text = textField?.text }) cell.handlers[.editingDidBegin] = NCActionHandler(cell.textField, for: [.editingDidBegin], handler: { [weak cell] _ in UIView.animate(withDuration: 0.25) { cell?.doneButton?.alpha = 1.0 } }) cell.handlers[.editingDidEnd] = NCActionHandler(cell.textField, for: [.editingDidEnd], handler: { [weak cell] _ in UIView.animate(withDuration: 0.25) { cell?.doneButton?.alpha = 0.0 } }) if let placeholder = placeholder { cell.textField.attributedPlaceholder = placeholder * [NSAttributedStringKey.foregroundColor: UIColor.lightGray] } } //MARK: - Private } extension Prototype { enum NCTextFieldTableViewCell { static let `default` = Prototype(nib: UINib(nibName: "NCTextFieldTableViewCell", bundle: nil), reuseIdentifier: "NCTextFieldTableViewCell") } }
lgpl-2.1
85fd7235ae6a2b552f25a78950d4cb34
25.479452
141
0.721159
3.7607
false
false
false
false
frootloops/swift
validation-test/stdlib/CollectionDiagnostics.swift
3
5476
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown import StdlibUnittest import StdlibCollectionUnittest // // Check that Collection.SubSequence is constrained to Collection. // // expected-error@+2 {{type 'CollectionWithBadSubSequence' does not conform to protocol 'Collection'}} // expected-error@+1 {{type 'CollectionWithBadSubSequence' does not conform to protocol 'Sequence'}} struct CollectionWithBadSubSequence : Collection { var startIndex: MinimalIndex { fatalError("unreachable") } var endIndex: MinimalIndex { fatalError("unreachable") } subscript(i: MinimalIndex) -> OpaqueValue<Int> { fatalError("unreachable") } // expected-note@+2 {{possibly intended match}} // expected-note@+1 {{possibly intended match}} typealias SubSequence = OpaqueValue<Int8> } func useCollectionTypeSubSequenceIndex<C : Collection>(_ c: C) {} func useCollectionTypeSubSequenceGeneratorElement<C : Collection>(_ c: C) {} func sortResultIgnored< S : Sequence, MC : MutableCollection >(_ sequence: S, mutableCollection: MC, array: [Int]) where S.Iterator.Element : Comparable, MC.Iterator.Element : Comparable { var sequence = sequence // expected-warning {{variable 'sequence' was never mutated; consider changing to 'let' constant}} var mutableCollection = mutableCollection // expected-warning {{variable 'mutableCollection' was never mutated; consider changing to 'let' constant}} var array = array // expected-warning {{variable 'array' was never mutated; consider changing to 'let' constant}} sequence.sorted() // expected-warning {{result of call to 'sorted()' is unused}} sequence.sorted { $0 < $1 } // expected-warning {{result of call to 'sorted(by:)' is unused}} mutableCollection.sorted() // expected-warning {{result of call to 'sorted()' is unused}} mutableCollection.sorted { $0 < $1 } // expected-warning {{result of call to 'sorted(by:)' is unused}} array.sorted() // expected-warning {{result of call to 'sorted()' is unused}} array.sorted { $0 < $1 } // expected-warning {{result of call to 'sorted(by:)' is unused}} } // expected-warning@+1 {{'Indexable' is deprecated: it will be removed in Swift 4.0. Please use 'Collection' instead}} struct GoodIndexable : Indexable { func index(after i: Int) -> Int { return i + 1 } var startIndex: Int { return 0 } var endIndex: Int { return 0 } subscript(pos: Int) -> Int { return 0 } subscript(bounds: Range<Int>) -> ArraySlice<Int> { return [] } } // expected-warning@+1 {{'Indexable' is deprecated: it will be removed in Swift 4.0. Please use 'Collection' instead}} struct AnotherGoodIndexable1 : Indexable { func index(after i: Int) -> Int { return i + 1 } var startIndex: Int { return 0 } var endIndex: Int { return 0 } subscript(pos: Int) -> Int { return 0 } } // expected-warning@+2 {{'Indexable' is deprecated: it will be removed in Swift 4.0. Please use 'Collection' instead}} // expected-error@+1 {{type 'BadIndexable2' does not conform to protocol 'Collection'}} struct BadIndexable2 : Indexable { var startIndex: Int { return 0 } var endIndex: Int { return 0 } subscript(pos: Int) -> Int { return 0 } subscript(bounds: Range<Int>) -> ArraySlice<Int> { return [] } // Missing index(after:) -> Int } // expected-warning@+1 {{'BidirectionalIndexable' is deprecated: it will be removed in Swift 4.0. Please use 'BidirectionalCollection' instead}} struct GoodBidirectionalIndexable1 : BidirectionalIndexable { var startIndex: Int { return 0 } var endIndex: Int { return 0 } func index(after i: Int) -> Int { return i + 1 } func index(before i: Int) -> Int { return i - 1 } subscript(pos: Int) -> Int { return 0 } subscript(bounds: Range<Int>) -> ArraySlice<Int> { return [] } } // We'd like to see: {{type 'BadBidirectionalIndexable' does not conform to protocol 'BidirectionalIndexable'}} // But the compiler doesn't generate that error. // expected-warning@+1 {{'BidirectionalIndexable' is deprecated: it will be removed in Swift 4.0. Please use 'BidirectionalCollection' instead}} struct BadBidirectionalIndexable : BidirectionalIndexable { var startIndex: Int { return 0 } var endIndex: Int { return 0 } subscript(pos: Int) -> Int { return 0 } subscript(bounds: Range<Int>) -> ArraySlice<Int> { return [] } // This is a poor error message; it would be better to get a message // that index(before:) was missing. // // expected-error@+1 {{'index(after:)' has different argument labels from those required by protocol 'BidirectionalCollection' ('index(before:)'}} func index(after i: Int) -> Int { return 0 } } // // Check that RangeReplaceableCollection.SubSequence is defaulted. // struct RangeReplaceableCollection_SubSequence_IsDefaulted : RangeReplaceableCollection { var startIndex: Int { fatalError() } var endIndex: Int { fatalError() } subscript(pos: Int) -> Int { return 0 } func index(after: Int) -> Int { fatalError() } func index(before: Int) -> Int { fatalError() } func index(_: Int, offsetBy: Int) -> Int { fatalError() } func distance(from: Int, to: Int) -> Int { fatalError() } mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newElements: C ) where C : Collection, C.Iterator.Element == Int { fatalError() } } // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected note produced: possibly intended match // <unknown>:0: error: unexpected note produced: possibly intended match
apache-2.0
009d702f37d30cb8719e94698b8927e7
38.970803
151
0.704711
4.095737
false
false
false
false
nextcloud/ios
iOSClient/Utility/NCPopupViewController.swift
1
11443
// // NCPopupViewController.swift // // Based on EzPopup by Huy Nguyen // Modified by Marino Faggiana for Nextcloud progect. // // Author Marino Faggiana <[email protected]> // // 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 public protocol NCPopupViewControllerDelegate: AnyObject { func popupViewControllerDidDismissByTapGesture(_ sender: NCPopupViewController) } // optional func public extension NCPopupViewControllerDelegate { func popupViewControllerDidDismissByTapGesture(_ sender: NCPopupViewController) {} } public class NCPopupViewController: UIViewController { private var centerYConstraint: NSLayoutConstraint? // Popup width, it's nil if width is determined by view's intrinsic size private(set) public var popupWidth: CGFloat? // Popup height, it's nil if width is determined by view's intrinsic size private(set) public var popupHeight: CGFloat? // Background alpha, default is 0.3 public var backgroundAlpha: CGFloat = 0.3 // Background color, default is black public var backgroundColor = UIColor.black // Allow tap outside popup to dismiss, default is true public var canTapOutsideToDismiss = true // Corner radius, default is 10 (0 no rounded corner) public var cornerRadius: CGFloat = 10 // Shadow enabled, default is true public var shadowEnabled = true // Border enabled, default is false public var borderEnabled = false // Move the popup position H when show/hide keyboard public var keyboardPosizionEnabled = true // The pop up view controller. It's not mandatory. private(set) public var contentController: UIViewController? // The pop up view private(set) public var contentView: UIView? // The delegate to receive pop up event public weak var delegate: NCPopupViewControllerDelegate? private var containerView = UIView() // MARK: - View Life Cycle // NOTE: Don't use this init method required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** Init with content view controller. Your pop up content is a view controller (easiest way to design it is using storyboard) - Parameters: - contentController: Popup content view controller - popupWidth: Width of popup content. If it isn't set, width will be determine by popup content view intrinsic size. - popupHeight: Height of popup content. If it isn't set, height will be determine by popup content view intrinsic size. */ public init(contentController: UIViewController, popupWidth: CGFloat? = nil, popupHeight: CGFloat? = nil) { super.init(nibName: nil, bundle: nil) self.contentController = contentController self.contentView = contentController.view self.popupWidth = popupWidth self.popupHeight = popupHeight modalPresentationStyle = .overFullScreen modalTransitionStyle = .crossDissolve } /** Init with content view - Parameters: - contentView: Popup content view - popupWidth: Width of popup content. If it isn't set, width will be determine by popup content view intrinsic size. - popupHeight: Height of popup content. If it isn't set, height will be determine by popup content view intrinsic size. */ public init(contentView: UIView, popupWidth: CGFloat? = nil, popupHeight: CGFloat? = nil) { super.init(nibName: nil, bundle: nil) self.contentView = contentView self.popupWidth = popupWidth self.popupHeight = popupHeight modalPresentationStyle = .overFullScreen modalTransitionStyle = .crossDissolve } override public func viewDidLoad() { super.viewDidLoad() setupUI() setupViews() addDismissGesture() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } // MARK: - Setup private func addDismissGesture() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissTapGesture(gesture:))) tapGesture.delegate = self view.addGestureRecognizer(tapGesture) } private func setupUI() { containerView.translatesAutoresizingMaskIntoConstraints = false contentView?.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = backgroundColor.withAlphaComponent(backgroundAlpha) if cornerRadius > 0 { contentView?.layer.cornerRadius = cornerRadius contentView?.layer.masksToBounds = true } if shadowEnabled { containerView.layer.shadowOpacity = 0.5 containerView.layer.shadowColor = UIColor.black.cgColor containerView.layer.shadowOffset = CGSize(width: 5, height: 5) containerView.layer.shadowRadius = 5 } if borderEnabled { containerView.layer.cornerRadius = cornerRadius containerView.layer.borderWidth = 0.3 containerView.layer.borderColor = UIColor.gray.cgColor } } private func setupViews() { if let contentController = contentController { addChild(contentController) } addViews() addSizeConstraints() addCenterPositionConstraints() } private func addViews() { view.addSubview(containerView) if let contentView = contentView { containerView.addSubview(contentView) let topConstraint = NSLayoutConstraint(item: contentView, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1, constant: 0) let leftConstraint = NSLayoutConstraint(item: contentView, attribute: .left, relatedBy: .equal, toItem: containerView, attribute: .left, multiplier: 1, constant: 0) let bottomConstraint = NSLayoutConstraint(item: contentView, attribute: .bottom, relatedBy: .equal, toItem: containerView, attribute: .bottom, multiplier: 1, constant: 0) let rightConstraint = NSLayoutConstraint(item: contentView, attribute: .right, relatedBy: .equal, toItem: containerView, attribute: .right, multiplier: 1, constant: 0) NSLayoutConstraint.activate([topConstraint, leftConstraint, bottomConstraint, rightConstraint]) } } // MARK: - Add constraints private func addSizeConstraints() { if let popupWidth = popupWidth { let widthConstraint = NSLayoutConstraint(item: containerView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: popupWidth) NSLayoutConstraint.activate([widthConstraint]) } if let popupHeight = popupHeight { let heightConstraint = NSLayoutConstraint(item: containerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: popupHeight) NSLayoutConstraint.activate([heightConstraint]) } } private func addCenterPositionConstraints() { let centerXConstraint = NSLayoutConstraint(item: containerView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0) centerYConstraint = NSLayoutConstraint(item: containerView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0) NSLayoutConstraint.activate([centerXConstraint, centerYConstraint!]) } // MARK: - func addPath() { let balloon = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 250)) balloon.backgroundColor = UIColor.clear let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: 200, y: 0)) path.addLine(to: CGPoint(x: 200, y: 200)) // Draw arrow path.addLine(to: CGPoint(x: 120, y: 200)) path.addLine(to: CGPoint(x: 100, y: 250)) path.addLine(to: CGPoint(x: 80, y: 200)) path.addLine(to: CGPoint(x: 0, y: 200)) path.close() let shape = CAShapeLayer() // shape.backgroundColor = UIColor.blue.cgColor shape.fillColor = UIColor.blue.cgColor shape.path = path.cgPath balloon.layer.addSublayer(shape) // [self.view addSubview:balloonView]; } // MARK: - Actions @objc func dismissTapGesture(gesture: UIGestureRecognizer) { dismiss(animated: true) { self.delegate?.popupViewControllerDidDismissByTapGesture(self) } } // MARK: - Keyboard notification @objc internal func keyboardWillShow(_ notification: Notification?) { var keyboardSize = CGSize.zero if let info = notification?.userInfo { let frameEndUserInfoKey = UIResponder.keyboardFrameEndUserInfoKey // Getting UIKeyboardSize. if let keyboardFrame = info[frameEndUserInfoKey] as? CGRect { let screenSize = UIScreen.main.bounds // Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381) let intersectRect = keyboardFrame.intersection(screenSize) if intersectRect.isNull { keyboardSize = CGSize(width: screenSize.size.width, height: 0) } else { keyboardSize = intersectRect.size } if keyboardPosizionEnabled { let popupDiff = screenSize.height - ((screenSize.height - (popupHeight ?? 0)) / 2) let keyboardDiff = screenSize.height - keyboardSize.height let diff = popupDiff - keyboardDiff if centerYConstraint != nil && diff > 0 { centerYConstraint?.constant = -(diff + 15) } } } } } @objc func keyboardWillHide(_ notification: Notification) { if keyboardPosizionEnabled { if centerYConstraint != nil { centerYConstraint?.constant = 0 } } } } // MARK: - UIGestureRecognizerDelegate extension NCPopupViewController: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard let touchView = touch.view, canTapOutsideToDismiss else { return false } return !touchView.isDescendant(of: containerView) } }
gpl-3.0
cdfd585f95cee85eaccdd9fb7378ca84
35.794212
192
0.670978
5.12909
false
false
false
false
meteochu/DecisionKitchen
iOS/DecisionKitchen/GameResponse.swift
1
954
// // GameResponse.swift // DecisionKitchen // // Created by Andy Liang on 2017-07-30. // Copyright © 2017 Andy Liang. All rights reserved. // import Foundation class GameResponse: NSObject { var diningOptions: [Int] = [] var selectedCategoryIndexes: [Int] = [] var preferredPriceRange: [Int] = [] var restaurantName: String = "" var deviceLocation: Location = Location(longitude: 0, latitude: 0) let group: Group let game: Game init(group: Group, game: Game) { self.group = group self.game = game super.init() } func createFirebaseObject() -> Game.Response { return Game.Response(location: deviceLocation, value: [ preferredPriceRange, selectedCategoryIndexes, diningOptions ]) } }
apache-2.0
2f9d1622421763a71a63528696988909
21.690476
70
0.529906
4.765
false
false
false
false
google/JacquardSDKiOS
JacquardSDK/Classes/Internal/TagAPIDetails/SetTouchMode.swift
1
2014
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Note that this only sets the inference mode, the command to change the notification queue depth must be sent separately. struct SetTouchModeCommand: CommandRequest { typealias Response = Void var component: Component var mode: TouchMode func parseResponse(outerProto: Any) -> Result<Response, Error> { guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response else { jqLogger.assert( "calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error" ) return .failure(CommandResponseStatus.errorAppUnknown) } guard outerProto.hasGoogle_Jacquard_Protocol_DataChannelResponse_data else { return .failure(CommandResponseStatus.errorAppUnknown) } return .success(()) } var request: V2ProtocolCommandRequestIDInjectable { var dataChannelRequest = Google_Jacquard_Protocol_DataChannelRequest() switch mode { case .gesture: dataChannelRequest.inference = .dataStreamEnable dataChannelRequest.touch = .dataStreamDisable case .continuous: dataChannelRequest.inference = .dataStreamDisable dataChannelRequest.touch = .dataStreamEnable } return Google_Jacquard_Protocol_Request.with { $0.domain = .gear $0.opcode = .gearData $0.componentID = component.componentID $0.Google_Jacquard_Protocol_DataChannelRequest_data = dataChannelRequest } } }
apache-2.0
18a2b089d598c40371da8b6c69c454f1
34.964286
124
0.738332
4.485523
false
false
false
false
cplaverty/KeitaiWaniKani
WaniKaniKit/Database/Coder/Radical+DatabaseCodable.swift
1
8987
// // Radical+DatabaseCodable.swift // WaniKaniKit // // Copyright © 2017 Chris Laverty. All rights reserved. // import FMDB private let table = Tables.radicals extension Radical: DatabaseCodable { static func read(from database: FMDatabase, level: Int) throws -> [ResourceCollectionItem] { let query = "SELECT \(table.id) FROM \(table) WHERE \(table.level) = ? AND \(table.hiddenAt) IS NULL" let resultSet = try database.executeQuery(query, values: [level]) var subjectIDs = [Int]() while resultSet.next() { subjectIDs.append(resultSet.long(forColumnIndex: 0)) } resultSet.close() return try ResourceCollectionItem.read(from: database, ids: subjectIDs, type: .radical) } static func read(from database: FMDatabase, ids: [Int]) throws -> [Int: Radical] { var items = [Int: Radical]() items.reserveCapacity(ids.count) for id in ids { items[id] = try Radical(from: database, id: id) } return items } init(from database: FMDatabase, id: Int) throws { let characterImages = try CharacterImage.read(from: database, id: id) let meanings = try Meaning.read(from: database, id: id) let auxiliaryMeaning = try AuxiliaryMeaning.read(from: database, id: id) let subjectAmalgamation = try SubjectRelation.read(from: database, type: .amalgamation, id: id) let query = """ SELECT \(table.createdAt), \(table.level), \(table.slug), \(table.hiddenAt), \(table.documentURL), \(table.characters), \(table.meaningMnemonic), \(table.lessonPosition) FROM \(table) WHERE \(table.id) = ? """ let resultSet = try database.executeQuery(query, values: [id]) defer { resultSet.close() } guard resultSet.next() else { throw DatabaseError.itemNotFound(id: id) } self.createdAt = resultSet.date(forColumn: table.createdAt.name)! self.level = resultSet.long(forColumn: table.level.name) self.slug = resultSet.string(forColumn: table.slug.name)! self.hiddenAt = resultSet.date(forColumn: table.hiddenAt.name) self.documentURL = resultSet.url(forColumn: table.documentURL.name)! self.characters = resultSet.string(forColumn: table.characters.name) self.characterImages = characterImages self.meanings = meanings self.auxiliaryMeanings = auxiliaryMeaning self.amalgamationSubjectIDs = subjectAmalgamation self.meaningMnemonic = resultSet.string(forColumn: table.meaningMnemonic.name)! self.lessonPosition = resultSet.long(forColumn: table.lessonPosition.name) } func write(to database: FMDatabase, id: Int) throws { try CharacterImage.write(items: characterImages, to: database, id: id) try Meaning.write(items: meanings, to: database, id: id) try AuxiliaryMeaning.write(items: auxiliaryMeanings, to: database, id: id) try SubjectRelation.write(items: amalgamationSubjectIDs, to: database, type: .amalgamation, id: id) let query = """ INSERT OR REPLACE INTO \(table) (\(table.id.name), \(table.createdAt.name), \(table.level.name), \(table.slug.name), \(table.hiddenAt.name), \(table.documentURL.name), \(table.characters.name), \(table.meaningMnemonic.name), \(table.lessonPosition.name)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) """ let values: [Any] = [ id, createdAt, level, slug, hiddenAt as Any, documentURL.absoluteString, characters as Any, meaningMnemonic, lessonPosition ] try database.executeUpdate(query, values: values) try SubjectSearch.write(to: database, id: id, characters: characters, level: level, meanings: meanings, readings: [], hidden: hiddenAt != nil) } } extension Radical.CharacterImage: BulkDatabaseCodable { private static let imagesTable = Tables.radicalCharacterImages private static let metadataTable = Tables.radicalCharacterImagesMetadata static func read(from database: FMDatabase, id: Int) throws -> [Radical.CharacterImage] { let allMetadata = try readMetadata(from: database, id: id) let table = imagesTable let query = """ SELECT \(table.url), \(table.contentType) FROM \(table) WHERE \(table.subjectID) = ? ORDER BY \(table.index) """ let resultSet = try database.executeQuery(query, values: [id]) defer { resultSet.close() } var index = 0 var items = [Radical.CharacterImage]() while resultSet.next() { items.append(Radical.CharacterImage(url: resultSet.url(forColumn: table.url.name)!, metadata: allMetadata[index]!, contentType: resultSet.string(forColumn: table.contentType.name)!)) index += 1 } return items } static func read(from database: FMDatabase, ids: [Int]) throws -> [Int: [Radical.CharacterImage]] { var items = [Int: [Radical.CharacterImage]]() items.reserveCapacity(ids.count) for id in ids { items[id] = try read(from: database, id: id) } return items } private static func readMetadata(from database: FMDatabase, id: Int) throws -> [Int: Metadata] { let table = metadataTable let query = """ SELECT \(table.index), \(table.key), \(table.value) FROM \(table) WHERE \(table.subjectID) = ? ORDER BY \(table.index) """ let resultSet = try database.executeQuery(query, values: [id]) defer { resultSet.close() } var items = [Int: [String: String]]() while resultSet.next() { let index = resultSet.long(forColumn: table.index.name) let key = resultSet.string(forColumn: table.key.name)! let value = resultSet.string(forColumn: table.value.name)! var metadataForItem = items[index, default: [String: String]()] metadataForItem[key] = value items[index] = metadataForItem } return items.mapValues({ dictionary in return Metadata(color: dictionary[Metadata.CodingKeys.color.rawValue], dimensions: dictionary[Metadata.CodingKeys.dimensions.rawValue], styleName: dictionary[Metadata.CodingKeys.styleName.rawValue], inlineStyles: dictionary[Metadata.CodingKeys.inlineStyles.rawValue].flatMap({ Bool($0) }) ) }) } static func write(items: [Radical.CharacterImage], to database: FMDatabase, id: Int) throws { try database.executeUpdate("DELETE FROM \(imagesTable) WHERE \(imagesTable.subjectID) = ?", values: [id]) try database.executeUpdate("DELETE FROM \(metadataTable) WHERE \(metadataTable.subjectID) = ?", values: [id]) let table = imagesTable let query = """ INSERT OR REPLACE INTO \(table) (\(table.subjectID.name), \(table.index.name), \(table.url.name), \(table.contentType.name)) VALUES (?, ?, ?, ?) """ for (index, item) in items.enumerated() { let values: [Any] = [ id, index, item.url.absoluteString, item.contentType ] try database.executeUpdate(query, values: values) try write(metadata: item.metadata, to: database, id: id, index: index) } } private static func write(metadata: Metadata, to database: FMDatabase, id: Int, index: Int) throws { try writeMetadataAttributeIfPresent(key: .color, value: metadata.color, to: database, id: id, index: index) try writeMetadataAttributeIfPresent(key: .dimensions, value: metadata.dimensions, to: database, id: id, index: index) try writeMetadataAttributeIfPresent(key: .styleName, value: metadata.styleName, to: database, id: id, index: index) try writeMetadataAttributeIfPresent(key: .inlineStyles, value: metadata.inlineStyles, to: database, id: id, index: index) } private static func writeMetadataAttributeIfPresent<T>(key: Metadata.CodingKeys, value: T?, to database: FMDatabase, id: Int, index: Int) throws { guard let value = value else { return } let table = metadataTable let query = """ INSERT OR REPLACE INTO \(table) (\(table.subjectID.name), \(table.index.name), \(table.key.name), \(table.value.name)) VALUES (?, ?, ?, ?) """ try database.executeUpdate(query, values: [id, index, key.rawValue, value]) } }
mit
2d48db7084c56a55edc0df7d790197ad
41.790476
230
0.606276
4.439723
false
false
false
false
pourhadi/DynUI
Example/Pods/SuperSerial/Pod/Classes/Extensions.swift
1
3934
// // Extensions.swift // SuperSerial // // Created by Daniel Pourhadi on 1/15/16. // Copyright © 2016 Daniel Pourhadi. All rights reserved. // import Foundation extension String: Serializable { public init?(fromSerialized: Serialized) { switch fromSerialized { case .Str(let string): self = string default: return nil } } public func ss_serialize() -> Serialized { return Serialized.Str(self) } } extension CollectionType where Generator.Element == Serialized { public func toString() -> String { let string = self.reduce("[", combine: { (last, obj) -> String in if (last as NSString).length == 1 { return "\(last)\(obj.toString())" } else { return "\(last),\(obj.toString())" } }) return "\(string)]" } } extension Dictionary:Deserializable {} extension Array:Deserializable {} extension CGPoint: AutoSerializable { public init!(withValuesForKeys: [String : Serializable]) { var x:Float = 0.0 var y:Float = 0.0 if let xVal = withValuesForKeys["x"] as? Float { x = xVal } if let yVal = withValuesForKeys["y"] as? Float { y = yVal } self.x = CGFloat(x) self.y = CGFloat(y) } } public protocol SerializableInt:IntegerType, Serializable, Deserializable {} extension SerializableInt { public func ss_serialize() -> Serialized { return Serialized.Integer(self as! Int) } public init?(fromSerialized:Serialized) { switch fromSerialized { case .Integer(let int): self = int as! Self default: return nil } } } extension Int: SerializableInt {} extension UInt:SerializableInt {} public protocol SerializableFloat:FloatingPointType, Serializable, Deserializable {} extension SerializableFloat { public func ss_serialize() -> Serialized { return Serialized.FloatingPoint(self as! Float) } public init?(fromSerialized:Serialized) { switch fromSerialized { case .FloatingPoint(let float): self = float as! Self default: return nil } } } extension Float:SerializableFloat {} extension Double:SerializableFloat {} extension CGFloat:SerializableFloat {} ///Serializable UIColor subclass public final class SSColor : UIColor, SerializableObject { public func ss_serialize() -> Serialized { return Serialized.CustomType(typeName: "SSColor", data: Serialized.Str(self.hexString())) } public convenience init?(fromSerialized:Serialized) { switch fromSerialized { case .Str(let string): self.init(rgba: string) break default: return nil } } public override init() { super.init() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required convenience public init(colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) { fatalError("init(colorLiteralRed:green:blue:alpha:) has not been implemented") } init?(rgba:String) { guard let hexString: String = rgba.substringFromIndex(rgba.startIndex.advancedBy(1)), var hexValue: UInt32 = 0 where NSScanner(string: hexString).scanHexInt(&hexValue) else { super.init() return } let hex8 = hexValue let divisor = CGFloat(255) let red = CGFloat((hex8 & 0xFF000000) >> 24) / divisor let green = CGFloat((hex8 & 0x00FF0000) >> 16) / divisor let blue = CGFloat((hex8 & 0x0000FF00) >> 8) / divisor let alpha = CGFloat( hex8 & 0x000000FF ) / divisor super.init(red: red, green: green, blue: blue, alpha: alpha) } }
mit
b754d739723587e4b68b6d2982e4ddfe
27.919118
107
0.60539
4.484607
false
false
false
false
daniel-hall/Stylish
StylishExample/StylishExample/ProgressBar.swift
1
6088
// // ProgressBar.swift // StylishExample // // Copyright (c) 2016 Daniel Hall // Twitter: @_danielhall // GitHub: https://github.com/daniel-hall // Website: http://danielhall.io // // 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. /* This is a custom progress bar view, which demonstrates how to make any UIView subclass participate in the Stylish process */ import Stylish import UIKit // 1. Create a custom view class marked as @IBDesignable and declare conformance to the Styleable protocol @IBDesignable class ProgressBar:UIView, Styleable { // 2. Create custom PropertyStylers that define a property key that can be read out of json, and a way to set the styleable properties of the ProgressBar component. These can be private to the type if you are only using JSON stylesheets and no code-created stylesheets struct ProgressColor: PropertyStyler { static var propertyKey: String { return "progressColor" } static func apply(value: UIColor?, to target: ProgressBar, using bundle: Bundle) { target.progressColor = value ?? .gray } } struct ProgressTrackColor: PropertyStyler { static var propertyKey: String { return "progressTrackColor" } static func apply(value: UIColor?, to target: ProgressBar, using bundle: Bundle) { target.trackColor = value ?? .white } } struct ProgressCornerRadiusRatio: PropertyStyler { static var propertyKey: String { return "progressCornerRadiusRatio" } static func apply(value: CGFloat?, to target: ProgressBar, using bundle: Bundle) { target.progressCornerRadiusPercentage = value ?? 0 } } // 3. Expose all the PropertyStylers as an array that can be passed into JSONStylesheet during initialization so they can participate in the parsing process static var propertyStylers: [AnyPropertyStylerType.Type] { return [ProgressColor.self, ProgressTrackColor.self, ProgressCornerRadiusRatio.self] } fileprivate let trackView = UIView() fileprivate let progressView = UIView() // 4. The Styleable protocol only requires a styles property, create one and mark it as @IBInspectable to make it available for setting in storyboards. It should call Stylish.applyStyleNames(:to:) whenever value is changed, as shown below. @IBInspectable var styles:String = "" { didSet { updateProgress() Stylish.applyStyleNames(styles, to: self, using: stylesheet) } } @IBInspectable public var stylesheet: String? = nil { didSet { updateProgress() Stylish.applyStyleNames(styles, to: self, using: stylesheet) } } var progressColor:UIColor = UIColor.gray { didSet { progressView.backgroundColor = progressColor } } var trackColor:UIColor = UIColor.white { didSet { trackView.backgroundColor = trackColor } } var progressCornerRadiusPercentage:CGFloat = 0.0 { didSet { updateProgress() progressView.layer.cornerRadius = progressView.bounds.height * progressCornerRadiusPercentage trackView.layer.cornerRadius = progressView.layer.cornerRadius } } @IBInspectable var progress:CGFloat = 0.5 { didSet { updateProgress() } } override func layoutSubviews() { updateProgress() } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { trackView.backgroundColor = trackColor progressView.backgroundColor = progressColor trackView.frame = bounds progressView.frame = bounds addSubview(trackView) addSubview(progressView) updateProgress() layer.masksToBounds = true trackView.layer.masksToBounds = true progressView.layer.masksToBounds = true clipsToBounds = true } fileprivate func updateProgress() { self.trackView.frame = self.bounds progressView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: trackView.bounds.width * progress, height: trackView.bounds.height)) } } // 5. Optionally, add a convenience typealias to the Style protocol, so any style can reference simply: "progressColor.set(value:)" instead of "ProgressBar.ProgressColor.set(value:)" extension Style { /// Sets a color value for the filled-in part of a ProgressBar instance typealias progressColor = ProgressBar.ProgressColor /// Sets a color value for the background track part of a ProgressBar instance typealias progressTrackColor = ProgressBar.ProgressTrackColor /// Sets a ratio of corner radius to height for the filled in progress part of a ProgressBar instance typealias progressCornerRadiusRatio = ProgressBar.ProgressCornerRadiusRatio }
mit
fe47c2211bb1368faadeda2d581ae08b
37.77707
272
0.693824
4.981997
false
false
false
false
aschwaighofer/swift
test/Interpreter/convenience_init_peer_delegation.swift
1
5923
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -Xfrontend -disable-objc-attr-requires-foundation-module -o %t/main // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %s // RUN: sed -e 's/required//g' < %s > %t/without_required.swift // RUN: %target-build-swift %t/without_required.swift -Xfrontend -disable-objc-attr-requires-foundation-module -o %t/without_required // RUN: %target-codesign %t/without_required // RUN: %target-run %t/without_required | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // XFAIL: CPU=arm64e import Darwin class Base { init(swift: ()) { print("\(#function) \(type(of: self))") } @objc(initAsObjC) required init(objc: ()) { print("\(#function) \(type(of: self))") } convenience init(swiftToSwift: ()) { print("\(#function) \(type(of: self))") self.init(swift: ()) } @objc convenience required init(objcToSwift: ()) { print("\(#function) \(type(of: self))") self.init(swift: ()) } convenience init(swiftToObjC: ()) { print("\(#function) \(type(of: self))") self.init(objc: ()) } @objc convenience required init(objcToObjC: ()) { print("\(#function) \(type(of: self))") self.init(objc: ()) } convenience init(swiftToSwiftConvenience: ()) { print("\(#function) \(type(of: self))") self.init(swiftToSwift: ()) } @objc convenience required init(objcToSwiftConvenience: ()) { print("\(#function) \(type(of: self))") self.init(swiftToSwift: ()) } convenience init(swiftToObjCConvenience: ()) { print("\(#function) \(type(of: self))") self.init(objcToObjC: ()) } @objc convenience required init(objcToObjCConvenience: ()) { print("\(#function) \(type(of: self))") self.init(objcToObjC: ()) } } class Sub: Base {} @objc protocol ForceObjCDispatch { @objc(initAsObjC) init(objc: ()) init(objcToSwift: ()) init(objcToObjC: ()) init(objcToSwiftConvenience: ()) init(objcToObjCConvenience: ()) } // Replace swift_allocObject so that we can keep track of what gets allocated. var baseCounter = 0 var subCounter = 0 typealias AllocObjectType = @convention(c) (UnsafeRawPointer, Int, Int) -> UnsafeMutableRawPointer let allocObjectImpl = dlsym(UnsafeMutableRawPointer(bitPattern: -1), "_swift_allocObject") .assumingMemoryBound(to: AllocObjectType.self) /// Like `ObjectIdentifier.init(Any.Type)`, but with a pointer as the /// destination type. func asUnsafeRawPointer(_ someClass: AnyObject.Type) -> UnsafeRawPointer { let opaque = Unmanaged.passUnretained(someClass as AnyObject).toOpaque() return UnsafeRawPointer(opaque) } let originalAllocObject = allocObjectImpl.pointee allocObjectImpl.pointee = { switch $0 { case asUnsafeRawPointer(Base.self): baseCounter += 1 case asUnsafeRawPointer(Sub.self): subCounter += 1 default: break } return originalAllocObject($0, $1, $2) } /// Checks that `op` performs `base` allocations of Base and `sub` allocations /// of Sub. @inline(never) func check(base: Int = 0, sub: Int = 0, file: StaticString = #file, line: UInt = #line, op: () -> AnyObject) { baseCounter = 0 subCounter = 0 _ = op() precondition(baseCounter == base, "expected \(base) Base instances, got \(baseCounter)", file: file, line: line) precondition(subCounter == sub, "expected \(sub) Sub instances, got \(subCounter)", file: file, line: line) } // CHECK: START print("START") // Check that this whole setup works. // CHECK-NEXT: init(swift:) Base check(base: 1) { Base(swift: ()) } // CHECK-NEXT: init(swift:) Sub check(sub: 1) { Sub(swift: ()) } // CHECK-NEXT: init(objc:) Base check(base: 1) { Base(objc: ()) } // CHECK-NEXT: init(objc:) Sub check(sub: 1) { Sub(objc: ()) } // CHECK-NEXT: init(swiftToSwift:) Sub // CHECK-NEXT: init(swift:) Sub check(sub: 1) { Sub(swiftToSwift: ()) } // CHECK-NEXT: init(objcToSwift:) Sub // CHECK-NEXT: init(swift:) Sub check(sub: 2) { Sub(objcToSwift: ()) } // CHECK-NEXT: init(swiftToObjC:) Sub // CHECK-NEXT: init(objc:) Sub check(sub: 1) { Sub(swiftToObjC: ()) } // CHECK-NEXT: init(objcToObjC:) Sub // CHECK-NEXT: init(objc:) Sub check(sub: 1) { Sub(objcToObjC: ()) } // CHECK-NEXT: init(swiftToSwiftConvenience:) Sub // CHECK-NEXT: init(swiftToSwift:) Sub // CHECK-NEXT: init(swift:) Sub check(sub: 1) { Sub(swiftToSwiftConvenience: ()) } // CHECK-NEXT: init(objcToSwiftConvenience:) Sub // CHECK-NEXT: init(swiftToSwift:) Sub // CHECK-NEXT: init(swift:) Sub check(sub: 2) { Sub(objcToSwiftConvenience: ()) } // CHECK-NEXT: init(swiftToObjCConvenience:) Sub // CHECK-NEXT: init(objcToObjC:) Sub // CHECK-NEXT: init(objc:) Sub check(sub: 1) { Sub(swiftToObjCConvenience: ()) } // CHECK-NEXT: init(objcToObjCConvenience:) Sub // CHECK-NEXT: init(objcToObjC:) Sub // CHECK-NEXT: init(objc:) Sub check(sub: 1) { Sub(objcToObjCConvenience: ()) } // Force ObjC dispatch without conforming Sub or Base to the protocol, // because it's possible that `required` perturbs things and we want to test // both ways. let SubAsObjC = unsafeBitCast(Sub.self as AnyObject, to: ForceObjCDispatch.Type.self) // CHECK-NEXT: init(objc:) Sub check(sub: 1) { SubAsObjC.init(objc: ()) } // CHECK-NEXT: init(objcToSwift:) Sub // CHECK-NEXT: init(swift:) Sub check(sub: 2) { SubAsObjC.init(objcToSwift: ()) } // CHECK-NEXT: init(objcToObjC:) Sub // CHECK-NEXT: init(objc:) Sub check(sub: 1) { SubAsObjC.init(objcToObjC: ()) } // CHECK-NEXT: init(objcToSwiftConvenience:) Sub // CHECK-NEXT: init(swiftToSwift:) Sub // CHECK-NEXT: init(swift:) Sub check(sub: 2) { SubAsObjC.init(objcToSwiftConvenience: ()) } // CHECK-NEXT: init(objcToObjCConvenience:) Sub // CHECK-NEXT: init(objcToObjC:) Sub // CHECK-NEXT: init(objc:) Sub check(sub: 1) { SubAsObjC.init(objcToObjCConvenience: ()) } // CHECK-NEXT: END print("END")
apache-2.0
0e4c8ab0da2b9becaa332fc2de22a99d
30.673797
133
0.662671
3.402068
false
false
false
false
TonyJin99/SinaWeibo
SinaWeibo/SinaWeibo/NetworkTools.swift
1
2277
// // NetworkTools.swift // SinaWeibo // // Created by Tony.Jin on 7/30/16. // Copyright © 2016 Innovatis Tech. All rights reserved. // import UIKit import AFNetworking class NetworkTools: AFHTTPSessionManager { static let sharedInstance: NetworkTools = { let baseURL = NSURL(string: "https://api.weibo.com/")! let instance = NetworkTools(baseURL: baseURL, sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration()) instance.responseSerializer.acceptableContentTypes = (NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as! Set) return instance }() func loadStatus(since_id: String, max_id: String, finished: (Array:[[String: AnyObject]]?, error: NSError?)->()){ let url = "https://api.weibo.com/2/statuses/home_timeline.json" let temp = (max_id != "0") ? "\(Int(max_id)! - 1)" : max_id let paras = ["access_token": "2.00pFZdLC25bUWE6b1e1f2b940lv3Oc", "since_id": since_id, "max_id": temp] GET(url, parameters: paras, progress: { (progress) in //print(progress) }, success: { (task, object) in //print(object) guard let array = (object as! [String: AnyObject])["statuses"] as? [[String: AnyObject]] else{ finished(Array: nil, error: NSError(domain: "https://www.facebook.com", code: 404, userInfo: ["Message": "没有获取到数据"])) return } finished(Array: array, error: nil) }) { (task, error) in finished(Array: nil, error: error) } } func sendStatus(status: String, finished: (objc: AnyObject?, error: NSError?)->()){ let url = "https://api.weibo.com/2/statuses/update.json" let paras = ["access_token": "2.00pFZdLC25bUWE6b1e1f2b940lv3Oc", "status": status] POST(url, parameters: paras, progress: { (progress) in //print(progress) }, success: { (task, object) in finished(objc: object, error: nil) }) { (task, error) in finished(objc: nil, error: error) } } }
apache-2.0
c49fdebb82cf737627832304978a9b30
36.081967
151
0.567197
4.046512
false
false
false
false
tananaev/traccar-client-ios
TraccarClient/Position.swift
1
1941
// // Copyright 2015 - 2017 Anton Tananaev ([email protected]) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import CoreData import CoreLocation public class Position: NSManagedObject { @NSManaged public var deviceId: String? @NSManaged public var time: NSDate? @NSManaged public var latitude: NSNumber? @NSManaged public var longitude: NSNumber? @NSManaged public var altitude: NSNumber? @NSManaged public var speed: NSNumber? @NSManaged public var course: NSNumber? @NSManaged public var battery: NSNumber? @NSManaged public var accuracy: NSNumber? public convenience init(managedObjectContext context: NSManagedObjectContext) { let entityDescription = NSEntityDescription.entity(forEntityName: "Position", in: context) self.init(entity: entityDescription!, insertInto: context) } public func setLocation(_ location: CLLocation) { time = location.timestamp as NSDate latitude = location.coordinate.latitude as NSNumber longitude = location.coordinate.longitude as NSNumber altitude = location.altitude as NSNumber if location.speed >= 0 { speed = location.speed * 1.94384 as NSNumber // knots from m/s } if location.course >= 0 { course = location.course as NSNumber } accuracy = location.horizontalAccuracy as NSNumber } }
apache-2.0
b394628978db1e7eee6947ad9ca38b49
36.326923
98
0.707367
4.804455
false
false
false
false
jboss-mobile/unified-push-helloworld
ios-swift/HelloWorldSwift/ViewController.swift
1
4707
/* * JBoss, Home of Professional Open Source. * Copyright Red Hat, Inc., and individual contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit class ViewController: UITableViewController { let AGNotificationCellIdentifier = "AGNotificationCell" var isRegistered = false // holds the messages received and displayed on tableview var messages: Array<String> = [] override func viewDidLoad() { super.viewDidLoad() // register to be notified when state changes NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.registered), name: "success_registered", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.errorRegistration), name: "error_register", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.messageReceived(_:)), name: "message_received", object: nil) } func registered() { print("registered") // workaround to get messages when app was not running let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults(); if(defaults.objectForKey("message_received") != nil) { let msg : String! = defaults.objectForKey("message_received") as! String defaults.removeObjectForKey("message_received") defaults.synchronize() if(msg != nil) { messages.append(msg) } } isRegistered = true tableView.reloadData() } func errorRegistration() { // can't do much, inform user to verify the UPS details entered and return let message = UIAlertController(title: "Registration Error!", message: "Please verify the provisionioning profile and the UPS details have been setup correctly.", preferredStyle: .Alert) self.presentViewController(message, animated:true, completion:nil) } func messageReceived(notification: NSNotification) { print("received") let obj:AnyObject? = notification.userInfo!["aps"]!["alert"] // if alert is a flat string if let msg = obj as? String { messages.append(msg) } else { // if the alert is a dictionary we need to extract the value of the body key let msg = obj!["body"] as! String messages.append(msg) } tableView.reloadData() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { var bgView:UIView? // determine current state if (!isRegistered) { // not yet registered let progress = self.navigationController?.storyboard?.instantiateViewControllerWithIdentifier("ProgressViewController") if let progress = progress {bgView = progress.view} } else if (messages.count == 0) { // registered but no notification received yet let empty = self.navigationController?.storyboard?.instantiateViewControllerWithIdentifier("EmptyViewController") if let empty = empty {bgView = empty.view} } // set the background view if needed if (bgView != nil) { self.tableView.backgroundView = bgView self.tableView.separatorStyle = .None return 0 } return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count; } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // if it's the first message in the stream, let's clear the 'empty' placeholder vier if (self.tableView.backgroundView != nil) { self.tableView.backgroundView = nil self.tableView.separatorStyle = .SingleLine } let cell = tableView.dequeueReusableCellWithIdentifier(AGNotificationCellIdentifier)! cell.textLabel?.text = messages[indexPath.row] return cell } }
apache-2.0
673c374c2065d4b5094cf9b2ec128895
38.554622
195
0.65392
5.318644
false
false
false
false
hikelee/cinema
Sources/App/Controllers/CommandController.swift
1
7075
import Vapor import HTTP import Foundation extension Projector { func hall() throws -> Hall?{ return try Hall.load("projector_id",id) } } enum ClientCommand:Int { case play = 1 //播放 case pause = 2//暂停 case start = 3//开始 case stop = 4//停止 case forward = 5//快进 case back = 6//回退 } class CommandApiController: Controller { let path = "/api/cinema/command" override func makeRouter(){ routerGroup.group(path){group in group.get("/"){try self.doCommand($0)} group.get("/feedback"){try self.doFeedback($0)} } } func jsonCommand(_ channelId:Int,_ item:OrderItem,_ ipAddress:String, _ command:ClientCommand,_ countdownSeconds:Int) throws ->JSON? { print("movieId:\(item.movieId)") //if let movie = try Movie.load(channelId:channelId, bizId: item.movieId?.int ?? 0), if let movie = try Movie.load(item.movieId), let url = movie.playUrl { return try JSON( node:[ "status":0, "command_id": item.id, "command": command.rawValue, "delay_seconds": countdownSeconds, "movie_id" : movie.id, "movie_title":movie.title, "movie_url": "http://\(ipAddress)\(url)" ]) } return nil } func doCommand(_ request: Request) throws -> ResponseRepresentable { guard let identification = request.data["id"]?.string?.uppercased() else{ return try JSON(node:["status":1,"message":"no id"]) } guard let projector = try Projector.load("identification",identification) else{ return try JSON(node:["status":1,"message":"no projector"]) } guard let server = try projector.server() else{ return try JSON(node:["status":1,"message":"no server"]) } guard let hall = try projector.hall() else { return try JSON(node:["status":1,"message":"no hall"]) } guard var order = try hall.order() else { return try JSON(node:["status":1,"message":"no order"]) } guard let ipAddress = server.ipAddress else { return try JSON(node:["status":1,"message":"no ip address"]) } guard let channelId = server.channelId?.int else { return try JSON(node:["status":1,"messgae":"no channelId"]) } let items = try order.items() if items.isEmpty { return try JSON(node:["status":1,"messgae":"no order items"]) } if var item = items.first(where:{$0.shouldStop}), let json = try jsonCommand(channelId,item,ipAddress,.stop,0){ item.stopSentTime = Date().string() item.stopCommand = .sent try item.save() return json } if items.first(where:{$0.isPlaying}) != nil{ return try JSON(node:["status":0,"message":"isplaying"]) } let isCountdown = items.contains(where:{$0.isCountdown}) let countdownSeconds = isCountdown ? 0 : order.countdownSeconds if var item = items.first(where:{$0.shouldPlay}), let json = try jsonCommand(channelId,item,ipAddress,.play,countdownSeconds){ item.playSentTime = Date().string() item.playCommand = .sent if countdownSeconds > 0 { item.isCountdown = true } try item.save() return json } //Maybe other cases occurs order.state = .finished order.exists = true try order.save() return try JSON(node:["status":1,"message":"wrong order state"]) } func doFeedback(_ request: Request) throws -> ResponseRepresentable { guard let itemId = request.data["command_id"]?.int else { return try JSON(node:["status":1,"message":"no command_id param found"]) } guard let success = request.data["success"]?.bool else { return try JSON(node:["status":1,"message":"no success param found"]) } guard let action = request.data["action"]?.int else { return try JSON(node:["status":1,"message":"no action param found"]) } guard var item = try OrderItem.load(itemId) else { return try JSON(node:["status":1,"message":"no order item found"]) } guard var order = try Order.load(item.orderId) else { return try JSON(node:["status":1,"message":"no order found"]) } switch action { case 1://播放 item.playFeedback(success) try item.save() if success { if order.actualStartTime == nil { order.actualStartTime = Date().string() } order.state = .ongoing try order.save() return try JSON(node:["status":0,"message":"movie play success"]) } return try JSON(node:["status":0,"message":"movie play failure"]) case 2: item.stopFeedback(success) try item.save() if(success) { let items = try order.items() if items.first(where:{$0.shouldPlay}) == nil { order.state = .finished order.actualEndTime = Date().string() try order.save() return try JSON( node:[ "status":0, "message1":"movie stop success", "message2":"order stop success" ]) } return try JSON( node:[ "status":0, "message1":"movie stop success", "message2":"waiting for request to play another movie", ]) } return try JSON(node:["status":0,"message":"movie stop failure"]) case 3: let errorMessage = request.data["error"]?.string item.reportError(errorMessage) try item.save() let items = try order.items() if items.first(where:{$0.shouldPlay}) == nil { order.state = .finished order.actualEndTime = Date().string() try order.save() return try JSON( node:[ "status":0, "message1":"movie play error", "message2":"order stop success", ]) } order.errorMessage = errorMessage try order.save() return try JSON( node:[ "status":0, "message1":"movie play error", "message2":"waiting for request to play another movie", ]) default: return try JSON(node:["status":1,"message":"wrong action param"]) } } }
mit
2f3c893e775072384b046441cd5d087a
36.887097
92
0.514829
4.698
false
false
false
false
dcunited001/SpectraNu
Spectra/SpectraXML/Parser.swift
1
9635
// // Parser.swift // // // Created by David Conner on 3/9/16. // // import Foundation import Swinject import Fuzi import ModelIO // GeneratorClosure =~ RegisterClosure // - they both transform the containers and options passed into generate & register // - they're both optional // - i need some way for each node type to "declare" the options it needs to be available // - as well as a function for default transformation 4 resolving params from [String: Container] // problems: how to pass the GeneratorClosures down through the tree of nodes (if necessary) // - for now, just passing nil down the tree, but allowing the following order for resolving params for generate // - (1) if closure exists, run & set params from the resulting Container Map & Options Map. // - this closure is only passed to the top level node for now. // - it's possible to pass thru to the child nodes. maybe later // - need a kind of inverted-map structure for options // - (2) if not, then if necessary params are defined in the Options Map, set the params 4 generate from those // - how to distinguish the params defined in option for a parent node and child nodes // - (3) otherwise, run the default behavior for fetching params from Container Map // ... public typealias GeneratorClosure = ((containers: [String: Container], options: [String: Any]) -> (containers: [String: Container], options: [String: Any])) public typealias RegisterClosure = (containers: [String: Container], options: [String: Any]) -> (containers: [String: Container], options: [String: Any]) public protocol SpectraParserNode { associatedtype NodeType associatedtype MDLType var id: String? { get set } // requires init() for copy() init(nodes: Container, elem: XMLElement) func parseXML(nodes: Container, elem: XMLElement) func generate(containers: [String: Container], options: [String: Any], injector: GeneratorClosure?) -> MDLType func register(nodes: Container, objectScope: ObjectScope) func copy() -> NodeType } extension SpectraParserNode { public func register(nodes: Container, objectScope: ObjectScope = .None) { let nodeCopy = self.copy() nodes.register(NodeType.self, name: self.id!) { _ in return nodeCopy }.inObjectScope(objectScope) } } public class SpectraParser { public var nodes: Container public init(nodes: Container = Container()) { self.nodes = nodes } public func getAsset(id: String?) -> AssetNode? { return nodes.resolve(AssetNode.self, name: id) } public func getVertexAttribute(id: String?) -> VertexAttributeNode? { return nodes.resolve(VertexAttributeNode.self, name: id) } public func getVertexDescriptor(id: String?) -> VertexDescriptorNode? { return nodes.resolve(VertexDescriptorNode.self, name: id) } public func getTransform(id: String?) -> TransformNode? { return nodes.resolve(TransformNode.self, name: id) } public func getObject(id: String?) -> ObjectNode? { return nodes.resolve(ObjectNode.self, name: id) } public func getPhysicalLens(id: String?) -> PhysicalLensNode? { return nodes.resolve(PhysicalLensNode.self, name: id) } public func getPhysicalImagingSurface(id: String?) -> PhysicalImagingSurfaceNode? { return nodes.resolve(PhysicalImagingSurfaceNode.self, name: id) } public func getCamera(id: String?) -> CameraNode? { return nodes.resolve(CameraNode.self, name: id) } public func getStereoscopicCamera(id: String?) -> StereoscopicCameraNode? { return nodes.resolve(StereoscopicCameraNode.self, name: id) } public func getMesh(id: String?) -> MeshNode? { return nodes.resolve(MeshNode.self, name: id) } public func getMeshGenerator(id: String?) -> MeshGeneratorNode? { return nodes.resolve(MeshGeneratorNode.self, name: id) } public func getSubmesh(id: String?) -> SubmeshNode? { return nodes.resolve(SubmeshNode.self, name: id) } public func getSubmeshGenerator(id: String?) -> SubmeshGeneratorNode? { return nodes.resolve(SubmeshGeneratorNode.self, name: id) } public func getTexture(id: String?) -> TextureNode? { return nodes.resolve(TextureNode.self, name: id) } public func getTextureGenerator(id: String?) -> TextureGeneratorNode? { return nodes.resolve(TextureGeneratorNode.self, name: id) } public func getTextureFilter(id: String?) -> TextureFilterNode? { return nodes.resolve(TextureFilterNode.self, name: id) } public func getTextureSampler(id: String?) -> TextureSamplerNode? { return nodes.resolve(TextureSamplerNode.self, name: id) } // TODO: Material // TODO: MaterialProperty // TODO: ScatteringFunction // TODO: Light // TODO: LightGenerator // public func get(id: String?) -> Node? { // return nodes.resolve(Node.self, name: id) // } // public func parseJSON() // public func parsePList() public func parseXML(xml: XMLDocument) { for child in xml.root!.children { let (tag, id) = (child.tag!, child.attributes["id"]) // TODO: how to refactor this giant switch statement if let nodeType = SpectraNodeType(rawValue: tag) { switch nodeType { case .Asset: let node = AssetNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .VertexAttribute: let node = VertexAttributeNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .VertexDescriptor: let node = VertexDescriptorNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .Transform: let node = TransformNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } // case .Object: // let node = ObjectNode(nodes: nodes, elem: child) // if (node.id != nil) { node.register(nodes) } case .PhysicalLens: let node = PhysicalLensNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .PhysicalImagingSurface: let node = PhysicalImagingSurfaceNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .Camera: let node = CameraNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .StereoscopicCamera: let node = StereoscopicCameraNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .Mesh: let node = MeshNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .MeshGenerator: let node = MeshGeneratorNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .Submesh: let node = SubmeshNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .SubmeshGenerator: let node = SubmeshGeneratorNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .Texture: let node = TextureNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .TextureGenerator: let node = TextureGeneratorNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } case .TextureFilter: let node = TextureFilterNode(nodes: nodes, elem: child) if (node.id != nil) { node.register(nodes) } // case .TextureSampler: break // case .Material: break // case .MaterialProperty: break // case .ScatteringFunction: break // case .Light: break // case .LightGenerator: break default: break } } } } public static func readXML(bundle: NSBundle, filename: String, bundleResourceName: String?) -> XMLDocument? { var resourceBundle: NSBundle = bundle if let resourceName = bundleResourceName { let bundleURL = bundle.URLForResource(resourceName, withExtension: "bundle") resourceBundle = NSBundle(URL: bundleURL!)! } let path = resourceBundle.pathForResource(filename, ofType: "xml") let data = NSData(contentsOfFile: path!) do { return try XMLDocument(data: data!) } catch let err as XMLError { switch err { case .ParserFailure, .InvalidData: print(err) case .LibXMLError(let code, let message): print("libxml error code: \(code), message: \(message)") default: break } } catch let err { print("error: \(err)") } return nil } }
mit
df3a52f6d4aa83770dc1eca26c888a77
39.826271
156
0.593773
4.41163
false
false
false
false
sleekbyte/tailor
src/test/swift/com/sleekbyte/tailor/functional/ForceCastTest.swift
1
764
if let movie = item as? Movie { print("Movie: '\(movie.name)', dir. \(movie.director)") } let trouble = "Objective C" let moreTrouble = s as AnyObject let crash = id as! NSDate let movie = item as! Movie print("Movie: '\(movie.name)', dir. \(movie.director)") func someFunction() { let someForceCast = NSNumber() as! Int } let someForceCast = NSNumber() as? Int let cell = tableView.dequeueReusableCellWithIdentifier("RecordCell", forIndexPath: indexPath) as! UITableViewCell let responseDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves, error: &error) as! NSDictionary let statusCode = responseDictionary["status_code"] as! NSNumber let statusText = responseDictionary["status_txt"] as! NSString
mit
3c06a5c4af543f3a79b86036a201cd42
32.217391
146
0.748691
4.220994
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/SettingsNotificationPickerViewModelTests.swift
1
1199
@testable import KsApi import Library import Prelude import ReactiveExtensions_TestHelpers import XCTest final class SettingsNotificationPickerViewModelTests: TestCase { private let vm = SettingsNotificationPickerViewModel() let frequencyValueText = TestObserver<String, Never>() override func setUp() { super.setUp() self.vm.outputs.frequencyValueText.observe(self.frequencyValueText.observer) } func testConfigure_userCreatorDigest_enabled() { let user = User.template |> UserAttribute.notification(.creatorDigest).keyPath .~ true let cellValue = SettingsNotificationCellValue( cellType: .emailFrequency, user: user ) self.vm.configure(with: cellValue) self.frequencyValueText.assertValue(EmailFrequency.dailySummary.descriptionText) } func testConfigure_userCreatorDigest_disabled() { let user = User.template |> UserAttribute.notification(.creatorDigest).keyPath .~ false let cellValue = SettingsNotificationCellValue( cellType: .emailFrequency, user: user ) self.vm.configure(with: cellValue) self.frequencyValueText.assertValue(EmailFrequency.twiceADaySummary.descriptionText) } }
apache-2.0
6a465ed8a78c47da6e804427c824d025
25.644444
88
0.75563
4.796
false
true
false
false
asowers1/ASUserDefaults
Pod/Classes/ASUserDefaultsManager.swift
1
1838
// // ASUserDefaultsManager.swift // Pods // // Created by Andrew Sowers on 2/15/16. // // import Foundation public protocol ASUserDefaultsManagerDelegate: class { func didSaveObject(object: AnyObject?, withName: String, inSuite: String) func didLoadObject(object: AnyObject?, withName: String, inSuite: String) } public class ASUserDefaultsManager : NSObject { var suiteZone: String? = nil // the default suite is nil, and this will result in NSUserDefaults using the standardUserDefaults suite static public let sharedManager = ASUserDefaultsManager() public weak var delegate: ASUserDefaultsManagerDelegate? // save will do its best to infer the type you'd like to save. Just remember, you should probably know the type you'd like to save/load public func save(value: AnyObject?, key: String) { var suite = "stardardUserDefaults" if let _ = self.suiteZone { NSUserDefaults(suiteName: suiteZone)?.setObject(value, forKey: key) suite = self.suiteZone! } else { NSUserDefaults.standardUserDefaults().setObject(value, forKey: key) } self.delegate?.didSaveObject(value, withName: key, inSuite: suite) } public func load(key: String) -> AnyObject? { var object: AnyObject? var suite = "standardUserDefaults" if let _ = self.suiteZone { object = NSUserDefaults(suiteName: suiteZone)?.objectForKey(key) suite = self.suiteZone! } else { object = NSUserDefaults.standardUserDefaults().objectForKey(key) } self.delegate?.didLoadObject(object, withName: key, inSuite: suite) return object } public func setSuiteName(suiteName: String?) { self.suiteZone = suiteName } }
mit
e9f17f3e2026c5852dbcda7bdbc4b4ea
32.436364
139
0.658324
4.664975
false
false
false
false
S2dentik/Taylor
TaylorIntegrationTests/Resources/TaylorIntegrationTestResources.bundle/Contents/Resources/Wrapper.swift
4
6730
// // Wrapper.swift // swetler // // Created by Seremet Mihai on 10/9/15. // Copyright © 2015 Yopeso. All rights reserved. // import Foundation public enum OutputVerbosity { case StandardOutput case StandardError } public final class Wrapper { private let resourceName = "Objective-Clean" private let resourceExtenstion = "app" public var arguments : [String] = [] public var outputVerbosity : OutputVerbosity private var runTask = NSTask() private let pipe = NSPipe() public static var itemsPathsToDelete = [String]() public static var originalPaths = [String : String]() public static var analyzePaths = [String]() // MARK: Initialization public init(verbosity: OutputVerbosity) { self.outputVerbosity = verbosity } convenience public init(verbosity: OutputVerbosity, parameters: Parameters) throws { self.init(verbosity: verbosity) if let path = parameters.projectPath.associated as? String { arguments.append(path) do { try copyResourceFilesIfNedeed(parameters, toPath: path) } catch let error { print(error) } } else if let files = parameters.filesPaths.associated as? [String] { guard let settings = parameters.settingsPath.associated as? String else { throw MissingResourcesError.StyleSettingsMissingError(message: "Missing style settings file path.") } guard let excludes = parameters.excludesPath.associated as? String else { throw MissingResourcesError.ExcludeFileMissingError(message: "Missing exclude file path.") } arguments.append(createWrapperEnviroment(filesToCheck: files, settingsFilePath: settings, excludeFilePath: excludes)) Wrapper.itemsPathsToDelete.append(arguments.last!) } if let path = arguments.last { Wrapper.analyzePaths.append(path) } } // MARK: Public interface public func getOutput() throws -> String { configureRunTask() try run() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String return output } // MARK: Private methods private func configureRunTask() { runTask.launchPath = findObjectiveCleanAppPath() if outputVerbosity == .StandardOutput { runTask.standardOutput = pipe } else { runTask.standardError = pipe } } private func run() throws { deleteAppCaches() runTask.arguments = arguments runTask.launch() executeAppleScript() } private func findObjectiveCleanAppPath() -> String? { let bundle = NSBundle(forClass: self.dynamicType) if let path = bundle.pathForResource(resourceName, ofType: resourceExtenstion) { return path.stringByAppendingPathComponent("/Contents/Resources/ObjClean.app/Contents/MacOS/ObjClean") } return nil } private func deleteAppCaches() { let objCleanCachePaths = ["/Users/" + NSUserName() + "/Library/Caches/com.objClean", "/Users/" + NSUserName() + "/Library/Caches/com.objClean.Enforcer"] let fileManager = NSFileManager.defaultManager() do { let _ = try objCleanCachePaths.filter({ fileManager.fileExistsAtPath($0) }).map { let _ = try fileManager.listOfFilesAtPath($0).map { fileManager.removeFileAtPath($0) } } } catch let error { print(error) } } private func executeAppleScript() { let operationQueue = NSOperationQueue() operationQueue.addOperation(CloseDialogWindowOperation()) } // MARK: Resources fils manipulation private func copyResourceFilesIfNedeed(parameters: Parameters, toPath path: String) throws { try copyExcludeFile(parameters, toPath: path) try copySettingsFile(parameters, toPath: path) } private func copyExcludeFile(parameters: Parameters, toPath: String) throws { if let excludes = parameters.excludesPath.associated as? String { if toPath.stringByAppendingPathComponent(excludesFileName) == excludes { return } try copyItemsAtPaths([excludes], toPath: toPath) Wrapper.itemsPathsToDelete.append(toPath.stringByAppendingPathComponent(excludes.lastPathComponent)) } } private func copySettingsFile(parameters: Parameters, toPath: String) throws { if let settings = parameters.settingsPath.associated as? String { if toPath.stringByAppendingPathComponent(styleSettingsFileName) == settings { return } try copyItemsAtPaths([settings], toPath: toPath) Wrapper.itemsPathsToDelete.append(toPath.stringByAppendingPathComponent(settings.lastPathComponent)) } } private func createWrapperEnviroment(filesToCheck filePaths: [String], settingsFilePath settingsPath: String, excludeFilePath excludePath: String) -> String { let resourcesDirectoryName = "." + String.randomStringWithLength(10) let resourcesPath = NSFileManager.defaultManager().currentDirectoryPath.stringByAppendingPathComponent(resourcesDirectoryName) let filesPath = resourcesPath.stringByAppendingPathComponent("Files") do { try createDirectoryAtPath(resourcesPath) try createDirectoryAtPath(filesPath) try copyItemsAtPaths([settingsPath, excludePath], toPath: resourcesPath) try copyItemsAtPaths(filePaths, toPath: filesPath) } catch let error { print(error) } return resourcesPath } private func copyItemsAtPaths(paths: [String], toPath: String) throws { let _ = try paths.map() { try NSFileManager.defaultManager().copyOrReplaceFileAtPath($0, toPath: toPath.stringByAppendingPathComponent($0.lastPathComponent)) Wrapper.originalPaths.updateValue(toPath.stringByAppendingPathComponent($0.lastPathComponent), forKey: $0) } } private func createDirectoryAtPath(path: String) throws { if !NSFileManager.defaultManager().fileExistsAtPath(path) { try NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: false, attributes: nil) } } }
mit
97e1744d1c68a610f80d4c2cb2694795
34.603175
162
0.645267
5.285939
false
false
false
false
kevintavog/PeachMetadata
source/PeachMetadata/ImportLightroomExport.swift
1
13768
// // ImportLightroomExport.swift // import RangicCore public enum ImportError : Error { case destinationIsAFile(path: String) case filenameExistsInDestination(filename: String) } protocol ImportProgress { func setCurrentStep(_ stepName: String) func setStepDetail(_ detail: String) } class ImportLightroomExport { fileprivate var importProgress: ImportProgress? fileprivate var destinationFolder: String? fileprivate var originalMediaData: [MediaData] fileprivate var exportedMediaData: [MediaData] init(originalMediaData: [MediaData], exportedMediaData: [MediaData]) { self.originalMediaData = originalMediaData self.exportedMediaData = exportedMediaData } func run(_ progress: ImportProgress, importFolder: String, destinationFolder: String) throws { self.importProgress = progress self.destinationFolder = destinationFolder // Setup - Generate data to make checks quicker try setup() // STEP: Move exported files try moveExported() // STEP: Move all original files to destination folder try moveOriginals() // STEP: Convert videos try convertVideos() // STEP: Archive originals try archiveOriginals() // STEP: Remove Original & Exported folders try removeImportFolders(importFolder) } func findWarnings() -> [String] { var result = [String]() var originalNames = [String:MediaData]() for o in originalMediaData { originalNames[o.url!.deletingPathExtension().lastPathComponent] = o } var exportedNames = [String:MediaData]() for e in exportedMediaData { exportedNames[e.url!.deletingPathExtension().lastPathComponent] = e } // Lightroom does a horrible job with the exported video metadata - the metadata dates are export time rather than // original time and the location information is in an unknown (possibly non-standard) location. On top of that, // the video is re-encoded as part of the export process. // For these reasons, videos in 'Exported' trigger a warning and are ignored for the import // Each non-video file in originals needs to have a matching file in exported for oname in originalNames { if oname.1.type! != .video && !exportedNames.keys.contains(oname.0) { result.append("Original file \(oname.1.name!) not in exported list") } // Annoyingly, the Canon T3i uses camera time when setting the UTC timestamp in videos - it should use UTC, but doesn't have a timezone setting if oname.1.type! == .video && oname.1.compatibleBrands.contains("CAEP") { result.append("Original file \(oname.1.name!) is a Canon movie - the timestamp will need to be adjusted to UTC") } } // Each exported file should have a matching file in originals for ename in exportedNames { if !originalNames.keys.contains(ename.0) { result.append("Exported file \(ename.1.name!) has no matching file in original list") } } // Each exported needs to have a proper date/time & a location for e in exportedMediaData { if !e.doFileAndExifTimestampsMatch() { result.append("Exported file \(e.name!) has mismatched timestamps") } if e.location == nil { result.append("Exported file \(e.name!) is missing location") } else { if SensitiveLocations.sharedInstance.isSensitive(e.location) { result.append("Exported file \(e.name!) is in a sensitive location") } } } // Exported files should not contain videos for e in exportedMediaData { if e.type == .video { result.append("Videos in Exported are ignored: \(e.name!)") } } return result } //------------------------------------------------------------------------------------------------------------- // Step functions //------------------------------------------------------------------------------------------------------------- func setup() throws { Logger.info("Importing to \(destinationFolder!)") importProgress?.setCurrentStep("Setting up") var existingFilenames = [String]() var isFolder: ObjCBool = false if FileManager.default.fileExists(atPath: destinationFolder!, isDirectory:&isFolder) { if !isFolder.boolValue { throw ImportError.destinationIsAFile(path: destinationFolder!) } let urls = try FileManager.default.contentsOfDirectory( at: NSURL(fileURLWithPath: destinationFolder!) as URL, includingPropertiesForKeys: nil, options:FileManager.DirectoryEnumerationOptions.skipsHiddenFiles) for u in urls { existingFilenames.append(u.lastPathComponent) } } else { try FileManager.default.createDirectory(atPath: destinationFolder!, withIntermediateDirectories: true, attributes: nil) } // Generate filenames that will be used - so we can find duplicates var generatedNames = Set<String>() var generatedUrlToName = [URL:String]() for md in originalMediaData { let name = generateDestinationName(md.name as NSString, isOriginal: true) generatedNames.insert(name) generatedUrlToName[md.url] = name } for md in exportedMediaData { let name = generateDestinationName(md.name as NSString, isOriginal: false) generatedNames.insert(name) generatedUrlToName[md.url] = name } // Do any generated/destination names conflict with existing filenames? for existing in existingFilenames { if generatedNames.contains(existing) { throw ImportError.filenameExistsInDestination(filename: existing) } } } func moveExported() throws { importProgress?.setCurrentStep("Moving files from exported folder") // Move all exportedMediaData files to destination folder before original in case of accidental overwrites for media in exportedMediaData { if media.type == .image { let destinationFile = "\(destinationFolder!)/\(media.name!)" importProgress?.setStepDetail("Moving from \(media.url!.path) to \(destinationFile)") do { try FileManager.default.moveItem(atPath: media.url!.path, toPath: destinationFile) } catch let error { Logger.error("Failed moving \(media.url!.path): \(error)") importProgress?.setStepDetail("Failed moving \(media.url!.path): \(error)") } } else { importProgress?.setStepDetail("Skipping unsupported file in 'Exported': \(media.name!)") } } } func moveOriginals() throws { importProgress?.setCurrentStep("Moving files from originals folder") // Rename *.JPG to *-org.JPG for media in originalMediaData { let destinationFile = "\(destinationFolder!)/\(generateDestinationName(media.name as NSString, isOriginal: true))" importProgress?.setStepDetail("Moving from \(media.url!.path) to \(destinationFile)") do { try FileManager.default.moveItem(atPath: media.url!.path, toPath: destinationFile) } catch let error { Logger.error("Failed moving \(media.url!.path): \(error)") importProgress?.setStepDetail("Failed moving \(media.url!.path): \(error)") } } } func convertVideos() throws { // Convert items that are videos that haven't already been converted let videos = originalMediaData.filter( { $0.type == .video && !$0.name.hasSuffix("_V.MP4") } ) if videos.count < 1 { return } importProgress?.setCurrentStep("Converting videos") for m in videos { importProgress?.setStepDetail(m.name!) let rotationOption = getRotationOption(m) // The video has been moved - refer to the new location let sourceName = "\(destinationFolder!)/\(m.name!)" convertVideo(sourceName, destinationName: "\(destinationFolder!)/\(m.nameWithoutExtension)_V.MP4", rotationOption: rotationOption) } } func archiveOriginals() throws { // The script is failing because it can't find 'ping' // importProgress?.setCurrentStep("Archiving originals") // let result = ProcessInvoker.run("/bin/bash", arguments: ["/Users/goatboy/Tools/archiveOriginals.sh"]) // addProcessResultDetail("archiveOriginals", processResult: result) } func removeImportFolders(_ importFolder: String) throws { importProgress?.setCurrentStep("Removing original/import folder: \(importFolder)") let enumerator = FileManager.default.enumerator( at: NSURL(fileURLWithPath: importFolder, isDirectory: true) as URL, includingPropertiesForKeys: [URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles, errorHandler: { (url: URL, error: Error) -> Bool in return true }) var hadError = false var fileCount = 0 if enumerator != nil { for e in enumerator!.allObjects { let url = e as! NSURL do { var resource: AnyObject? try url.getResourceValue(&resource, forKey: URLResourceKey.isDirectoryKey) if let isDirectory = resource as? Bool { if !isDirectory { fileCount += 1 } } } catch let error { hadError = true Logger.error("Failed finding remaining files in original/import folder: \(error)") } } } if fileCount == 0 && hadError == false { try FileManager.default.removeItem(atPath: importFolder) } else { Logger.error("Not removing original folder due to existing files") importProgress?.setStepDetail("Not removing original folder due to existing files") } } //------------------------------------------------------------------------------------------------------------- // Utility functions //------------------------------------------------------------------------------------------------------------- func getRotationOption(_ mediaData: MediaData) -> String { if let rotation = mediaData.rotation { switch rotation { case 90: return "--rotate=4" case 180: return "--rotate=3" case 270: return "--rotate=7" case 0: return "" default: Logger.warn("Unhandled rotation \(mediaData.rotation!)") return "" } } return "" } func convertVideo(_ sourceName: String, destinationName: String, rotationOption: String) { // Use the HandBrake command line - it uses ffmpeg and is both easier to install and has a more stable CLI than ffmpeg let handbrakePath = "/Applications/Extras/HandBrakeCLI" let handbrakeResult = ProcessInvoker.run(handbrakePath, arguments: [ "-e", "x264", "-q", "20.0", "-a", "1", "-E", "faac", "-B", "160", "-6", "dpl2", "-R", "Auto", "-D", "0.0", "--audio-copy-mask", "aac,ac3,dtshd,dts,mp3", "--audio-fallback", "ffac3", "-f", "mp4", "--loose-anamorphic", "--modulus", "2", "-m", "--x264-preset", "veryfast", "--h264-profile", "auto", "--h264-level", "auto", "-O", rotationOption, "-i", sourceName, "-o", destinationName]) addProcessResultDetail("Handbrake", processResult: handbrakeResult) // Copy the original video metadata to the new video let exiftoolResult = ProcessInvoker.run(ExifToolRunner.exifToolPath, arguments: ["-overwrite_original", "-tagsFromFile", sourceName, destinationName]) addProcessResultDetail("ExifTool", processResult: exiftoolResult) // Update the file timestamp on the new video to match the metadata timestamp let mediaData = FileMediaData.create(NSURL(fileURLWithPath: destinationName) as URL, mediaType: .video) let _ = mediaData.setFileDateToExifDate() } func addProcessResultDetail(_ name: String, processResult: ProcessInvoker) { importProgress?.setStepDetail("\(name) exit code: \(processResult.exitCode)") if processResult.exitCode != 0 { importProgress?.setStepDetail("\(name) standard output: \(processResult.output)") importProgress?.setStepDetail("\(name) error output: \(processResult.error)") } } func generateDestinationName(_ name: NSString, isOriginal: Bool) -> String { var newName = name if isOriginal && name.pathExtension.compare("JPG", options: NSString.CompareOptions.caseInsensitive, range: nil, locale: nil) == .orderedSame { newName = name.deletingPathExtension.appending("-org.JPG") as NSString } return newName as String } }
mit
bd7cf23bea2b61d902794da6a59c6c3e
39.375367
155
0.584326
5.052477
false
false
false
false
Chaosspeeder/YourGoals
YourGoals/UI/Views/Actionable Table Cells/ActionableTableView.swift
1
6597
// // UITasksView.swift // YourGoals // // Created by André Claaßen on 01.11.17. // Copyright © 2017 André Claaßen. All rights reserved. // import UIKit import MGSwipeTableCell /// todo: this protocol should be split in two different protocols protocol ActionableTableViewDelegate { func requestForEdit(actionable: Actionable) func showNotification(forError error: Error) func goalChanged(goal: Goal) func progressChanged(actionable: Actionable) func commitmentChanged() func registerCells(inTableView: UITableView) func dequeueActionableCell(fromTableView: UITableView, atIndexPath: IndexPath) -> ActionableCell } /// a specialized UITableView for displaying tasks, habits and actionables in general class ActionableTableView: UIView, UITableViewDataSource, UITableViewDelegate, ActionableTableCellDelegate { var tasksTableView:UITableView! var reorderTableView: LongPressReorderTableView! var sections = [ActionableSection]() var items = [[ActionableItem]]() var timer = Timer() var timerPaused = false var editTask:Task? = nil var delegate:ActionableTableViewDelegate! var dataSource:ActionableDataSource? var constraint:NSLayoutConstraint? = nil var constraintOffset:CGFloat = 0 var panGestureRecognizer:UIPanGestureRecognizer! var theme: Theme! var manager: GoalsStorageManager! var calculatestartingTimes = false var reorderInfo:ReorderInfo? override init(frame: CGRect) { super.init(frame: frame) commonSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonSetup() } func commonSetup() { self.backgroundColor = UIColor.clear self.tasksTableView = UITableView(frame: self.bounds) self.configureTaskTableView(self.tasksTableView) self.reorderTableView = LongPressReorderTableView(self.tasksTableView, selectedRowScale: .big) self.reorderTableView.delegate = self self.reorderTableView.enableLongPressReorder() self.addSubview(self.tasksTableView) self.reorderTableView.delegate = self self.scheduleTimerWithTimeInterval(tableView: self.tasksTableView) } /// configure the actionable task view with a data source for actionabels and a delegate for actions /// /// - Parameters: /// - dataSource: a actionable data source /// - delegate: a delegate for actions like editing or so. /// - varyingHeightConstraint: an optional constraint, if the actionable table view should modify the constriaitn func configure(manager: GoalsStorageManager, dataSource: ActionableDataSource, delegate: ActionableTableViewDelegate, varyingHeightConstraint: NSLayoutConstraint? = nil) { self.theme = Theme.defaultTheme self.manager = manager self.dataSource = dataSource self.delegate = delegate if let constraint = varyingHeightConstraint { self.configure(constraint: constraint) } self.delegate.registerCells(inTableView: self.tasksTableView) reload() } /// reload the tasks table view func reload() { do { guard let dataSource = self.dataSource else { assertionFailure("you need to configure the ActionableTableView with a datasource first") return } // load sections and items let backburnedGoals = SettingsUserDefault.standard.backburnedGoals let date = Date() self.sections = try dataSource.fetchSections(forDate: date, withBackburned: backburnedGoals) self.items.removeAll() if self.sections.count == 0 { self.items.append(try dataSource.fetchItems(forDate: date, withBackburned: backburnedGoals, andSection: nil)) } else { for section in sections { self.items.append(try dataSource.fetchItems(forDate: date, withBackburned: backburnedGoals, andSection: section)) } } self.tasksTableView.reloadData() } catch let error { self.delegate.showNotification(forError: error) } } /// timer for updating the remaining time for a task /// /// - Parameter tableView: the table vie func scheduleTimerWithTimeInterval(tableView: UITableView) { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTaskInProgess), userInfo: tableView, repeats: true) timerPaused = false } /// show actual timer in active tasks /// /// - Parameter timer: timer @objc func updateTaskInProgess(timer:Timer) { guard !self.timerPaused else { return } self.reload() } func reloadTableView() { self.tasksTableView.reloadData() } // MARK: - Data Source Helper Methods func numberOfActionables(_ section:Int) -> Int { return self.items[section].count } /// get the actionable for the section and the row in the section /// /// - Parameter path: the path with section and row /// - Returns: index actionable func itemForIndexPath(path: IndexPath) -> ActionableItem { return self.items[path.section][path.row] } /// retrieve the index path of all task cells, which are in progess /// /// - Returns: array of index paths func indexPathsInProgress() -> [IndexPath] { var indexPaths = [IndexPath]() let date = Date() for sectionTuple in self.items.enumerated() { for actionableTuple in sectionTuple.element.enumerated() { let item = actionableTuple.element if item.actionable.isProgressing(atDate: date) { indexPaths.append(IndexPath(row: actionableTuple.offset, section: sectionTuple.offset)) } } } return indexPaths } // MARK: - ActionableTableCellDelegate func actionableStateChangeDesired(item: ActionableItem) { do { try switchBehavior(item: item, date: Date(), behavior: .state) } catch let error { delegate.showNotification(forError: error) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate.requestForEdit(actionable: self.itemForIndexPath(path: indexPath).actionable) } }
lgpl-3.0
3adfa9b91412a3b4403f1599dae15a4d
35.21978
175
0.655188
5.074673
false
false
false
false
labi3285/QXConsMaker
QXConsMaker/RemakeLayoutVc.swift
1
1696
// // RemakeLayoutVc.swift // QXAutoLayoutDemo // // Created by Richard.q.x on 16/5/9. // Copyright © 2016年 labi3285_lab. All rights reserved. // import UIKit class RemakeLayoutVc: UIViewController { var A: UILabel? var i: Int = 0 override func viewDidLoad() { view.backgroundColor = UIColor.white let msg = NewLabel(title: "click to change layout", inView: self.view) A = NewLabel(title: "", inView: self.view) msg.LEFT.EQUAL(view).OFFSET(20).MAKE() msg.TOP.EQUAL(view).OFFSET(100).MAKE() A!.CENTER_X.EQUAL(view).MAKE() A!.CENTER_Y.EQUAL(view).MAKE() A!.WIDTH.EQUAL(100).MAKE() A!.HEIGHT.EQUAL(100).MAKE() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { i += 1 let v = i % 3 if v == 0 { A!.REMOVE_CONSES() A!.CENTER_X.EQUAL(view).MAKE() A!.CENTER_Y.EQUAL(view).MAKE() A!.WIDTH.EQUAL(100).MAKE() A!.HEIGHT.EQUAL(100).MAKE() } else if v == 1 { A!.REMOVE_CONSES() A!.CENTER_X.EQUAL(view).MAKE() A!.CENTER_Y.EQUAL(view).MAKE() A!.WIDTH.EQUAL(200).MAKE() A!.HEIGHT.EQUAL(200).MAKE() } else { A!.REMOVE_CONSES() A!.LEFT.EQUAL(view).MAKE() A!.CENTER_Y.EQUAL(view).MAKE() A!.WIDTH.EQUAL(100).MAKE() A!.HEIGHT.EQUAL(100).MAKE() } UIView.animate(withDuration: 1, animations: { self.view.layoutIfNeeded() }) } }
apache-2.0
95b32ae402a1c2b4c2f2a18407190215
25.046154
79
0.500295
3.75388
false
false
false
false
willsbor/AutoPullRequestUI
AutoPullRequest/ViewController.swift
1
17881
// // ViewController.swift // AutoPullRequest // // Created by willsbor Kang on 2015/12/7. // Copyright © 2015年 gogolook. All rights reserved. // import Cocoa import SSKeychain class ViewController: NSViewController, NSTextFieldDelegate { @IBOutlet weak var githubAccountTextField: NSTextField! @IBOutlet weak var githubPasswordTextField: NSSecureTextField! @IBOutlet weak var githubRepoTextField: NSTextField! @IBOutlet weak var githubRepoBranchTextField: NSTextField! @IBOutlet weak var sourceDirTextField: NSTextField! @IBOutlet weak var workspaceTextField: NSTextField! @IBOutlet weak var processingAnimationIndicator: NSProgressIndicator! @IBOutlet weak var applyButton: NSButton! @IBOutlet weak var commitMessageTextField: NSTextField! @IBOutlet weak var sourceBrowseButton: NSButton! @IBOutlet weak var resetButton: NSButton! @IBOutlet weak var scriptButton: NSButton! @IBOutlet weak var logMessageTestScroll: NSScrollView! var repo_path = "" var repo_branch = "" var github_user = "" var github_password = "" var source_dir = "" var workspace_dir = "" var commit_message = "" //var python_script = "/Users/willsborkang/Documents/gogolook/iOS/XcassetsOven/AutoPullRequest.py" var python_script: String = "AutoPullRequest.py"; func resetValue() { self.repo_path = "https://github.com/Gogolook-Inc/DesignImages.git" self.repo_branch = "whoscall-ios" self.github_user = "[email protected]" self.github_password = "" self.source_dir = "" self.workspace_dir = "/tmp/autopullrequest.workspace" self.representedObject = nil } override func viewDidLoad() { super.viewDidLoad() self.loadValues() // Do any additional setup after loading the view. self.workspaceTextField.enabled = false self.sourceDirTextField.enabled = false NSNotificationCenter.defaultCenter().addObserver(self, selector: "controlTextDidChange:", name: NSControlTextDidChangeNotification, object: nil) } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. self.githubAccountTextField.stringValue = self.github_user self.githubPasswordTextField.stringValue = self.github_password self.githubRepoTextField.stringValue = self.repo_path self.githubRepoBranchTextField.stringValue = self.repo_branch self.sourceDirTextField.stringValue = self.source_dir self.workspaceTextField.stringValue = self.workspace_dir self.commitMessageTextField.stringValue = self.commit_message } } override func controlTextDidChange(obj: NSNotification) { self.github_user = self.githubAccountTextField.stringValue self.github_password = self.githubPasswordTextField.stringValue self.repo_path = self.githubRepoTextField.stringValue self.repo_branch = self.githubRepoBranchTextField.stringValue self.source_dir = self.sourceDirTextField.stringValue self.workspace_dir = self.workspaceTextField.stringValue self.commit_message = self.commitMessageTextField.stringValue if let object = obj.object where object as! NSObject == self.githubAccountTextField { let password = SSKeychain.passwordForService("AutoPullRequest", account: self.github_user) if password != nil { self.github_password = password self.githubPasswordTextField.stringValue = self.github_password } } } internal func control(control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool { if control == self.sourceDirTextField { return false } else if control == self.workspaceTextField { return false } return true } func getNowDir() -> String { let pipe = NSPipe() let file = pipe.fileHandleForReading let task = NSTask() task.launchPath = "/bin/pwd" task.arguments = [] task.standardOutput = pipe task.launch() let data = file.readDataToEndOfFile() file.closeFile() if let result = String(data: data, encoding: NSUTF8StringEncoding) { // let range = // var lenght = result.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) - 1 let sub = result.substringToIndex(result.endIndex.advancedBy(-1)) print("result = \(sub)") print("=========\n\n") return sub } else { return "." } } func exePython(command: [String]) -> String { var log = "" log += "=========\nexec = \(command.joinWithSeparator(" "))" + "\n" //let pid = NSProcessInfo.processInfo().processIdentifier let pipe = NSPipe() let file = pipe.fileHandleForReading let errorpipe = NSPipe() let errorfile = errorpipe.fileHandleForReading let task = NSTask() task.launchPath = "/usr/bin/python" task.arguments = command task.standardOutput = pipe task.standardError = errorpipe task.launch() let data = file.readDataToEndOfFile() file.closeFile() let errordata = errorfile.readDataToEndOfFile() errorfile.closeFile() log += "finished [\(command.joinWithSeparator(" "))]" + "\n" if let result = String(data: data, encoding: NSUTF8StringEncoding) { log += "result = \(result)" + "\n" log += "=========\n\n" + "\n" } if let errorResult = String(data: errordata, encoding: NSUTF8StringEncoding) { log += "errorResult = \(errorResult)" + "\n" log += "=========\n\n" + "\n" } log = log.stringByReplacingOccurrencesOfString(self.github_password, withString: "##########") return log } func _runCommand(launchPath: String, arguments: [String]) -> (errordata: NSData, data: NSData) { let pipe = NSPipe() let file = pipe.fileHandleForReading let errorpipe = NSPipe() let errorfile = errorpipe.fileHandleForReading let task = NSTask() task.launchPath = launchPath task.arguments = arguments task.standardOutput = pipe task.standardError = errorpipe task.launch() let data = file.readDataToEndOfFile() file.closeFile() let errordata = errorfile.readDataToEndOfFile() errorfile.closeFile() return (data, errordata) } func _checkAndInstall(finishedBlock: (Void) -> Void) { let (_, errordata) = self._runCommand("/usr/bin/hash", arguments: ["hub"]) if let errorResult = String(data: errordata, encoding: NSUTF8StringEncoding) { if errorResult != "" { let alert = NSAlert() alert.addButtonWithTitle("install") alert.addButtonWithTitle("cancel") alert.messageText = "please install \"hub\" first\nhttps://github.com/github/hub" alert.alertStyle = .WarningAlertStyle if (alert.runModal() == NSAlertFirstButtonReturn) { let (_, installErrorResult) = self._runCommand("/usr/bin/osascript", arguments: ["-e", "do shell script \"gem install hub\" with administrator privileges"]) if let errorResult = String(data: installErrorResult, encoding: NSUTF8StringEncoding) { if errorResult == "" { let alert = NSAlert() alert.addButtonWithTitle("OK") alert.messageText = "install hub success" alert.alertStyle = .WarningAlertStyle if (alert.runModal() == NSAlertFirstButtonReturn) { finishedBlock() } } else { let alert = NSAlert() alert.addButtonWithTitle("OK") alert.messageText = "install hub success failed" alert.alertStyle = .WarningAlertStyle alert.runModal() } } else { let alert = NSAlert() alert.addButtonWithTitle("OK") alert.messageText = "install hub success failed[" + errorResult + "]" alert.alertStyle = .WarningAlertStyle alert.runModal() } } } else { finishedBlock() } } else { finishedBlock() } } func _valueCheck(control: NSControl, message: String, condition: ((Void) -> Bool)) -> Bool { if condition() { let alert = NSAlert() alert.addButtonWithTitle("OK") alert.messageText = message alert.alertStyle = .WarningAlertStyle if (alert.runModal() == NSAlertFirstButtonReturn) { control.becomeFirstResponder() } return false } return true } @IBAction func clickAutoPullRequestButton(sender: AnyObject) { let pannel = NSOpenPanel() pannel.canChooseFiles = true pannel.canChooseDirectories = false pannel.canCreateDirectories = false pannel.allowsMultipleSelection = false pannel.allowedFileTypes = ["py"] let clicked = pannel.runModal() if clicked == NSFileHandlingPanelOKButton { if let url = pannel.URLs.first { var filePath = url.absoluteString filePath = filePath.stringByReplacingOccurrencesOfString("file://", withString: "") self.python_script = filePath } } } @IBAction func clickResetButton(sender: AnyObject) { let alert = NSAlert() alert.addButtonWithTitle("Reset") alert.addButtonWithTitle("Cancel") alert.messageText = "Reset Value to Default?" alert.alertStyle = .WarningAlertStyle if (alert.runModal() == NSAlertFirstButtonReturn) { self.resetValue() self.saveValues() } } @IBAction func clickBrowse(sender: AnyObject) { let pannel = NSOpenPanel() pannel.canChooseFiles = false pannel.canChooseDirectories = true pannel.canCreateDirectories = true pannel.allowsMultipleSelection = false let clicked = pannel.runModal() if clicked == NSFileHandlingPanelOKButton { if let url = pannel.URLs.first { var filePath = url.absoluteString filePath = filePath.stringByReplacingOccurrencesOfString("file://", withString: "") self.sourceDirTextField.stringValue = filePath self.source_dir = self.sourceDirTextField.stringValue } } } @IBAction func clickApply(sender: AnyObject) { self._checkAndInstall { () -> Void in self._clickApply(sender) } } func _clickApply(sender: AnyObject) { if !self._valueCheck(self.githubAccountTextField, message: "account is Empty", condition: { return self.github_user.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0 }) { return } if !self._valueCheck(self.githubPasswordTextField, message: "password is Empty", condition: { return self.github_password.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0 }) { return } if !self._valueCheck(self.sourceBrowseButton, message: "Select One Source Directory", condition: { return self.source_dir.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0 }) { return } if !self._valueCheck(self.commitMessageTextField, message: "Commit Message Can't be empty!!", condition: { return self.commit_message.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0 }) { return } self.processingAnimationIndicator.startAnimation(nil) self.applyButton.enabled = false self.scriptButton.enabled = false self.githubAccountTextField.enabled = false self.githubPasswordTextField.enabled = false self.githubRepoBranchTextField.enabled = false self.githubRepoTextField.enabled = false self.sourceBrowseButton.enabled = false self.commitMessageTextField.enabled = false self.resetButton.enabled = false self.saveValues() dispatch_async(dispatch_get_main_queue()) { () -> Void in var log = "" if let textView = self.logMessageTestScroll.contentView.documentView as? NSTextView { textView.string = log } log += self.exePython([self.python_script, "-c", self.workspace_dir, "--repo", self.repo_path, "--branch", self.repo_branch, "-a", self.github_user, "-x", self.github_password]) + "\n" log += self.exePython([self.python_script, "-w", self.workspace_dir, "-u", self.source_dir, "-p", self.commit_message, "--repo", self.repo_path, "--branch", self.repo_branch, "-a", self.github_user, "-x", self.github_password]) + "\n" if let textView = self.logMessageTestScroll.contentView.documentView as? NSTextView { textView.string = log } print(log) let alert = NSAlert() alert.addButtonWithTitle("OK") alert.messageText = "Task Finished" alert.alertStyle = .InformationalAlertStyle alert.runModal() self.commitMessageTextField.stringValue = "" self.commit_message = "" self.saveValues() self.processingAnimationIndicator.stopAnimation(nil) self.applyButton.enabled = true self.scriptButton.enabled = true self.githubAccountTextField.enabled = true self.githubPasswordTextField.enabled = true self.githubRepoBranchTextField.enabled = true self.githubRepoTextField.enabled = true self.sourceDirTextField.enabled = true self.sourceBrowseButton.enabled = true self.commitMessageTextField.enabled = true self.resetButton.enabled = true } } func saveValues() { NSUserDefaults.standardUserDefaults().setObject(self.github_user, forKey: "github_user") // NSUserDefaults.standardUserDefaults().setObject(self.github_password, forKey: "") NSUserDefaults.standardUserDefaults().setObject(self.repo_path, forKey: "repo_path") NSUserDefaults.standardUserDefaults().setObject(self.repo_branch, forKey: "repo_branch") NSUserDefaults.standardUserDefaults().setObject(self.source_dir, forKey: "source_dir") NSUserDefaults.standardUserDefaults().setObject(self.workspace_dir, forKey: "workspace_dir") NSUserDefaults.standardUserDefaults().setObject(self.commit_message, forKey: "commit_message") NSUserDefaults.standardUserDefaults().setObject(self.python_script, forKey: "python_script") NSUserDefaults.standardUserDefaults().synchronize() SSKeychain.setPassword(self.github_password, forService: "AutoPullRequest", account: self.github_user) } func loadValues() { self.resetValue() if let value = NSUserDefaults.standardUserDefaults().objectForKey("github_user") { self.github_user = value as! String } if let value = NSUserDefaults.standardUserDefaults().objectForKey("repo_path") { self.repo_path = value as! String } if let value = NSUserDefaults.standardUserDefaults().objectForKey("repo_branch") { self.repo_branch = value as! String } if let value = NSUserDefaults.standardUserDefaults().objectForKey("source_dir") { self.source_dir = value as! String } if let value = NSUserDefaults.standardUserDefaults().objectForKey("workspace_dir") { self.workspace_dir = value as! String } if let value = NSUserDefaults.standardUserDefaults().objectForKey("commit_message") { self.commit_message = value as! String } if let value = NSUserDefaults.standardUserDefaults().objectForKey("python_script") { self.python_script = value as! String } else { self.python_script = self.getNowDir() + "/" + "AutoPullRequest.py" } let password = SSKeychain.passwordForService("AutoPullRequest", account: self.github_user) if password != nil { self.github_password = password self.githubPasswordTextField.stringValue = self.github_password } self.representedObject = nil } }
mit
d98ed0f2e34f5049f4667a98e9100752
37.865217
246
0.586363
5.286221
false
false
false
false
devmynd/harbor
Harbor/TextField.swift
1
1016
import AppKit class TextField: NSTextField { fileprivate let commandKey = NSEventModifierFlags.command.rawValue override func performKeyEquivalent(with theEvent: NSEvent) -> Bool { if let key = self.unmodifiedKeyForEvent(theEvent) { if let action = self.actionForKey(key) { if NSApp.sendAction(action, to:nil, from:self) { return true } } } return super.performKeyEquivalent(with: theEvent) } func unmodifiedKeyForEvent(_ event: NSEvent) -> String? { if event.type == .keyDown { if (event.modifierFlags.rawValue & NSEventModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey { return event.charactersIgnoringModifiers } } return nil } func actionForKey(_ key: String) -> Selector? { switch(key) { case "x": return #selector(NSText.cut(_:)) case "c": return #selector(NSText.copy(_:)) case "v": return #selector(NSText.paste(_:)) default: return nil } } }
mit
9bf0fe7e5fe0315cb23e31d39d5c7cd9
24.4
114
0.645669
4.34188
false
false
false
false
QuaereVeritatem/FoodTracker
FoodTracker/FoodTracker/Meal.swift
1
2696
// // Meal.swift // FoodTracker // // Created by Robert Martin on 9/15/16. // Copyright © 2016 Robert Martin. All rights reserved. // import UIKit //This is class is equivalent to MealData on the other foodtracker [Done..delete this comment] class Meal: NSObject, NSCoding { // MARK: Common Properties Shared by Archiver and Backendless var name: String var rating: Int // MARK: Archiver Only Properties var photo: UIImage? // MARK: Backendless Only Properties var objectId: String? var photoUrl: String? var thumbnailUrl: String? var replacePhoto: Bool = false // MARK: Archiving Paths //a persistent path on the file system where data will be saved and loaded.. //access the path using the syntax Meal.ArchiveURL.path!(when accessed outside the class) static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! static let ArchiveURL = DocumentsDirectory.appendingPathComponent("meals") //constants marked with static keyword apply to the class instead of an instance of the class. // MARK: Types struct PropertyKey { static let nameKey = "name" static let photoKey = "photo" static let ratingKey = "rating" } // MARK: Initialization init?(name: String, photo: UIImage?, rating: Int) { // Initialize stored properties. self.name = name self.photo = photo self.rating = rating super.init() // Initialization should fail if there is no name or if the rating is negative. if name.isEmpty || rating < 0 { return nil } } // MARK: NSCoding //The encodeWithCoder(_:) method prepares the class’s information to be archived, and the initializer unarchives the data when the class is created. func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: PropertyKey.nameKey) aCoder.encode(photo, forKey: PropertyKey.photoKey) aCoder.encode(rating, forKey: PropertyKey.ratingKey) } required convenience init?(coder aDecoder: NSCoder) { let name = aDecoder.decodeObject(forKey: PropertyKey.nameKey) as! String // Because photo is an optional property of Meal, use conditional cast. let photo = aDecoder.decodeObject(forKey: PropertyKey.photoKey) as? UIImage let rating = aDecoder.decodeInteger(forKey: PropertyKey.ratingKey) // Must call designated initializer. self.init(name: name, photo: photo, rating: rating) } }
mit
5bc0b94d8845a56e07d272b69b8d6b1d
30.682353
152
0.645006
4.878623
false
false
false
false
wscqs/QSWB
DSWeibo/DSWeibo/Classes/Home/StatusPictureView.swift
1
5161
// // StatusPictureView.swift // DSWeibo // // Created by xiaomage on 15/9/13. // Copyright © 2015年 小码哥. All rights reserved. // import UIKit import SDWebImage class StatusPictureView: UICollectionView { var status: Status? { didSet{ // 1. 刷新表格 reloadData() } } private var pictureLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() init() { super.init(frame: CGRectZero, collectionViewLayout: pictureLayout) // 1.注册cell registerClass(PictureViewCell.self, forCellWithReuseIdentifier: XMGPictureViewCellReuseIdentifier) // 2.设置数据源 dataSource = self delegate = self // 2.设置cell之间的间隙 pictureLayout.minimumInteritemSpacing = 10 pictureLayout.minimumLineSpacing = 10 // 3.设置配图的背景颜色 backgroundColor = UIColor.darkGrayColor() } /** 计算配图的尺寸 */ func calculateImageSize() -> CGSize { // 1.取出配图个数 let count = status?.storedPicURLS?.count // 2.如果没有配图zero if count == 0 || count == nil { return CGSizeZero } // 3.如果只有一张配图, 返回图片的实际大小 if count == 1 { // 3.1取出缓存的图片 let key = status?.storedPicURLS!.first?.absoluteString let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key!) pictureLayout.itemSize = image.size // 3.2返回缓存图片的尺寸 return image.size } // 4.如果有4张配图, 计算田字格的大小 let width = 90 let margin = 10 pictureLayout.itemSize = CGSize(width: width, height: width) if count == 4 { let viewWidth = width * 2 + margin return CGSize(width: viewWidth, height: viewWidth) } // 5.如果是其它(多张), 计算九宫格的大小 // 5.1计算列数 let colNumber = 3 // 5.2计算行数 let rowNumber = (count! - 1) / 3 + 1 // 宽度 = 列数 * 图片的宽度 + (列数 - 1) * 间隙 let viewWidth = colNumber * width + (colNumber - 1) * margin // 高度 = 行数 * 图片的高度 + (行数 - 1) * 间隙 let viewHeight = rowNumber * width + (rowNumber - 1) * margin return CGSize(width: viewWidth, height: viewHeight) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private class PictureViewCell: UICollectionViewCell { // 定义属性接收外界传入的数据 var imageURL: NSURL? { didSet{ iconImageView.sd_setImageWithURL(imageURL!) } } override init(frame: CGRect) { super.init(frame: frame) // 初始化UI setupUI() } private func setupUI() { // 1.添加子控件 contentView.addSubview(iconImageView) // 2.布局子控件 iconImageView.xmg_Fill(contentView) } // MARK: - 懒加载 private lazy var iconImageView:UIImageView = UIImageView() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } } /// 选中图片的通知名称 let XMGStatusPictureViewSelected = "XMGStatusPictureViewSelected" /// 当前选中图片的索引对应的key let XMGStatusPictureViewIndexKey = "XMGStatusPictureViewIndexKey" /// 需要展示的所有图片对应的key let XMGStatusPictureViewURLsKey = "XMGStatusPictureViewURLsKey" extension StatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return status?.storedPicURLS?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // 1.取出cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XMGPictureViewCellReuseIdentifier, forIndexPath: indexPath) as! PictureViewCell // 2.设置数据 cell.imageURL = status?.storedPicURLS![indexPath.item] // 3.返回cell return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { // print(indexPath.item) // print(status?.storedLargePicURLS![indexPath.item]) let info = [XMGStatusPictureViewIndexKey : indexPath, XMGStatusPictureViewURLsKey : status!.storedLargePicURLS!] NSNotificationCenter.defaultCenter().postNotificationName(XMGStatusPictureViewSelected, object: self, userInfo: info) } }
mit
f806de00faaf4bba88d3addef1e82bfe
28.735849
152
0.596235
4.992608
false
false
false
false
daxiangfei/RTSwiftUtils
RTSwiftUtils/Extension/NSAttributedStringExtension.swift
1
3309
// // NSAttributedStringExtension.swift // RongTeng // // Created by rongteng on 16/5/17. // Copyright © 2016年 Mike. All rights reserved. // import Foundation import UIKit extension NSAttributedString { ///二部分 色值和字体都不同 public class func attributedOfTwoPart(onePartTitle:String,onePartForegroundColor:UIColor,onePartFontSize:CGFloat,twoPartTitle:String,twoPartForegroundColor:UIColor,twoPartFontSize:CGFloat) -> NSAttributedString { let resultAtt = NSMutableAttributedString() let oneAttDic = [NSAttributedStringKey.foregroundColor:onePartForegroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: onePartFontSize)] let oneAtt = NSAttributedString(string: onePartTitle, attributes: oneAttDic) resultAtt.append(oneAtt) let twoAttDic = [NSAttributedStringKey.foregroundColor:twoPartForegroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: twoPartFontSize)] let twoAtt = NSAttributedString(string: twoPartTitle, attributes: twoAttDic) resultAtt.append(twoAtt) return resultAtt } ///二部分 色值相同 字体不同 public class func attributedOfTwoPartWithSameColor(foregroundColor:UIColor,onePartTitle:String,onePartFontSize:CGFloat,twoPartTitle:String,twoPartFontSize:CGFloat) -> NSAttributedString { let resultAtt = NSMutableAttributedString() let oneAttDic = [NSAttributedStringKey.foregroundColor:foregroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: onePartFontSize)] let oneAtt = NSAttributedString(string: onePartTitle, attributes: oneAttDic) resultAtt.append(oneAtt) let twoAttDic = [NSAttributedStringKey.foregroundColor:foregroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: twoPartFontSize)] let twoAtt = NSAttributedString(string: twoPartTitle, attributes: twoAttDic) resultAtt.append(twoAtt) return resultAtt } ///创建一个 有下划线的文字 public class func attributedOfUnderLine(title:String,titleColor:UIColor) -> NSAttributedString { let oneAttDic = [NSAttributedStringKey.underlineStyle:NSUnderlineStyle.styleSingle.rawValue, NSAttributedStringKey.underlineColor:titleColor, NSAttributedStringKey.foregroundColor:titleColor] as [NSAttributedStringKey : Any] let oneAtt = NSAttributedString(string: title, attributes: oneAttDic) return oneAtt } ///下划线和正常类型 public class func attributedForUnderLineAndNormal(oneTitle:String,oneTitleColor:UIColor,twoTitle:String,twoTitleColor:UIColor) -> NSAttributedString { let resultAtt = NSMutableAttributedString() let oneAttDic = [NSAttributedStringKey.underlineStyle:NSUnderlineStyle.styleSingle.rawValue, NSAttributedStringKey.underlineColor:oneTitleColor, NSAttributedStringKey.foregroundColor:oneTitleColor] as [NSAttributedStringKey : Any] let oneAtt = NSAttributedString(string: oneTitle, attributes: oneAttDic) resultAtt.append(oneAtt) let twoAttDic = [NSAttributedStringKey.foregroundColor:twoTitleColor] let twoAtt = NSAttributedString(string: twoTitle, attributes: twoAttDic) resultAtt.append(twoAtt) return resultAtt } }
mit
6165063dd0d47c71158b22e0541dec9e
33.297872
214
0.766439
4.797619
false
false
false
false
sschiau/swift
test/Syntax/round_trip_misc.swift
1
942
// RUN: %round-trip-syntax-test --swift-syntax-test %swift-syntax-test --file %s class C { // Erroneous typealias decl. typealias Inner: Foo = Int typealias Alias1 = [Generic<Int // Implict accessor with attribute at the top of its body. var x: Int { @objc func f() {} } } do { typealias Alias2 = () -> (a b: [Generic<Int } do { typealias Alias3 = (a b C, } do { typealias Alias3 = () -> @objc func } do { typealias } do { typealias Alias = A & B & C.D<> } do { typealias boo bar = Int } // Orphan '}' at top level } // Orphan #elseif, #else, #endif at top level. #elseif foobar #else #endif // Compound name. foo(x:y:)() // Type identifier with erroneous component. let a: Int.) // Type with unknown attribute followed by parentheses. typealias b = @foobar() -> Void typealias c = @foobar(a) () -> Void // keypath expressions. let d = \.foo let e = \.[1] let f = \.?.bar let optionalArray: [Int]?
apache-2.0
df055b7af8e6dad1dd80a33092e89cb3
15.241379
80
0.622081
3.03871
false
true
false
false
ReactKit/SwiftState
Tests/SwiftStateTests/StateMachineTests.swift
1
24262
// // StateMachineTests.swift // SwiftState // // Created by Yasuhiro Inami on 2014/08/03. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import SwiftState import XCTest class StateMachineTests: _TestCase { func testInit() { let machine = StateMachine<MyState, NoEvent>(state: .state0) XCTAssertEqual(machine.state, MyState.state0) } //-------------------------------------------------- // MARK: - tryState a.k.a `<-` //-------------------------------------------------- // machine <- state func testTryState() { let machine = StateMachine<MyState, NoEvent>(state: .state0) // tryState 0 => 1, without registering any transitions machine <- .state1 XCTAssertEqual(machine.state, MyState.state0, "0 => 1 should fail because transition is not added yet.") // add 0 => 1 machine.addRoute(.state0 => .state1) // tryState 0 => 1 machine <- .state1 XCTAssertEqual(machine.state, MyState.state1) } func testTryState_string() { let machine = StateMachine<String, NoEvent>(state: "0") // tryState 0 => 1, without registering any transitions machine <- "1" XCTAssertEqual(machine.state, "0", "0 => 1 should fail because transition is not added yet.") // add 0 => 1 machine.addRoute("0" => "1") // tryState 0 => 1 machine <- "1" XCTAssertEqual(machine.state, "1") } //-------------------------------------------------- // MARK: - addRoute //-------------------------------------------------- // add state1 => state2 func testAddRoute() { let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in machine.addRoute(.state0 => .state1) } XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertTrue(machine.hasRoute(.state0 => .state1)) // true XCTAssertFalse(machine.hasRoute(.state0 => .state2)) XCTAssertFalse(machine.hasRoute(.state1 => .state0)) XCTAssertFalse(machine.hasRoute(.state1 => .state1)) XCTAssertFalse(machine.hasRoute(.state1 => .state2)) } // add .any => state func testAddRoute_fromAnyState() { let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in machine.addRoute(.any => .state1) // Any => State1 } XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertTrue(machine.hasRoute(.state0 => .state1)) // true XCTAssertFalse(machine.hasRoute(.state0 => .state2)) XCTAssertFalse(machine.hasRoute(.state1 => .state0)) XCTAssertTrue(machine.hasRoute(.state1 => .state1)) // true XCTAssertFalse(machine.hasRoute(.state1 => .state2)) } // add state => .any func testAddRoute_toAnyState() { let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in machine.addRoute(.state1 => .any) // State1 => Any } XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertFalse(machine.hasRoute(.state0 => .state1)) XCTAssertFalse(machine.hasRoute(.state0 => .state2)) XCTAssertTrue(machine.hasRoute(.state1 => .state0)) // true XCTAssertTrue(machine.hasRoute(.state1 => .state1)) // true XCTAssertTrue(machine.hasRoute(.state1 => .state2)) // true } // add .any => .any func testAddRoute_bothAnyState() { let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in machine.addRoute(.any => .any) // Any => Any } XCTAssertTrue(machine.hasRoute(.state0 => .state0)) // true XCTAssertTrue(machine.hasRoute(.state0 => .state1)) // true XCTAssertTrue(machine.hasRoute(.state0 => .state2)) // true XCTAssertTrue(machine.hasRoute(.state1 => .state0)) // true XCTAssertTrue(machine.hasRoute(.state1 => .state1)) // true XCTAssertTrue(machine.hasRoute(.state1 => .state2)) // true } // add state0 => state0 func testAddRoute_sameState() { let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in machine.addRoute(.state0 => .state0) } XCTAssertTrue(machine.hasRoute(.state0 => .state0)) } // add route + condition func testAddRoute_condition() { var flag = false let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 machine.addRoute(.state0 => .state1, condition: { _ in flag }) } XCTAssertFalse(machine.hasRoute(.state0 => .state1)) flag = true XCTAssertTrue(machine.hasRoute(.state0 => .state1)) } // add route + condition + blacklist func testAddRoute_condition_blacklist() { let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => Any, except 0 => 2 machine.addRoute(.state0 => .any, condition: { context in return context.toState != .state2 }) } XCTAssertTrue(machine.hasRoute(.state0 => .state0)) XCTAssertTrue(machine.hasRoute(.state0 => .state1)) XCTAssertFalse(machine.hasRoute(.state0 => .state2)) XCTAssertTrue(machine.hasRoute(.state0 => .state3)) } // add route + handler func testAddRoute_handler() { var invokedCount = 0 let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in machine.addRoute(.state0 => .state1) { context in XCTAssertEqual(context.fromState, MyState.state0) XCTAssertEqual(context.toState, MyState.state1) invokedCount += 1 } } XCTAssertEqual(invokedCount, 0, "Transition has not started yet.") // tryState 0 => 1 machine <- .state1 XCTAssertEqual(invokedCount, 1) } // add route + conditional handler func testAddRoute_conditionalHandler() { var invokedCount = 0 var flag = false let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 without condition to guarantee 0 => 1 transition machine.addRoute(.state0 => .state1) // add 0 => 1 with condition + conditionalHandler machine.addRoute(.state0 => .state1, condition: { _ in flag }) { context in XCTAssertEqual(context.fromState, MyState.state0) XCTAssertEqual(context.toState, MyState.state1) invokedCount += 1 } // add 1 => 0 for resetting state machine.addRoute(.state1 => .state0) } // tryState 0 => 1 machine <- .state1 XCTAssertEqual(machine.state, MyState.state1) XCTAssertEqual(invokedCount, 0, "Conditional handler should NOT be performed because flag=false.") // tryState 1 => 0 (resetting to 0) machine <- .state0 XCTAssertEqual(machine.state, MyState.state0) flag = true // tryState 0 => 1 machine <- .state1 XCTAssertEqual(machine.state, MyState.state1) XCTAssertEqual(invokedCount, 1) } // MARK: addRoute using array func testAddRoute_array_left() { let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 2 or 1 => 2 machine.addRoute([.state0, .state1] => .state2) } XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertFalse(machine.hasRoute(.state0 => .state1)) XCTAssertTrue(machine.hasRoute(.state0 => .state2)) XCTAssertFalse(machine.hasRoute(.state1 => .state0)) XCTAssertFalse(machine.hasRoute(.state1 => .state1)) XCTAssertTrue(machine.hasRoute(.state1 => .state2)) } func testAddRoute_array_right() { let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 or 0 => 2 machine.addRoute(.state0 => [.state1, .state2]) } XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertTrue(machine.hasRoute(.state0 => .state1)) XCTAssertTrue(machine.hasRoute(.state0 => .state2)) XCTAssertFalse(machine.hasRoute(.state1 => .state0)) XCTAssertFalse(machine.hasRoute(.state1 => .state1)) XCTAssertFalse(machine.hasRoute(.state1 => .state2)) } func testAddRoute_array_both() { let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 2 or 0 => 3 or 1 => 2 or 1 => 3 machine.addRoute([MyState.state0, MyState.state1] => [MyState.state2, MyState.state3]) } XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertFalse(machine.hasRoute(.state0 => .state1)) XCTAssertTrue(machine.hasRoute(.state0 => .state2)) XCTAssertTrue(machine.hasRoute(.state0 => .state3)) XCTAssertFalse(machine.hasRoute(.state1 => .state0)) XCTAssertFalse(machine.hasRoute(.state1 => .state1)) XCTAssertTrue(machine.hasRoute(.state1 => .state2)) XCTAssertTrue(machine.hasRoute(.state1 => .state3)) XCTAssertFalse(machine.hasRoute(.state2 => .state0)) XCTAssertFalse(machine.hasRoute(.state2 => .state1)) XCTAssertFalse(machine.hasRoute(.state2 => .state2)) XCTAssertFalse(machine.hasRoute(.state2 => .state3)) XCTAssertFalse(machine.hasRoute(.state3 => .state0)) XCTAssertFalse(machine.hasRoute(.state3 => .state1)) XCTAssertFalse(machine.hasRoute(.state3 => .state2)) XCTAssertFalse(machine.hasRoute(.state3 => .state3)) } //-------------------------------------------------- // MARK: - removeRoute //-------------------------------------------------- func testRemoveRoute() { let machine = StateMachine<MyState, NoEvent>(state: .state0) let routeDisposable = machine.addRoute(.state0 => .state1) XCTAssertTrue(machine.hasRoute(.state0 => .state1)) // remove route routeDisposable.dispose() XCTAssertFalse(machine.hasRoute(.state0 => .state1)) } func testRemoveRoute_handler() { let machine = StateMachine<MyState, NoEvent>(state: .state0) let routeDisposable = machine.addRoute(.state0 => .state1, handler: { _ in }) XCTAssertTrue(machine.hasRoute(.state0 => .state1)) // remove route routeDisposable.dispose() XCTAssertFalse(machine.hasRoute(.state0 => .state1)) } //-------------------------------------------------- // MARK: - addHandler //-------------------------------------------------- func testAddHandler() { var invokedCount = 0 let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 machine.addRoute(.state0 => .state1) machine.addHandler(.state0 => .state1) { context in XCTAssertEqual(context.fromState, MyState.state0) XCTAssertEqual(context.toState, MyState.state1) invokedCount += 1 } } // not tried yet XCTAssertEqual(invokedCount, 0, "Transition has not started yet.") // tryState 0 => 1 machine <- .state1 XCTAssertEqual(invokedCount, 1) } func testAddHandler_order() { var invokedCount = 0 let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 machine.addRoute(.state0 => .state1) // order = 100 (default) machine.addHandler(.state0 => .state1) { context in XCTAssertEqual(invokedCount, 1) XCTAssertEqual(context.fromState, MyState.state0) XCTAssertEqual(context.toState, MyState.state1) invokedCount += 1 } // order = 99 machine.addHandler(.state0 => .state1, order: 99) { context in XCTAssertEqual(invokedCount, 0) XCTAssertEqual(context.fromState, MyState.state0) XCTAssertEqual(context.toState, MyState.state1) invokedCount += 1 } } XCTAssertEqual(invokedCount, 0) // tryState 0 => 1 machine <- .state1 XCTAssertEqual(invokedCount, 2) } func testAddHandler_multiple() { var passed1 = false var passed2 = false let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 machine.addRoute(.state0 => .state1) machine.addHandler(.state0 => .state1) { context in passed1 = true } // add 0 => 1 once more machine.addRoute(.state0 => .state1) machine.addHandler(.state0 => .state1) { context in passed2 = true } } // tryState 0 => 1 machine <- .state1 XCTAssertTrue(passed1) XCTAssertTrue(passed2) } func testAddHandler_overload() { var passed = false let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in machine.addRoute(.state0 => .state1) machine.addHandler(.state0 => .state1) { context in // empty } machine.addHandler(.state0 => .state1) { context in passed = true } } XCTAssertFalse(passed) machine <- .state1 XCTAssertTrue(passed) } //-------------------------------------------------- // MARK: - removeHandler //-------------------------------------------------- func testRemoveHandler() { var passed = false let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 machine.addRoute(.state0 => .state1) let handlerDisposable = machine.addHandler(.state0 => .state1) { context in XCTFail("Should never reach here") } // add 0 => 1 once more machine.addRoute(.state0 => .state1) machine.addHandler(.state0 => .state1) { context in passed = true } // remove handler handlerDisposable.dispose() } XCTAssertFalse(passed) // tryState 0 => 1 machine <- .state1 XCTAssertTrue(passed) } func testRemoveHandler_unregistered() { let machine = StateMachine<MyState, NoEvent>(state: .state0) // add 0 => 1 machine.addRoute(.state0 => .state1) let handlerDisposable = machine.addHandler(.state0 => .state1) { context in // empty } XCTAssertFalse(handlerDisposable.disposed) // remove handler handlerDisposable.dispose() // remove already unregistered handler XCTAssertTrue(handlerDisposable.disposed, "removeHandler should fail because handler is already removed.") } func testRemoveErrorHandler() { var passed = false let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 2 => 1 machine.addRoute(.state2 => .state1) let handlerDisposable = machine.addErrorHandler { context in XCTFail("Should never reach here") } // add 2 => 1 once more machine.addRoute(.state2 => .state1) machine.addErrorHandler { context in passed = true } // remove handler handlerDisposable.dispose() } // tryState 0 => 1 machine <- .state1 XCTAssertTrue(passed) } func testRemoveErrorHandler_unregistered() { let machine = StateMachine<MyState, NoEvent>(state: .state0) // add 0 => 1 machine.addRoute(.state0 => .state1) let handlerDisposable = machine.addErrorHandler { context in // empty } XCTAssertFalse(handlerDisposable.disposed) // remove handler handlerDisposable.dispose() // remove already unregistered handler XCTAssertTrue(handlerDisposable.disposed, "removeHandler should fail because handler is already removed.") } //-------------------------------------------------- // MARK: - addRouteChain //-------------------------------------------------- func testAddRouteChain() { var success = false let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 => 2 => 3 machine.addRouteChain(.state0 => .state1 => .state2 => .state3) { context in success = true } } // initial XCTAssertEqual(machine.state, MyState.state0) // 0 => 1 machine <- .state1 XCTAssertEqual(machine.state, MyState.state1) XCTAssertFalse(success, "RouteChain is not completed yet.") // 1 => 2 machine <- .state2 XCTAssertEqual(machine.state, MyState.state2) XCTAssertFalse(success, "RouteChain is not completed yet.") // 2 => 3 machine <- .state3 XCTAssertEqual(machine.state, MyState.state3) XCTAssertTrue(success) } func testAddChainHandler() { var success = false let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add all routes machine.addRoute(.any => .any) // add 0 => 1 => 2 => 3 machine.addChainHandler(.state0 => .state1 => .state2 => .state3) { context in success = true } } // initial XCTAssertEqual(machine.state, MyState.state0) // 0 => 1 machine <- .state1 XCTAssertEqual(machine.state, MyState.state1) XCTAssertFalse(success, "RouteChain is not completed yet.") // 1 => 2 machine <- .state2 XCTAssertEqual(machine.state, MyState.state2) XCTAssertFalse(success, "RouteChain is not completed yet.") // 2 => 2 (fails & resets chaining count) machine <- .state2 XCTAssertEqual(machine.state, MyState.state2, "State should not change.") XCTAssertFalse(success, "RouteChain failed and reset count.") // 2 => 3 (chaining is failed) machine <- .state3 XCTAssertEqual(machine.state, MyState.state3) XCTAssertFalse(success, "RouteChain is already failed.") // go back to 0 & run 0 => 1 => 2 => 3 machine <- .state0 <- .state1 <- .state2 <- .state3 XCTAssertEqual(machine.state, MyState.state3) XCTAssertTrue(success, "RouteChain is resetted & should succeed its chaining.") } //-------------------------------------------------- // MARK: - Event/StateRouteMapping //-------------------------------------------------- func testAddStateRouteMapping() { var routeMappingDisposable: Disposable? let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 & 0 => 2 routeMappingDisposable = machine.addStateRouteMapping { fromState, userInfo -> [MyState]? in if fromState == .state0 { return [.state1, .state2] } else { return nil } } } XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertTrue(machine.hasRoute(.state0 => .state1)) XCTAssertTrue(machine.hasRoute(.state0 => .state2)) XCTAssertFalse(machine.hasRoute(.state1 => .state0)) XCTAssertFalse(machine.hasRoute(.state1 => .state1)) XCTAssertFalse(machine.hasRoute(.state1 => .state2)) XCTAssertFalse(machine.hasRoute(.state2 => .state0)) XCTAssertFalse(machine.hasRoute(.state2 => .state1)) XCTAssertFalse(machine.hasRoute(.state2 => .state2)) // remove routeMapping routeMappingDisposable?.dispose() XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertFalse(machine.hasRoute(.state0 => .state1)) XCTAssertFalse(machine.hasRoute(.state0 => .state2)) XCTAssertFalse(machine.hasRoute(.state1 => .state0)) XCTAssertFalse(machine.hasRoute(.state1 => .state1)) XCTAssertFalse(machine.hasRoute(.state1 => .state2)) XCTAssertFalse(machine.hasRoute(.state2 => .state0)) XCTAssertFalse(machine.hasRoute(.state2 => .state1)) XCTAssertFalse(machine.hasRoute(.state2 => .state2)) } func testAddStateRouteMapping_handler() { var invokedCount = 0 var routeMappingDisposable: Disposable? let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 & 0 => 2 routeMappingDisposable = machine.addStateRouteMapping({ fromState, userInfo -> [MyState]? in if fromState == .state0 { return [.state1, .state2] } else { return nil } }, handler: { context in invokedCount += 1 }) } // initial XCTAssertEqual(machine.state, MyState.state0) XCTAssertEqual(invokedCount, 0) // 0 => 1 machine <- .state1 XCTAssertEqual(machine.state, MyState.state1) XCTAssertEqual(invokedCount, 1) // remove routeMapping routeMappingDisposable?.dispose() // 1 => 2 (fails) machine <- .state1 XCTAssertEqual(machine.state, MyState.state1) XCTAssertEqual(invokedCount, 1) } /// Test `Event/StateRouteMapping`s. func testAddBothRouteMappings() { var routeMappingDisposable: Disposable? let machine = StateMachine<MyState, NoEvent>(state: .state0) { machine in // add 0 => 1 & 0 => 2 routeMappingDisposable = machine.addStateRouteMapping { fromState, userInfo -> [MyState]? in if fromState == .state0 { return [.state1, .state2] } else { return nil } } // add 1 => 0 (can also use `RouteMapping` closure for single-`toState`) machine.addRouteMapping { event, fromState, userInfo -> MyState? in guard event == nil else { return nil } if fromState == .state1 { return .state0 } else { return nil } } } XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertTrue(machine.hasRoute(.state0 => .state1)) XCTAssertTrue(machine.hasRoute(.state0 => .state2)) XCTAssertTrue(machine.hasRoute(.state1 => .state0)) XCTAssertFalse(machine.hasRoute(.state1 => .state1)) XCTAssertFalse(machine.hasRoute(.state1 => .state2)) XCTAssertFalse(machine.hasRoute(.state2 => .state0)) XCTAssertFalse(machine.hasRoute(.state2 => .state1)) XCTAssertFalse(machine.hasRoute(.state2 => .state2)) // remove routeMapping routeMappingDisposable?.dispose() XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertFalse(machine.hasRoute(.state0 => .state1)) XCTAssertFalse(machine.hasRoute(.state0 => .state2)) XCTAssertTrue(machine.hasRoute(.state1 => .state0)) XCTAssertFalse(machine.hasRoute(.state1 => .state1)) XCTAssertFalse(machine.hasRoute(.state1 => .state2)) XCTAssertFalse(machine.hasRoute(.state2 => .state0)) XCTAssertFalse(machine.hasRoute(.state2 => .state1)) XCTAssertFalse(machine.hasRoute(.state2 => .state2)) } }
mit
eca837d7afc022f984fd79533283d0d9
30.102564
114
0.5608
4.714341
false
false
false
false