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
dduan/swift
validation-test/compiler_crashers_fixed/00179-swift-protocolcompositiontype-build.swift
11
2506
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse a } struct e : f { i f = g } func i<g : g, e : f where e.f == g> (c: e) { } func i<h : f where h A { func c() -> String } class B { func d() -> String { return "" } } class C: B, A { override func d() -> String { return "" } func c() -> String { return "" } } func e<T where T: A, T: B>(t: T) { d } protocol t { } protocol d : t { } protocol g : t { } s q l }) } d(t(u, t(w, y))) protocol e { r j } struct m<v : e> { k x: v k x: v.j } protocol n for (mx : e?) in c { } } struct A<T> { let a: [(T, () -> ())] = [] } ) func o<t>() -> (t, t -> t) -> t { j j j.o = { } { t) { h } } protocol o { class func o() } class j: o{ class func o {} e o<j : u> { k [] } n=p r n=p func n<q>() { b b { o o } } func n(j: Any, t: Any) -> (((Any, Any) -> Any) -> Any) { k { (s: (Any, Any) -> Any) -> Any l k s(j, t) } } func b(s: (((Any, Any) -> Any) -> Any) protocol p { class func g() } class h: p { class func g() { } } (h() as p).dynamicType.g() protocol p { } protocol h : p { } protocol g : p { } protocol n { o : A { func b(b: X.Type) { } } f> { c(d ()) } func b(e)-> <d>(() -> d) func m(c: b) -> <h>(() -> h) -> b { f) -> j) -> > j { l i !(k) } d l) func d<m>-> (m, m - func b<e>(e : e) -> c { e func m<u>() -> (u, u - w } w protocol k : w { func v <h: h m h.p == k>(l: h.p) { } } protocol h { n func w(w: } class h<u : h> { class A: A { } class B : C { } typealias C = B func i(c: () -> ()) { } class a { var _ = i() { } } d) func e(h: b) -> <f>(() -> f) -> b { return { c):h())" } } class f<d : d, j : d k d.l == j> { } protocol d { i l i i } struct l<l : d> : d { i j i() { l.i() } } protocol f { } protocol d : f { protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() func b((Any, e))(e: (Any) -> <d>(()-> d) -> f func c<e>() -> (e -> e) -> e { e, e -> e) ->)func d(f: b) -> <e>(() -> e) -> == q.n> { } o l { u n } y q) -> ()) } o n ()) }
apache-2.0
faf6a6b5def5765463307d29e80f3883
13.402299
78
0.438947
2.386667
false
false
false
false
Arcovv/CleanArchitectureRxSwift
RealmPlatform/Entities/RMAddress.swift
1
1458
// // RMAddress.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 10.03.17. // Copyright © 2017 sergdort. All rights reserved. // import QueryKit import Domain import RealmSwift import Realm final class RMAddress: Object { dynamic var city: String = "" dynamic var geo: RMLocation? dynamic var street: String = "" dynamic var suite: String = "" dynamic var zipcode: String = "" } extension RMAddress { static var city: Attribute<String> { return Attribute("city")} static var street: Attribute<String> { return Attribute("street")} static var suite: Attribute<String> { return Attribute("suite")} static var zipcode: Attribute<String> { return Attribute("zipcode")} static var geo: Attribute<RMLocation> { return Attribute("geo")} } extension RMAddress: DomainConvertibleType { func asDomain() -> Address { return Address(city: city, geo: geo!.asDomain(), street: street, suite: suite, zipcode: zipcode) } } extension Address: RealmRepresentable { internal var uid: String { return "" } func asRealm() -> RMAddress { return RMAddress.build { object in object.city = city object.geo = geo.asRealm() object.street = street object.suite = suite object.zipcode = zipcode } } }
mit
05038721c441ec92128e9d4169921fe9
25.490909
72
0.608099
4.510836
false
false
false
false
pietu/SImperial
SImperial/PopOverViewController.swift
1
1475
// // PopOverViewController.swift // SImperial // // Created by Petteri Parkkila on 05/12/16. // Copyright © 2016 Pietu. All rights reserved. // import UIKit class PopOverViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var isFromUnit: Bool = false var compelition: ((_ unit: Dictionary<String,Dimension>) -> Void)? = nil var unitSelections: [Dictionary<String,Dimension>]? = nil internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let selections = self.unitSelections { return selections.count } else { return 0 } } internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "unitCell") cell.textLabel?.font = UIFont(name: "Montserrat-Regular", size: 17) if let selections = self.unitSelections { if let name = selections[indexPath.row].keys.first { cell.textLabel?.text = name + ", " + (selections[indexPath.row][name]?.symbol)! } } else { cell.textLabel?.text = "No content available" } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let selections = self.unitSelections { if let cb = compelition { cb(selections[indexPath.row]) } } self.dismiss(animated: true, completion: nil) } }
apache-2.0
56691bd429ad7f6005451c69459eb7cf
31.755556
107
0.689281
4.309942
false
false
false
false
changjianfeishui/iOS_Tutorials_Of_Swift
Custom View Controller Transitions/iLoveCatz/iLoveCatz/SwipeInteractionController.swift
1
2081
// // SwipeInteractionController.swift // iLoveCatz // // Created by XB on 16/5/17. // Copyright © 2016年 XB. All rights reserved. // import UIKit class SwipeInteractionController: UIPercentDrivenInteractiveTransition { var interactionInProgress:Bool = false private var _shouldCompleteTransition:Bool = false private var _navigationController:UINavigationController! //This method allows you to attach the interaction controller to a view controller. func wireToViewController(viewController:UIViewController) { _navigationController = viewController.navigationController! self.prepareGestureRecognizerInView(viewController.view) } //This method adds a gesture recognizer to the view controller’s view to detect a pan. func prepareGestureRecognizerInView(view:UIView) { let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) view.addGestureRecognizer(gesture) } func handlePan(pan:UIPanGestureRecognizer) -> Void { let translation = pan.translationInView(pan.view?.superview) switch pan.state { case .Began: // 1. Start an interactive transition! self.interactionInProgress = true _navigationController.popViewControllerAnimated(true) case .Changed: // 2. compute the current position var fraction = -(translation.x / 200.0) fraction = CGFloat(fminf(fmaxf(Float(fraction), 0.0), 1.0)) // 3. should we complete? _shouldCompleteTransition = (fraction > 0.5) // 4. update the animation self.updateInteractiveTransition(fraction) case .Ended,.Cancelled: self.interactionInProgress = false if !_shouldCompleteTransition||pan.state == UIGestureRecognizerState.Cancelled { self.cancelInteractiveTransition() }else{ self.finishInteractiveTransition() } default: break } } }
mit
fbcf2d01beb4e5a0a6af74abf374dbbf
35.421053
92
0.656551
5.448819
false
false
false
false
benlangmuir/swift
test/SILGen/address_only_types.swift
2
9718
// RUN: %target-swift-emit-silgen -module-name address_only_types -parse-as-library -parse-stdlib %s | %FileCheck %s precedencegroup AssignmentPrecedence { assignment: true } typealias Int = Builtin.Int64 enum Bool { case true_, false_ } protocol Unloadable { func foo() -> Int var address_only_prop : Unloadable { get } var loadable_prop : Int { get } } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B9_argument{{[_0-9a-zA-Z]*}}F func address_only_argument(_ x: Unloadable) { // CHECK: bb0([[XARG:%[0-9]+]] : $*any Unloadable): // CHECK: debug_value [[XARG]] {{.*}} expr op_deref // CHECK-NEXT: tuple // CHECK-NEXT: return } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B17_ignored_argument{{[_0-9a-zA-Z]*}}F func address_only_ignored_argument(_: Unloadable) { // CHECK: bb0([[XARG:%[0-9]+]] : $*any Unloadable): // CHECK-NOT: dealloc_stack {{.*}} [[XARG]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B7_return{{[_0-9a-zA-Z]*}}F func address_only_return(_ x: Unloadable, y: Int) -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*any Unloadable, [[XARG:%[0-9]+]] : $*any Unloadable, [[YARG:%[0-9]+]] : $Builtin.Int64): // CHECK-NEXT: debug_value [[XARG]] : $*any Unloadable, let, name "x", {{.*}} expr op_deref // CHECK-NEXT: debug_value [[YARG]] : $Builtin.Int64, let, name "y" // CHECK-NEXT: copy_addr [[XARG]] to [initialization] [[RET]] // CHECK-NEXT: [[VOID:%[0-9]+]] = tuple () // CHECK-NEXT: return [[VOID]] return x } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B15_missing_return{{[_0-9a-zA-Z]*}}F func address_only_missing_return() -> Unloadable { // CHECK: unreachable } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B27_conditional_missing_return{{[_0-9a-zA-Z]*}}F func address_only_conditional_missing_return(_ x: Unloadable) -> Unloadable { // CHECK: bb0({{%.*}} : $*any Unloadable, {{%.*}} : $*any Unloadable): // CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE:bb[0-9]+]] switch Bool.true_ { case .true_: // CHECK: [[TRUE]]: // CHECK: copy_addr %1 to [initialization] %0 : $*any Unloadable // CHECK: return return x case .false_: () } // CHECK: [[FALSE]]: // CHECK: unreachable } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B29_conditional_missing_return_2 func address_only_conditional_missing_return_2(_ x: Unloadable) -> Unloadable { // CHECK: bb0({{%.*}} : $*any Unloadable, {{%.*}} : $*any Unloadable): // CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE1:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE1:bb[0-9]+]] switch Bool.true_ { case .true_: return x case .false_: () } // CHECK: [[FALSE1]]: // CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE2:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE2:bb[0-9]+]] switch Bool.true_ { case .true_: return x case .false_: () } // CHECK: [[FALSE2]]: // CHECK: unreachable // CHECK: bb{{.*}}: // CHECK: return } var crap : Unloadable = some_address_only_function_1() func some_address_only_function_1() -> Unloadable { return crap } func some_address_only_function_2(_ x: Unloadable) -> () {} // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B7_call_1 func address_only_call_1() -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*any Unloadable): return some_address_only_function_1() // FIXME emit into // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_1AA10Unloadable_pyF // CHECK: apply [[FUNC]]([[RET]]) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B21_call_1_ignore_returnyyF func address_only_call_1_ignore_return() { // CHECK: bb0: some_address_only_function_1() // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_1AA10Unloadable_pyF // CHECK: apply [[FUNC]]([[TEMP]]) // CHECK: destroy_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B7_call_2{{[_0-9a-zA-Z]*}}F func address_only_call_2(_ x: Unloadable) { // CHECK: bb0([[XARG:%[0-9]+]] : $*any Unloadable): // CHECK: debug_value [[XARG]] : $*any Unloadable, {{.*}} expr op_deref some_address_only_function_2(x) // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F // CHECK: apply [[FUNC]]([[XARG]]) // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B12_call_1_in_2{{[_0-9a-zA-Z]*}}F func address_only_call_1_in_2() { // CHECK: bb0: some_address_only_function_2(some_address_only_function_1()) // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable // CHECK: [[FUNC1:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F // CHECK: apply [[FUNC1]]([[TEMP]]) // CHECK: [[FUNC2:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F // CHECK: apply [[FUNC2]]([[TEMP]]) // CHECK: dealloc_stack [[TEMP]] // CHECK: return } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B12_materialize{{[_0-9a-zA-Z]*}}F func address_only_materialize() -> Int { // CHECK: bb0: return some_address_only_function_1().foo() // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable // CHECK: [[FUNC:%[0-9]+]] = function_ref @$s18address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F // CHECK: apply [[FUNC]]([[TEMP]]) // CHECK: [[TEMP_PROJ:%[0-9]+]] = open_existential_addr immutable_access [[TEMP]] : $*any Unloadable to $*[[OPENED:@opened\(.*, any Unloadable\) Self]] // CHECK: [[FOO_METHOD:%[0-9]+]] = witness_method $[[OPENED]], #Unloadable.foo : // CHECK: [[RET:%[0-9]+]] = apply [[FOO_METHOD]]<[[OPENED]]>([[TEMP_PROJ]]) // CHECK: destroy_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B21_assignment_from_temp{{[_0-9a-zA-Z]*}}F func address_only_assignment_from_temp(_ dest: inout Unloadable) { // CHECK: bb0([[DEST:%[0-9]+]] : $*any Unloadable): dest = some_address_only_function_1() // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable // CHECK: %[[ACCESS:.*]] = begin_access [modify] [unknown] %0 : // CHECK: copy_addr [take] [[TEMP]] to %[[ACCESS]] : // CHECK-NOT: destroy_addr [[TEMP]] // CHECK: dealloc_stack [[TEMP]] } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B19_assignment_from_lv{{[_0-9a-zA-Z]*}}F func address_only_assignment_from_lv(_ dest: inout Unloadable, v: Unloadable) { var v = v // CHECK: bb0([[DEST:%[0-9]+]] : $*any Unloadable, [[VARG:%[0-9]+]] : $*any Unloadable): // CHECK: [[VBOX:%.*]] = alloc_box ${ var any Unloadable } // CHECK: [[V_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[VBOX]] // CHECK: [[PBOX:%[0-9]+]] = project_box [[V_LIFETIME]] // CHECK: copy_addr [[VARG]] to [initialization] [[PBOX]] : $*any Unloadable dest = v // CHECK: [[READBOX:%.*]] = begin_access [read] [unknown] [[PBOX]] : // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable // CHECK: copy_addr [[READBOX]] to [initialization] [[TEMP]] : // CHECK: [[RET:%.*]] = begin_access [modify] [unknown] %0 : // CHECK: copy_addr [take] [[TEMP]] to [[RET]] : // CHECK: destroy_value [[VBOX]] } var global_prop : Unloadable { get { return crap } set {} } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B33_assignment_from_temp_to_property{{[_0-9a-zA-Z]*}}F func address_only_assignment_from_temp_to_property() { // CHECK: bb0: global_prop = some_address_only_function_1() // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable // CHECK: [[SETTER:%[0-9]+]] = function_ref @$s18address_only_types11global_propAA10Unloadable_pvs // CHECK: apply [[SETTER]]([[TEMP]]) // CHECK: dealloc_stack [[TEMP]] } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B31_assignment_from_lv_to_property{{[_0-9a-zA-Z]*}}F func address_only_assignment_from_lv_to_property(_ v: Unloadable) { // CHECK: bb0([[VARG:%[0-9]+]] : $*any Unloadable): // CHECK: debug_value [[VARG]] : $*any Unloadable, {{.*}} expr op_deref // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $any Unloadable // CHECK: copy_addr [[VARG]] to [initialization] [[TEMP]] // CHECK: [[SETTER:%[0-9]+]] = function_ref @$s18address_only_types11global_propAA10Unloadable_pvs // CHECK: apply [[SETTER]]([[TEMP]]) // CHECK: dealloc_stack [[TEMP]] global_prop = v } // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types0a1_B4_varAA10Unloadable_pyF func address_only_var() -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*any Unloadable): var x = some_address_only_function_1() // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var any Unloadable } // CHECK: [[XBOX_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[XBOX]] // CHECK: [[XPB:%.*]] = project_box [[XBOX_LIFETIME]] // CHECK: apply {{%.*}}([[XPB]]) return x // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XPB]] : // CHECK: copy_addr [[ACCESS]] to [initialization] %0 // CHECK: destroy_value [[XBOX]] // CHECK: return } func unloadable_to_unloadable(_ x: Unloadable) -> Unloadable { return x } var some_address_only_nontuple_arg_function : (Unloadable) -> Unloadable = unloadable_to_unloadable // CHECK-LABEL: sil hidden [ossa] @$s18address_only_types05call_a1_B22_nontuple_arg_function{{[_0-9a-zA-Z]*}}F func call_address_only_nontuple_arg_function(_ x: Unloadable) { some_address_only_nontuple_arg_function(x) }
apache-2.0
4e59732c54b9c6217e37a25e0d2a081c
41.069264
153
0.621836
2.948422
false
false
false
false
benlangmuir/swift
stdlib/public/core/StringUTF8Validation.swift
30
8056
private func _isUTF8MultiByteLeading(_ x: UInt8) -> Bool { return (0xC2...0xF4).contains(x) } private func _isNotOverlong_F0(_ x: UInt8) -> Bool { return (0x90...0xBF).contains(x) } private func _isNotOverlong_F4(_ x: UInt8) -> Bool { return UTF8.isContinuation(x) && x <= 0x8F } private func _isNotOverlong_E0(_ x: UInt8) -> Bool { return (0xA0...0xBF).contains(x) } private func _isNotOverlong_ED(_ x: UInt8) -> Bool { return UTF8.isContinuation(x) && x <= 0x9F } internal struct UTF8ExtraInfo: Equatable { public var isASCII: Bool } internal enum UTF8ValidationResult { case success(UTF8ExtraInfo) case error(toBeReplaced: Range<Int>) } extension UTF8ValidationResult: Equatable {} private struct UTF8ValidationError: Error {} internal func validateUTF8(_ buf: UnsafeBufferPointer<UInt8>) -> UTF8ValidationResult { if _allASCII(buf) { return .success(UTF8ExtraInfo(isASCII: true)) } var iter = buf.makeIterator() var lastValidIndex = buf.startIndex @inline(__always) func guaranteeIn(_ f: (UInt8) -> Bool) throws { guard let cu = iter.next() else { throw UTF8ValidationError() } guard f(cu) else { throw UTF8ValidationError() } } @inline(__always) func guaranteeContinuation() throws { try guaranteeIn(UTF8.isContinuation) } func _legacyInvalidLengthCalculation(_ _buffer: (_storage: UInt32, ())) -> Int { // function body copied from UTF8.ForwardParser._invalidLength if _buffer._storage & 0b0__1100_0000__1111_0000 == 0b0__1000_0000__1110_0000 { // 2-byte prefix of 3-byte sequence. The top 5 bits of the decoded result // must be nonzero and not a surrogate let top5Bits = _buffer._storage & 0b0__0010_0000__0000_1111 if top5Bits != 0 && top5Bits != 0b0__0010_0000__0000_1101 { return 2 } } else if _buffer._storage & 0b0__1100_0000__1111_1000 == 0b0__1000_0000__1111_0000 { // Prefix of 4-byte sequence. The top 5 bits of the decoded result // must be nonzero and no greater than 0b0__0100_0000 let top5bits = UInt16(_buffer._storage & 0b0__0011_0000__0000_0111) if top5bits != 0 && top5bits.byteSwapped <= 0b0__0000_0100__0000_0000 { return _buffer._storage & 0b0__1100_0000__0000_0000__0000_0000 == 0b0__1000_0000__0000_0000__0000_0000 ? 3 : 2 } } return 1 } func _legacyNarrowIllegalRange(buf: Slice<UnsafeBufferPointer<UInt8>>) -> Range<Int> { var reversePacked: UInt32 = 0 if let third = buf.dropFirst(2).first { reversePacked |= UInt32(third) reversePacked <<= 8 } if let second = buf.dropFirst().first { reversePacked |= UInt32(second) reversePacked <<= 8 } reversePacked |= UInt32(buf.first!) let _buffer: (_storage: UInt32, x: ()) = (reversePacked, ()) let invalids = _legacyInvalidLengthCalculation(_buffer) return buf.startIndex ..< buf.startIndex + invalids } func findInvalidRange(_ buf: Slice<UnsafeBufferPointer<UInt8>>) -> Range<Int> { var endIndex = buf.startIndex var iter = buf.makeIterator() _ = iter.next() while let cu = iter.next(), UTF8.isContinuation(cu) { endIndex += 1 } let illegalRange = Range(buf.startIndex...endIndex) _internalInvariant(illegalRange.clamped(to: (buf.startIndex..<buf.endIndex)) == illegalRange, "illegal range out of full range") // FIXME: Remove the call to `_legacyNarrowIllegalRange` and return `illegalRange` directly return _legacyNarrowIllegalRange(buf: buf[illegalRange]) } do { var isASCII = true while let cu = iter.next() { if UTF8.isASCII(cu) { lastValidIndex &+= 1; continue } isASCII = false if _slowPath(!_isUTF8MultiByteLeading(cu)) { throw UTF8ValidationError() } switch cu { case 0xC2...0xDF: try guaranteeContinuation() lastValidIndex &+= 2 case 0xE0: try guaranteeIn(_isNotOverlong_E0) try guaranteeContinuation() lastValidIndex &+= 3 case 0xE1...0xEC: try guaranteeContinuation() try guaranteeContinuation() lastValidIndex &+= 3 case 0xED: try guaranteeIn(_isNotOverlong_ED) try guaranteeContinuation() lastValidIndex &+= 3 case 0xEE...0xEF: try guaranteeContinuation() try guaranteeContinuation() lastValidIndex &+= 3 case 0xF0: try guaranteeIn(_isNotOverlong_F0) try guaranteeContinuation() try guaranteeContinuation() lastValidIndex &+= 4 case 0xF1...0xF3: try guaranteeContinuation() try guaranteeContinuation() try guaranteeContinuation() lastValidIndex &+= 4 case 0xF4: try guaranteeIn(_isNotOverlong_F4) try guaranteeContinuation() try guaranteeContinuation() lastValidIndex &+= 4 default: Builtin.unreachable() } } return .success(UTF8ExtraInfo(isASCII: isASCII)) } catch { return .error(toBeReplaced: findInvalidRange(buf[lastValidIndex...])) } } internal func repairUTF8(_ input: UnsafeBufferPointer<UInt8>, firstKnownBrokenRange: Range<Int>) -> String { _internalInvariant(!input.isEmpty, "empty input doesn't need to be repaired") _internalInvariant(firstKnownBrokenRange.clamped(to: input.indices) == firstKnownBrokenRange) // During this process, `remainingInput` contains the remaining bytes to process. It's split into three // non-overlapping sub-regions: // // 1. `goodChunk` (may be empty) containing bytes that are known good UTF-8 and can be copied into the output String // 2. `brokenRange` (never empty) the next range of broken bytes, // 3. the remainder (implicit, will become the next `remainingInput`) // // At the beginning of the process, the `goodChunk` starts at the beginning and extends to just before the first // known broken byte. The known broken bytes are covered in the `brokenRange` and everything following that is // the remainder. // We then copy the `goodChunk` into the target buffer and append a UTF8 replacement character. `brokenRange` is // skipped (replaced by the replacement character) and we restart the same process. This time, `goodChunk` extends // from the byte after the previous `brokenRange` to the next `brokenRange`. var result = _StringGuts() let replacementCharacterCount = Unicode.Scalar._replacementCharacter.withUTF8CodeUnits { $0.count } result.reserveCapacity(input.count + 5 * replacementCharacterCount) // extra space for some replacement characters var brokenRange: Range<Int> = firstKnownBrokenRange var remainingInput = input repeat { _internalInvariant(!brokenRange.isEmpty, "broken range empty") _internalInvariant(!remainingInput.isEmpty, "empty remaining input doesn't need to be repaired") let goodChunk = remainingInput[..<brokenRange.startIndex] // very likely this capacity reservation does not actually do anything because we reserved space for the entire // input plus up to five replacement characters up front result.reserveCapacity(result.count + remainingInput.count + replacementCharacterCount) // we can now safely append the next known good bytes and a replacement character result.appendInPlace(UnsafeBufferPointer(rebasing: goodChunk), isASCII: false /* appending replacement character anyway, so let's not bother */) Unicode.Scalar._replacementCharacter.withUTF8CodeUnits { result.appendInPlace($0, isASCII: false) } remainingInput = UnsafeBufferPointer(rebasing: remainingInput[brokenRange.endIndex...]) switch validateUTF8(remainingInput) { case .success: result.appendInPlace(remainingInput, isASCII: false) return String(result) case .error(let newBrokenRange): brokenRange = newBrokenRange } } while !remainingInput.isEmpty return String(result) }
apache-2.0
f083c3d8cd4008e74a61961c3f593c66
38.490196
119
0.67428
4.108108
false
false
false
false
malaonline/iOS
mala-ios/Model/Course/TeacherModel.swift
1
2233
// // TeacherModel.swift // mala-ios // // Created by Erdi on 12/23/15. // Copyright © 2015 Mala Online. All rights reserved. // import UIKit class TeacherModel: BaseObjectModel { // MARK: - Property var avatar: String? var gender: String? var level: Int = 0 var min_price: Int = 0 var max_price: Int = 0 var subject: String? var grades_shortname: String? var tags: [String]? // MARK: - Constructed override init() { super.init() } override init(dict: [String: Any]) { super.init(dict: dict) setValuesForKeys(dict) } convenience init(id: Int, name: String, avatar: String, degree: Int, minPrice: Int, maxPrice: Int, subject: String, shortname: String, tags: [String]) { self.init() self.id = id self.name = name self.avatar = avatar self.level = degree self.min_price = minPrice self.max_price = maxPrice self.subject = subject self.grades_shortname = shortname self.tags = tags } convenience init(id: Int, name: String, avatar: String) { self.init() self.id = id self.name = name self.avatar = avatar } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Override override func setValue(_ value: Any?, forUndefinedKey key: String) { println("TeacherModel - Set for UndefinedKey: \(key)") } override func setValue(_ value: Any?, forKey key: String) { // keep the price's value to 0(Int), if the value is null if (key == "min_price" || key == "max_price") && value == nil { return } if key == "avatar" { if let urlString = value as? String { avatar = urlString } return } super.setValue(value, forKey: key) } // MARK: - Description override var description: String { let keys = ["id", "name", "avatar", "gender", "level", "min_price", "max_price", "subject", "grades_shortname", "tags"] return dictionaryWithValues(forKeys: keys).description } }
mit
3695d9d7128e8bc6831bac330fcb0bbe
26.555556
156
0.56586
4.028881
false
false
false
false
BeezleLabs/HackerTracker-iOS
hackertracker/CalendarUtility.swift
1
5494
// // CalendarUtility.swift // hackertracker // // Created by caleb on 8/1/20. // Copyright © 2020 Beezle Labs. All rights reserved. // import EventKit import Foundation import UIKit struct CalendarUtility { let eventStore = EKEventStore() let status: EKAuthorizationStatus = EKEventStore.authorizationStatus(for: EKEntityType.event) func requestAuthorization() { eventStore.requestAccess(to: EKEntityType.event) { _, error in if let error = error { print("Request authorization error: \(error.localizedDescription)") } } } func requestAuthorizationAndSave(htEvent: HTEventModel, view: HTEventDetailViewController) { eventStore.requestAccess(to: EKEntityType.event) { authorized, error in if authorized { DispatchQueue.main.async { self.addEventToCalendar(htEvent: htEvent, view: view) } } if let error = error { print("Request authorization error: \(error.localizedDescription)") } } } func addEvent(htEvent: HTEventModel, view: HTEventDetailViewController) { switch status { case .notDetermined: requestAuthorizationAndSave(htEvent: htEvent, view: view) case .authorized: addEventToCalendar(htEvent: htEvent, view: view) case .restricted, .denied: deniedAccessAlert(view: view) @unknown default: break } } private func addEventToCalendar(htEvent: HTEventModel, view: HTEventDetailViewController) { let event = createEvent(htEvent: htEvent) if !isDuplicate(newEvent: event) { saveAlert(htEvent: htEvent, event: event, view: view) } else { duplicateAlert(htEvent: htEvent, view: view) } } private func createEvent(htEvent: HTEventModel) -> EKEvent { let event = EKEvent(eventStore: eventStore) var notes = htEvent.description let speakers = htEvent.speakers.map { $0.name } if !speakers.isEmpty { if speakers.count > 1 { notes = "Speakers: \(speakers.joined(separator: ", "))\n\n\(htEvent.description)" } else { notes = "Speaker: \(speakers.first ?? "")\n\n\(htEvent.description)" } } event.calendar = eventStore.defaultCalendarForNewEvents event.startDate = htEvent.begin event.endDate = htEvent.end event.title = htEvent.title event.location = htEvent.location.name event.notes = notes if !htEvent.links.isEmpty { if htEvent.links.contains(where: { $0.url.contains("https://forum.defcon.org") }) { if let link = htEvent.links.first(where: { $0.url.contains("https://forum.defcon.org") }), let url = URL(string: link.url) { event.url = url } } else { if let link = htEvent.links.first, let url = URL(string: link.url) { event.url = url } } } return event } private func saveAlert(htEvent: HTEventModel, event: EKEvent, view: HTEventDetailViewController) { let saveAlert = UIAlertController( title: "Add \(htEvent.conferenceName) event to calendar", message: htEvent.title, preferredStyle: .alert ) saveAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) saveAlert.addAction(UIAlertAction(title: "Save", style: .default) { _ in try? self.eventStore.save(event, span: .thisEvent) }) view.present(saveAlert, animated: true) } private func deniedAccessAlert(view: HTEventDetailViewController) { let deniedAlert = UIAlertController( title: "Calendar access is currently disabled for HackerTracker", message: "Select OK to view application settings", preferredStyle: .alert ) deniedAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) deniedAlert.addAction(UIAlertAction(title: "OK", style: .default) { _ in if let url = URL(string: UIApplication.openSettingsURLString) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } }) view.present(deniedAlert, animated: true) } private func duplicateAlert(htEvent: HTEventModel, view: HTEventDetailViewController) { let duplicateAlert = UIAlertController( title: "Duplicate \(htEvent.conferenceName) event found in your calendar", message: htEvent.title, preferredStyle: .alert ) duplicateAlert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) view.present(duplicateAlert, animated: true) } private func isDuplicate(newEvent: EKEvent) -> Bool { let predicate = eventStore .predicateForEvents(withStart: newEvent.startDate, end: newEvent.endDate, calendars: nil) let currentEvents = eventStore.events(matching: predicate) let duplicateEvent = currentEvents .contains(where: { $0.title == newEvent.title && $0.startDate == newEvent.startDate && $0.endDate == newEvent.endDate }) return duplicateEvent } }
gpl-2.0
1fcbe19eb0c739bbc3f5a5661af391db
36.882759
186
0.612598
4.655085
false
false
false
false
i-schuetz/SwiftCharts
SwiftCharts/Axis/ChartAxisLayerDefault.swift
1
16075
// // ChartAxisLayerDefault.swift // SwiftCharts // // Created by ischuetz on 25/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit /** This class allows customizing the layout of an axis layer and its contents. An example of how some of these settings affect the layout of a Y axis is shown below. ```` ┌───────────────────────────────────────────────────────────────────┐ │ screenTop │ │ ┌───────────────────────────────────────────────────────────┐ │ │ │ ───────────────────────────────────────────────────────── │ │ labelsToAxisSpacingX │ │ ◀───┼───┼──── similar for labelsToAxisSpacingY │ │ Label 1 Label 2 Label 3 Label 4 Label 5 │ │ │ │ ◀───┼───┼──── labelsSpacing (only supported for X axes) screenLeading ────┼─▶ │ Label A Label B Label C Label D Label E │ │ │ │ │ │ │ │ ◀────────────────────────────┼───┼──── axisTitleLabelsToLabelsSpacing │ │ │ │ │ │ Title │ ◀─┼──── screenTrailing │ └───────────────────────────────────────────────────────────┘ │ │ screenBottom │ └───────────────────────────────────────────────────────────────────┘ ```` */ open class ChartAxisSettings { var screenLeading: CGFloat = 0 var screenTrailing: CGFloat = 0 var screenTop: CGFloat = 0 var screenBottom: CGFloat = 0 var labelsSpacing: CGFloat = 5 var labelsToAxisSpacingX: CGFloat = 5 var labelsToAxisSpacingY: CGFloat = 5 var axisTitleLabelsToLabelsSpacing: CGFloat = 5 var lineColor:UIColor = UIColor.black var axisStrokeWidth: CGFloat = 2.0 var isAxisLineVisible: Bool = true convenience init(_ chartSettings: ChartSettings) { self.init() self.labelsSpacing = chartSettings.labelsSpacing self.labelsToAxisSpacingX = chartSettings.labelsToAxisSpacingX self.labelsToAxisSpacingY = chartSettings.labelsToAxisSpacingY self.axisTitleLabelsToLabelsSpacing = chartSettings.axisTitleLabelsToLabelsSpacing self.screenLeading = chartSettings.leading self.screenTop = chartSettings.top self.screenTrailing = chartSettings.trailing self.screenBottom = chartSettings.bottom self.axisStrokeWidth = chartSettings.axisStrokeWidth } } public typealias ChartAxisValueLabelDrawers = (scalar: Double, drawers: [ChartLabelDrawer]) /// Helper class to notify other layers about frame changes which affect content available space public final class ChartAxisLayerWithFrameDelta { let layer: ChartAxisLayer let delta: CGFloat init(layer: ChartAxisLayer, delta: CGFloat) { self.layer = layer self.delta = delta } } extension Optional where Wrapped: ChartAxisLayerWithFrameDelta { var deltaDefault0: CGFloat { return self?.delta ?? 0 } } public enum AxisLabelsSpaceReservationMode { case minPresentedSize /// Doesn't reserve less space than the min presented label width/height so far case maxPresentedSize /// Doesn't reserve less space than the max presented label width/height so far case fixed(CGFloat) /// Fixed value, ignores labels width/height case current /// Reserves space for currently visible labels } public typealias ChartAxisValueLabelDrawersWithAxisLayer = (valueLabelDrawers: ChartAxisValueLabelDrawers, layer: ChartAxisLayer) public struct ChartAxisLayerTapSettings { public let expandArea: CGSize let handler: ((ChartAxisValueLabelDrawersWithAxisLayer) -> Void)? public init(expandArea: CGSize = CGSize(width: 10, height: 10), handler: ((ChartAxisValueLabelDrawersWithAxisLayer) -> Void)? = nil) { self.expandArea = expandArea self.handler = handler } } /// A default implementation of ChartAxisLayer, which delegates drawing of the axis line and labels to the appropriate Drawers open class ChartAxisLayerDefault: ChartAxisLayer { open var axis: ChartAxis var origin: CGPoint { fatalError("Override") } var end: CGPoint { fatalError("Override") } open var frame: CGRect { return CGRect(x: origin.x, y: origin.y, width: width, height: height) } open var frameWithoutLabels: CGRect { return CGRect(x: origin.x, y: origin.y, width: widthWithoutLabels, height: heightWithoutLabels) } open var visibleFrame: CGRect { fatalError("Override") } /// Constant dimension between origin and end var offset: CGFloat open var currentAxisValues: [Double] = [] public let valuesGenerator: ChartAxisValuesGenerator open var labelsGenerator: ChartAxisLabelsGenerator let axisTitleLabels: [ChartAxisLabel] let settings: ChartAxisSettings // exposed for subclasses var lineDrawer: ChartLineDrawer? var labelDrawers: [ChartAxisValueLabelDrawers] = [] var axisTitleLabelDrawers: [ChartLabelDrawer] = [] let labelsConflictSolver: ChartAxisLabelsConflictSolver? open weak var chart: Chart? let labelSpaceReservationMode: AxisLabelsSpaceReservationMode let clipContents: Bool open var tapSettings: ChartAxisLayerTapSettings? public var canChangeFrameSize: Bool = true var widthWithoutLabels: CGFloat { return width } var heightWithoutLabels: CGFloat { return settings.axisStrokeWidth + settings.labelsToAxisSpacingX + settings.axisTitleLabelsToLabelsSpacing + axisTitleLabelsHeight } open var axisValuesScreenLocs: [CGFloat] { return self.currentAxisValues.map{axis.screenLocForScalar($0)} } open var axisValuesWithFrames: [(axisValue: Double, frames: [CGRect])] { return labelDrawers.map { axisValue, drawers in (axisValue: axisValue, frames: drawers.map{$0.frame}) } } var visibleAxisValuesScreenLocs: [CGFloat] { return currentAxisValues.reduce(Array<CGFloat>()) {u, scalar in return u + [axis.screenLocForScalar(scalar)] } } // smallest screen space between axis values open var minAxisScreenSpace: CGFloat { return axisValuesScreenLocs.reduce((CGFloat.greatestFiniteMagnitude, -CGFloat.greatestFiniteMagnitude)) {tuple, screenLoc in let minSpace = tuple.0 let previousScreenLoc = tuple.1 return (min(minSpace, abs(screenLoc - previousScreenLoc)), screenLoc) }.0 } lazy private(set) var axisTitleLabelsHeight: CGFloat = { return self.axisTitleLabels.reduce(0) { sum, label in sum + label.textSize.height } }() lazy private(set) var axisTitleLabelsWidth: CGFloat = { return self.axisTitleLabels.reduce(0) { sum, label in sum + label.textSize.width } }() open func keepInBoundaries() { axis.keepInBoundaries() initDrawers() chart?.view.setNeedsDisplay() } var width: CGFloat { fatalError("override") } open var lineP1: CGPoint { fatalError("override") } open var lineP2: CGPoint { fatalError("override") } var height: CGFloat { fatalError("override") } open var low: Bool { fatalError("override") } /// Frame of layer after last update. This is used to detect deltas with the frame resulting from an update. Note that the layer's frame can be altered by only updating the model data (this depends on how the concrete axis layer calculates the frame), which is why this frame is not always identical to the layer's frame directly before calling udpate. var lastFrame: CGRect = CGRect.zero // NOTE: Assumes axis values sorted by scalar (can be increasing or decreasing) public required init(axis: ChartAxis, offset: CGFloat, valuesGenerator: ChartAxisValuesGenerator, labelsGenerator: ChartAxisLabelsGenerator, axisTitleLabels: [ChartAxisLabel], settings: ChartAxisSettings, labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, labelSpaceReservationMode: AxisLabelsSpaceReservationMode, clipContents: Bool) { self.axis = axis self.offset = offset self.valuesGenerator = valuesGenerator self.labelsGenerator = labelsGenerator self.axisTitleLabels = axisTitleLabels self.settings = settings self.labelsConflictSolver = labelsConflictSolver self.labelSpaceReservationMode = labelSpaceReservationMode self.clipContents = clipContents self.lastFrame = frame self.currentAxisValues = valuesGenerator.generate(axis) } open func update() { prepareUpdate() updateInternal() postUpdate() } fileprivate func clearDrawers() { lineDrawer = nil labelDrawers = [] axisTitleLabelDrawers = [] } func prepareUpdate() { clearDrawers() } func updateInternal() { initDrawers() } func postUpdate() { lastFrame = frame } open func handleAxisInnerFrameChange(_ xLow: ChartAxisLayerWithFrameDelta?, yLow: ChartAxisLayerWithFrameDelta?, xHigh: ChartAxisLayerWithFrameDelta?, yHigh: ChartAxisLayerWithFrameDelta?) { } open func chartInitialized(chart: Chart) { self.chart = chart update() } /** Draws the axis' line, labels and axis title label - parameter context: The context to draw the axis contents in - parameter chart: The chart that this axis belongs to */ open func chartViewDrawing(context: CGContext, chart: Chart) { func draw() { if settings.isAxisLineVisible { if let lineDrawer = lineDrawer { context.setLineWidth(CGFloat(settings.axisStrokeWidth)) lineDrawer.triggerDraw(context: context, chart: chart) } } for (_, labelDrawers) in labelDrawers { for labelDrawer in labelDrawers { labelDrawer.triggerDraw(context: context, chart: chart) } } for axisTitleLabelDrawer in axisTitleLabelDrawers { axisTitleLabelDrawer.triggerDraw(context: context, chart: chart) } } if clipContents { context.saveGState() context.addRect(visibleFrame) context.clip() draw() context.restoreGState() } else { draw() } } open func chartContentViewDrawing(context: CGContext, chart: Chart) {} open func chartDrawersContentViewDrawing(context: CGContext, chart: Chart, view: UIView) {} open func handleGlobalTap(_ location: CGPoint) {} func initDrawers() { fatalError("override") } func generateLineDrawer(offset: CGFloat) -> ChartLineDrawer { fatalError("override") } func generateAxisTitleLabelsDrawers(offset: CGFloat) -> [ChartLabelDrawer] { fatalError("override") } /// Generates label drawers to be displayed on the screen. Calls generateDirectLabelDrawers to generate labels and passes result to an optional conflict solver, which maps the labels array to a new one such that the conflicts are solved. If there's no conflict solver returns the drawers unmodified. func generateLabelDrawers(offset: CGFloat) -> [ChartAxisValueLabelDrawers] { let directLabelDrawers = generateDirectLabelDrawers(offset: offset) return labelsConflictSolver.map{$0.solveConflicts(directLabelDrawers)} ?? directLabelDrawers } /// Generates label drawers which correspond directly to axis values. No conflict solving. func generateDirectLabelDrawers(offset: CGFloat) -> [ChartAxisValueLabelDrawers] { fatalError("override") } open func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) { fatalError("override") } open func zoom(_ scaleX: CGFloat, scaleY: CGFloat, centerX: CGFloat, centerY: CGFloat) { fatalError("override") } open func pan(_ deltaX: CGFloat, deltaY: CGFloat) { fatalError("override") } open func handlePanStart(_ location: CGPoint) {} open func handlePanStart() {} open func handlePanFinish() {} open func handleZoomFinish() {} open func handlePanEnd() {} open func handleZoomEnd() {} open func copy(_ axis: ChartAxis? = nil, offset: CGFloat? = nil, valuesGenerator: ChartAxisValuesGenerator? = nil, labelsGenerator: ChartAxisLabelsGenerator? = nil, axisTitleLabels: [ChartAxisLabel]? = nil, settings: ChartAxisSettings? = nil, labelsConflictSolver: ChartAxisLabelsConflictSolver? = nil, labelSpaceReservationMode: AxisLabelsSpaceReservationMode? = nil, clipContents: Bool? = nil) -> ChartAxisLayerDefault { return type(of: self).init( axis: axis ?? self.axis, offset: offset ?? self.offset, valuesGenerator: valuesGenerator ?? self.valuesGenerator, labelsGenerator: labelsGenerator ?? self.labelsGenerator, axisTitleLabels: axisTitleLabels ?? self.axisTitleLabels, settings: settings ?? self.settings, labelsConflictSolver: labelsConflictSolver ?? self.labelsConflictSolver, labelSpaceReservationMode: labelSpaceReservationMode ?? self.labelSpaceReservationMode, clipContents: clipContents ?? self.clipContents ) } open func handleGlobalTap(_ location: CGPoint) -> Any? { guard let tapSettings = tapSettings else {return nil} if visibleFrame.contains(location) { if let tappedLabelDrawers = (labelDrawers.filter{$0.drawers.contains{drawer in drawer.frame.insetBy(dx: -tapSettings.expandArea.width, dy: -tapSettings.expandArea.height).contains(location)}}).first { tapSettings.handler?((valueLabelDrawers: tappedLabelDrawers, layer: self)) return tappedLabelDrawers } else { return nil } } else { return nil } } open func processZoom(deltaX: CGFloat, deltaY: CGFloat, anchorX: CGFloat, anchorY: CGFloat) -> Bool { return false } open func processPan(location: CGPoint, deltaX: CGFloat, deltaY: CGFloat, isGesture: Bool, isDeceleration: Bool) -> Bool { return false } }
apache-2.0
f3abf1b76d45438ce43c7fe2f50d718e
37.319899
426
0.61717
5.375618
false
false
false
false
devpunk/cartesian
cartesian/View/DrawProject/Menu/VDrawProjectMenuNodes.swift
1
4301
import UIKit class VDrawProjectMenuNodes:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { private var model:MDrawProjectMenuNodes? private weak var controller:CDrawProject! private weak var collectionView:VCollection! private let kRows:CGFloat = 2 private let kDeselectTime:TimeInterval = 0.2 init(controller:CDrawProject) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller let collectionView:VCollection = VCollection() collectionView.alwaysBounceHorizontal = true collectionView.dataSource = self collectionView.delegate = self collectionView.registerCell(cell:VDrawProjectMenuNodesCell.self) self.collectionView = collectionView if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow { flow.scrollDirection = UICollectionViewScrollDirection.horizontal } addSubview(collectionView) NSLayoutConstraint.equals( view:collectionView, toView:self) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow { let height:CGFloat = bounds.maxY let cellSide:CGFloat = height / kRows let cellSize:CGSize = CGSize(width:cellSide, height:cellSide) flow.itemSize = cellSize } super.layoutSubviews() } //MARK: private private func modelAtIndex(index:IndexPath) -> MDrawProjectMenuNodesItem { let item:MDrawProjectMenuNodesItem = model!.items[index.item] return item } //MARK: public func refresh() { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.model = MDrawProjectMenuNodes() DispatchQueue.main.async { [weak self] in self?.collectionView.reloadData() } } } //MARK: collectionView delegate func numberOfSections(in collectionView:UICollectionView) -> Int { return 1 } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { guard let count:Int = model?.items.count else { return 0 } return count } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MDrawProjectMenuNodesItem = modelAtIndex(index:indexPath) let cell:VDrawProjectMenuNodesCell = collectionView.dequeueReusableCell( withReuseIdentifier: VDrawProjectMenuNodesCell.reusableIdentifier, for:indexPath) as! VDrawProjectMenuNodesCell cell.config(model:item) return cell } func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) { collectionView.isUserInteractionEnabled = false let item:MDrawProjectMenuNodesItem = modelAtIndex(index:indexPath) DispatchQueue.main.asyncAfter( deadline:DispatchTime.now() + kDeselectTime) { [weak collectionView] in collectionView?.selectItem( at:nil, animated:true, scrollPosition:UICollectionViewScrollPosition()) collectionView?.isUserInteractionEnabled = true } if item.available { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.controller.addNode( entityName:item.entityName) } } else { controller.viewProject.showStore(purchase:item) } } }
mit
12ff6f2ec78ea0775dd1a8aaa99d3db3
28.458904
124
0.610556
5.891781
false
false
false
false
iWeslie/Ant
Ant/Ant/LunTan/Detials/Controller/CarServiceDVC.swift
1
8539
// // CarServiceDVC.swift // Ant // // Created by Weslie on 2017/8/4. // Copyright © 2017年 LiuXinQiang. All rights reserved. // import UIKit class CarServiceDVC: UIViewController, UITableViewDelegate, UITableViewDataSource { var tableView: UITableView? var modelInfo: LunTanDetialModel? override func viewDidLoad() { super.viewDidLoad() loadDetialTableView() let view = Menu() self.tabBarController?.tabBar.isHidden = true view.frame = CGRect(x: 0, y: screenHeight - 124, width: screenWidth, height: 60) self.view.addSubview(view) } func loadDetialTableView() { let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 60) self.tableView = UITableView(frame: frame, style: .grouped) self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.backgroundColor = UIColor.init(white: 0.9, alpha: 1) self.tableView?.separatorStyle = .singleLine tableView?.register(UINib(nibName: "CarServiceBasicInfo", bundle: nil), forCellReuseIdentifier: "carServiceBasicInfo") tableView?.register(UINib(nibName: "CarServiceDetial", bundle: nil), forCellReuseIdentifier: "carServiceDetial") tableView?.register(UINib(nibName: "LocationInfo", bundle: nil), forCellReuseIdentifier: "locationInfo") tableView?.register(UINib(nibName: "DetialControduction", bundle: nil), forCellReuseIdentifier: "detialControduction") tableView?.register(UINib(nibName: "ConnactOptions", bundle: nil), forCellReuseIdentifier: "connactOptions") tableView?.register(UINib(nibName: "MessageHeader", bundle: nil), forCellReuseIdentifier: "messageHeader") tableView?.register(UINib(nibName: "MessagesCell", bundle: nil), forCellReuseIdentifier: "messagesCell") tableView?.separatorStyle = .singleLine self.view.addSubview(tableView!) } func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 3 case 2: return 5 case 4: return 10 default: return 1 } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { switch section { case 0: let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width * 0.6) let urls = [ "http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVHOV0AI20009.jpg", "http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVIJ30AI20009.png", "http://img5.cache.netease.com/photo/0009/2016-05-27/BO1HVLIM0AI20009.jpg", "http://img6.cache.netease.com/photo/0009/2016-05-27/BO1HVJCD0AI20009.jpg", "http://img2.cache.netease.com/photo/0009/2016-05-27/BO1HVPUT0AI20009.png" ] var urlArray: [URL] = [URL]() for str in urls { let url = URL(string: str) urlArray.append(url!) } return LoopView(images: urlArray, frame: frame, isAutoScroll: true) case 1: let detialHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView detialHeader?.DetialHeaderLabel.text = "详情介绍" return detialHeader case 2: let connactHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView connactHeader?.DetialHeaderLabel.text = "联系人方式" return connactHeader default: return nil } } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if section == 2 { return Bundle.main.loadNibNamed("Share", owner: nil, options: nil)?.first as? UIView } else { return nil } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { switch section { case 0: return UIScreen.main.bounds.width * 0.6 case 1: return 30 case 2: return 30 case 3: return 10 case 4: return 0.00001 default: return 0.00001 } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == 2 { return 140 } else { return 0.00001 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? switch indexPath.section { case 0: switch indexPath.row { case 0: cell = tableView.dequeueReusableCell(withIdentifier: "carServiceBasicInfo") if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! { cell?.separatorInset = UIEdgeInsets.zero } case 1: cell = tableView.dequeueReusableCell(withIdentifier: "carServiceDetial") if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! { cell?.separatorInset = UIEdgeInsets.zero } case 2: cell = tableView.dequeueReusableCell(withIdentifier: "locationInfo") default: break } case 1: cell = tableView.dequeueReusableCell(withIdentifier: "detialControduction") case 2: let connactoptions = tableView.dequeueReusableCell(withIdentifier: "connactOptions") as! ConnactOptions // guard modelInfo.con else { // <#statements#> // } if let contact = modelInfo?.connactDict[indexPath.row] { if let key = contact.first?.key{ connactoptions.con_Ways.text = key } } if let value = modelInfo?.connactDict[indexPath.row].first?.value { connactoptions.con_Detial.text = value } switch modelInfo?.connactDict[indexPath.row].first?.key { case "联系人"?: connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_profile") case "电话"?: connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_phone") case "微信"?: connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_wechat") case "QQ"?: connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_qq") case "邮箱"?: connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_email") default: break } cell = connactoptions if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! { cell?.separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0) } case 3: cell = tableView.dequeueReusableCell(withIdentifier: "messageHeader") case 4: cell = tableView.dequeueReusableCell(withIdentifier: "messagesCell") default: break } return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: switch indexPath.row { case 0: return 60 case 1: return 100 case 2: return 40 default: return 20 } case 1: return detialHeight + 10 case 2: return 50 case 3: return 40 case 4: return 120 default: return 20 } } }
apache-2.0
74d29e637500fda7279886ca35908aca
35.796537
130
0.574235
4.916136
false
false
false
false
leoru/Brainstorage
Brainstorage-iOS/Vendor/PullToRefreshSwift/UIScrollViewExtension.swift
1
1625
// // PullToRefreshConst.swift // PullToRefreshSwift // // Created by Yuji Hato on 12/11/14. // import Foundation import UIKit extension UIScrollView { private var pullToRefreshView: PullToRefreshView? { get { var pullToRefreshView = viewWithTag(PullToRefreshConst.tag) return pullToRefreshView as? PullToRefreshView } } func addPullToRefresh(refreshCompletion :(() -> ())) { let refreshViewFrame = CGRectMake(0, -PullToRefreshConst.height, self.frame.size.width, PullToRefreshConst.height) var refreshView = PullToRefreshView(refreshCompletion: refreshCompletion, frame: refreshViewFrame) refreshView.tag = PullToRefreshConst.tag addSubview(refreshView) } func startPullToRefresh() { pullToRefreshView?.state = .Refreshing } func stopPullToRefresh() { pullToRefreshView?.state = .Normal } // If you want to PullToRefreshView fixed top potision, Please call this function in scrollViewDidScroll func fixedPullToRefreshViewForDidScroll() { if PullToRefreshConst.fixedTop { if self.contentOffset.y < -PullToRefreshConst.height { if var frame = pullToRefreshView?.frame { frame.origin.y = self.contentOffset.y pullToRefreshView?.frame = frame } } else { if var frame = pullToRefreshView?.frame { frame.origin.y = -PullToRefreshConst.height pullToRefreshView?.frame = frame } } } } }
mit
b03679bb6d2fa97885ee039a9cbd8a4e
31.5
122
0.626462
5.642361
false
false
false
false
canatac/SimpleForm
simpleForm/simpleForm/MasterViewController.swift
1
9497
// // MasterViewController.swift // simpleForm // // Created by Can ATAC on 06/07/2015. // Copyright (c) 2015 Can ATAC. All rights reserved. // import UIKit import CoreData class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate { var detailViewController: DetailViewController? = nil var managedObjectContext: NSManagedObjectContext? = nil override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } 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: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController } } 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) as! NSManagedObject // 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. var error: NSError? = nil if !context.save(&error) { // 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. //println("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) as! NSManagedObject 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] as! NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell 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) var error: NSError? = nil if !context.save(&error) { // 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. //println("Unresolved error \(error), \(error.userInfo)") abort() } } } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject 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) let sortDescriptors = [sortDescriptor] 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 var error: NSError? = nil if !_fetchedResultsController!.performFetch(&error) { // 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. //println("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) default: return } } 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
7a8bf1b6a2b747b573841e6526afb111
45.783251
360
0.690218
6.215314
false
false
false
false
evering7/Speak
SourceRSS+CoreDataClass.swift
1
4713
// // SourceRSS+CoreDataClass.swift // iSpeaking // // Created by JianFei Li on 26/04/2017. // Copyright © 2017 JianFei Li. All rights reserved. // import Foundation import CoreData import UIKit @objc(SourceFeedDisk) public class SourceFeedDisk: NSManagedObject { @nonobjc public class func fetchRequest() -> NSFetchRequest<SourceFeedDisk> { return NSFetchRequest<SourceFeedDisk>(entityName: "SourceFeedDisk") } // for coredata use // db 2, feed 9, svr 3, total 14 @NSManaged public var feed_Title: String? @NSManaged public var feed_Language: String? @NSManaged public var feed_URL: String? @NSManaged public var feed_Author: String? @NSManaged public var feed_Tags: String? @NSManaged public var feed_IsRSSorAtom : NSNumber @NSManaged public var svr_Likes: Int64 @NSManaged public var svr_Dislikes: Int64 @NSManaged public var svr_SubscribeCount: Int64 @NSManaged public var db_ID: Int64 @NSManaged public var db_DownloadedXMLFileName: String? @NSManaged public var feed_UpdateTime: NSDate? // @NSManaged public var isLastUpdateSuccess: NSNumber @NSManaged public var feed_IsDownloadSuccess: NSNumber @NSManaged public var feed_DownloadTime: NSDate? var feed_IsRSSorAtomBool: Bool { get { return Bool(feed_IsRSSorAtom) } set { self.feed_IsRSSorAtom = NSNumber(value: newValue)} } var feed_IsDownloadSuccessBool: Bool { get {return Bool(feed_IsDownloadSuccess)} set {self.feed_IsDownloadSuccess = NSNumber(value: newValue)} } func loadSourceFeed_FromDisk_ToMemory() -> SourceFeedMem { let memSourceRSS: SourceFeedMem = SourceFeedMem() memSourceRSS.feed_Title = self.feed_Title! memSourceRSS.feed_Language = self.feed_Language! memSourceRSS.feed_URL = self.feed_URL! memSourceRSS.feed_Author = self.feed_Author! memSourceRSS.feed_Tags = self.feed_Tags! memSourceRSS.feed_IsRSSorAtom = self.feed_IsRSSorAtomBool memSourceRSS.svr_Likes = self.svr_Likes memSourceRSS.svr_Dislikes = self.svr_Dislikes memSourceRSS.svr_SubscribeCount = self.svr_SubscribeCount memSourceRSS.db_ID = self.db_ID memSourceRSS.db_DownloadedXMLFileName = self.db_DownloadedXMLFileName! memSourceRSS.feed_UpdateTime = self.feed_UpdateTime! as Date // indicate the web feed self update time // memSourceRSS.isLastUpdateSuccess = self.isLastUpdateSuccess2 memSourceRSS.feed_IsDownloadSuccess = self.feed_IsDownloadSuccessBool memSourceRSS.feed_DownloadTime = self.feed_DownloadTime! as Date return memSourceRSS } } class SourceFeedMem: NSObject{ // for memory use var feed_Title: String = "" var feed_Language: String = "" var feed_URL: String = "" var feed_Author: String = "no name" var feed_Tags: String = "" var svr_Likes: Int64 = 0 var svr_Dislikes: Int64 = 0 var svr_SubscribeCount: Int64 = 0 var db_ID: Int64 = 0 var db_DownloadedXMLFileName = "" var feed_UpdateTime: Date = Date() // var isLastUpdateSuccess: Bool = false var feed_IsDownloadSuccess: Bool = false var feed_DownloadTime: Date = Date() var feed_IsRSSorAtom : Bool = true // true indicate RSS, false indicate Atom var mem_rssFeed: RSSFeed = RSSFeed() var mem_atomFeed: AtomFeed = AtomFeed() func downloadFeedFile_FromWeb_ToMemory() { // 1. get path of local xml file let tempPath = getRSSxmlFileURLfromLastComponent(lastPathCompo: self.db_DownloadedXMLFileName).path self.feed_IsDownloadSuccess = false if self.db_DownloadedXMLFileName == "" || !isFileExist(fileFullPath: tempPath){ // generate file name,too if the file not exist let strFileURL = getUnusedRandomFeedXmlFileURL() printLog(message: "get unused random rss xml file url \(strFileURL.path)") printLog(message: "last path component \(strFileURL.lastPathComponent)") // 6. use StructSourceRSS, register some info of the file self.db_DownloadedXMLFileName = strFileURL.lastPathComponent } HttpDownloader.loadXMLFileSync(sourceFeed: self, completion: { (path, error) in if error == nil{ printLog(message: "Successfully download to \(path)") self.feed_IsDownloadSuccess = true return } return }) } }
mit
78c2afa488171e92c20a78d54ab955bd
33.394161
110
0.649618
4.184725
false
false
false
false
vfn/Kingfisher
Kingfisher/UIImageView+Kingfisher.swift
2
8077
// // UIImageView+Kingfisher.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2015 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. import Foundation // MARK: - Set Images /** * Set image to use from web. */ public extension UIImageView { /** Set an image with a URL. It will ask for Kingfisher's manager to get the image for the URL. The memory and disk will be searched first. If the manager does not find it, it will try to download the image at this URL and store it for next use. :param: URL The URL of image. :returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL and a placeholder image. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL, a placaholder image and options. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil) } /** Set an image with a URL, a placeholder image, options and completion handler. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: completionHandler Called when the image retrieved and set. :returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler) } /** Set an image with a URL, a placeholder image, options, progress handler and completion handler. :param: URL The URL of image. :param: placeholderImage A placeholder image when retrieving the image at URL. :param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. :param: progressBlock Called when the image downloading progress gets updated. :param: completionHandler Called when the image retrieved and set. :returns: A task represents the retriving process. */ public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, optionsInfo: KingfisherOptionsInfo?, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { image = placeholderImage kf_setWebURL(URL) let task = KingfisherManager.sharedManager.retrieveImageWithURL(URL, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in if let progressBlock = progressBlock { dispatch_async(dispatch_get_main_queue(), { () -> Void in progressBlock(receivedSize: receivedSize, totalSize: totalSize) }) } }, completionHandler: {[weak self] (image, error, cacheType, imageURL) -> () in dispatch_async(dispatch_get_main_queue(), { () -> Void in if let sSelf = self where imageURL == sSelf.kf_webURL && image != nil { sSelf.image = image; } completionHandler?(image: image, error: error, cacheType:cacheType, imageURL: imageURL) }) }) return task } } // MARK: - Associated Object private var lastURLkey: Void? public extension UIImageView { /// Get the image URL binded to this image view. public var kf_webURL: NSURL? { get { return objc_getAssociatedObject(self, &lastURLkey) as? NSURL } } private func kf_setWebURL(URL: NSURL) { objc_setAssociatedObject(self, &lastURLkey, URL, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } // MARK: - Deprecated public extension UIImageView { @availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo: instead.") public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, options: KingfisherOptions) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil) } @availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:completionHandler: instead.") public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, options: KingfisherOptions, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler) } @availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.") public func kf_setImageWithURL(URL: NSURL, placeholderImage: UIImage?, options: KingfisherOptions, progressBlock: DownloadProgressBlock?, completionHandler: CompletionHandler?) -> RetrieveImageTask { return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler) } }
mit
5678086c0b0ed57402373721fcfd94ca
43.872222
176
0.660146
5.317314
false
false
false
false
dreamsxin/swift
test/Interpreter/objc_class_properties_runtime.swift
3
1823
// RUN: rm -rf %t && mkdir -p %t // RUN: %clang -arch x86_64 -mmacosx-version-min=10.11 -isysroot %sdk -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o // RUN: %swiftc_driver -target $(echo '%target-triple' | sed -E -e 's/macosx10.(9|10).*/macosx10.11/') -sdk %sdk -I %S/Inputs/ObjCClasses/ %t/ObjCClasses.o %s -o %t/a.out // RUN: %t/a.out // REQUIRES: OS=macosx // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import StdlibUnittest import ObjCClasses class SwiftClass : ProtoWithClassProperty { static var getCount = 0 static var setCount = 0 private static var _value: CInt = 0 @objc class func reset() { getCount = 0 setCount = 0 _value = 0 } @objc class var value: CInt { get { getCount += 1 return _value } set { setCount += 1 _value = newValue } } @objc class var optionalClassProp: Bool { return true } } class Subclass : ClassWithClassProperty { static var getCount = 0 static var setCount = 0 override class func reset() { getCount = 0 setCount = 0 super.reset() } override class var value: CInt { get { getCount += 1 return super.value } set { setCount += 1 super.value = newValue } } override class var optionalClassProp: Bool { return true } } var ClassProperties = TestSuite("ClassProperties") ClassProperties.test("runtime") .skip(.osxMinorRange(10, 0...10, reason: "not supported on 10.10 or below")) .code { let theClass: AnyObject = SwiftClass.self let prop = class_getProperty(object_getClass(theClass), "value") expectNotEmpty(prop) let nameAsCString = property_getName(prop)! expectNotEmpty(nameAsCString) expectEqual("value", String(cString: nameAsCString)) } runAllTests()
apache-2.0
69ba76eddbed6667f69e5e4bd4ad8781
20.447059
170
0.65277
3.624254
false
true
false
false
chengxianghe/MissGe
MissGe/MissGe/Class/Helper/XHUploadImagesHelper.swift
1
9767
// // XHUploadImagesHelper.swift // MissGe // // Created by chengxianghe on 2017/4/25. // Copyright © 2017年 cn. All rights reserved. // import Foundation import TUNetworking enum XHUploadImageMode: UInt { /** 失败自动重传 */ case retry /** 失败直接忽略 */ case ignore } typealias XHUploadImageCompletion = (_ successImageUrls: [XHUploadImageModel]?, _ failedImages: [XHUploadImageModel]?) -> Void typealias XHUploadImageProgress = (_ totals: NSInteger, _ completions: NSInteger) -> Void class XHUploadImagesHelper: NSObject { //外部参数 var imageArray: [String]! // 需要上传的图片数组 里面存本地文件的地址 var mode = XHUploadImageMode.ignore var completion: XHUploadImageCompletion? var progress: XHUploadImageProgress? var maxTime: TimeInterval = 60.0 // 最长时间限制 默认单张60s // 内部参数 var requestArray = [XHUploadImageRequest]() // 已经发起的请求 var requestReadyArray = [XHUploadImageRequest]() // 准备发起的请求 var resultModelArray = [XHUploadImageModel]() // 请求回来的保存的数据 var maxNum: Int = 3 // 同时最大并发数 默认 kDefaultUploadMaxNum var isEnd = false // 是否已经结束请求 func cancelOneRequest(_ request: XHUploadImageRequest) { request.cancel() } func cancelUploadRequest() { // 先取消 结束回调 NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(endUpload), object: nil) self.isEnd = true for request in self.requestArray { self.cancelOneRequest(request) } self.completion = nil self.progress = nil } func removeRequest(_ request: XHUploadImageRequest) { self.requestArray.remove(at: self.requestArray.index(of: request)!) self.cancelOneRequest(request) if (self.requestReadyArray.count > 0 && self.requestArray.count < self.maxNum) { let req = self.requestReadyArray.first! self.requestArray.append(req) self.startRequest(req) self.requestReadyArray.remove(at: self.requestReadyArray.index(of: req)!) } } func addRequest(_ request: XHUploadImageRequest) { if (self.requestArray.count < self.maxNum) { self.requestArray.append(request) self.startRequest(request) } else { self.requestReadyArray.append(request) } } func startRequest(_ request: XHUploadImageRequest) { // [request cancelRequest]; print("*********正在上传图index:\(request.imageIndex) ....") request.upload(constructingBody: { (formData: AFMultipartFormData) in // if request.imageData != nil { // formData.appendPart(withFileData: request.imageData!, name: "image", fileName: "uploadImg_\(request.imageIndex).gif", mimeType: "image/gif") // } else if request.imagePath != nil { do { try formData.appendPart(withFileURL: URL.init(fileURLWithPath: request.imagePath!), name: "image", fileName: request.name, mimeType: request.isGif ? "image/gif" : "image/jpeg") } catch let error as NSError { print(error) } // } else { // print("上传的图片没有数据imagePath、imageData不可都为nil") // } }, progress: { (progress) in print("progressView: \(progress.fractionCompleted)") }, success: { (baseRequest, responseObject) in print("上传成功"); self.checkResult(request) }) { (baseRequest, error) in print("上传失败:\(error.localizedDescription)"); self.checkResult(request) } } open func uploadImages(images: [String], uploadMode: XHUploadImageMode, progress: XHUploadImageProgress?, completion: XHUploadImageCompletion?) { self.uploadImages(images: images, uploadMode: uploadMode, maxTime: TimeInterval(images.count * 60), progress: progress, completion: completion) } open func uploadImages(images: [String], uploadMode: XHUploadImageMode, maxTime: TimeInterval, progress: XHUploadImageProgress?, completion: XHUploadImageCompletion?) { self.requestArray.removeAll() self.requestReadyArray.removeAll() self.resultModelArray.removeAll() self.completion = completion; self.progress = progress; self.mode = uploadMode; self.imageArray = images; self.maxTime = maxTime; self.isEnd = false; // TODO: 根据网络环境 决定 同时上传数量 self.maxNum = 3; // 定时回调endUpload self.perform(#selector(endUpload), with: nil, afterDelay: maxTime) var i = 0 for str in images { let request = XHUploadImageRequest.init() request.imagePath = str request.imageIndex = i request.name = (str as NSString).lastPathComponent request.isGif = (str as NSString).pathExtension.uppercased() == "GIF" self.addRequest(request) i = i + 1 } // 先回调一下progress self.progress?(self.imageArray.count, self.resultModelArray.count); } func checkResult(_ request: XHUploadImageRequest) { if (self.isEnd) { return; } if (self.mode == .retry && request.resultImageUrl == nil) { // 失败自动重传 self.startRequest(request) return; } else { let model = XHUploadImageModel.init() model.imageIndex = request.imageIndex; model.imagePath = request.imagePath; model.resultImageUrl = request.resultImageUrl; model.resultImageId = request.resultImageId; self.resultModelArray.append(model) self.removeRequest(request) } // 进度回调 self.progress?(self.imageArray.count, self.resultModelArray.count); if (self.resultModelArray.count == self.imageArray.count) { self.endUpload() } } @objc func endUpload() { // 全部完成 NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(endUpload), object: nil) // 排序 self.resultModelArray.sort { (obj1, obj2) -> Bool in // 从小到大 return obj1.imageIndex > obj2.imageIndex; } var successImages = [XHUploadImageModel]() var failedImages = [XHUploadImageModel]() for model in resultModelArray { if (model.resultImageUrl != nil) { successImages.append(model) } else { failedImages.append(model) } } self.completion?(successImages,failedImages); self.cancelUploadRequest() } } //mark: - Class: GMBUploadImageModel class XHUploadImageModel: NSObject { var imageIndex: Int = 0 var imagePath: String! var resultImageUrl: String? // 接口返回的 图片地址 var resultImageId: String? // 接口返回的 图片id } /// imageData和imagePath不可都为nil class XHUploadImageRequest: TUUploadRequest { var imageIndex: Int = 0 var isGif: Bool = false var name: String = "" var imagePath: String? // 上传的普通图片路径 // var imageData: Data? // 上传的gif图片data var resultImageUrl: String? // 接口返回的 图片地址 var resultImageId: String? // 接口返回的 图片id override func requestUrl() -> String? { let str = "http://t.gexiaojie.com/api.php?&output=json&_app_key=f722d367b8a96655c4f3365739d38d85&_app_secret=30248115015ec6c79d3bed2915f9e4cc&c=upload&a=postUpload&token=" return str.appending(MLNetConfig.shareInstance.token) } // 请求成功后返回的参数 override func requestHandleResult() { if(self.responseObject == nil) { return ; } /** { "result":"200", "msg":"\u56fe\u50cf\u4e0a\u4f20\u6210\u529f", "content": { "image_name":"uploadImg_0.png", "url":"http:\/\/img.gexiaojie.com\/post\/2016\/0718\/160718100723P003873V86.png", "image_id":25339} } } */ guard let result = self.responseObject as? [String:Any] else { return } guard let temp = result["content"] as? [String:Any] else { return } if (temp["url"] != nil) { self.resultImageUrl = temp["url"] as? String; if let tempImageId = temp["image_id"] as? Int { self.resultImageId = "\(tempImageId)" } else if let tempImageId = temp["image_id"] as? String { self.resultImageId = tempImageId } print("*********上传图index:\(self.imageIndex) 成功!:\(String(describing: self.resultImageUrl))(id:\(String(describing: self.resultImageId))))") // print("*********上传图index:%ld 成功!:%@(id:%d)", (long)self.imageIndex, self.resultImageUrl, (int)self.resultImageId); } else { print("*********上传图index:\(self.imageIndex) 失败!:\(String(describing: self.imagePath))") } } }
mit
64a307d0783185dc3f8484c68c0f9415
32.738182
196
0.582776
4.317357
false
false
false
false
emilstahl/swift
test/Serialization/search-paths-relative.swift
20
1514
// RUN: rm -rf %t && mkdir -p %t/secret // RUN: %target-swift-frontend -emit-module -o %t/secret %S/Inputs/struct_with_operators.swift // RUN: mkdir -p %t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule/ // RUN: %target-swift-frontend -emit-module -o %t/Frameworks/has_alias.framework/Modules/has_alias.swiftmodule/%target-swiftmodule-name %S/Inputs/alias.swift -module-name has_alias // RUN: cd %t/secret && %target-swiftc_driver -emit-module -o %t/has_xref.swiftmodule -I . -F ../Frameworks -parse-as-library %S/Inputs/has_xref.swift %S/../Inputs/empty.swift -Xfrontend -serialize-debugging-options -Xcc -DDUMMY // RUN: %target-swift-frontend %s -parse -I %t // Check the actual serialized search paths. // RUN: llvm-bcanalyzer -dump %t/has_xref.swiftmodule > %t/has_xref.swiftmodule.txt // RUN: FileCheck %s < %t/has_xref.swiftmodule.txt // RUN: FileCheck -check-prefix=NEGATIVE %s < %t/has_xref.swiftmodule.txt // XFAIL: linux import has_xref numeric(42) // CHECK-LABEL: <OPTIONS_BLOCK // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-working-directory' // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '{{.+}}/secret' // CHECK: <XCC abbrevid={{[0-9]+}}/> blob data = '-DDUMMY' // CHECK: </OPTIONS_BLOCK> // CHECK-LABEL: <INPUT_BLOCK // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=1/> blob data = '{{.+}}/secret/../Frameworks' // CHECK: <SEARCH_PATH abbrevid={{[0-9]+}} op0=0/> blob data = '{{.+}}/secret/.' // CHECK: </INPUT_BLOCK> // NEGATIVE-NOT: '.' // NEGATIVE-NOT: '../Frameworks'
apache-2.0
e76aeef29c7895bb28168227802047d7
46.3125
228
0.673052
2.939806
false
false
false
false
MoathOthman/MOHUD
Demo/MOHUDDemo/ViewController.swift
1
2895
// // ViewController.swift // MOHUDDemo // // Created by Moath_Othman on 9/21/15. // Copyright © 2015 Moba. All rights reserved. // import UIKit //import MOHUD class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showDefault(_ sender: AnyObject) { MOHUD.show() // MOHUD.setBlurStyle(.Light) MOHUD.hideAfter(3) } @IBAction func showWithCancelAndContinue(_ sender: AnyObject) { MOHUD.show(true) MOHUD.setBlurStyle(.dark) MOHUD.onCancel = { debugPrint("User Canceled") } MOHUD.onContinoue = { debugPrint("User want to contniue without the progress indicator ") } } @IBAction func showWithStatus(_ sender: AnyObject) { MOHUD.showWithStatus("Processing") MOHUD.hideAfter(3) } @IBAction func showSuccess(_ sender: AnyObject) { MOHUD.showSuccess("You Made it so now you can fly") } @IBAction func showSubtitle(_ sender: AnyObject) { MOHUD.showSubtitle(title: "Connection", subtitle: "Please Wait") MOHUD.hideAfter(3) } @IBAction func showFailure(_ sender: AnyObject) { MOHUD.showWithError("Failed :(") } @IBOutlet weak var showFailure: UIButton! } @IBDesignable class GradientView: UIView { override func draw(_ rect: CGRect) { //2 - get the current context let startColor = UIColor ( red: 0.1216, green: 0.1294, blue: 0.1412, alpha: 1.0 ) let endColor = UIColor ( red: 0.4745, green: 0.7412, blue: 0.8353, alpha: 1.0 ) let context = UIGraphicsGetCurrentContext() let colors = [startColor.cgColor, endColor.cgColor] //3 - set up the color space let colorSpace = CGColorSpaceCreateDeviceRGB() //4 - set up the color stops let colorLocations:[CGFloat] = [0.0, 1.0] //5 - create the gradient let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: colorLocations) //6 - draw the gradient let startPoint = CGPoint.zero let endPoint = CGPoint(x:self.bounds.width , y:self.bounds.height) context?.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0)) } }
mit
4a6edfdc17a15d77aa484c020d392833
31.155556
89
0.581894
4.579114
false
false
false
false
JamieScanlon/AugmentKit
AugmentKit/Renderer/Render Modules/AnchorsRenderModule.swift
1
36454
// // AnchorsRenderModule.swift // AugmentKit // // MIT License // // Copyright (c) 2018 JamieScanlon // // 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 ARKit import AugmentKitShader import MetalKit class AnchorsRenderModule: RenderModule, SkinningModule { static var identifier = "AnchorsRenderModule" // // Setup // var moduleIdentifier: String { return AnchorsRenderModule.identifier } var renderLayer: Int { return 11 } var state: ShaderModuleState = .uninitialized var sharedModuleIdentifiers: [String]? = [SharedBuffersRenderModule.identifier] var renderDistance: Double = 500 var errors = [AKError]() // The number of anchor instances to render private(set) var anchorInstanceCount: Int = 0 func initializeBuffers(withDevice aDevice: MTLDevice, maxInFlightFrames: Int, maxInstances: Int) { guard device == nil else { return } state = .initializing device = aDevice // Calculate our uniform buffer sizes. We allocate `maxInFlightFrames` instances for uniform // storage in a single buffer. This allows us to update uniforms in a ring (i.e. triple // buffer the uniforms) so that the GPU reads from one slot in the ring wil the CPU writes // to another. Anchor uniforms should be specified with a max instance count for instancing. // Also uniform storage must be aligned (to 256 bytes) to meet the requirements to be an // argument in the constant address space of our shading functions. let materialUniformBufferSize = RenderModuleConstants.alignedMaterialSize * maxInFlightFrames let jointTransformBufferSize = Constants.alignedJointTransform * Constants.maxJointCount * maxInFlightFrames let effectsUniformBufferSize = Constants.alignedEffectsUniformSize * maxInFlightFrames let environmentUniformBufferSize = Constants.alignedEnvironmentUniformSize * maxInFlightFrames // Create and allocate our uniform buffer objects. Indicate shared storage so that both the // CPU can access the buffer materialUniformBuffer = device?.makeBuffer(length: materialUniformBufferSize, options: .storageModeShared) materialUniformBuffer?.label = "Material Uniform Buffer" jointTransformBuffer = device?.makeBuffer(length: jointTransformBufferSize, options: []) jointTransformBuffer?.label = "Joint Transform Buffer" effectsUniformBuffer = device?.makeBuffer(length: effectsUniformBufferSize, options: .storageModeShared) effectsUniformBuffer?.label = "Effects Uniform Buffer" environmentUniformBuffer = device?.makeBuffer(length: environmentUniformBufferSize, options: .storageModeShared) environmentUniformBuffer?.label = "Environment Uniform Buffer" geometricEntities = [] } func loadAssets(forGeometricEntities theGeometricEntities: [AKGeometricEntity], fromModelProvider modelProvider: ModelProvider?, textureLoader aTextureLoader: MTKTextureLoader, completion: (() -> Void)) { guard let modelProvider = modelProvider else { print("Serious Error - Model Provider not found.") let underlyingError = NSError(domain: AKErrorDomain, code: AKErrorCodeModelProviderNotFound, userInfo: nil) let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: moduleIdentifier, underlyingError: underlyingError)))) recordNewError(newError) completion() return } textureLoader = aTextureLoader geometricEntities.append(contentsOf: theGeometricEntities) // // Create and load our models // var numModels = theGeometricEntities.count // Load the default model modelProvider.loadAsset(forObjectType: "AnyAnchor", identifier: nil) { [weak self] asset in guard let asset = asset else { print("Warning (AnchorsRenderModule) - Failed to get a MDLAsset for type \"AnyAnchor\") from the modelProvider. Aborting the render phase.") let newError = AKError.warning(.modelError(.modelNotFound(ModelErrorInfo(type: "AnyAnchor")))) recordNewError(newError) completion() return } self?.modelAssetsByUUID[generalUUID] = asset if numModels == 0 { completion() } } // Load the per-geometry models for geometricEntity in theGeometricEntities { if let identifier = geometricEntity.identifier { modelProvider.loadAsset(forObjectType: "AnyAnchor", identifier: identifier) { [weak self] asset in guard let asset = asset else { print("Warning (AnchorsRenderModule) - Failed to get a MDLAsset for type \"AnyAnchor\") with identifier \(identifier) from the modelProvider. Aborting the render phase.") let newError = AKError.warning(.modelError(.modelNotFound(ModelErrorInfo(type: "AnyAnchor", identifier: identifier)))) recordNewError(newError) completion() return } self?.modelAssetsByUUID[identifier] = asset self?.shaderPreferenceByUUID[identifier] = geometricEntity.shaderPreference } } numModels -= 1 if numModels <= 0 { completion() } } } func loadPipeline(withModuleEntities: [AKEntity], metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, modelManager: ModelManager, renderPass: RenderPass? = nil, numQualityLevels: Int = 1, completion: (([DrawCallGroup]) -> Void)? = nil) { guard let device = device else { print("Serious Error - device not found") let underlyingError = NSError(domain: AKErrorDomain, code: AKErrorCodeDeviceNotFound, userInfo: nil) let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: moduleIdentifier, underlyingError: underlyingError)))) recordNewError(newError) state = .uninitialized completion?([]) return } // Make sure there is at least one general purpose model guard modelAssetsByUUID[generalUUID] != nil else { print("Warning (AnchorsRenderModule) - Anchor Model was not found. Aborting the render phase.") let underlyingError = NSError(domain: AKErrorDomain, code: AKErrorCodeModelNotFound, userInfo: nil) let newError = AKError.warning(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: moduleIdentifier, underlyingError: underlyingError)))) recordNewError(newError) state = .ready completion?([]) return } var drawCallGroups = [DrawCallGroup]() // Get a list of uuids let filteredGeometryUUIDs = geometricEntities.compactMap({$0.identifier}) // filter the `modelAssetsByUUID` by the model asses contained in the list of uuids let filteredModelsByUUID = modelAssetsByUUID.filter { (uuid, asset) in filteredGeometryUUIDs.contains(uuid) } let total = filteredModelsByUUID.count var count = 0 // Create a draw call group for every model asset. Each model asset may have multiple instances. for item in filteredModelsByUUID { guard let geometricEntity = geometricEntities.first(where: {$0.identifier == item.key}) else { continue } let uuid = item.key let mdlAsset = item.value let shaderPreference: ShaderPreference = { if let prefernece = shaderPreferenceByUUID[uuid] { return prefernece } else { return .pbr } }() modelManager.meshGPUData(for: mdlAsset, shaderPreference: shaderPreference) { [weak self] (meshGPUData, cacheKey) in // Create a draw call group that contins all of the individual draw calls for this model if let meshGPUData = meshGPUData, let drawCallGroup = self?.createDrawCallGroup(forUUID: uuid, withMetalLibrary: metalLibrary, renderDestination: renderDestination, renderPass: renderPass, meshGPUData: meshGPUData, geometricEntity: geometricEntity, numQualityLevels: numQualityLevels) { drawCallGroup.moduleIdentifier = AnchorsRenderModule.identifier drawCallGroups.append(drawCallGroup) } count += 1 if count == total { // Because there must be a deterministic way to order the draw calls so the draw call groups are sorted by UUID. drawCallGroups.sort { $0.uuid.uuidString < $1.uuid.uuidString } self?.state = .ready completion?(drawCallGroups) } } } } // // Per Frame Updates // func updateBufferState(withBufferIndex theBufferIndex: Int) { bufferIndex = theBufferIndex materialUniformBufferOffset = RenderModuleConstants.alignedMaterialSize * bufferIndex jointTransformBufferOffset = Constants.alignedJointTransform * Constants.maxJointCount * bufferIndex effectsUniformBufferOffset = Constants.alignedEffectsUniformSize * bufferIndex environmentUniformBufferOffset = Constants.alignedEnvironmentUniformSize * bufferIndex materialUniformBufferAddress = materialUniformBuffer?.contents().advanced(by: materialUniformBufferOffset) jointTransformBufferAddress = jointTransformBuffer?.contents().advanced(by: jointTransformBufferOffset) effectsUniformBufferAddress = effectsUniformBuffer?.contents().advanced(by: effectsUniformBufferOffset) environmentUniformBufferAddress = environmentUniformBuffer?.contents().advanced(by: environmentUniformBufferOffset) } func updateBuffers(withModuleEntities moduleEntities: [AKEntity], cameraProperties: CameraProperties, environmentProperties: EnvironmentProperties, shadowProperties: ShadowProperties, argumentBufferProperties theArgumentBufferProperties: ArgumentBufferProperties, forRenderPass renderPass: RenderPass) { argumentBufferProperties = theArgumentBufferProperties let anchors: [AKAugmentedAnchor] = moduleEntities.compactMap({ if let anAnchor = $0 as? AKAugmentedAnchor { return anAnchor } else { return nil } }) // Update the anchor uniform buffer with transforms of the current frame's anchors anchorInstanceCount = 0 var anchorsByUUID = [UUID: [AKAugmentedAnchor]]() environmentTextureByUUID = [:] // // Gather the UUID's // for akAnchor in anchors { guard let arAnchor = akAnchor.arAnchor else { continue } // Ignore anchors that are beyond the renderDistance let distance = anchorDistance(withTransform: arAnchor.transform, cameraProperties: cameraProperties) guard Double(distance) < renderDistance else { continue } anchorInstanceCount += 1 if anchorInstanceCount > Constants.maxAnchorInstanceCount { anchorInstanceCount = Constants.maxAnchorInstanceCount break } // If an anchor is passed in that does not seem to be associated with any model, assign it the `generalUUD` so it will be rendered with a general model let uuid: UUID = { if modelAssetsByUUID[arAnchor.identifier] != nil { return arAnchor.identifier } else { return generalUUID } }() // collect all of the anchors by uuid. A uuid can be associated with multiple anchors (like the general uuid). if let currentAnchors = anchorsByUUID[uuid] { var mutableCurrentAnchors = currentAnchors mutableCurrentAnchors.append(akAnchor) anchorsByUUID[uuid] = mutableCurrentAnchors } else { anchorsByUUID[uuid] = [akAnchor] } // See if this anchor is associated with an environment anchor. An environment anchor applies to a region of space which may contain several anchors. The environment anchor that has the smallest volume is assumed to be more localized and therefore be the best for for this anchor let environmentProbes: [AREnvironmentProbeAnchor] = environmentProperties.environmentAnchorsWithReatedAnchors.compactMap{ if $0.value.contains(arAnchor.identifier) { return $0.key } else { return nil } } if environmentProbes.count > 1 { var bestEnvironmentProbe: AREnvironmentProbeAnchor? environmentProbes.forEach { if let theBestEnvironmentProbe = bestEnvironmentProbe { let existingVolume = AKCube(position: AKVector(x: theBestEnvironmentProbe.transform.columns.3.x, y: theBestEnvironmentProbe.transform.columns.3.y, z: theBestEnvironmentProbe.transform.columns.3.z), extent: AKVector(theBestEnvironmentProbe.extent)).volume() let newVolume = AKCube(position: AKVector(x: $0.transform.columns.3.x, y: $0.transform.columns.3.y, z: $0.transform.columns.3.z), extent: AKVector($0.extent)).volume() if newVolume < existingVolume { bestEnvironmentProbe = $0 } } else { bestEnvironmentProbe = $0 } } if let environmentProbeAnchor = bestEnvironmentProbe, let texture = environmentProbeAnchor.environmentTexture { environmentTextureByUUID[uuid] = texture } } else { if let environmentProbeAnchor = environmentProbes.first, let texture = environmentProbeAnchor.environmentTexture { environmentTextureByUUID[uuid] = texture } } } // // Update Textures // // // Update the Buffers // var anchorMeshIndex = 0 for drawCallGroup in renderPass.drawCallGroups { let uuid = drawCallGroup.uuid for drawCall in drawCallGroup.drawCalls { let akAnchors = anchorsByUUID[uuid] ?? [] anchorCountByUUID[uuid] = akAnchors.count guard let drawData = drawCall.drawData else { continue } for akAnchor in akAnchors { // // Update skeletons // updateSkeletonAnimation(from: drawData, frameNumber: cameraProperties.currentFrame, frameRate: cameraProperties.frameRate) // // Update Environment // environmentData = { var myEnvironmentData = EnvironmentData() if let texture = environmentTextureByUUID[uuid] { myEnvironmentData.environmentTexture = texture myEnvironmentData.hasEnvironmentMap = true return myEnvironmentData } else { myEnvironmentData.hasEnvironmentMap = false } return myEnvironmentData }() let environmentUniforms = environmentUniformBufferAddress?.assumingMemoryBound(to: EnvironmentUniforms.self).advanced(by: anchorMeshIndex) // Set up lighting for the scene using the ambient intensity if provided let ambientIntensity: Float = { if let lightEstimate = environmentProperties.lightEstimate { return Float(lightEstimate.ambientIntensity) / 1000.0 } else { return 1 } }() let ambientLightColor: SIMD3<Float> = { if let lightEstimate = environmentProperties.lightEstimate { return getRGB(from: lightEstimate.ambientColorTemperature) } else { return SIMD3<Float>(0.5, 0.5, 0.5) } }() environmentUniforms?.pointee.ambientLightIntensity = ambientIntensity environmentUniforms?.pointee.ambientLightColor = ambientLightColor// * ambientIntensity var directionalLightDirection : SIMD3<Float> = environmentProperties.directionalLightDirection directionalLightDirection = simd_normalize(directionalLightDirection) environmentUniforms?.pointee.directionalLightDirection = directionalLightDirection let directionalLightColor: SIMD3<Float> = SIMD3<Float>(0.6, 0.6, 0.6) environmentUniforms?.pointee.directionalLightColor = directionalLightColor// * ambientIntensity environmentUniforms?.pointee.directionalLightMVP = environmentProperties.directionalLightMVP environmentUniforms?.pointee.shadowMVPTransformMatrix = shadowProperties.shadowMVPTransformMatrix if environmentData?.hasEnvironmentMap == true { environmentUniforms?.pointee.hasEnvironmentMap = 1 } else { environmentUniforms?.pointee.hasEnvironmentMap = 0 } // // Update Effects uniform // let effectsUniforms = effectsUniformBufferAddress?.assumingMemoryBound(to: AnchorEffectsUniforms.self).advanced(by: anchorMeshIndex) var hasSetAlpha = false var hasSetGlow = false var hasSetTint = false var hasSetScale = false if let effects = akAnchor.effects { let currentTime: TimeInterval = Double(cameraProperties.currentFrame) / cameraProperties.frameRate for effect in effects { switch effect.effectType { case .alpha: if let value = effect.value(forTime: currentTime) as? Float { effectsUniforms?.pointee.alpha = value hasSetAlpha = true } case .glow: if let value = effect.value(forTime: currentTime) as? Float { effectsUniforms?.pointee.glow = value hasSetGlow = true } case .tint: if let value = effect.value(forTime: currentTime) as? SIMD3<Float> { effectsUniforms?.pointee.tint = value hasSetTint = true } case .scale: if let value = effect.value(forTime: currentTime) as? Float { let scaleMatrix = matrix_identity_float4x4 effectsUniforms?.pointee.scale = scaleMatrix.scale(x: value, y: value, z: value) hasSetScale = true } } } } if !hasSetAlpha { effectsUniforms?.pointee.alpha = 1 } if !hasSetGlow { effectsUniforms?.pointee.glow = 0 } if !hasSetTint { effectsUniforms?.pointee.tint = SIMD3<Float>(1,1,1) } if !hasSetScale { effectsUniforms?.pointee.scale = matrix_identity_float4x4 } anchorMeshIndex += 1 } } } // // Update the shadow map // shadowMap = shadowProperties.shadowMap } func draw(withRenderPass renderPass: RenderPass, sharedModules: [SharedRenderModule]?) { guard anchorInstanceCount > 0 else { return } guard let renderEncoder = renderPass.renderCommandEncoder else { return } // Push a debug group allowing us to identify render commands in the GPU Frame Capture tool renderEncoder.pushDebugGroup("Draw Anchors") if let argumentBufferProperties = argumentBufferProperties, let vertexArgumentBuffer = argumentBufferProperties.vertexArgumentBuffer { renderEncoder.pushDebugGroup("Argument Buffer") renderEncoder.setVertexBuffer(vertexArgumentBuffer, offset: argumentBufferProperties.vertexArgumentBufferOffset(forFrame: bufferIndex), index: Int(kBufferIndexPrecalculationOutputBuffer.rawValue)) renderEncoder.popDebugGroup() } if let environmentUniformBuffer = environmentUniformBuffer, renderPass.usesEnvironment { renderEncoder.pushDebugGroup("Draw Environment Uniforms") if let environmentTexture = environmentData?.environmentTexture, environmentData?.hasEnvironmentMap == true { renderEncoder.setFragmentTexture(environmentTexture, index: Int(kTextureIndexEnvironmentMap.rawValue)) } renderEncoder.setFragmentBuffer(environmentUniformBuffer, offset: environmentUniformBufferOffset, index: Int(kBufferIndexEnvironmentUniforms.rawValue)) renderEncoder.popDebugGroup() } if let effectsBuffer = effectsUniformBuffer, renderPass.usesEffects { renderEncoder.pushDebugGroup("Draw Effects Uniforms") renderEncoder.setFragmentBuffer(effectsBuffer, offset: effectsUniformBufferOffset, index: Int(kBufferIndexAnchorEffectsUniforms.rawValue)) renderEncoder.popDebugGroup() } if let shadowMap = shadowMap, renderPass.usesShadows { renderEncoder.pushDebugGroup("Attach Shadow Buffer") renderEncoder.setFragmentTexture(shadowMap, index: Int(kTextureIndexShadowMap.rawValue)) renderEncoder.popDebugGroup() } var drawCallGroupIndex: Int32 = 0 var drawCallIndex: Int32 = 0 var baseIndex = 0 for drawCallGroup in renderPass.drawCallGroups { guard drawCallGroup.moduleIdentifier == moduleIdentifier else { drawCallIndex += Int32(drawCallGroup.drawCalls.count) drawCallGroupIndex += 1 continue } // Use the render pass filter function to skip draw call groups on an individual basis if let filterFunction = renderPass.drawCallGroupFilterFunction { guard filterFunction(drawCallGroup) else { drawCallIndex += Int32(drawCallGroup.drawCalls.count) drawCallGroupIndex += 1 continue } } let uuid = drawCallGroup.uuid // TODO: remove. I think this should always be 1. Even if draw call groups share geometries, we should only be incrementing the base index once per draw call. The whole idea of sharing geometries is probably misguided anyway let anchorcount = (anchorCountByUUID[uuid] ?? 0) if anchorcount > 1 { print("There are \(anchorcount) geometries sharing this one UUID. This is something to refactor.") } // Geometry Draw Calls. The order of the draw calls in the draw call group determines the order in which they are dispatched to the GPU for rendering. for drawCall in drawCallGroup.drawCalls { guard let drawData = drawCall.drawData else { drawCallIndex += 1 continue } drawCall.prepareDrawCall(withRenderPass: renderPass) if renderPass.usesGeometry { // Set the offset index of the draw call into the argument buffer renderEncoder.setVertexBytes(&drawCallIndex, length: MemoryLayout<Int32>.size, index: Int(kBufferIndexDrawCallIndex.rawValue)) // Set the offset index of the draw call group into the argument buffer renderEncoder.setVertexBytes(&drawCallGroupIndex, length: MemoryLayout<Int32>.size, index: Int(kBufferIndexDrawCallGroupIndex.rawValue)) if renderPass.hasSkeleton { // Set any buffers fed into our render pipeline renderEncoder.setVertexBuffer(jointTransformBuffer, offset: jointTransformBufferOffset, index: Int(kBufferIndexMeshJointTransforms.rawValue)) } } var mutableDrawData = drawData mutableDrawData.instanceCount = anchorcount // Set the mesh's vertex data buffers and draw draw(withDrawData: mutableDrawData, with: renderEncoder, baseIndex: baseIndex, includeGeometry: renderPass.usesGeometry, includeSkeleton: renderPass.hasSkeleton, includeLighting: renderPass.usesLighting) baseIndex += anchorcount drawCallIndex += 1 } drawCallGroupIndex += 1 } renderEncoder.popDebugGroup() } func frameEncodingComplete(renderPasses: [RenderPass]) { // Here it is safe to update textures guard let renderPass = renderPasses.first(where: {$0.name == "Main Render Pass"}) else { return } for drawCallGroup in renderPass.drawCallGroups { let uuid = drawCallGroup.uuid for drawCall in drawCallGroup.drawCalls { guard let drawData = drawCall.drawData else { continue } guard let akAnchor = geometricEntities.first(where: {$0 is AKAugmentedAnchor && $0.identifier == uuid}) else { continue } // // Update Base Color texture // // Currently only supports AugmentedUIViewSurface's with a single submesh if let viewSurface = akAnchor as? AugmentedUIViewSurface, viewSurface.needsColorTextureUpdate, let baseColorTexture = drawData.subData[0].baseColorTexture, drawData.subData.count == 1 { DispatchQueue.main.sync { viewSurface.updateTextureWithCurrentPixelData(baseColorTexture) } } } } } // // Util // func recordNewError(_ akError: AKError) { errors.append(akError) } // MARK: - Private private enum Constants { static let maxAnchorInstanceCount = 256 static let maxJointCount = 100 static let alignedJointTransform = (MemoryLayout<matrix_float4x4>.stride & ~0xFF) + 0x100 static let alignedEffectsUniformSize = ((MemoryLayout<AnchorEffectsUniforms>.stride * Constants.maxAnchorInstanceCount) & ~0xFF) + 0x100 static let alignedEnvironmentUniformSize = ((MemoryLayout<EnvironmentUniforms>.stride * Constants.maxAnchorInstanceCount) & ~0xFF) + 0x100 } private var bufferIndex: Int = 0 private var device: MTLDevice? private var textureLoader: MTKTextureLoader? private var geometricEntities = [AKGeometricEntity]() private var generalUUID = UUID() private var modelAssetsByUUID = [UUID: MDLAsset]() private var shaderPreferenceByUUID = [UUID: ShaderPreference]() private var materialUniformBuffer: MTLBuffer? private var jointTransformBuffer: MTLBuffer? private var effectsUniformBuffer: MTLBuffer? private var environmentUniformBuffer: MTLBuffer? private var environmentData: EnvironmentData? private var shadowMap: MTLTexture? private var argumentBufferProperties: ArgumentBufferProperties? // Offset within materialUniformBuffer to set for the current frame private var materialUniformBufferOffset: Int = 0 // Offset within jointTransformBuffer to set for the current frame private var jointTransformBufferOffset = 0 // Offset within effectsUniformBuffer to set for the current frame private var effectsUniformBufferOffset: Int = 0 // Offset within environmentUniformBuffer to set for the current frame private var environmentUniformBufferOffset: Int = 0 // Addresses to write anchor uniforms to each frame private var materialUniformBufferAddress: UnsafeMutableRawPointer? // Addresses to write jointTransform to each frame private var jointTransformBufferAddress: UnsafeMutableRawPointer? // Addresses to write effects uniforms to each frame private var effectsUniformBufferAddress: UnsafeMutableRawPointer? // Addresses to write environment uniforms to each frame private var environmentUniformBufferAddress: UnsafeMutableRawPointer? // number of frames in the anchor animation by anchor index private var anchorAnimationFrameCount = [Int]() private var anchorCountByUUID = [UUID: Int]() private var environmentTextureByUUID = [UUID: MTLTexture]() private func createDrawCallGroup(forUUID uuid: UUID, withMetalLibrary metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, renderPass: RenderPass?, meshGPUData: MeshGPUData, geometricEntity: AKGeometricEntity, numQualityLevels: Int) -> DrawCallGroup { guard let renderPass = renderPass else { print("Warning - Skipping all draw calls because the render pass is nil.") let underlyingError = NSError(domain: AKErrorDomain, code: AKErrorCodeRenderPassNotFound, userInfo: nil) let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: moduleIdentifier, underlyingError: underlyingError)))) recordNewError(newError) return DrawCallGroup(drawCalls: [], uuid: uuid) } let shaderPreference = meshGPUData.shaderPreference // Create a draw call group containing draw calls. Each draw call is associated with a `DrawData` object in the `MeshGPUData` var drawCalls = [DrawCall]() for drawData in meshGPUData.drawData { let fragmentShaderName: String = { if shaderPreference == .simple { return "anchorGeometryFragmentLightingSimple" } else if shaderPreference == .blinn { return "anchorGeometryFragmentLightingBlinnPhong" } else { return "anchorGeometryFragmentLighting" } }() let vertexShaderName: String = { if drawData.hasSkeleton { return "anchorGeometryVertexTransformSkinned" } else { if drawData.isRaw { return "rawGeometryVertexTransform" } else { return "anchorGeometryVertexTransform" } } }() // The cull mode is set to from because the x geometry is flipped in the shader let drawCall = DrawCall(metalLibrary: metalLibrary, renderPass: renderPass, vertexFunctionName: vertexShaderName, fragmentFunctionName: fragmentShaderName, vertexDescriptor: meshGPUData.vertexDescriptor, cullMode: .front, drawData: drawData, numQualityLevels: numQualityLevels) drawCalls.append(drawCall) } let drawCallGroup = DrawCallGroup(drawCalls: drawCalls, uuid: uuid, generatesShadows: geometricEntity.generatesShadows) return drawCallGroup } private func updateSkeletonAnimation(from drawData: DrawData, frameNumber: UInt, frameRate: Double = 60) { let capacity = Constants.alignedJointTransform * Constants.maxJointCount let boundJointTransformData = jointTransformBufferAddress?.bindMemory(to: matrix_float4x4.self, capacity: capacity) let jointTransformData = UnsafeMutableBufferPointer<matrix_float4x4>(start: boundJointTransformData, count: Constants.maxJointCount) if let skeleton = drawData.skeleton { let keyTimes = skeleton.animations.map{ $0.keyTime } let time = (Double(frameNumber) * 1.0 / frameRate) let keyframeIndex = lowerBoundKeyframeIndex(keyTimes, key: time) ?? 0 let jointTransforms = evaluateJointTransforms(skeletonData: skeleton, keyframeIndex: keyframeIndex) for k in 0..<jointTransforms.count { jointTransformData[k] = jointTransforms[k] } } } }
mit
7b166706e92af282b55d9294d3ab4e06
46.342857
307
0.598343
5.84761
false
false
false
false
britez/sdk-ios
Example/sdk_ios_v2/ViewController.swift
1
2585
// // ViewController.swift // DEC2_sdk_ios // // Created by Ezequiel Apfel on 04/25/2017. // Copyright (c) 2017 Ezequiel Apfel. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { //MARK: Properties @IBOutlet weak var cardNumber: UITextField! @IBOutlet weak var expirationMonth: UITextField! @IBOutlet weak var expirationYear: UITextField! @IBOutlet weak var securityCode: UITextField! @IBOutlet weak var cardHolderName: UITextField! @IBOutlet weak var docType: UITextField! @IBOutlet weak var docNumber: UITextField! @IBOutlet weak var textResult: UILabel! var paymentTokenApi:PaymentsTokenAPI = PaymentsTokenAPI(publicKey: "e9cdb99fff374b5f91da4480c8dca741", isSandbox: true) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. cardNumber.delegate = self expirationMonth.delegate = self expirationYear.delegate = self securityCode.delegate = self cardHolderName.delegate = self docType.delegate = self docNumber.delegate = self } @IBAction func proceedPayment(_ sender: UIButton) { let pti = PaymentTokenInfo() pti.cardNumber = cardNumber.text pti.cardExpirationMonth = expirationMonth.text pti.cardExpirationYear = expirationYear.text pti.cardHolderName = cardHolderName.text pti.securityCode = securityCode.text let holder = CardHolderIdentification() holder.type = docType.text holder.number = docNumber.text pti.cardHolderIdentification = holder self.paymentTokenApi.createPaymentToken(paymentTokenInfo: pti) { (paymentToken, error) in guard error == nil else { if case let ErrorResponse.Error(_, _, dec as ModelError) = error! { self.textResult.text = dec.toString() } return } if let paymentToken = paymentToken { self.textResult.text = paymentToken.toString() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backButtonTapped(_ sender: UIButton) { dismiss(animated: true, completion: nil) } }
mit
5387c4681020fb8badaeb8106fc41fbf
30.144578
123
0.621663
5.232794
false
false
false
false
adrfer/swift
test/DebugInfo/for.swift
1
473
// RUN: %target-swift-frontend -g -emit-ir %s | FileCheck %s // Verify that variables bound in the for statements are in distinct scopes. for var i = 0; i < 3; i += 1 { // CHECK: !DILocalVariable(name: "i", scope: ![[SCOPE1:[0-9]+]] // CHECK: ![[SCOPE1]] = distinct !DILexicalBlock(scope: ![[MAIN:[0-9]+]] } for var i = 0; i < 3; i += 1 { // CHECK: !DILocalVariable(name: "i", scope: ![[SCOPE2:[0-9]+]] // CHECK: ![[SCOPE2]] = distinct !DILexicalBlock(scope: ![[MAIN]] }
apache-2.0
9e36aa97ab4508e58c145666faf6b98f
38.416667
76
0.606765
2.866667
false
false
false
false
itsjingun/govhacknz_mates
Mates/Controllers/MTSFindMatesResultViewController.swift
1
3730
// // MTSFindMatesResultViewController.swift // Mates // // Created by Jingun Lee on 4/07/15. // import UIKit class MTSFindMatesResultViewController: MTSBaseViewController, UITableViewDelegate, UITableViewDataSource { var userProfiles: Array<MTSUserProfile>? // UI Views @IBOutlet weak var viewLoadingContainer: UIView! @IBOutlet weak var tableViewUserProfiles: UITableView! override func viewDidLoad() { super.viewDidLoad() setupViews() loadMates() } private func setupViews() { tableViewUserProfiles.delegate = self tableViewUserProfiles.dataSource = self } private func loadMates() { let userService = MTSUserService() // Find matching users asynchronously. userService.findMatchingUsers( {(userProfiles: Array<MTSUserProfile>) -> () in // On success self.userProfiles = userProfiles self.fadeOutAndHideView(self.viewLoadingContainer, withDuration: 0.5) self.updateViews() }, failure: { (code, error) -> () in // On failure // Show error alert message and pop the view controller. self.showAlertViewWithTitle("Error", message: error, onComplete: { () -> () in self.navigationController?.popViewControllerAnimated(true) }) } ) } private func fadeOutAndHideView(view: UIView!, withDuration: NSTimeInterval) { UIView.animateWithDuration(withDuration, animations: { () -> Void in view.alpha = 0.0 }, completion: { (Bool) -> Void in view.hidden = true }) } private func updateViews() { self.tableViewUserProfiles.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UITableViewDataSource func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let userProfile = userProfiles![indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("userProfileTableViewCell", forIndexPath: indexPath) as? MTSUserProfileTableViewCell // Set name and age. cell!.setNameAndAge(userProfile.username, age: userProfile.age) // Set gender. cell!.setGender(userProfile.genderString) return cell! } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if userProfiles != nil { return userProfiles!.count } return 0 } // MARK: - UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("mateDetailsSegue", sender: self) tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get user profile for selected row. let selectedIndex = self.tableViewUserProfiles.indexPathForSelectedRow()!.row let userProfile = userProfiles![selectedIndex] // Set data in destination controller. if let mateDetailsViewController = segue.destinationViewController as? MTSMateDetailsViewController { mateDetailsViewController.userProfile = userProfile } } }
gpl-2.0
b86262b1f793916b538264b6b07ee3c2
31.155172
147
0.615818
5.720859
false
false
false
false
chenyangcun/SwiftDate
ExampleProject/ExampleProject/ViewController.swift
2
1515
// // ViewController.swift // ExampleProject // // Created by Mark Norgren on 5/21/15. // // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let date = NSDate() _ = date.toString(format: DateFormat.Custom("YYYY-MM-DD")) _ = date+1.day let two_months_ago = date-2.months print(two_months_ago.toLongDateString()) let date_as_utc = date.toUTC() //UTC 时间 let date_as_beijing = date_as_utc.toTimezone("GMT+0800") //北京时间 print(date_as_utc.toLongTimeString()) print(date_as_beijing?.toLongTimeString()) let d = NSDate()-1.hour print(d.year) let date1 = NSDate.date(fromString: "2015-07-26", format: DateFormat.Custom("YYYY-MM-DD")) let date2 = NSDate.date(fromString: "2015-07-27", format: DateFormat.Custom("YYYY-MM-DD")) if date2 > date1 { // TODO something print("Hello") } let abb = d.toRelativeString(abbreviated: true, maxUnits: 3) print("data: \(abb)") // // let w = NSDate()-1.month // print("Prev month: \(w)") // // var w2 = NSDate().add("month",value:-1) // print(date) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
2d52ff7bbcbce9ab63c73fdffb672a60
21.432836
98
0.546241
3.805063
false
false
false
false
KrishMunot/swift
test/IRGen/lazy_globals.swift
6
2104
// RUN: %target-swift-frontend -parse-as-library -emit-ir -primary-file %s | FileCheck %s // REQUIRES: CPU=x86_64 // CHECK: @globalinit_[[T:.*]]_token0 = internal global i64 0, align 8 // CHECK: @_Tv12lazy_globals1xSi = hidden global %Si zeroinitializer, align 8 // CHECK: @_Tv12lazy_globals1ySi = hidden global %Si zeroinitializer, align 8 // CHECK: @_Tv12lazy_globals1zSi = hidden global %Si zeroinitializer, align 8 // CHECK: define internal void @globalinit_[[T]]_func0() {{.*}} { // CHECK: entry: // CHECK: store i64 1, i64* getelementptr inbounds (%Si, %Si* @_Tv12lazy_globals1xSi, i32 0, i32 0), align 8 // CHECK: store i64 2, i64* getelementptr inbounds (%Si, %Si* @_Tv12lazy_globals1ySi, i32 0, i32 0), align 8 // CHECK: store i64 3, i64* getelementptr inbounds (%Si, %Si* @_Tv12lazy_globals1zSi, i32 0, i32 0), align 8 // CHECK: ret void // CHECK: } // CHECK: define hidden i8* @_TF12lazy_globalsau1xSi() {{.*}} { // CHECK: entry: // CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*)) // CHECK: ret i8* bitcast (%Si* @_Tv12lazy_globals1xSi to i8*) // CHECK: } // CHECK: define hidden i8* @_TF12lazy_globalsau1ySi() {{.*}} { // CHECK: entry: // CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*)) // CHECK: ret i8* bitcast (%Si* @_Tv12lazy_globals1ySi to i8*) // CHECK: } // CHECK: define hidden i8* @_TF12lazy_globalsau1zSi() {{.*}} { // CHECK: entry: // CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*)) // CHECK: ret i8* bitcast (%Si* @_Tv12lazy_globals1zSi to i8*) // CHECK: } var (x, y, z) = (1, 2, 3) // CHECK: define hidden i64 @_TF12lazy_globals4getXFT_Si() {{.*}} { // CHECK: entry: // CHECK: %0 = call i8* @_TF12lazy_globalsau1xSi() // CHECK: %1 = bitcast i8* %0 to %Si* // CHECK: %._value = getelementptr inbounds %Si, %Si* %1, i32 0, i32 0 // CHECK: %2 = load i64, i64* %._value, align 8 // CHECK: ret i64 %2 // CHECK: } func getX() -> Int { return x }
apache-2.0
af1caf83007687e7240a4262c58f2047
44.73913
119
0.63308
2.827957
false
false
false
false
qinting513/SwiftNote
swift之Alamofire-SwiftyJONS-Kingfisher/Pods/SwiftyJSON/Source/SwiftyJSON.swift
30
34526
// SwiftyJSON.swift // // Copyright (c) 2014 - 2016 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Error ///Error domain public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int = 999 public let ErrorIndexOutOfBounds: Int = 900 public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type :Int{ case number case string case bool case array case dictionary case null case unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer = nil) { do { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(object) } catch let aError as NSError { if error != nil { error?.pointee = aError } self.init(NSNull()) } } /** Creates a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ public static func parse(_ string:String) -> JSON { return string.data(using: String.Encoding.utf8) .flatMap{ JSON(data: $0) } ?? JSON(NSNull()) } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: Any) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ public init(_ jsonDictionary:[String: JSON]) { var dictionary = [String: Any](minimumCapacity: jsonDictionary.count) for (key, json) in jsonDictionary { dictionary[key] = json.object } self.init(dictionary) } /// Private object fileprivate var rawArray: [Any] = [] fileprivate var rawDictionary: [String : Any] = [:] fileprivate var rawString: String = "" fileprivate var rawNumber: NSNumber = 0 fileprivate var rawNull: NSNull = NSNull() fileprivate var rawBool: Bool = false /// Private type fileprivate var _type: Type = .null /// prviate error fileprivate var _error: NSError? = nil /// Object in JSON public var object: Any { get { switch self.type { case .array: return self.rawArray case .dictionary: return self.rawDictionary case .string: return self.rawString case .number: return self.rawNumber case .bool: return self.rawBool default: return self.rawNull } } set { _error = nil switch newValue { case let number as NSNumber: if number.isBool { _type = .bool self.rawBool = number.boolValue } else { _type = .number self.rawNumber = number } case let string as String: _type = .string self.rawString = string case _ as NSNull: _type = .null case let array as [JSON]: _type = .array self.rawArray = array.map { $0.object } case let array as [Any]: _type = .array self.rawArray = array case let dictionary as [String : Any]: _type = .dictionary self.rawDictionary = dictionary default: _type = .unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// JSON type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null JSON @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } } public enum JSONIndex:Comparable { case array(Int) case dictionary(DictionaryIndex<String, JSON>) case null } public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left == right case (.dictionary(let left), .dictionary(let right)): return left == right case (.null, .null): return true default: return false } } public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left < right case (.dictionary(let left), .dictionary(let right)): return left < right default: return false } } extension JSON: Collection { public typealias Index = JSONIndex public var startIndex: Index { switch type { case .array: return .array(rawArray.startIndex) case .dictionary: return .dictionary(dictionaryValue.startIndex) default: return .null } } public var endIndex: Index { switch type { case .array: return .array(rawArray.endIndex) case .dictionary: return .dictionary(dictionaryValue.endIndex) default: return .null } } public func index(after i: Index) -> Index { switch i { case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): return .dictionary(dictionaryValue.index(after: idx)) default: return .null } } public subscript (position: Index) -> (String, JSON) { switch position { case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) case .dictionary(let idx): return dictionaryValue[idx] default: return ("", JSON.null) } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { var jsonKey:JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.key(self) } } extension JSON { /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. fileprivate subscript(index index: Int) -> JSON { get { if self.type != .array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return r } } set { if self.type == .array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } } } } /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. fileprivate subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return r } set { if self.type == .dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue case .key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value as Any) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value as Any) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { let array = elements self.init(dictionaryLiteral: array) } public init(dictionaryLiteral elements: [(String, Any)]) { let jsonFromDictionaryLiteral: ([String : Any]) -> JSON = { dictionary in let initializeElement = Array(dictionary.keys).flatMap { key -> (String, Any)? in if let value = dictionary[key] { return (key, value) } return nil } return JSON(dictionaryLiteral: initializeElement) } var dict = [String : Any](minimumCapacity: elements.count) for element in elements { let elementToSet: Any if let json = element.1 as? JSON { elementToSet = json.object } else if let jsonArray = element.1 as? [JSON] { elementToSet = JSON(jsonArray).object } else if let dictionary = element.1 as? [String : Any] { elementToSet = jsonFromDictionaryLiteral(dictionary).object } else if let dictArray = element.1 as? [[String : Any]] { let jsonArray = dictArray.map { jsonFromDictionaryLiteral($0) } elementToSet = JSON(jsonArray).object } else { elementToSet = element.1 } dict[element.0] = elementToSet } self.init(dict) } } extension JSON: Swift.ExpressibleByArrayLiteral { public init(arrayLiteral elements: Any...) { self.init(elements as Any) } } extension JSON: Swift.ExpressibleByNilLiteral { public init(nilLiteral: ()) { self.init(NSNull() as Any) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) } } public var rawValue: Any { return self.object } public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"]) } return try JSONSerialization.data(withJSONObject: self.object, options: opt) } public func rawString(_ encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { switch self.type { case .array, .dictionary: do { let data = try self.rawData(options: opt) return String(data: data, encoding: encoding) } catch _ { return nil } case .string: return self.rawString case .number: return self.rawNumber.stringValue case .bool: return self.rawBool.description case .null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { if let string = self.rawString(options:.prettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .array { return self.rawArray.map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [Any]? { get { switch self.type { case .array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array as Any } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { var d = [String : JSON](minimumCapacity: rawDictionary.count) for (key, value) in rawDictionary { d[key] = JSON(value) } return d } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } //Optional [String : AnyObject] public var dictionaryObject: [String : Any]? { get { switch self.type { case .dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v as Any } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON { // : Swift.Bool //Optional bool public var bool: Bool? { get { switch self.type { case .bool: return self.rawBool default: return nil } } set { if let newValue = newValue { self.object = newValue as Bool } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .bool: return self.rawBool case .number: return self.rawNumber.boolValue case .string: return self.rawString.caseInsensitiveCompare("true") == .orderedSame default: return false } } set { self.object = newValue } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .string: return self.object as? String default: return nil } } set { if let newValue = newValue { self.object = NSString(string:newValue) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .string: return self.object as? String ?? "" case .number: return self.rawNumber.stringValue case .bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .number: return self.rawNumber case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .string: let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber { // indicates parse error return NSDecimalNumber.zero } return decimal case .number: return self.object as? NSNumber ?? NSNumber(value: 0) case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return NSNumber(value: 0.0) } } set { self.object = newValue } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func exists() -> Bool{ if let errorValue = error, errorValue.code == ErrorNotExist || errorValue.code == ErrorIndexOutOfBounds || errorValue.code == ErrorWrongType { return false } return true } } //MARK: - URL extension JSON { //Optional URL public var URL: URL? { get { switch self.type { case .string: if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { // We have to use `Foundation.URL` otherwise it conflicts with the variable name. return Foundation.URL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(value: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(value: newValue) } } public var int: Int? { get { return self.number?.intValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.intValue } set { self.object = NSNumber(value: newValue) } } public var uInt: UInt? { get { return self.number?.uintValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.uintValue } set { self.object = NSNumber(value: newValue) } } public var int8: Int8? { get { return self.number?.int8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.int8Value } set { self.object = NSNumber(value: newValue) } } public var uInt8: UInt8? { get { return self.number?.uint8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.uint8Value } set { self.object = NSNumber(value: newValue) } } public var int16: Int16? { get { return self.number?.int16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.int16Value } set { self.object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { return self.number?.uint16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.uint16Value } set { self.object = NSNumber(value: newValue) } } public var int32: Int32? { get { return self.number?.int32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.int32Value } set { self.object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { return self.number?.uint32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.uint32Value } set { self.object = NSNumber(value: newValue) } } public var int64: Int64? { get { return self.number?.int64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.int64Value } set { self.object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { return self.number?.uint64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.uint64Value } set { self.object = NSNumber(value: newValue) } } } //MARK: - Comparable extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber case (.string, .string): return lhs.rawString == rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber case (.string, .string): return lhs.rawString <= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber case (.string, .string): return lhs.rawString >= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber case (.string, .string): return lhs.rawString > rhs.rawString default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber case (.string, .string): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(value: true) private let falseNumber = NSNumber(value: false) private let trueObjCType = String(cString: trueNumber.objCType) private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool:Bool { get { let objCType = String(cString: self.objCType) if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType){ return true } else { return false } } } } func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedSame } } func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedAscending } } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedDescending } } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedAscending } }
apache-2.0
6d1d28205498de95d6731d857c6e2092
25.497314
265
0.525807
4.735427
false
false
false
false
biohazardlover/NintendoEverything
Pods/SwiftSoup/Sources/OrderedSet.swift
1
12571
// // OrderedSet.swift // SwiftSoup // // Created by Nabil Chatbi on 12/11/16. // Copyright © 2016 Nabil Chatbi. All rights reserved. // import Foundation /// An ordered, unique collection of objects. public class OrderedSet<T: Hashable> { public typealias Index = Int fileprivate var contents = [T: Index]() // Needs to have a value of Index instead of Void for fast removals fileprivate var sequencedContents = Array<UnsafeMutablePointer<T>>() /** Inititalizes an empty ordered set. - returns: An empty ordered set. */ public init() { } deinit { removeAllObjects() } /** Initializes a new ordered set with the order and contents of sequence. If an object appears more than once in the sequence it will only appear once in the ordered set, at the position of its first occurance. - parameter sequence: The sequence to initialize the ordered set with. - returns: An initialized ordered set with the contents of sequence. */ public init<S: Sequence>(sequence: S) where S.Iterator.Element == T { for object in sequence { if contents[object] == nil { contents[object] = contents.count let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) pointer.initialize(to: object) sequencedContents.append(pointer) } } } public required init(arrayLiteral elements: T...) { for object in elements { if contents[object] == nil { contents[object] = contents.count let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) pointer.initialize(to: object) sequencedContents.append(pointer) } } } /** Locate the index of an object in the ordered set. It is preferable to use this method over the global find() for performance reasons. - parameter object: The object to find the index for. - returns: The index of the object, or nil if the object is not in the ordered set. */ public func index(of object: T) -> Index? { if let index = contents[object] { return index } return nil } /** Appends an object to the end of the ordered set. - parameter object: The object to be appended. */ public func append(_ object: T) { if let lastIndex = index(of: object) { remove(object) insert(object, at: lastIndex) } else { contents[object] = contents.count let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) pointer.initialize(to: object) sequencedContents.append(pointer) } } /** Appends a sequence of objects to the end of the ordered set. - parameter sequence: The sequence of objects to be appended. */ public func append<S: Sequence>(contentsOf sequence: S) where S.Iterator.Element == T { var gen = sequence.makeIterator() while let object: T = gen.next() { append(object) } } /** Removes an object from the ordered set. If the object exists in the ordered set, it will be removed. If it is not the last object in the ordered set, subsequent objects will be shifted down one position. - parameter object: The object to be removed. */ public func remove(_ object: T) { if let index = contents[object] { contents[object] = nil sequencedContents[index].deallocate(capacity: 1) sequencedContents.remove(at: index) for (object, i) in contents { if i < index { continue } contents[object] = i - 1 } } } /** Removes the given objects from the ordered set. - parameter objects: The objects to be removed. */ public func remove<S: Sequence>(_ objects: S) where S.Iterator.Element == T { var gen = objects.makeIterator() while let object: T = gen.next() { remove(object) } } /** Removes an object at a given index. This method will cause a fatal error if you attempt to move an object to an index that is out of bounds. - parameter index: The index of the object to be removed. */ public func removeObject(at index: Index) { if index < 0 || index >= count { fatalError("Attempting to remove an object at an index that does not exist") } remove(sequencedContents[index].pointee) } /** Removes all objects in the ordered set. */ public func removeAllObjects() { contents.removeAll() for sequencedContent in sequencedContents { sequencedContent.deallocate(capacity: 1) } sequencedContents.removeAll() } /** Swaps two objects contained within the ordered set. Both objects must exist within the set, or the swap will not occur. - parameter first: The first object to be swapped. - parameter second: The second object to be swapped. */ public func swapObject(_ first: T, with second: T) { if let firstPosition = contents[first] { if let secondPosition = contents[second] { contents[first] = secondPosition contents[second] = firstPosition sequencedContents[firstPosition].pointee = second sequencedContents[secondPosition].pointee = first } } } /** Tests if the ordered set contains any objects within a sequence. - parameter other: The sequence to look for the intersection in. - returns: Returns true if the sequence and set contain any equal objects, otherwise false. */ public func intersects<S: Sequence>(_ other: S) -> Bool where S.Iterator.Element == T { var gen = other.makeIterator() while let object: T = gen.next() { if contains(object) { return true } } return false } /** Tests if a the ordered set is a subset of another sequence. - parameter sequence: The sequence to check. - returns: true if the sequence contains all objects contained in the receiver, otherwise false. */ public func isSubset<S: Sequence>(of sequence: S) -> Bool where S.Iterator.Element == T { for (object, _) in contents { if !sequence.contains(object) { return false } } return true } /** Moves an object to a different index, shifting all objects in between the movement. This method is a no-op if the object doesn't exist in the set or the index is the same that the object is currently at. This method will cause a fatal error if you attempt to move an object to an index that is out of bounds. - parameter object: The object to be moved - parameter index: The index that the object should be moved to. */ public func moveObject(_ object: T, toIndex index: Index) { if index < 0 || index >= count { fatalError("Attempting to move an object at an index that does not exist") } if let position = contents[object] { // Return if the client attempted to move to the current index if position == index { return } let adjustment = position > index ? -1 : 1 var currentIndex = position while currentIndex != index { let nextIndex = currentIndex + adjustment let firstObject = sequencedContents[currentIndex].pointee let secondObject = sequencedContents[nextIndex].pointee sequencedContents[currentIndex].pointee = secondObject sequencedContents[nextIndex].pointee = firstObject contents[firstObject] = nextIndex contents[secondObject] = currentIndex currentIndex += adjustment } } } /** Moves an object from one index to a different index, shifting all objects in between the movement. This method is a no-op if the index is the same that the object is currently at. This method will cause a fatal error if you attempt to move an object fro man index that is out of bounds or to an index that is out of bounds. - parameter index: The index of the object to be moved. - parameter toIndex: The index that the object should be moved to. */ public func moveObject(at index: Index, to toIndex: Index) { if ((index < 0 || index >= count) || (toIndex < 0 || toIndex >= count)) { fatalError("Attempting to move an object at or to an index that does not exist") } moveObject(self[index], toIndex: toIndex) } /** Inserts an object at a given index, shifting all objects above it up one. This method will cause a fatal error if you attempt to insert the object out of bounds. If the object already exists in the OrderedSet, this operation is a no-op. - parameter object: The object to be inserted. - parameter index: The index to be inserted at. */ public func insert(_ object: T, at index: Index) { if index > count || index < 0 { fatalError("Attempting to insert an object at an index that does not exist") } if contents[object] != nil { return } // Append our object, then swap them until its at the end. append(object) for i in (index..<count-1).reversed() { swapObject(self[i], with: self[i+1]) } } /** Inserts objects at a given index, shifting all objects above it up one. This method will cause a fatal error if you attempt to insert the objects out of bounds. If an object in objects already exists in the OrderedSet it will not be added. Objects that occur twice in the sequence will only be added once. - parameter objects: The objects to be inserted. - parameter index: The index to be inserted at. */ public func insert<S: Sequence>(_ objects: S, at index: Index) where S.Iterator.Element == T { if index > count || index < 0 { fatalError("Attempting to insert an object at an index that does not exist") } var addedObjectCount = 0 for object in objects { if contents[object] == nil { let seqIdx = index + addedObjectCount let element = UnsafeMutablePointer<T>.allocate(capacity: 1) element.initialize(to: object) sequencedContents.insert(element, at: seqIdx) contents[object] = seqIdx addedObjectCount += 1 } } // Now we'll remove duplicates and update the shifted objects position in the contents // dictionary. for i in index + addedObjectCount..<count { contents[sequencedContents[i].pointee] = i } } /// Returns the last object in the set, or `nil` if the set is empty. public var last: T? { return sequencedContents.last?.pointee } } extension OrderedSet: ExpressibleByArrayLiteral { } extension OrderedSet where T: Comparable {} extension OrderedSet { public var count: Int { return contents.count } public var isEmpty: Bool { return count == 0 } public var first: T? { guard count > 0 else { return nil } return sequencedContents[0].pointee } public func index(after i: Int) -> Int { return sequencedContents.index(after: i) } public var startIndex: Int { return 0 } public var endIndex: Int { return contents.count } public subscript(index: Index) -> T { get { return sequencedContents[index].pointee } set { let previousCount = contents.count contents[sequencedContents[index].pointee] = nil contents[newValue] = index // If the count is reduced we used an existing value, and need to sync up sequencedContents if contents.count == previousCount { sequencedContents[index].pointee = newValue } else { sequencedContents.remove(at: index) } } } } extension OrderedSet: Sequence { public typealias Iterator = OrderedSetGenerator<T> public func makeIterator() -> Iterator { return OrderedSetGenerator(set: self) } } public struct OrderedSetGenerator<T: Hashable>: IteratorProtocol { public typealias Element = T private var generator: IndexingIterator<Array<UnsafeMutablePointer<T>>> public init(set: OrderedSet<T>) { generator = set.sequencedContents.makeIterator() } public mutating func next() -> Element? { return generator.next()?.pointee } } extension OrderedSetGenerator where T: Comparable {} public func +<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T { let joinedSet = lhs joinedSet.append(contentsOf: rhs) return joinedSet } public func +=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T { lhs.append(contentsOf: rhs) } public func -<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T { let purgedSet = lhs purgedSet.remove(rhs) return purgedSet } public func -=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T { lhs.remove(rhs) } extension OrderedSet: Equatable { } public func ==<T> (lhs: OrderedSet<T>, rhs: OrderedSet<T>) -> Bool { if lhs.count != rhs.count { return false } for object in lhs { if lhs.contents[object] != rhs.contents[object] { return false } } return true } extension OrderedSet: CustomStringConvertible { public var description: String { let children = map({ "\($0)" }).joined(separator: ", ") return "OrderedSet (\(count) object(s)): [\(children)]" } }
mit
33a1023c5d5e7813b3f0c2b5195046f3
27.247191
113
0.694829
3.627706
false
false
false
false
scinfu/SwiftSoup
Sources/OrderedSet.swift
1
12847
// // OrderedSet.swift // SwiftSoup // // Created by Nabil Chatbi on 12/11/16. // Copyright © 2016 Nabil Chatbi. All rights reserved. // import Foundation /// An ordered, unique collection of objects. public class OrderedSet<T: Hashable> { public typealias Index = Int fileprivate var contents = [T: Index]() // Needs to have a value of Index instead of Void for fast removals fileprivate var sequencedContents = Array<UnsafeMutablePointer<T>>() /** Inititalizes an empty ordered set. - returns: An empty ordered set. */ public init() { } deinit { removeAllObjects() } /** Initializes a new ordered set with the order and contents of sequence. If an object appears more than once in the sequence it will only appear once in the ordered set, at the position of its first occurance. - parameter sequence: The sequence to initialize the ordered set with. - returns: An initialized ordered set with the contents of sequence. */ public init<S: Sequence>(sequence: S) where S.Iterator.Element == T { for object in sequence { if contents[object] == nil { contents[object] = contents.count let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) pointer.initialize(to: object) sequencedContents.append(pointer) } } } public required init(arrayLiteral elements: T...) { for object in elements { if contents[object] == nil { contents[object] = contents.count let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) pointer.initialize(to: object) sequencedContents.append(pointer) } } } /** Locate the index of an object in the ordered set. It is preferable to use this method over the global find() for performance reasons. - parameter object: The object to find the index for. - returns: The index of the object, or nil if the object is not in the ordered set. */ public func index(of object: T) -> Index? { if let index = contents[object] { return index } return nil } /** Appends an object to the end of the ordered set. - parameter object: The object to be appended. */ public func append(_ object: T) { if let lastIndex = index(of: object) { remove(object) insert(object, at: lastIndex) } else { contents[object] = contents.count let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1) pointer.initialize(to: object) sequencedContents.append(pointer) } } /** Appends a sequence of objects to the end of the ordered set. - parameter sequence: The sequence of objects to be appended. */ public func append<S: Sequence>(contentsOf sequence: S) where S.Iterator.Element == T { var gen = sequence.makeIterator() while let object: T = gen.next() { append(object) } } /** Removes an object from the ordered set. If the object exists in the ordered set, it will be removed. If it is not the last object in the ordered set, subsequent objects will be shifted down one position. - parameter object: The object to be removed. */ public func remove(_ object: T) { if let index = contents[object] { contents[object] = nil #if !swift(>=4.1) sequencedContents[index].deallocate(capacity: 1) #else sequencedContents[index].deallocate() #endif sequencedContents.remove(at: index) for (object, i) in contents { if i < index { continue } contents[object] = i - 1 } } } /** Removes the given objects from the ordered set. - parameter objects: The objects to be removed. */ public func remove<S: Sequence>(_ objects: S) where S.Iterator.Element == T { var gen = objects.makeIterator() while let object: T = gen.next() { remove(object) } } /** Removes an object at a given index. This method will cause a fatal error if you attempt to move an object to an index that is out of bounds. - parameter index: The index of the object to be removed. */ public func removeObject(at index: Index) { if index < 0 || index >= count { fatalError("Attempting to remove an object at an index that does not exist") } remove(sequencedContents[index].pointee) } /** Removes all objects in the ordered set. */ public func removeAllObjects() { contents.removeAll() for sequencedContent in sequencedContents { #if !swift(>=4.1) sequencedContent.deallocate(capacity: 1) #else sequencedContent.deallocate() #endif } sequencedContents.removeAll() } /** Swaps two objects contained within the ordered set. Both objects must exist within the set, or the swap will not occur. - parameter first: The first object to be swapped. - parameter second: The second object to be swapped. */ public func swapObject(_ first: T, with second: T) { if let firstPosition = contents[first] { if let secondPosition = contents[second] { contents[first] = secondPosition contents[second] = firstPosition sequencedContents[firstPosition].pointee = second sequencedContents[secondPosition].pointee = first } } } /** Tests if the ordered set contains any objects within a sequence. - parameter other: The sequence to look for the intersection in. - returns: Returns true if the sequence and set contain any equal objects, otherwise false. */ public func intersects<S: Sequence>(_ other: S) -> Bool where S.Iterator.Element == T { var gen = other.makeIterator() while let object: T = gen.next() { if contains(object) { return true } } return false } /** Tests if a the ordered set is a subset of another sequence. - parameter sequence: The sequence to check. - returns: true if the sequence contains all objects contained in the receiver, otherwise false. */ public func isSubset<S: Sequence>(of sequence: S) -> Bool where S.Iterator.Element == T { for (object, _) in contents { if !sequence.contains(object) { return false } } return true } /** Moves an object to a different index, shifting all objects in between the movement. This method is a no-op if the object doesn't exist in the set or the index is the same that the object is currently at. This method will cause a fatal error if you attempt to move an object to an index that is out of bounds. - parameter object: The object to be moved - parameter index: The index that the object should be moved to. */ public func moveObject(_ object: T, toIndex index: Index) { if index < 0 || index >= count { fatalError("Attempting to move an object at an index that does not exist") } if let position = contents[object] { // Return if the client attempted to move to the current index if position == index { return } let adjustment = position > index ? -1 : 1 var currentIndex = position while currentIndex != index { let nextIndex = currentIndex + adjustment let firstObject = sequencedContents[currentIndex].pointee let secondObject = sequencedContents[nextIndex].pointee sequencedContents[currentIndex].pointee = secondObject sequencedContents[nextIndex].pointee = firstObject contents[firstObject] = nextIndex contents[secondObject] = currentIndex currentIndex += adjustment } } } /** Moves an object from one index to a different index, shifting all objects in between the movement. This method is a no-op if the index is the same that the object is currently at. This method will cause a fatal error if you attempt to move an object fro man index that is out of bounds or to an index that is out of bounds. - parameter index: The index of the object to be moved. - parameter toIndex: The index that the object should be moved to. */ public func moveObject(at index: Index, to toIndex: Index) { if ((index < 0 || index >= count) || (toIndex < 0 || toIndex >= count)) { fatalError("Attempting to move an object at or to an index that does not exist") } moveObject(self[index], toIndex: toIndex) } /** Inserts an object at a given index, shifting all objects above it up one. This method will cause a fatal error if you attempt to insert the object out of bounds. If the object already exists in the OrderedSet, this operation is a no-op. - parameter object: The object to be inserted. - parameter index: The index to be inserted at. */ public func insert(_ object: T, at index: Index) { if index > count || index < 0 { fatalError("Attempting to insert an object at an index that does not exist") } if contents[object] != nil { return } // Append our object, then swap them until its at the end. append(object) for i in (index..<count-1).reversed() { swapObject(self[i], with: self[i+1]) } } /** Inserts objects at a given index, shifting all objects above it up one. This method will cause a fatal error if you attempt to insert the objects out of bounds. If an object in objects already exists in the OrderedSet it will not be added. Objects that occur twice in the sequence will only be added once. - parameter objects: The objects to be inserted. - parameter index: The index to be inserted at. */ public func insert<S: Sequence>(_ objects: S, at index: Index) where S.Iterator.Element == T { if index > count || index < 0 { fatalError("Attempting to insert an object at an index that does not exist") } var addedObjectCount = 0 for object in objects { if contents[object] == nil { let seqIdx = index + addedObjectCount let element = UnsafeMutablePointer<T>.allocate(capacity: 1) element.initialize(to: object) sequencedContents.insert(element, at: seqIdx) contents[object] = seqIdx addedObjectCount += 1 } } // Now we'll remove duplicates and update the shifted objects position in the contents // dictionary. for i in index + addedObjectCount..<count { contents[sequencedContents[i].pointee] = i } } /// Returns the last object in the set, or `nil` if the set is empty. public var last: T? { return sequencedContents.last?.pointee } } extension OrderedSet: ExpressibleByArrayLiteral { } extension OrderedSet where T: Comparable {} extension OrderedSet { public var count: Int { return contents.count } public var isEmpty: Bool { return count == 0 } public var first: T? { guard count > 0 else { return nil } return sequencedContents[0].pointee } public func index(after i: Int) -> Int { return sequencedContents.index(after: i) } public var startIndex: Int { return 0 } public var endIndex: Int { return contents.count } public subscript(index: Index) -> T { get { return sequencedContents[index].pointee } set { let previousCount = contents.count contents[sequencedContents[index].pointee] = nil contents[newValue] = index // If the count is reduced we used an existing value, and need to sync up sequencedContents if contents.count == previousCount { sequencedContents[index].pointee = newValue } else { sequencedContents.remove(at: index) } } } } extension OrderedSet: Sequence { public typealias Iterator = OrderedSetGenerator<T> public func makeIterator() -> Iterator { return OrderedSetGenerator(set: self) } } public struct OrderedSetGenerator<T: Hashable>: IteratorProtocol { public typealias Element = T private var generator: IndexingIterator<Array<UnsafeMutablePointer<T>>> public init(set: OrderedSet<T>) { generator = set.sequencedContents.makeIterator() } public mutating func next() -> Element? { return generator.next()?.pointee } } extension OrderedSetGenerator where T: Comparable {} public func +<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T { let joinedSet = lhs joinedSet.append(contentsOf: rhs) return joinedSet } public func +=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T { lhs.append(contentsOf: rhs) } public func -<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Iterator.Element == T { let purgedSet = lhs purgedSet.remove(rhs) return purgedSet } public func -=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Iterator.Element == T { lhs.remove(rhs) } extension OrderedSet: Equatable { } public func ==<T> (lhs: OrderedSet<T>, rhs: OrderedSet<T>) -> Bool { if lhs.count != rhs.count { return false } for object in lhs { if lhs.contents[object] != rhs.contents[object] { return false } } return true } extension OrderedSet: CustomStringConvertible { public var description: String { let children = map({ "\($0)" }).joined(separator: ", ") return "OrderedSet (\(count) object(s)): [\(children)]" } }
mit
0c599e569588e87741ed846185294363
27.357616
113
0.687218
3.660872
false
false
false
false
Sharelink/Bahamut
Bahamut/ChatService.swift
1
9847
// // ReplyService.swift // Bahamut // // Created by AlexChow on 15/7/29. // Copyright (c) 2015年 GStudio. All rights reserved. // import Foundation import UIKit import EVReflection //MARK:ChatService let ChatServiceNewMessageEntities = "ChatServiceNewMessageEntities" let NewCreatedChatModels = "NewCreatedChatModels" let NewChatModelsCreated = "NewChatModelsCreated" extension Message { func isInvalidData() -> Bool { return msgId == nil || shareId == nil || senderId == nil || msgType == nil || chatId == nil || msg == nil || time == nil } } class ChatService:NSNotificationCenter,ServiceProtocol { static let messageServiceNewMessageReceived = "ChatServiceNewMessageReceived" private(set) var chattingShareId:String! private var chatMessageServerUrl:String! @objc static var ServiceName:String {return "Chat Service"} @objc func appStartInit(appName:String) {} @objc func userLoginInit(userId: String) { self.chatMessageServerUrl = BahamutRFKit.sharedInstance.appApiServer let route = ChicagoRoute() route.ExtName = "NotificationCenter" route.CmdName = "UsrNewMsg" ChicagoClient.sharedInstance.addChicagoObserver(route, observer: self, selector: #selector(ChatService.newMessage(_:))) let chatServerChangedRoute = ChicagoRoute() chatServerChangedRoute.ExtName = "NotificationCenter" route.CmdName = "ChatServerChanged" ChicagoClient.sharedInstance.addChicagoObserver(chatServerChangedRoute, observer: self, selector: #selector(ChatService.chatServerChanged(_:))) self.setServiceReady() self.getMessageFromServer() } func userLogout(userId: String) { ChicagoClient.sharedInstance.removeObserver(self) } static let messageListUpdated = "messageListUpdated" func setChatAtShare(shareId:String) { self.chattingShareId = shareId } func isChatingAtShare(shareId:String) -> Bool { if String.isNullOrEmpty(shareId) { return false } return shareId == self.chattingShareId } func leaveChatRoom() { self.chattingShareId = nil } func chatServerChanged(a:NSNotification) { class ReturnValue:EVObject { var chatServerUrl:String! } if let userInfo = a.userInfo { if let json = userInfo[ChicagoClientReturnJsonValue] as? String { let value = ReturnValue(json: json) if let chatUrl = value.chatServerUrl { if String.isNullOrWhiteSpace(chatUrl) { self.chatMessageServerUrl = chatUrl } } } } } func newMessage(a:NSNotification) { getMessageFromServer() } func getMessageFromServer() { let req = GetNewMessagesRequest() req.apiServerUrl = self.chatMessageServerUrl let client = BahamutRFKit.sharedInstance.getBahamutClient() client.execute(req) { (result:SLResult<[Message]>) -> Void in if var msgs = result.returnObject { msgs = msgs.filter{!$0.isInvalidData()} //isInvalidData():AlamofireJsonToObject Issue:responseArray will invoke all completeHandler if msgs.count == 0 { return } self.recevieMessage(msgs) let dreq = NotifyNewMessagesReceivedRequest() dreq.apiServerUrl = self.chatMessageServerUrl client.execute(dreq, callback: { (result:SLResult<EVObject>) -> Void in }) } } } func getChatModel(chatId:String) -> ChatModel! { return getChatModelByEntity(PersistentManager.sharedInstance.getShareChat(chatId)) } func getChatModelByEntity(entity:ShareChatEntity!) -> ChatModel! { if entity == nil{ return nil } let uService = ServiceContainer.getService(UserService) let cm = ChatModel() cm.shareId = entity.shareId cm.chatId = entity.chatId cm.sharelinkers = entity.getUsers() if cm.sharelinkers.count >= 1{ let user = uService.getUser(cm.sharelinkers.last!) cm.chatTitle = user?.getNoteName() cm.chatIcon = user?.avatarId cm.audienceId = user?.userId }else{ cm.chatTitle = "chat hub" } cm.shareId = entity.shareId cm.chatEntity = entity return cm } func getChatIdWithAudienceOfShareId(shareId:String,audienceId:String) -> String { return "\(shareId)&\(audienceId)" } func getMessage(chatId:String,limit:Int = 7,beforeTime:NSDate! = nil) -> [MessageEntity] { return PersistentManager.sharedInstance.getMessage(chatId, limit: limit, beforeTime: beforeTime) } func saveNewMessage(msgId:String,chatId:String,shareId:String!,type:MessageType,time:NSDate,senderId:String,msgText:String?,data:NSData?) -> MessageEntity! { let msgEntity = PersistentManager.sharedInstance.getNewMessage(msgId) msgEntity.chatId = chatId msgEntity.type = type.rawValue msgEntity.time = time msgEntity.senderId = senderId msgEntity.shareId = shareId if type == .Text { msgEntity.msgText = msgText ?? "" }else if type == .Voice { msgEntity.msgData = data ?? NSData() msgEntity.msgText = msgText ?? "0" }else if type == .Picture { msgEntity.msgData = data ?? NSData() } PersistentManager.sharedInstance.saveMessageChanges() return msgEntity } func sendMessage(chatId:String,msg:MessageEntity,shareId:String,audienceId:String) { let req = SendMessageRequest() req.apiServerUrl = self.chatMessageServerUrl req.time = msg.time req.type = msg.type req.chatId = chatId req.message = msg.msgText req.messageData = msg.msgData req.audienceId = audienceId req.shareId = shareId let client = BahamutRFKit.sharedInstance.getBahamutClient() client.execute(req) { (result:SLResult<Message>) -> Void in if result.isSuccess { msg.isSend = true PersistentManager.sharedInstance.saveMessageChanges() }else { msg.sendFailed = NSNumber(bool: true) } } } private func recevieMessage(msgs:[Message]) { let uService = ServiceContainer.getService(UserService) var msgEntities = [MessageEntity]() var newChatModels = [ChatModel]() for msg in msgs { let me = saveNewMessage(msg.msgId, chatId: msg.chatId,shareId: msg.shareId, type: MessageType(rawValue: msg.msgType)!, time: msg.timeOfDate, senderId: msg.senderId, msgText: msg.msg, data: msg.msgData) if let ce = PersistentManager.sharedInstance.getShareChat(me.chatId) { ce.newMessage = ce.newMessage.integerValue + 1 }else { let ce = createChatEntity(msg.chatId, audienceIds: [uService.myUserId,me.senderId], shareId: me.shareId) ce.newMessage = 1 PersistentManager.sharedInstance.saveMessageChanges() let model = getChatModelByEntity(ce) newChatModels.append(model) } msgEntities.append(me) } PersistentManager.sharedInstance.saveMessageChanges() self.postNotificationName(ChatService.messageServiceNewMessageReceived, object: self, userInfo: [ChatServiceNewMessageEntities:msgEntities]) if newChatModels.count > 0 { self.postNotificationName(NewChatModelsCreated, object: self, userInfo: [NewCreatedChatModels:newChatModels]) } } func getShareChatHub(shareId:String,shareSenderId:String) -> ShareChatHub { let uService = ServiceContainer.getService(UserService) var shareChats = PersistentManager.sharedInstance.getShareChats(shareId) if shareChats.count == 0 { let chatId = getChatIdWithAudienceOfShareId(shareId, audienceId: uService.myUserId) var audienceIds = [uService.myUserId] if uService.myUserId != shareSenderId { audienceIds.append(shareSenderId) } let newSCE = createChatEntity(chatId, audienceIds: audienceIds, shareId: shareId) shareChats.append(newSCE) } let chatModels = shareChats.map{return self.getChatModel($0.chatId)}.filter{$0 != nil} let sc = ShareChatHub() for cm in chatModels { sc.addChatModel(cm) } sc.shareId = shareId return sc } private func createChatEntity(chatId:String,audienceIds:[String],shareId:String) -> ShareChatEntity { let newSCE = PersistentManager.sharedInstance.saveNewChat(shareId,chatId: chatId) for audience in audienceIds { newSCE.addUser(audience) } PersistentManager.sharedInstance.saveMessageChanges() return newSCE } func getShareNewMessageCount(shareId:String) -> Int { let shareChats = PersistentManager.sharedInstance.getShareChats(shareId) var sum = 0 for sc in shareChats { sum = sum + sc.newMessage.integerValue } return sum } }
mit
9d3733ce124028f4817122b3ddc388cf
32.835052
213
0.610564
4.583333
false
false
false
false
nheagy/WordPress-iOS
WordPress/Classes/Utility/ImmuTable+WordPress.swift
1
1894
import WordPressShared /* Until https://github.com/wordpress-mobile/WordPress-iOS/pull/4591 is fixed, we need to use the custom WPTableViewSectionHeaderFooterView. This lives as an extension on a separate file because it's specific to our UI implementation and shouldn't be in a generic ImmuTable that we might eventually release as a standalone library. */ extension ImmuTableViewHandler { public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let title = self.tableView(tableView, titleForHeaderInSection: section) { return WPTableViewSectionHeaderFooterView.heightForHeader(title, width: tableView.frame.width) } else { return UITableViewAutomaticDimension } } public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let title = self.tableView(tableView, titleForHeaderInSection: section) else { return nil } let view = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Header) view.title = title return view } public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if let title = self.tableView(tableView, titleForFooterInSection: section) { return WPTableViewSectionHeaderFooterView.heightForFooter(title, width: tableView.frame.width) } else { return UITableViewAutomaticDimension } } public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let title = self.tableView(tableView, titleForFooterInSection: section) else { return nil } let view = WPTableViewSectionHeaderFooterView(reuseIdentifier: nil, style: .Footer) view.title = title return view } }
gpl-2.0
82ed385b0a519cb7849412362fa078b3
39.297872
106
0.712249
5.554252
false
false
false
false
DavidSkrundz/Lua
Sources/Lua/Value/Value.swift
1
2274
// // Value.swift // Lua // /// Represents a Lua value that can be converted to a Swift value /// /// Includes: /// - `Int` /// - `UInt32` /// - `Double` /// - `String` /// - `Nil` /// - `Number` /// - `Table` /// - `Function` /// - `UserData` /// - `UnsafeMutableRawPointer` public protocol Value { var hashValue: Int { get } } extension Int: Value {} extension UInt32: Value {} extension Double: Value {} extension String: Value {} extension Nil: Value {} extension Number: Value {} extension Table: Value {} extension Function: Value {} extension UserData: Value {} extension UnsafeMutableRawPointer: Value {} public func equal(_ lhs: Value, _ rhs: Value) -> Bool { switch (lhs, rhs) { case is (Int, Int): return (lhs as! Int) == (rhs as! Int) case is (UInt32, UInt32): return (lhs as! UInt32) == (rhs as! UInt32) case is (Double, Double): return (lhs as! Double) == (rhs as! Double) case is (String, String): return (lhs as! String) == (rhs as! String) case is (Number, Number): return (lhs as! Number) == (rhs as! Number) case is (Table, Table): return (lhs as! Table) == (rhs as! Table) case is (Function, Function): return (lhs as! Function) == (rhs as! Function) case is (UserData, UserData): return (lhs as! UserData) == (rhs as! UserData) case is (UnsafeMutableRawPointer, UnsafeMutableRawPointer): return (lhs as! UnsafeMutableRawPointer) == (rhs as! UnsafeMutableRawPointer) case is (Int, Number): return (lhs as! Int) == (rhs as! Number).intValue case is (UInt32, Number): return (lhs as! UInt32) == (rhs as! Number).uintValue case is (Double, Number): return (lhs as! Double) == (rhs as! Number).doubleValue case is (Number, Int): return (lhs as! Number).intValue == (rhs as! Int) case is (Number, UInt32): return (lhs as! Number).uintValue == (rhs as! UInt32) case is (Number, Double): return (lhs as! Number).doubleValue == (rhs as! Double) default: return false } } public func ==(lhs: [Value], rhs: [Value]) -> Bool { if lhs.count != rhs.count { return false } return zip(lhs, rhs) .map { equal($0, $1) } .reduce(true) { $0 && $1 } } public func !=(lhs: [Value], rhs: [Value]) -> Bool { return !(lhs == rhs) }
lgpl-3.0
9d6051ef3525353637ac814481ed60b9
31.485714
87
0.616095
3.314869
false
false
false
false
tskulbru/NBMaterialDialogIOS
Pod/Classes/NBMaterialToast.swift
2
6674
// // NBMaterialToast.swift // NBMaterialDialogIOS // // Created by Torstein Skulbru on 02/05/15. // Copyright (c) 2015 Torstein Skulbru. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Torstein Skulbru // // 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. public enum NBLunchDuration : TimeInterval { case short = 1.0 case medium = 2.0 case long = 3.5 } @objc open class NBMaterialToast : UIView { fileprivate let kHorizontalMargin: CGFloat = 16.0 fileprivate let kVerticalBottomMargin: CGFloat = 16.0 internal let kMinHeight: CGFloat = 48.0 internal let kHorizontalPadding: CGFloat = 24.0 internal let kVerticalPadding: CGFloat = 16.0 internal let kFontRoboto: UIFont = UIFont.robotoRegularOfSize(14) internal let kFontColor: UIColor = NBConfig.PrimaryTextLight internal let kDefaultBackground: UIColor = UIColor(hex: 0x323232, alpha: 1.0) internal var lunchDuration: NBLunchDuration! internal var hasRoundedCorners: Bool! internal var constraintViews: [String: AnyObject]! internal var constraintMetrics: [String: AnyObject]! override init(frame: CGRect) { super.init(frame: frame) lunchDuration = NBLunchDuration.medium hasRoundedCorners = true isUserInteractionEnabled = false backgroundColor = kDefaultBackground } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal func __show() { UIView.animate(withDuration: 0.2, animations: { self.alpha = 1.0 }, completion: { (finished) in self.__hide() }) } internal func __hide() { UIView.animate(withDuration: 0.8, delay: lunchDuration.rawValue, options: [], animations: { self.alpha = 0.0 }, completion: { (finished) in self.removeFromSuperview() }) } internal class func __createWithTextAndConstraints(_ windowView: UIView, text: String, duration: NBLunchDuration) -> NBMaterialToast { let toast = NBMaterialToast() toast.lunchDuration = duration toast.alpha = 0.0 toast.translatesAutoresizingMaskIntoConstraints = false let textLabel = UILabel() textLabel.backgroundColor = UIColor.clear textLabel.textAlignment = NSTextAlignment.left textLabel.font = toast.kFontRoboto textLabel.textColor = toast.kFontColor textLabel.numberOfLines = 0 textLabel.translatesAutoresizingMaskIntoConstraints = false textLabel.text = text if toast.hasRoundedCorners! { toast.layer.masksToBounds = true toast.layer.cornerRadius = 15.0 } toast.addSubview(textLabel) windowView.addSubview(toast) toast.constraintViews = [ "textLabel": textLabel, "toast": toast ] toast.constraintMetrics = [ "vPad": toast.kVerticalPadding as AnyObject, "hPad": toast.kHorizontalPadding as AnyObject, "minHeight": toast.kMinHeight as AnyObject, "vMargin": toast.kVerticalBottomMargin as AnyObject, "hMargin": toast.kHorizontalMargin as AnyObject ] toast.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-vPad-[textLabel]-vPad-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: toast.constraintMetrics, views: toast.constraintViews)) toast.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-hPad-[textLabel]-hPad-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: toast.constraintMetrics, views: toast.constraintViews)) toast.setContentHuggingPriority(750, for: UILayoutConstraintAxis.vertical) toast.setContentHuggingPriority(750, for: UILayoutConstraintAxis.horizontal) toast.setContentCompressionResistancePriority(750, for: UILayoutConstraintAxis.horizontal) windowView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[toast(>=minHeight)]-vMargin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: toast.constraintMetrics, views: toast.constraintViews)) windowView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=hMargin)-[toast]-(>=hMargin)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: toast.constraintMetrics, views: toast.constraintViews)) windowView.addConstraint(NSLayoutConstraint(item: toast, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: windowView, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0)) return toast } /** Displays a classic toast message with a user defined text, shown for a standard period of time - parameter windowView: The window which the toast is to be attached - parameter text: The message to be displayed */ open class func showWithText(_ windowView: UIView, text: String) { NBMaterialToast.showWithText(windowView, text: text, duration: NBLunchDuration.medium) } /** Displays a classic toast message with a user defined text and duration - parameter windowView: The window which the toast is to be attached - parameter text: The message to be displayed - parameter duration: The duration of the toast */ open class func showWithText(_ windowView: UIView, text: String, duration: NBLunchDuration) { let toast: NBMaterialToast = NBMaterialToast.__createWithTextAndConstraints(windowView, text: text, duration: duration) toast.__show() } }
mit
b67174df76a781d1fe44e513a28d3c48
42.058065
233
0.707372
4.818773
false
false
false
false
haaakon/Indus-Valley
Indus ValleyTests/VolumeTests.swift
1
1140
// // Indus_ValleyTests.swift // Indus ValleyTests // // Created by Håkon Bogen on 19/04/15. // Copyright (c) 2015 haaakon. All rights reserved. // import UIKit import XCTest class VolumeTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testCreateVolume() { let singleLitre = Volume(quantity: 1, unit: .Litre) XCTAssert(singleLitre.quantity == 1, "one litre was not set with correct value") XCTAssert(singleLitre.unit == VolumeUnit.Litre, "one litre did not get correct unit") } func testCreateDesilitre() { let desilitre = Volume(quantity: 4, unit: .Desilitre) XCTAssert(desilitre.quantity == 4, "one desilitre was not set with correct value") XCTAssert(desilitre.unit == VolumeUnit.Desilitre, "one desilitre did not get correct unit") } }
mit
062e40a0ac25f0b9d83fd497cbc5a053
30.638889
111
0.665496
3.847973
false
true
false
false
anzfactory/QiitaCollection
QiitaCollection/AnonymousAccount.swift
1
8056
// // AnonymousAccount.swift // QiitaCollection // // Created by ANZ on 2015/03/23. // Copyright (c) 2015年 anz. All rights reserved. // import UIKit class AnonymousAccount: NSObject { let qiitaApiManager: QiitaApiManager = QiitaApiManager.sharedInstance let userDataManager: UserDataManager = UserDataManager.sharedInstance func signin(code: String, completion: (qiitaAccount: QiitaAccount?) -> Void) { self.qiitaApiManager.postAuthorize(ThirdParty.Qiita.ClientID.rawValue, clientSecret: ThirdParty.Qiita.ClientSecret.rawValue, code: code) { (token, isError) -> Void in if isError { completion(qiitaAccount:nil); return } // 保存 self.userDataManager.setQiitaAccessToken(token) self.qiitaApiManager.getAuthenticatedUser({ (item, isError) -> Void in if isError { completion(qiitaAccount:nil) return } self.userDataManager.qiitaAuthenticatedUserID = item!.id let account = QiitaAccount() completion(qiitaAccount:account) }) } } func signout(completion: (anonymous: AnonymousAccount?) -> Void) { completion(anonymous: self) } func newEntries(page:Int, completion: (total: Int, items:[EntryEntity]) -> Void) { self.qiitaApiManager.getEntriesNew(page, completion: { (total, items, isError) -> Void in if isError { completion(total: 0, items: [EntryEntity]()) return } completion(total: total, items: items) }) } func searchEntries(page: Int, query:String, completion: (total: Int, items:[EntryEntity]) -> Void) { self.qiitaApiManager.getEntriesSearch(query, page: page) { (total, items, isError) -> Void in if isError { completion(total:0, items:[EntryEntity]()) return } completion(total: total, items: items) } } func read(entryId: String, completion: (entry: EntryEntity?) -> Void) { self.qiitaApiManager.getEntry(entryId, completion: { (item, isError) -> Void in if isError { completion(entry: nil) return } completion(entry: item!) }) } func hasDownloadFiles() -> Bool { return UserDataManager.sharedInstance.entryFiles.count > 0 } func downloadEntryTitles() -> [String] { return [String].convert(self.userDataManager.entryFiles, key: "title") } func downloadEntryId(atIndex: Int) -> String { let item: [String: String] = self.userDataManager.entryFiles[atIndex] if let id = item["id"] { return id } else { return "" } } func download(entry: EntryEntity, completion: (isError: Bool) -> Void) { let manager: FileManager = FileManager() manager.save(entry.id, dataString: entry.htmlBody, completion: { (isError) -> Void in if isError { completion(isError: true) return } self.userDataManager.appendSavedEntry(entry.id, title: entry.title) completion(isError: false) return }) } func loadLocalEntry(entryId: String, completion: (isError: Bool, title: String, body: String) -> Void) { // ローカルファイルから読み出す FileManager().read(entryId, completion: { (text) -> Void in if text.isEmpty { completion(isError:true, title: "", body: "") return } let title = UserDataManager.sharedInstance.titleSavedEntry(entryId) completion(isError: false, title: title, body: text) }) } func removeLocalEntry(atIndex: Int, completion: (isError: Bool, titles:[String]) -> Void) { let entryId: String = self.userDataManager.entryFiles[atIndex]["id"]! FileManager().remove(entryId, completion: { (isError) -> Void in if isError { completion(isError: true, titles:self.downloadEntryTitles()) return } self.userDataManager.removeEntry(entryId) completion(isError: false, titles:self.downloadEntryTitles()) }) } func pinEntryTitles() -> [String] { return [String].convert(self.userDataManager.pins, key: "title") } func pinEntryId(atIndex: Int) -> String { if let id = self.userDataManager.pins[atIndex]["id"] { return id } else { return "" } } func pin(entry: EntryEntity) { self.userDataManager.appendPinEntry(entry.id, entryTitle: entry.title) } func removePin(atIndex: Int) { self.userDataManager.clearPinEntry(atIndex) } func saveQueries() -> [[String: String]] { return self.userDataManager.queries } func saveQueryTitles() -> [String] { return [String].convert(self.userDataManager.queries, key: "title") } func saveQuery(query: String, title: String) { self.userDataManager.appendQuery(query, label: title) } func removeQuery(atIndex: Int) { self.userDataManager.clearQuery(atIndex) } func existsMuteUser(userId: String) -> Bool { return contains(self.userDataManager.muteUsers, userId) } func muteUserNames() -> [String] { return self.userDataManager.muteUsers } func muteUserId(atIndex: Int) -> String { return self.userDataManager.muteUsers[atIndex] } func cancelMute(atIndex: Int) { self.userDataManager.clearMutedUser(self.muteUserNames()[atIndex]) } func cancelMuteUser(userId: String) { self.userDataManager.clearMutedUser(userId) } func mute(userId: String) { self.userDataManager.appendMuteUserId(userId) } func comments(page: Int, entryId: String, completion: (total: Int, items:[CommentEntity]) -> Void) { self.qiitaApiManager.getEntriesComments(entryId, page: page) { (total, items, isError) -> Void in if isError { completion(total: 0, items: [CommentEntity]()) return } completion(total: total, items: items) } } func other(userId: String, completion: (user: OtherAccount?) -> Void) { self.qiitaApiManager.getUser(userId, completion: { (item, isError) -> Void in if item == nil { completion(user: nil) } else { completion(user: OtherAccount(qiitaId: item!.id)) } }) } func saveHistory(entry: EntryEntity) { ParseManager.sharedInstance.putHistory(entry) } func histories(page:Int, completion:(items: [HistoryEntity]) -> Void) { ParseManager.sharedInstance.getHistory(page, completion: { (items) -> Void in completion(items: items) }) } func weekRanking(completion: (items: [RankEntity]) -> Void) { ParseManager.sharedInstance.getWeekRanking(0, completion: { (items) -> Void in completion(items: items) }) } func adventList(year: Int, page: Int, completion: (items: [KimonoEntity]) -> Void) { ParseManager.sharedInstance.getAdventList(year, page: page) { (items) -> Void in completion(items: items) } } func adventEntires(objectId: String, completion: (items: [AdventEntity]) -> Void) { ParseManager.sharedInstance.getAdventEntries(objectId, completion: { (items) -> Void in completion(items:items) }) } }
mit
f61ea4851efd8eba55cdf09077b2439e
31.742857
174
0.571304
4.555366
false
false
false
false
ainame/Swift-WebP
Sources/WebP/WebPEncoderConfig.swift
1
8526
import Foundation import CWebP extension CWebP.WebPImageHint: ExpressibleByIntegerLiteral { /// Create an instance initialized to `value`. public init(integerLiteral value: Int) { switch UInt32(value) { case CWebP.WEBP_HINT_DEFAULT.rawValue: self = CWebP.WEBP_HINT_DEFAULT case CWebP.WEBP_HINT_PICTURE.rawValue: self = CWebP.WEBP_HINT_PICTURE case CWebP.WEBP_HINT_PHOTO.rawValue: self = CWebP.WEBP_HINT_PHOTO case CWebP.WEBP_HINT_GRAPH.rawValue: self = CWebP.WEBP_HINT_GRAPH default: fatalError() } } } // mapping from CWebP.WebPConfig public struct WebPEncoderConfig: InternalRawRepresentable { public enum WebPImageHint: CWebP.WebPImageHint { case `default` = 0 case picture = 1 case photo = 2 case graph = 3 } // Lossless encoding (0=lossy(default), 1=lossless). public var lossless: Int = 0 // between 0 (smallest file) and 100 (biggest) public var quality: Float // quality/speed trade-off (0=fast, 6=slower-better) public var method: Int // Hint for image type (lossless only for now). public var imageHint: WebPImageHint = .default // Parameters related to lossy compression only: // if non-zero, set the desired target size in bytes. // Takes precedence over the 'compression' parameter. public var targetSize: Int = 0 // if non-zero, specifies the minimal distortion to // try to achieve. Takes precedence over target_size. public var targetPSNR: Float = 0 // maximum number of segments to use, in [1..4] public var segments: Int // Spatial Noise Shaping. 0=off, 100=maximum. public var snsStrength: Int // range: [0 = off .. 100 = strongest] public var filterStrength: Int // range: [0 = off .. 7 = least sharp] public var filterSharpness: Int // filtering type: 0 = simple, 1 = strong (only used // if filter_strength > 0 or autofilter > 0) public var filterType: Int // Auto adjust filter's strength [0 = off, 1 = on] public var autofilter: Int // Algorithm for encoding the alpha plane (0 = none, // 1 = compressed with WebP lossless). Default is 1. public var alphaCompression: Int = 1 // Predictive filtering method for alpha plane. // 0: none, 1: fast, 2: best. Default if 1. public var alphaFiltering: Int // Between 0 (smallest size) and 100 (lossless). // Default is 100. public var alphaQuality: Int = 100 // number of entropy-analysis passes (in [1..10]). public var pass: Int // if true, export the compressed picture back. // In-loop filtering is not applied. public var showCompressed: Bool // preprocessing filter: // 0=none, 1=segment-smooth, 2=pseudo-random dithering public var preprocessing: Int // log2(number of token partitions) in [0..3]. Default // is set to 0 for easier progressive decoding. public var partitions: Int = 0 // quality degradation allowed to fit the 512k limit // on prediction modes coding (0: no degradation, // 100: maximum possible degradation). public var partitionLimit: Int // If true, compression parameters will be remapped // to better match the expected output size from // JPEG compression. Generally, the output size will // be similar but the degradation will be lower. public var emulateJpegSize: Bool // If non-zero, try and use multi-threaded encoding. public var threadLevel: Int // If set, reduce memory usage (but increase CPU use). public var lowMemory: Bool // Near lossless encoding [0 = max loss .. 100 = off // Int(default)]. public var nearLossless: Int = 100 // if non-zero, preserve the exact RGB values under // transparent area. Otherwise, discard this invisible // RGB information for better compression. The default // value is 0. public var exact: Int public var qmin: Int = 0 public var qmax: Int = 100 // reserved for future lossless feature var useDeltaPalette: Bool // if needed, use sharp (and slow) RGB->YUV conversion var useSharpYUV: Bool static public func preset(_ preset: Preset, quality: Float) -> WebPEncoderConfig { let webPConfig = preset.webPConfig(quality: quality) return WebPEncoderConfig(rawValue: webPConfig)! } internal init?(rawValue: CWebP.WebPConfig) { lossless = Int(rawValue.lossless) quality = rawValue.quality method = Int(rawValue.method) imageHint = WebPImageHint(rawValue: rawValue.image_hint)! targetSize = Int(rawValue.target_size) targetPSNR = Float(rawValue.target_PSNR) segments = Int(rawValue.segments) snsStrength = Int(rawValue.sns_strength) filterStrength = Int(rawValue.filter_strength) filterSharpness = Int(rawValue.filter_sharpness) filterType = Int(rawValue.filter_type) autofilter = Int(rawValue.autofilter) alphaCompression = Int(rawValue.alpha_compression) alphaFiltering = Int(rawValue.alpha_filtering) alphaQuality = Int(rawValue.alpha_quality) pass = Int(rawValue.pass) showCompressed = rawValue.show_compressed != 0 ? true : false preprocessing = Int(rawValue.preprocessing) partitions = Int(rawValue.partitions) partitionLimit = Int(rawValue.partition_limit) emulateJpegSize = rawValue.emulate_jpeg_size != 0 ? true : false threadLevel = Int(rawValue.thread_level) lowMemory = rawValue.low_memory != 0 ? true : false nearLossless = Int(rawValue.near_lossless) exact = Int(rawValue.exact) useDeltaPalette = rawValue.use_delta_palette != 0 ? true : false useSharpYUV = rawValue.use_sharp_yuv != 0 ? true : false qmin = Int(rawValue.qmin) qmax = Int(rawValue.qmax) } internal var rawValue: CWebP.WebPConfig { let show_compressed = showCompressed ? Int32(1) : Int32(0) let emulate_jpeg_size = emulateJpegSize ? Int32(1) : Int32(0) let low_memory = lowMemory ? Int32(1) : Int32(0) let use_delta_palette = useDeltaPalette ? Int32(1) : Int32(0) let use_sharp_yuv = useSharpYUV ? Int32(1) : Int32(0) return CWebP.WebPConfig( lossless: Int32(lossless), quality: Float(quality), method: Int32(method), image_hint: imageHint.rawValue, target_size: Int32(targetSize), target_PSNR: Float(targetPSNR), segments: Int32(segments), sns_strength: Int32(snsStrength), filter_strength: Int32(filterStrength), filter_sharpness: Int32(filterSharpness), filter_type: Int32(filterType), autofilter: Int32(autofilter), alpha_compression: Int32(alphaCompression), alpha_filtering: Int32(alphaFiltering), alpha_quality: Int32(alphaQuality), pass: Int32(pass), show_compressed: show_compressed, preprocessing: Int32(preprocessing), partitions: Int32(partitions), partition_limit: Int32(partitionLimit), emulate_jpeg_size: emulate_jpeg_size, thread_level: Int32(threadLevel), low_memory: low_memory, near_lossless: Int32(nearLossless), exact: Int32(exact), use_delta_palette: Int32(use_delta_palette), use_sharp_yuv: Int32(use_sharp_yuv), qmin: Int32(qmin), qmax: Int32(qmax) ) } public enum Preset { case `default`, picture, photo, drawing, icon, text func webPConfig(quality: Float) -> CWebP.WebPConfig { var config = CWebP.WebPConfig() switch self { case .default: WebPConfigPreset(&config, WEBP_PRESET_DEFAULT, quality) case .picture: WebPConfigPreset(&config, WEBP_PRESET_PICTURE, quality) case .photo: WebPConfigPreset(&config, WEBP_PRESET_PHOTO, quality) case .drawing: WebPConfigPreset(&config, WEBP_PRESET_DRAWING, quality) case .icon: WebPConfigPreset(&config, WEBP_PRESET_ICON, quality) case .text: WebPConfigPreset(&config, WEBP_PRESET_TEXT, quality) } return config } } }
mit
519d6e735ff2f344fabc50c00833bfa7
34.974684
86
0.634412
4.021698
false
true
false
false
Brsoyan/HBPhoneNumberFormatter
HBPhoneNumberFormatter-Swift/HBPhoneNumberFormatter.swift
1
8818
// // HBPhoneNumberFormatter.swift // HBPhoneNumberFormatter // // Created by Hovhannes Stepanyan on 6/11/18. // import UIKit class HBPhoneNumberFormatter: NSObject { var isShake: Bool = true var shakeSize: CGFloat = 5.0 var shakeDuration: CGFloat = 0.1 var shakeRepeatCount: CGFloat = 2.0 /// Create formatter and setup your custom formatting, like this @"(111) 1233-222" init(formatting: String) { super.init() let count = formatting.count var buffer = [unichar]() let _formatting = NSString(string: formatting) _formatting.getCharacters(&buffer, range: NSMakeRange(0, count)) for char in buffer { let character = String(char) if !self.isNumber(character) { symbols[String(buffer.index(of: char)!)] = character } } self.numberCount = formatting.count - symbols.count } /// Call this method from your uiviewcontroller <UITextFieldDelegate> similar method. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if !self.isNumber(string) { self.shake(textField: textField) return false } if range.length > 0 && self.prefix == textField.text { self.shake(textField: textField) return false } if range.length > 0 { self.isDelete = true } else { self.isDelete = false } let number = self.getNumber(textField.text) let numberCount = number.count if numberCount == self.numberCount { if var symbol = self.symbolFor(textField.text?.count) { textField.text = String(format: "%@%@", textField.text!, symbol) symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) } if range.location == self.numberCount + self.symbols.count + self.prefix.count { self.shake(textField:textField) } if range.length == 0 { return false } } // TextField is Empty if textField.text?.count == self.prefix.count { if self.numberCount + self.symbols.count > (textField.text?.count ?? 0) { if var symbol = self.symbolFor(self.prefix.count) { if textField.text?.count != 0 { textField.text = String(format:"%@%@", textField.text! ,symbol) } else { textField.text = String(format:"%@" , symbol) } symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) textField.text = String(format:"%@%@", textField.text!, string) symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) } else { textField.text = String(format:"%@", string) let symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) } } return false } // When added symbol in textField if textField.text?.count == range.location { if self.numberCount + self.symbols.count + self.prefix.count > (textField.text?.count ?? 0) { if var symbol = self.symbolFor(textField.text?.count) { textField.text = String(format:"%@%@", textField.text!, symbol) symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) } if !self.isDelete && (textField.text?.count ?? 0) > 0 { textField.text = String(format:"%@%@", textField.text!, string) } if var symbol = self.symbolFor(textField.text?.count) { textField.text = String(format:"%@%@", textField.text!, symbol) symbol = self.symbolFor(textField.text?.count)! self.add(symbol, in: textField) } if self.isDelete { textField.text = String(format:"%@%@", textField.text!, string) } return false } return false } // Delete text from textField if range.length > 0 { if range.location >= self.prefix.count { if textField.text?.count == range.location { textField.text = textField.text?.substring(to: (textField.text?.endIndex)!) } else { textField.text = textField.text?.substring(to: String.Index.init(encodedOffset: range.location)) } if var symbol = self.symbolFor((textField.text?.count)! - 1) { while(true) { textField.text = textField.text!.substring(to: (textField.text?.endIndex)!) if let _symbol = self.symbolFor((textField.text?.count)! - 1) { symbol = _symbol break } } } } else { textField.text = textField.text!.substring(to: String.Index.init(encodedOffset: self.prefix.count)) } return false } return true } /// Set Contry code Prefix func setCountryName(_ name: String, textField: UITextField) { guard let code = CountryCode.countryCodeWith(name: name) else { print("We dosn't finde %@ .HB Default prefix is United States", name) self.prefix = CountryCode.countryCodeWith(name: "United States")! textField.text = String(format: "%@", self.prefix) return } self.prefix = code textField.text = String(format: "%@", code) } /// You can check your formatting is valid or not. func numberIsValidPhoneText(_ phoneText: String) -> Bool { let text = self.getNumber(phoneText) let length = text.count ?? 0 if length == self.numberCount && self.isNumber(text) { return true } else { return false } } // MARK: Private API private var symbols: Dictionary<String, Any> = [String: Any]() private var numberCount: Int = 0 private var isDelete: Bool = false private var prefix: String = "" private func isNumber(_ number: String) -> Bool { let digits = CharacterSet(charactersIn: "0123456789").inverted return NSString(string: number).rangeOfCharacter(from: digits).location == NSNotFound } private func shake(textField: UITextField) { if self.isShake { let shake = CABasicAnimation(keyPath:"position") shake.duration = CFTimeInterval(self.shakeDuration) shake.repeatCount = Float(self.shakeRepeatCount) shake.autoreverses = true shake.fromValue = NSValue(cgPoint: CGPoint(x: textField.center.x - self.shakeSize, y: textField.center.y)) shake.toValue = NSValue(cgPoint: CGPoint(x: textField.center.x + self.shakeSize, y: textField.center.y)) textField.layer.add(shake, forKey:"position") } } private func getNumber(_ mobileNumber: String?) -> String { let len = mobileNumber?.count ?? 0 var buffer = [unichar]() NSString(string: mobileNumber!).getCharacters(&buffer, range:NSMakeRange(0, len)) var number = "" for i in self.prefix.count..<len { let character = String(format:"%C", buffer[i]) if self.isNumber(character) { if number.count != 0 { number = String(format:"%@%@", number, character) } else { number = String(format:"%@", character) } } } return number; } private func symbolFor(_ index: Int?) -> String? { let _index = (index ?? 0) - self.prefix.count for key in self.symbols.keys { if key == String(_index) { return self.symbols[key] as? String; } } return nil } private func add(_ symbol: String, in textField: UITextField) { var _symbol = symbol while _symbol.count > 0 { textField.text = String(format:"%@%@", textField.text!, symbol) _symbol = self.symbolFor(textField.text?.count)! } } }
mit
6b4904e23a94787f3894cba08911ced5
38.900452
129
0.532887
4.771645
false
false
false
false
fluidsonic/JetPack
Xcode/Tests/Support.swift
1
4687
import JetPack import XCTest struct EmptyStruct {} final class EmptyEqualObject: CustomStringConvertible, Hashable { init() {} var description: String { return "EmptyEqualObject(\(pointer(of: self)))" } func hash(into hasher: inout Hasher) {} } final class EmptyNonEqualObject: CustomStringConvertible, Hashable { init() {} var description: String { return "EmptyNonEqualObject(\(pointer(of: self)))" } func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } } func == (a: EmptyEqualObject, b: EmptyEqualObject) -> Bool { return true } func == (a: EmptyNonEqualObject, b: EmptyNonEqualObject) -> Bool { return a === b } func XCTAssertEqual<X: Equatable, Y: Equatable> (_ expression1: (X, Y)?, _ expression2: (X, Y)?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertTrue(expression1.0 == expression2.0 && expression1.1 == expression2.1, file: file, line: line) return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertEqual<X: Equatable, Y: Equatable> (_ expression1: [(X, Y)]?, _ expression2: [(X, Y)]?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertEqual(expression1.count, expression2.count, file: file, line: line) for index in 0 ..< expression1.count { XCTAssertEqual(expression1[index], expression2[index], file: file, line: line) } return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertEqual<T: Equatable> (_ expression1: [T]?, _ expression2: [T]?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertEqual(expression1, expression2, file: file, line: line) return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertEqual<T: Equatable> (_ expression1: [T?], _ expression2: [T?], file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(expression1.count, expression2.count, file: file, line: line) for index in 0 ..< expression1.count { XCTAssertEqual(expression1[index], expression2[index], file: file, line: line) } } func XCTAssertEqual<T: Equatable> (_ expression1: [T?]?, _ expression2: [T?]?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertEqual(expression1.count, expression2.count, file: file, line: line) for index in 0 ..< expression1.count { XCTAssertEqual(expression1[index], expression2[index], file: file, line: line) } return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertIdentical<T: AnyObject> (_ expression1: T?, _ expression2: T?, file: StaticString = #file, line: UInt = #line) { XCTAssertTrue(expression1 === expression2, "\(String(describing: expression1)) is not identical to \(String(describing: expression2))", file: file, line: line) } func XCTAssertIdentical<T: AnyObject> (_ expression1: [T]?, _ expression2: [T]?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertEqual(expression1.count, expression2.count, file: file, line: line) for index in 0 ..< expression1.count { XCTAssertIdentical(expression1[index], expression2[index], file: file, line: line) } return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertIdentical<T: AnyObject> (_ expression1: Set<T>?, _ expression2: Set<T>?, file: StaticString = #file, line: UInt = #line) { if let expression1 = expression1, let expression2 = expression2 { XCTAssertEqual(expression1.count, expression2.count, file: file, line: line) for (element1, element2) in zip(expression1, expression2) { XCTAssertIdentical(element1, element2, file: file, line: line) } return } XCTAssertTrue(expression1 == nil && expression2 == nil, file: file, line: line) } func XCTAssertEqual(_ expression1: CGRect, _ expression2: CGRect, accuracy: CGFloat, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(expression1.origin.x, expression2.origin.x, accuracy: accuracy, file: file, line: line) XCTAssertEqual(expression1.origin.y, expression2.origin.y, accuracy: accuracy, file: file, line: line) XCTAssertEqual(expression1.width, expression2.width, accuracy: accuracy, file: file, line: line) XCTAssertEqual(expression1.height, expression2.height, accuracy: accuracy, file: file, line: line) }
mit
4fde5246c08910183d5f4d71c21c9f8c
31.10274
160
0.708342
3.482169
false
false
false
false
tunespeak/AlamoRecord
Example/Pods/NotificationBannerSwift/NotificationBanner/Classes/GrowingNotificationBanner.swift
1
8777
/* The MIT License (MIT) Copyright (c) 2017-2018 Dalton Hinterscher 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 SnapKit public class GrowingNotificationBanner: BaseNotificationBanner { public enum IconPosition { case top case center } /// The height of the banner when it is presented override public var bannerHeight: CGFloat { get { if let customBannerHeight = customBannerHeight { return customBannerHeight } else { // Calculate the height based on contents of labels // Determine available width for displaying the label var boundingWidth = UIScreen.main.bounds.width - padding * 2 // Substract safeAreaInsets from width, if available // We have to use keyWindow to ask for safeAreaInsets as `self` only knows its' safeAreaInsets in layoutSubviews if #available(iOS 11.0, *), let keyWindow = UIApplication.shared.keyWindow { let safeAreaOffset = keyWindow.safeAreaInsets.left + keyWindow.safeAreaInsets.right boundingWidth -= safeAreaOffset } if leftView != nil { boundingWidth -= iconSize + padding } if rightView != nil { boundingWidth -= iconSize + padding } let titleHeight = ceil(titleLabel?.text?.height( forConstrainedWidth: boundingWidth, font: titleFont ) ?? 0.0) let subtitleHeight = ceil(subtitleLabel?.text?.height( forConstrainedWidth: boundingWidth, font: subtitleFont ) ?? 0.0) let topOffset: CGFloat = shouldAdjustForNotchFeaturedIphone() ? 44.0 : verticalSpacing let minHeight: CGFloat = shouldAdjustForNotchFeaturedIphone() ? 88.0 : 64.0 var actualBannerHeight = topOffset + titleHeight + subtitleHeight + verticalSpacing if !subtitleHeight.isZero && !titleHeight.isZero { actualBannerHeight += innerSpacing } return max(actualBannerHeight, minHeight) } } set { customBannerHeight = newValue } } /// Spacing between the last label and the bottom edge of the banner private let verticalSpacing: CGFloat = 14.0 /// Spacing between title and subtitle private let innerSpacing: CGFloat = 2.5 /// The bottom most label of the notification if a subtitle is provided public private(set) var subtitleLabel: UILabel? /// The view that is presented on the left side of the notification private var leftView: UIView? /// The view that is presented on the right side of the notification private var rightView: UIView? /// Square size for left/right view if set private let iconSize: CGFloat = 24.0 /// Font used for the title label internal var titleFont: UIFont = UIFont.systemFont(ofSize: 17.5, weight: UIFont.Weight.bold) /// Font used for the subtitle label internal var subtitleFont: UIFont = UIFont.systemFont(ofSize: 15.0) public init(title: String? = nil, subtitle: String? = nil, leftView: UIView? = nil, rightView: UIView? = nil, style: BannerStyle = .info, colors: BannerColorsProtocol? = nil, iconPosition: IconPosition = .center) { self.leftView = leftView self.rightView = rightView super.init(style: style, colors: colors) let labelsView = UIStackView() labelsView.axis = .vertical labelsView.spacing = innerSpacing let outerStackView = UIStackView() outerStackView.spacing = padding switch iconPosition { case .top: outerStackView.alignment = .top case .center: outerStackView.alignment = .center } if let leftView = leftView { outerStackView.addArrangedSubview(leftView) leftView.snp.makeConstraints { $0.size.equalTo(iconSize) } } outerStackView.addArrangedSubview(labelsView) if let title = title { titleLabel = UILabel() titleLabel!.font = titleFont titleLabel!.numberOfLines = 0 titleLabel!.textColor = .white titleLabel!.text = title titleLabel!.setContentHuggingPriority(.required, for: .vertical) labelsView.addArrangedSubview(titleLabel!) } if let subtitle = subtitle { subtitleLabel = UILabel() subtitleLabel!.font = subtitleFont subtitleLabel!.numberOfLines = 0 subtitleLabel!.textColor = .white subtitleLabel!.text = subtitle if title == nil { subtitleLabel!.setContentHuggingPriority(.required, for: .vertical) } labelsView.addArrangedSubview(subtitleLabel!) } if let rightView = rightView { outerStackView.addArrangedSubview(rightView) rightView.snp.makeConstraints { $0.size.equalTo(iconSize) } } contentView.addSubview(outerStackView) outerStackView.snp.makeConstraints { (make) in if #available(iOS 11.0, *) { make.left.equalTo(safeAreaLayoutGuide).offset(padding) make.right.equalTo(safeAreaLayoutGuide).offset(-padding) } else { make.left.equalToSuperview().offset(padding) make.right.equalToSuperview().offset(-padding) } make.centerY.equalToSuperview() } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public extension GrowingNotificationBanner { func applyStyling(cornerRadius: CGFloat? = nil, titleFont: UIFont? = nil, titleColor: UIColor? = nil, titleTextAlign: NSTextAlignment? = nil, subtitleFont: UIFont? = nil, subtitleColor: UIColor? = nil, subtitleTextAlign: NSTextAlignment? = nil) { if let cornerRadius = cornerRadius { contentView.layer.cornerRadius = cornerRadius } if let titleFont = titleFont { self.titleFont = titleFont titleLabel!.font = titleFont } if let titleColor = titleColor { titleLabel!.textColor = titleColor } if let titleTextAlign = titleTextAlign { titleLabel!.textAlignment = titleTextAlign } if let subtitleFont = subtitleFont { self.subtitleFont = subtitleFont subtitleLabel!.font = subtitleFont } if let subtitleColor = subtitleColor { subtitleLabel!.textColor = subtitleColor } if let subtitleTextAlign = subtitleTextAlign { subtitleLabel!.textAlignment = subtitleTextAlign } if titleFont != nil || subtitleFont != nil { updateBannerHeight() } } }
mit
f6c698ea08d994c496b49d94eb562be4
36.669528
147
0.582545
5.995219
false
false
false
false
shajrawi/swift
test/type/self.swift
2
4546
// RUN: %target-typecheck-verify-swift -swift-version 5 struct S0<T> { func foo(_ other: Self) { } } class C0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{21-25=C0}} } enum E0<T> { func foo(_ other: Self) { } } // rdar://problem/21745221 struct X { typealias T = Int } extension X { struct Inner { } } extension X.Inner { func foo(_ other: Self) { } } // SR-695 class Mario { func getFriend() -> Self { return self } // expected-note{{overridden declaration is here}} func getEnemy() -> Mario { return self } } class SuperMario : Mario { override func getFriend() -> SuperMario { // expected-error{{cannot override a Self return type with a non-Self return type}} return SuperMario() } override func getEnemy() -> Self { return self } } final class FinalMario : Mario { override func getFriend() -> FinalMario { return FinalMario() } } // These references to Self are now possible (SE-0068) class A<T> { typealias _Self = Self // expected-error@-1 {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'A'?}} let b: Int required init(a: Int) { print("\(Self.self).\(#function)") Self.y() b = a } static func z(n: Self? = nil) { // expected-error@-1 {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'A'?}} print("\(Self.self).\(#function)") } class func y() { print("\(Self.self).\(#function)") Self.z() } func x() -> A? { print("\(Self.self).\(#function)") Self.y() Self.z() let _: Self = Self.init(a: 66) // expected-error@-1 {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'A'?}} return Self.init(a: 77) as? Self as? A // expected-warning@-1 {{conditional cast from 'Self' to 'Self' always succeeds}} // expected-warning@-2 {{conditional downcast from 'Self?' to 'A<T>' is equivalent to an implicit conversion to an optional 'A<T>'}} } func copy() -> Self { let copy = Self.init(a: 11) return copy } var copied: Self { // expected-error {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'A'?}} let copy = Self.init(a: 11) return copy } subscript (i: Int) -> Self { // expected-error {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'A'?}} get { return Self.init(a: i) } set(newValue) { } } } class B: A<Int> { let a: Int required convenience init(a: Int) { print("\(Self.self).\(#function)") self.init() } init() { print("\(Self.self).\(#function)") Self.y() Self.z() a = 99 super.init(a: 88) } override class func y() { print("override \(Self.self).\(#function)") } override func copy() -> Self { let copy = super.copy() as! Self // supported return copy } override var copied: Self { // expected-error {{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'B'?}} let copy = super.copied as! Self // unsupported return copy } } class C { required init() { } func f() { func g(_: Self) {} } func g() { _ = Self.init() as? Self // expected-warning@-1 {{conditional cast from 'Self' to 'Self' always succeeds}} } } struct S2 { let x = 99 struct S3<T> { let x = 99 static func x() { Self.y() } func f() { func g(_: Self) {} } static func y() { print("HERE") } func foo(a: [Self]) -> Self? { Self.x() return Self.init() as? Self // expected-warning@-1 {{conditional cast from 'S2.S3<T>' to 'S2.S3<T>' always succeeds}} } } func copy() -> Self { let copy = Self.init() return copy } var copied: Self { let copy = Self.init() return copy } } extension S2 { static func x() { Self.y() } static func y() { print("HERE") } func f() { func g(_: Self) {} } func foo(a: [Self]) -> Self? { Self.x() return Self.init() as? Self // expected-warning@-1 {{conditional cast from 'S2' to 'S2' always succeeds}} } subscript (i: Int) -> Self { get { return Self.init() } set(newValue) { } } } enum E { static func f() { func g(_: Self) {} print("f()") } case e func h(h: Self) -> Self { Self.f() return .e } }
apache-2.0
61298abcdbbc6e22788373b452f0c55a
22.312821
161
0.578531
3.34757
false
false
false
false
tad-iizuka/swift-sdk
Source/ConversationV1/Models/MessageResponse.swift
2
2391
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** A response from the Conversation service. */ public struct MessageResponse: JSONDecodable { /// The raw JSON object used to construct this model. public let json: [String: Any] /// The user input from the request. public let input: Input? /// Whether to return more than one intent. /// Included in the response only when sent with the request. public let alternateIntents: Bool? /// Information about the state of the conversation. public let context: Context /// An array of terms from the request that were identified as entities. /// The array is empty if no entities were identified. public let entities: [Entity] /// An array of terms from the request that were identified as intents. Each intent has an /// associated confidence. The list is sorted in descending order of confidence. If there are /// 10 or fewer intents then the sum of the confidence values is 100%. The array is empty if /// no intents were identified. public let intents: [Intent] /// An output object that includes the response to the user, /// the nodes that were hit, and messages from the log. public let output: Output /// Used internally to initialize a `MessageResponse` model from JSON. public init(json: JSON) throws { self.json = try json.getDictionaryObject() input = try? json.decode(at: "input") alternateIntents = try? json.getBool(at: "alternate_intents") context = try json.decode(at: "context") entities = try json.decodedArray(at: "entities", type: Entity.self) intents = try json.decodedArray(at: "intents", type: Intent.self) output = try json.decode(at: "output") } }
apache-2.0
3820b34e211781993f67af90f8a24b71
38.85
97
0.691343
4.528409
false
false
false
false
xylxi/SLWebImage
SLImageCacheDemo/SLImageCacheDemo/ViewController.swift
1
3113
// // ViewController.swift // SLImageCache // // Created by DMW_W on 16/7/4. // Copyright © 2016年 XYLXI. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = 200 let yepAvatarURLStrings = [ "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/84c9a0a9-c6eb-4495-9b50-0d551749956a", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/7cf09c38-355b-4daa-b733-5fede0181e5f", "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-2.jpg", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/0e47196b-1656-4b79-8953-457afaca6f7b", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/e2b84ebe-533d-4845-a842-774de98c8504", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/e24117db-d360-4c0b-8159-c908bf216e38", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/0738b75f-b223-4e34-a61c-add693f99f74", "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-8.jpg", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/134f80a5-d273-4e7c-b490-f0de862c4ac4", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/d0c29846-e064-4b4c-b4aa-bd0bd2d8d435", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/d124dcfe-07ec-4ac6-aaf3-5ba6afd131ad", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/70f6f156-7707-471d-8c98-fcb7d2a6edb1", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/24795538-fc57-428b-843e-211e6b89a00c", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/70a3d702-7769-4616-8410-0a7f5d39d883", "https://yep-avatars.s3.cn-north-1.amazonaws.com.cn/db49a8c6-dd2f-464d-8d06-03e7268c7fb4", "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-1.jpg", ] for str in yepAvatarURLStrings { self.datas.append(NSURL(string: str)!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var datas = [NSURL]() } extension ViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.datas.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("SLTableViewCell", forIndexPath: indexPath) as! SLTableViewCell cell.model = self.datas[indexPath.row]; if indexPath.row == 0 { print(cell.imgView.sl_url) } return cell; } } class SLTableViewCell: UITableViewCell { @IBOutlet weak var imgView: UIImageView! var model: NSURL! { didSet { self.imgView.sl_setImageWithURL(model); } } }
mit
ea91200b8827269ff703cf65475384fc
41.027027
126
0.666881
3.113113
false
false
false
false
eldesperado/SpareTimeAlarmApp
SpareTimeMusicApp/SpringAnimation.swift
1
2240
// // SpringAnimation.swift // Example // // Created by Wojciech Lukaszuk on 06/09/14. // Copyright (c) 2014 Wojtek Lukaszuk. All rights reserved. // import QuartzCore class SpringAnimation: CAKeyframeAnimation { var damping: CGFloat = 10.0 var mass: CGFloat = 1.0 var stiffness: CGFloat = 300.0 var velocity: CGFloat = 0 var fromValue: CGFloat = 0.0 var toValue: CGFloat = 0.0 override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! SpringAnimation duration = durationForEpsilon(0.01) copy.values = interpolatedValues() copy.duration = duration copy.mass = mass copy.stiffness = stiffness copy.damping = damping copy.velocity = velocity copy.fromValue = fromValue copy.toValue = toValue return copy } func interpolatedValues() -> [CGFloat] { var values: [CGFloat] = [] var value: CGFloat = 0 let valuesCount: Int = Int(duration * 60) let ω0: CGFloat = sqrt(stiffness / mass) // angular frequency let β: CGFloat = damping / (2 * mass) // amount of damping let v0 : CGFloat = velocity let x0: CGFloat = 1 // substituted initial value for i in 0..<valuesCount { let t: CGFloat = CGFloat(i)/60.0 if β < ω0 { // underdamped let ω1: CGFloat = sqrt(ω0 * ω0 - β * β) value = exp(-β * t) * (x0 * cos(ω1 * t) + CGFloat((β * x0 + v0) / ω1) * sin(ω1 * t)) } else if β == ω0 { // critically damped value = exp(-β * t) * (x0 + (β * x0 + v0) * t) } else { // overdamped let ω2: CGFloat = sqrt(β * β - ω0 * ω0) let sinhVal = sinh( ω2 * t) let coshVal = cosh(CGFloat(ω2 * t)) value = exp(-β * t) * (x0 * coshVal + ((β * x0 + v0) / ω2) * sinhVal) } values.append(toValue - value * (toValue - fromValue)) } return values } func durationForEpsilon(epsilon: CGFloat) -> CFTimeInterval { let beta: CGFloat = damping / (2 * mass) var duration: CGFloat = 0 while exp(-beta * duration) >= epsilon { duration += 0.1 } return CFTimeInterval(duration) } }
mit
f3052a3552c7a2f2c319ed19f5b7e725
25.035294
92
0.576854
3.614379
false
false
false
false
Toxote/iOS
Toxote/Toxote/GameScene.swift
1
7230
// // GameScene.swift // SpriteKitSimpleGame // // Created by Laura Yang on 2017-01-27. // Copyright © 2017 Laura Yang. All rights reserved. // import SpriteKit func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } func / (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x / scalar, y: point.y / scalar) } #if !(arch(x86_64) || arch(arm64)) func sqrt(a: CGFloat) -> CGFloat { return CGFloat(sqrtf(Float(a))) } #endif extension CGPoint { func length() -> CGFloat { return sqrt(x*x + y*y) } func normalized() -> CGPoint { return self / length() } } struct PhysicsCategory { static let None : UInt32 = 0 static let All : UInt32 = UInt32.max static let Monster : UInt32 = 0b1 // 1 static let Projectile: UInt32 = 0b10 // 2 } class GameScene: SKScene, SKPhysicsContactDelegate { // 1 let player = SKSpriteNode(imageNamed: "player") var monstersDestroyed = 0 override func didMove(to view: SKView) { // 2 backgroundColor = SKColor.white // 3 player.position = CGPoint(x: size.width * 0.1, y: size.height * 0.5) // 4 addChild(player) physicsWorld.gravity = CGVector.zero physicsWorld.contactDelegate = self run(SKAction.repeatForever( SKAction.sequence([ SKAction.run(addMonster), SKAction.wait(forDuration: 0.5) ]) )) let backgroundMusic = SKAudioNode(fileNamed: "background-music-aac.caf") backgroundMusic.autoplayLooped = true addChild(backgroundMusic) } func random() -> CGFloat { return CGFloat(Float(arc4random()) / 0xFFFFFFFF) } func random(min: CGFloat, max: CGFloat) -> CGFloat { return random() * (max - min) + min } func addMonster() { // Create sprite let monster = SKSpriteNode(imageNamed: "monster") monster.physicsBody = SKPhysicsBody(rectangleOf: monster.size) // 1 monster.physicsBody?.isDynamic = true // 2 monster.physicsBody?.categoryBitMask = PhysicsCategory.Monster // 3 monster.physicsBody?.contactTestBitMask = PhysicsCategory.Projectile // 4 monster.physicsBody?.collisionBitMask = PhysicsCategory.None // 5 // Determine where to spawn the monster along the Y axis let actualY = random(min: monster.size.height/2, max: size.height - monster.size.height/2) // Position the monster slightly off-screen along the right edge, // and along a random position along the Y axis as calculated above monster.position = CGPoint(x: size.width + monster.size.width/2, y: actualY) // Add the monster to the scene addChild(monster) // Determine speed of the monster let actualDuration = random(min: CGFloat(2.0), max: CGFloat(4.0)) // Create the actions let actionMove = SKAction.move(to: CGPoint(x: -monster.size.width/2, y: actualY), duration: TimeInterval(actualDuration)) let actionMoveDone = SKAction.removeFromParent() let loseAction = SKAction.run() { let reveal = SKTransition.flipHorizontal(withDuration: 0.5) let gameOverScene = GameOverScene(size: self.size, won: false) self.view?.presentScene(gameOverScene, transition: reveal) } monster.run(SKAction.sequence([actionMove, loseAction, actionMoveDone])) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { run(SKAction.playSoundFileNamed("pew-pew-lei.caf", waitForCompletion: false)) // 1 - Choose one of the touches to work with guard let touch = touches.first else { return } let touchLocation = touch.location(in: self) // 2 - Set up initial location of projectile let projectile = SKSpriteNode(imageNamed: "projectile") projectile.position = player.position projectile.physicsBody = SKPhysicsBody(circleOfRadius: projectile.size.width/2) projectile.physicsBody?.isDynamic = true projectile.physicsBody?.categoryBitMask = PhysicsCategory.Projectile projectile.physicsBody?.contactTestBitMask = PhysicsCategory.Monster projectile.physicsBody?.collisionBitMask = PhysicsCategory.None projectile.physicsBody?.usesPreciseCollisionDetection = true // 3 - Determine offset of location to projectile let offset = touchLocation - projectile.position // 4 - Bail out if you are shooting down or backwards if (offset.x < 0) { return } // 5 - OK to add now - you've double checked position addChild(projectile) // 6 - Get the direction of where to shoot let direction = offset.normalized() // 7 - Make it shoot far enough to be guaranteed off screen let shootAmount = direction * 1000 // 8 - Add the shoot amount to the current position let realDest = shootAmount + projectile.position // 9 - Create the actions let actionMove = SKAction.move(to: realDest, duration: 2.0) let actionMoveDone = SKAction.removeFromParent() projectile.run(SKAction.sequence([actionMove, actionMoveDone])) } func projectileDidCollideWithMonster(projectile: SKSpriteNode, monster: SKSpriteNode) { print("Hit") projectile.removeFromParent() monster.removeFromParent() monstersDestroyed += 1 if (monstersDestroyed > 30) { let reveal = SKTransition.flipHorizontal(withDuration: 0.5) let gameOverScene = GameOverScene(size: self.size, won: true) self.view?.presentScene(gameOverScene, transition: reveal) } } func didBegin(_ contact: SKPhysicsContact) { // 1 var firstBody: SKPhysicsBody var secondBody: SKPhysicsBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } // 2 if ((firstBody.categoryBitMask & PhysicsCategory.Monster != 0) && (secondBody.categoryBitMask & PhysicsCategory.Projectile != 0)) { if let monster = firstBody.node as? SKSpriteNode, let projectile = secondBody.node as? SKSpriteNode { projectileDidCollideWithMonster(projectile: projectile, monster: monster) } } } }
gpl-3.0
10a6415eb3ed9679c32c3cbb0173120e
32.780374
129
0.607553
4.685029
false
false
false
false
novi/mysql-swift
Tests/MySQLTests/QueryParameterTests.swift
1
12457
// // QueryParameterTests.swift // MySQL // // Created by Yusuke Ito on 4/21/16. // Copyright © 2016 Yusuke Ito. All rights reserved. // import XCTest import MySQL import SQLFormatter // the URL as QueryParameter should be extension URL: QueryParameter { public func queryParameter(option: QueryParameterOption) throws -> QueryParameterType { return self.absoluteString.queryParameter(option: option) } } extension QueryParameterTests { static var allTests : [(String, (QueryParameterTests) -> () throws -> Void)] { return [ ("testIDType", testIDType), ("testIDTypeInContainer", testIDTypeInContainer), ("testEnumType", testEnumType), ("testAutoincrementType", testAutoincrementType), ("testDateComponentsType", testDateComponentsType), ("testDataAndURLType", testDataAndURLType), ("testDecimalType", testDecimalType), ("testCodableIDType", testCodableIDType), ("testCodableIDType_AutoincrementNoID", testCodableIDType_AutoincrementNoID) ] } } final class QueryParameterTests: XCTestCase { private struct IDInt: IDType { let id: Int init(_ id: Int) { self.id = id } } private struct IDString: IDType { let id: String init(_ id: String) { self.id = id } } private struct ModelWithIDType_StringAutoincrement: Encodable, QueryParameter { let idStringAutoincrement: AutoincrementID<IDString> } private struct ModelWithIDType_IntAutoincrement: Encodable, QueryParameter { let idIntAutoincrement: AutoincrementID<IDInt> } private enum SomeEnumParameter: String, QueryRawRepresentableParameter { case first = "first 1" case second = "second' 2" } private enum SomeEnumCodable: String, Codable, QueryParameter { case first = "first 1" case second = "second' 2" } // https://developer.apple.com/documentation/swift/optionset private struct ShippingOptions: OptionSet, QueryRawRepresentableParameter { let rawValue: Int static let nextDay = ShippingOptions(rawValue: 1 << 0) static let secondDay = ShippingOptions(rawValue: 1 << 1) static let priority = ShippingOptions(rawValue: 1 << 2) static let standard = ShippingOptions(rawValue: 1 << 3) static let express: ShippingOptions = [.nextDay, .secondDay] static let all: ShippingOptions = [.express, .priority, .standard] } private struct ModelWithData: Encodable, QueryParameter { let data: Data } private struct ModelWithDate: Encodable, QueryParameter { let date: Date } private struct ModelWithDateComponents: Encodable, QueryParameter { let dateComponents: DateComponents } private struct ModelWithURL: Encodable, QueryParameter { let url: URL } private struct ModelWithDecimal: Encodable, QueryParameter { let value: Decimal } func testIDType() throws { let idInt: QueryParameter = IDInt(1234) XCTAssertEqual(try idInt.queryParameter(option: queryOption).escaped(), "1234") //let id: SomeID = try SomeID.fromSQLValue(string: "5678") //XCTAssertEqual(id.id, 5678) let idString: QueryParameter = IDString("123abc") XCTAssertEqual(try idString.queryParameter(option: queryOption).escaped(), "'123abc'") let idIntAutoincrement: QueryParameter = AutoincrementID(IDInt(1234)) XCTAssertEqual(try idIntAutoincrement.queryParameter(option: queryOption).escaped(), "1234") let idStringAutoincrement: QueryParameter = AutoincrementID(IDString("123abc")) XCTAssertEqual(try idStringAutoincrement.queryParameter(option: queryOption).escaped(), "'123abc'") } func testIDTypeInContainer() throws { do { let param: QueryParameter = ModelWithIDType_IntAutoincrement(idIntAutoincrement: .ID(IDInt(1234))) XCTAssertEqual(try param.queryParameter(option: queryOption).escaped(), "`idIntAutoincrement` = 1234") } do { let param: QueryParameter = ModelWithIDType_StringAutoincrement(idStringAutoincrement: .ID(IDString("123abc"))) XCTAssertEqual(try param.queryParameter(option: queryOption).escaped(), "`idStringAutoincrement` = '123abc'") } } func testEnumType() throws { do { let someVal: QueryParameter = SomeEnumParameter.second let escaped = "second' 2".escaped() XCTAssertEqual(try someVal.queryParameter(option: queryOption).escaped() , escaped) } do { let someVal: QueryParameter = SomeEnumCodable.second let escaped = "second' 2".escaped() XCTAssertEqual(try someVal.queryParameter(option: queryOption).escaped() , escaped) } do { let someOption: QueryParameter = ShippingOptions.all XCTAssertEqual(try someOption.queryParameter(option: queryOption).escaped() , "\(ShippingOptions.all.rawValue)") } } func testAutoincrementType() throws { let userID: AutoincrementID<UserID> = .ID(UserID(333)) XCTAssertEqual(userID, AutoincrementID.ID(UserID(333))) let someStringID: AutoincrementID<SomeStringID> = .ID(SomeStringID("id678@")) XCTAssertEqual(someStringID, AutoincrementID.ID(SomeStringID("id678@"))) let noID: AutoincrementID<UserID> = .noID XCTAssertEqual(noID, AutoincrementID.noID) } func testDateComponentsType() throws { do { let compsEmpty = DateComponents() let model = ModelWithDateComponents(dateComponents: compsEmpty) let _ = try model.queryParameter(option: queryOption).escaped() XCTFail("this should be throws an error") } catch { // OK } do { // MySQL YEAR type var comps = DateComponents() comps.year = 2155 let model = ModelWithDateComponents(dateComponents: comps) let queryString = try model.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`dateComponents` = '2155'") } do { // MySQL TIME type var comps = DateComponents() comps.hour = -838 comps.minute = 59 comps.second = 59 let model = ModelWithDateComponents(dateComponents: comps) let queryString = try model.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`dateComponents` = '-838:59:59'") } do { // MySQL TIME type // with nanosecond var comps = DateComponents() comps.hour = -838 comps.minute = 59 comps.second = 59 comps.nanosecond = 1234567 let model = ModelWithDateComponents(dateComponents: comps) let queryString = try model.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`dateComponents` = '-838:59:59.001235'") } do { // MySQL DATETIME, TIMESTAMP type var comps = DateComponents() comps.year = 9999 comps.month = 12 comps.day = 31 comps.hour = 23 comps.minute = 59 comps.second = 59 let model = ModelWithDateComponents(dateComponents: comps) let queryString = try model.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`dateComponents` = '9999-12-31 23:59:59'") } do { // MySQL DATETIME, TIMESTAMP type // with nanosecond var comps = DateComponents() comps.year = 9999 comps.month = 12 comps.day = 31 comps.hour = 23 comps.minute = 59 comps.second = 59 comps.nanosecond = 1234567 let model = ModelWithDateComponents(dateComponents: comps) let queryString = try model.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`dateComponents` = '9999-12-31 23:59:59.001235'") } } func testDataAndURLType() throws { do { let dataModel = ModelWithData(data: Data([0x12, 0x34, 0x56, 0xff, 0x00])) let queryString = try dataModel.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`data` = x'123456ff00'") } do { let urlModel = ModelWithURL(url: URL(string: "https://apple.com/iphone")!) let queryString = try urlModel.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`url` = 'https://apple.com/iphone'") } do { let param: QueryParameter = URL(string: "https://apple.com/iphone")! let queryString = try param.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "'https://apple.com/iphone'") } } func testDecimalType() throws { let decimalModel = ModelWithDecimal(value: Decimal(1.2345e100)) let queryString = try decimalModel.queryParameter(option: queryOption).escaped() XCTAssertEqual(queryString, "`value` = '12345000000000010240000000000000000000000000000000000000000000000000000000000000000000000000000000000'") } private enum UserType: String, Codable { case user = "user" case admin = "admin" } private struct CodableModel: Codable, QueryParameter { let id: UserID let name: String let userType: UserType } private struct CodableModelWithAutoincrement: Codable, QueryParameter { let id: AutoincrementID<UserID> let name: String let userType: UserType } func testCodableIDType() throws { let expectedResult = Set(arrayLiteral: "`id` = 123", "`name` = 'test4456'", "`userType` = 'user'") do { let parameter: QueryParameter = CodableModel(id: UserID(123), name: "test4456", userType: .user) let result = try parameter.queryParameter(option: queryOption).escaped() XCTAssertEqual(Set(result.split(separator: ",").map(String.init).map({ $0.trimmingCharacters(in: .whitespaces) })), expectedResult) } do { let parameter: QueryParameter = CodableModelWithAutoincrement(id: AutoincrementID(UserID(123)), name: "test4456", userType: .user) let result = try parameter.queryParameter(option: queryOption).escaped() XCTAssertEqual(Set(result.split(separator: ",").map(String.init).map({ $0.trimmingCharacters(in: .whitespaces) })), expectedResult) } } func testCodableIDType_AutoincrementNoID() throws { let expectedResult = Set(arrayLiteral: "`name` = 'test4456'", "`userType` = 'user'") let parameter: QueryParameter = CodableModelWithAutoincrement(id: .noID, name: "test4456", userType: .user) let result = try parameter.queryParameter(option: queryOption).escaped() XCTAssertEqual(Set(result.split(separator: ",").map(String.init).map({ $0.trimmingCharacters(in: .whitespaces) })), expectedResult) } }
mit
230f071fbaf6f5d278aed83125f91c86
35.961424
143
0.580122
4.972455
false
true
false
false
practicalswift/swift
stdlib/public/core/StringUnicodeScalarView.swift
1
14991
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of Unicode scalar values. /// /// You can access a string's view of Unicode scalar values by using its /// `unicodeScalars` property. Unicode scalar values are the 21-bit codes /// that are the basic unit of Unicode. Each scalar value is represented by /// a `Unicode.Scalar` instance and is equivalent to a UTF-32 code unit. /// /// let flowers = "Flowers 💐" /// for v in flowers.unicodeScalars { /// print(v.value) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 128144 /// /// Some characters that are visible in a string are made up of more than one /// Unicode scalar value. In that case, a string's `unicodeScalars` view /// contains more elements than the string itself. /// /// let flag = "🇵🇷" /// for c in flag { /// print(c) /// } /// // 🇵🇷 /// /// for v in flag.unicodeScalars { /// print(v.value) /// } /// // 127477 /// // 127479 /// /// You can convert a `String.UnicodeScalarView` instance back into a string /// using the `String` type's `init(_:)` initializer. /// /// let favemoji = "My favorite emoji is 🎉" /// if let i = favemoji.unicodeScalars.firstIndex(where: { $0.value >= 128 }) { /// let asciiPrefix = String(favemoji.unicodeScalars[..<i]) /// print(asciiPrefix) /// } /// // Prints "My favorite emoji is " @_fixed_layout public struct UnicodeScalarView { @usableFromInline internal var _guts: _StringGuts @inlinable @inline(__always) internal init(_ _guts: _StringGuts) { self._guts = _guts _invariantCheck() } } } extension String.UnicodeScalarView { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { // TODO: Assert start/end are scalar aligned } #endif // INTERNAL_CHECKS_ENABLED } extension String.UnicodeScalarView: BidirectionalCollection { public typealias Index = String.Index /// The position of the first Unicode scalar value if the string is /// nonempty. /// /// If the string is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Index { @inline(__always) get { return _guts.startIndex } } /// The "past the end" position---that is, the position one greater than /// the last valid subscript argument. /// /// In an empty Unicode scalars view, `endIndex` is equal to `startIndex`. @inlinable public var endIndex: Index { @inline(__always) get { return _guts.endIndex } } /// Returns the next consecutive location after `i`. /// /// - Precondition: The next location exists. @inlinable @inline(__always) public func index(after i: Index) -> Index { _internalInvariant(i < endIndex) // TODO(String performance): isASCII fast-path if _fastPath(_guts.isFastUTF8) { let len = _guts.fastUTF8ScalarLength(startingAt: i._encodedOffset) return i.encoded(offsetBy: len) } return _foreignIndex(after: i) } /// Returns the previous consecutive location before `i`. /// /// - Precondition: The previous location exists. @inlinable @inline(__always) public func index(before i: Index) -> Index { precondition(i._encodedOffset > 0) // TODO(String performance): isASCII fast-path if _fastPath(_guts.isFastUTF8) { let len = _guts.withFastUTF8 { utf8 -> Int in return _utf8ScalarLength(utf8, endingAt: i._encodedOffset) } _internalInvariant(len <= 4, "invalid UTF8") return i.encoded(offsetBy: -len) } return _foreignIndex(before: i) } /// Accesses the Unicode scalar value at the given position. /// /// The following example searches a string's Unicode scalars view for a /// capital letter and then prints the character and Unicode scalar value /// at the found index: /// /// let greeting = "Hello, friend!" /// if let i = greeting.unicodeScalars.firstIndex(where: { "A"..."Z" ~= $0 }) { /// print("First capital letter: \(greeting.unicodeScalars[i])") /// print("Unicode scalar value: \(greeting.unicodeScalars[i].value)") /// } /// // Prints "First capital letter: H" /// // Prints "Unicode scalar value: 72" /// /// - Parameter position: A valid index of the character view. `position` /// must be less than the view's end index. @inlinable public subscript(position: Index) -> Unicode.Scalar { @inline(__always) get { String(_guts)._boundsCheck(position) let i = _guts.scalarAlign(position) return _guts.errorCorrectedScalar(startingAt: i._encodedOffset).0 } } } extension String.UnicodeScalarView { @_fixed_layout public struct Iterator: IteratorProtocol { @usableFromInline internal var _guts: _StringGuts @usableFromInline internal var _position: Int = 0 @usableFromInline internal var _end: Int @inlinable internal init(_ guts: _StringGuts) { self._end = guts.count self._guts = guts } @inlinable @inline(__always) public mutating func next() -> Unicode.Scalar? { guard _fastPath(_position < _end) else { return nil } let (result, len) = _guts.errorCorrectedScalar(startingAt: _position) _position &+= len return result } } @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_guts) } } extension String.UnicodeScalarView: CustomStringConvertible { @inlinable public var description: String { @inline(__always) get { return String(_guts) } } } extension String.UnicodeScalarView: CustomDebugStringConvertible { public var debugDescription: String { return "StringUnicodeScalarView(\(self.description.debugDescription))" } } extension String { /// Creates a string corresponding to the given collection of Unicode /// scalars. /// /// You can use this initializer to create a new string from a slice of /// another string's `unicodeScalars` view. /// /// let picnicGuest = "Deserving porcupine" /// if let i = picnicGuest.unicodeScalars.firstIndex(of: " ") { /// let adjective = String(picnicGuest.unicodeScalars[..<i]) /// print(adjective) /// } /// // Prints "Deserving" /// /// The `adjective` constant is created by calling this initializer with a /// slice of the `picnicGuest.unicodeScalars` view. /// /// - Parameter unicodeScalars: A collection of Unicode scalar values. @inlinable @inline(__always) public init(_ unicodeScalars: UnicodeScalarView) { self.init(unicodeScalars._guts) } /// The index type for a string's `unicodeScalars` view. public typealias UnicodeScalarIndex = UnicodeScalarView.Index /// The string's value represented as a collection of Unicode scalar values. @inlinable public var unicodeScalars: UnicodeScalarView { @inline(__always) get { return UnicodeScalarView(_guts) } @inline(__always) set { _guts = newValue._guts } } } extension String.UnicodeScalarView : RangeReplaceableCollection { /// Creates an empty view instance. @inlinable @inline(__always) public init() { self.init(_StringGuts()) } /// Reserves enough space in the view's underlying storage to store the /// specified number of ASCII characters. /// /// Because a Unicode scalar value can require more than a single ASCII /// character's worth of storage, additional allocation may be necessary /// when adding to a Unicode scalar view after a call to /// `reserveCapacity(_:)`. /// /// - Parameter n: The minimum number of ASCII character's worth of storage /// to allocate. /// /// - Complexity: O(*n*), where *n* is the capacity being reserved. public mutating func reserveCapacity(_ n: Int) { self._guts.reserveCapacity(n) } /// Appends the given Unicode scalar to the view. /// /// - Parameter c: The character to append to the string. public mutating func append(_ c: Unicode.Scalar) { self._guts.append(String(c)._guts) } /// Appends the Unicode scalar values in the given sequence to the view. /// /// - Parameter newElements: A sequence of Unicode scalar values. /// /// - Complexity: O(*n*), where *n* is the length of the resulting view. public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Element == Unicode.Scalar { // TODO(String performance): Skip extra String allocation let scalars = String(decoding: newElements.map { $0.value }, as: UTF32.self) self = (String(self._guts) + scalars).unicodeScalars } /// Replaces the elements within the specified bounds with the given Unicode /// scalar values. /// /// Calling this method invalidates any existing indices for use with this /// string. /// /// - Parameters: /// - bounds: The range of elements to replace. The bounds of the range /// must be valid indices of the view. /// - newElements: The new Unicode scalar values to add to the string. /// /// - Complexity: O(*m*), where *m* is the combined length of the view and /// `newElements`. If the call to `replaceSubrange(_:with:)` simply /// removes elements at the end of the string, the complexity is O(*n*), /// where *n* is equal to `bounds.count`. public mutating func replaceSubrange<C>( _ bounds: Range<Index>, with newElements: C ) where C : Collection, C.Element == Unicode.Scalar { // TODO(String performance): Skip extra String and Array allocation let utf8Replacement = newElements.flatMap { String($0).utf8 } let replacement = utf8Replacement.withUnsafeBufferPointer { return String._uncheckedFromUTF8($0) } var copy = String(_guts) copy.replaceSubrange(bounds, with: replacement) self = copy.unicodeScalars } } // Index conversions extension String.UnicodeScalarIndex { /// Creates an index in the given Unicode scalars view that corresponds /// exactly to the specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the string's /// `unicodeScalars` view: /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.firstIndex(of: 32)! /// let scalarIndex = String.Index(utf16Index, within: cafe.unicodeScalars)! /// /// print(String(cafe.unicodeScalars[..<scalarIndex])) /// // Prints "Café" /// /// If the index passed as `sourcePosition` doesn't have an exact /// corresponding position in `unicodeScalars`, the result of the /// initializer is `nil`. For example, an attempt to convert the position of /// the trailing surrogate of a UTF-16 surrogate pair results in `nil`. /// /// - Parameters: /// - sourcePosition: A position in the `utf16` view of a string. /// `utf16Index` must be an element of /// `String(unicodeScalars).utf16.indices`. /// - unicodeScalars: The `UnicodeScalarView` in which to find the new /// position. public init?( _ sourcePosition: String.Index, within unicodeScalars: String.UnicodeScalarView ) { guard unicodeScalars._guts.isOnUnicodeScalarBoundary(sourcePosition) else { return nil } self = sourcePosition } /// Returns the position in the given string that corresponds exactly to this /// index. /// /// This example first finds the position of a space (UTF-8 code point `32`) /// in a string's `utf8` view and then uses this method find the same position /// in the string. /// /// let cafe = "Café 🍵" /// let i = cafe.unicodeScalars.firstIndex(of: "🍵") /// let j = i.samePosition(in: cafe)! /// print(cafe[j...]) /// // Prints "🍵" /// /// - Parameter characters: The string to use for the index conversion. /// This index must be a valid index of at least one view of `characters`. /// - Returns: The position in `characters` that corresponds exactly to /// this index. If this index does not have an exact corresponding /// position in `characters`, this method returns `nil`. For example, /// an attempt to convert the position of a UTF-8 continuation byte /// returns `nil`. public func samePosition(in characters: String) -> String.Index? { return String.Index(self, within: characters) } } // Reflection extension String.UnicodeScalarView : CustomReflectable { /// Returns a mirror that reflects the Unicode scalars view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } //===--- Slicing Support --------------------------------------------------===// /// In Swift 3.2, in the absence of type context, /// /// someString.unicodeScalars[ /// someString.unicodeScalars.startIndex /// ..< someString.unicodeScalars.endIndex] /// /// was deduced to be of type `String.UnicodeScalarView`. Provide a /// more-specific Swift-3-only `subscript` overload that continues to produce /// `String.UnicodeScalarView`. extension String.UnicodeScalarView { public typealias SubSequence = Substring.UnicodeScalarView @available(swift, introduced: 4) public subscript(r: Range<Index>) -> String.UnicodeScalarView.SubSequence { return String.UnicodeScalarView.SubSequence(self, _bounds: r) } } // Foreign string Support extension String.UnicodeScalarView { @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(after i: Index) -> Index { _internalInvariant(_guts.isForeign) let cu = _guts.foreignErrorCorrectedUTF16CodeUnit(at: i) let len = _isLeadingSurrogate(cu) ? 2 : 1 return i.encoded(offsetBy: len) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(before i: Index) -> Index { _internalInvariant(_guts.isForeign) let priorIdx = i.priorEncoded let cu = _guts.foreignErrorCorrectedUTF16CodeUnit(at: priorIdx) let len = _isTrailingSurrogate(cu) ? 2 : 1 return i.encoded(offsetBy: -len) } }
apache-2.0
87d4437a1bb4f0fb53d721fc9fd23e3a
33.307339
85
0.653496
4.329378
false
false
false
false
huonw/swift
benchmark/single-source/MapReduce.swift
9
5056
//===--- MapReduce.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils import Foundation public let MapReduce = [ BenchmarkInfo(name: "MapReduce", runFunction: run_MapReduce, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceAnyCollection", runFunction: run_MapReduceAnyCollection, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceAnyCollectionShort", runFunction: run_MapReduceAnyCollectionShort, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceClass", runFunction: run_MapReduceClass, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceClassShort", runFunction: run_MapReduceClassShort, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceLazyCollection", runFunction: run_MapReduceLazyCollection, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceLazyCollectionShort", runFunction: run_MapReduceLazyCollectionShort, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceLazySequence", runFunction: run_MapReduceLazySequence, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceSequence", runFunction: run_MapReduceSequence, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceShort", runFunction: run_MapReduceShort, tags: [.validation, .algorithm]), BenchmarkInfo(name: "MapReduceShortString", runFunction: run_MapReduceShortString, tags: [.validation, .algorithm, .String]), BenchmarkInfo(name: "MapReduceString", runFunction: run_MapReduceString, tags: [.validation, .algorithm, .String]), ] @inline(never) public func run_MapReduce(_ N: Int) { var numbers = [Int](0..<1000) var c = 0 for _ in 1...N*100 { numbers = numbers.map { $0 &+ 5 } c += numbers.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceAnyCollection(_ N: Int) { let numbers = AnyCollection([Int](0..<1000)) var c = 0 for _ in 1...N*100 { let mapped = numbers.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceAnyCollectionShort(_ N: Int) { let numbers = AnyCollection([Int](0..<10)) var c = 0 for _ in 1...N*10000 { let mapped = numbers.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceShort(_ N: Int) { var numbers = [Int](0..<10) var c = 0 for _ in 1...N*10000 { numbers = numbers.map { $0 &+ 5 } c += numbers.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceSequence(_ N: Int) { let numbers = sequence(first: 0) { $0 < 1000 ? $0 &+ 1 : nil } var c = 0 for _ in 1...N*100 { let mapped = numbers.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceLazySequence(_ N: Int) { let numbers = sequence(first: 0) { $0 < 1000 ? $0 &+ 1 : nil } var c = 0 for _ in 1...N*100 { let mapped = numbers.lazy.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceLazyCollection(_ N: Int) { let numbers = [Int](0..<1000) var c = 0 for _ in 1...N*100 { let mapped = numbers.lazy.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceLazyCollectionShort(_ N: Int) { let numbers = [Int](0..<10) var c = 0 for _ in 1...N*10000 { let mapped = numbers.lazy.map { $0 &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceString(_ N: Int) { let s = "thequickbrownfoxjumpsoverthelazydogusingasmanycharacteraspossible123456789" var c: UInt64 = 0 for _ in 1...N*100 { c += s.utf8.map { UInt64($0 &+ 5) }.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceShortString(_ N: Int) { let s = "12345" var c: UInt64 = 0 for _ in 1...N*100 { c += s.utf8.map { UInt64($0 &+ 5) }.reduce(0, &+) } CheckResults(c != 0) } @inline(never) public func run_MapReduceClass(_ N: Int) { #if _runtime(_ObjC) let numbers = (0..<1000).map { NSDecimalNumber(value: $0) } var c = 0 for _ in 1...N*100 { let mapped = numbers.map { $0.intValue &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) #endif } @inline(never) public func run_MapReduceClassShort(_ N: Int) { #if _runtime(_ObjC) let numbers = (0..<10).map { NSDecimalNumber(value: $0) } var c = 0 for _ in 1...N*10000 { let mapped = numbers.map { $0.intValue &+ 5 } c += mapped.reduce(0, &+) } CheckResults(c != 0) #endif }
apache-2.0
6a33b1ae7428cb5f039790897dc036f4
27.727273
134
0.632911
3.441797
false
false
false
false
moked/iuob
iUOB 2/Controllers/Schedule Builder/OptionsVC.swift
1
16606
// // OptionsVC.swift // iUOB 2 // // Created by Miqdad Altaitoon on 12/17/16. // Copyright © 2016 Miqdad Altaitoon. All rights reserved. // import UIKit import Alamofire import Kanna import MBProgressHUD import NYAlertViewController /// first load all courses data. then, options filters: time and sections class OptionsVC: UIViewController { // MARK: - Properties @IBOutlet weak var totalCombinationsLabel: UILabel! @IBOutlet weak var tooMuchLabel: UILabel! @IBOutlet weak var workingDaysSegmentedControl: UISegmentedControl! @IBOutlet weak var startAtSegmentedControl: UISegmentedControl! @IBOutlet weak var finishAtSegmentedControl: UISegmentedControl! @IBOutlet weak var lecturesLocationsSegmentedControl: UISegmentedControl! @IBOutlet weak var filterChangedImageView: UIImageView! @IBOutlet weak var sectionsFilterOutlet: UIButton! @IBOutlet weak var nextButtonOutlet: UIBarButtonItem! var addedCourses: [String] = [] // added courses by the user var semester: Int = 0 var courseSectionDict = [String: [Section]]() // source of all sctions var filteredCourseSectionDict = [String: [Section]]() // courseSectionDict after applaying filters var filterChanged = false // if user used filter at last or not // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() nextButtonOutlet.isEnabled = false filterChangedImageView.isHidden = true tooMuchLabel.text = "" disableAll() sectionsFilterOutlet.layer.cornerRadius = 15 getDepartments() googleAnalytics() } func googleAnalytics() { if let tracker = GAI.sharedInstance().defaultTracker { tracker.set(kGAIScreenName, value: NSStringFromClass(type(of: self)).components(separatedBy: ".").last!) let builder: NSObject = GAIDictionaryBuilder.createScreenView().build() tracker.send(builder as! [NSObject : AnyObject]) } } func disableAll() { workingDaysSegmentedControl.isEnabled = false startAtSegmentedControl.isEnabled = false finishAtSegmentedControl.isEnabled = false lecturesLocationsSegmentedControl.isEnabled = false sectionsFilterOutlet.isEnabled = false totalCombinationsLabel.text = "0" } func enableAll() { workingDaysSegmentedControl.isEnabled = true startAtSegmentedControl.isEnabled = true finishAtSegmentedControl.isEnabled = true lecturesLocationsSegmentedControl.isEnabled = true sectionsFilterOutlet.isEnabled = true } /// first, get department url to check if this semester available or not func getDepartments() { let url = "\(Constants.baseURL)/cgi/enr/schedule2.abrv" MBProgressHUD.showAdded(to: self.view, animated: true) Alamofire.request(url, method: .get, parameters: ["prog": "1", "cyer": "2016", "csms": semester]) .validate() .responseString { response in MBProgressHUD.hide(for: self.view, animated: true) if response.result.error == nil { let departments = UOBParser.parseDepartments(response.result.value!) if departments.count == 0 { self.showAlert(title: "Sorry", msg: "Schedule for 2016\\\(self.semester) is not available. Make sure you select the right semester.") } else { self.getNextCourseData(0) // get first course } } else { self.showAlert(title: "Error", msg: (response.result.error?.localizedDescription)!) } } } /// function to get all courses recuresvly /// /// - Parameter index: course index func getNextCourseData(_ index: Int) { let thisCourse = addedCourses[index] let seperate = thisCourse.index(thisCourse.endIndex, offsetBy: -3) // last three characters represent the courseNo e.g 101 in ITCS101 let courseNo = thisCourse.substring(from: seperate) let department = thisCourse.substring(to: seperate) var departmentCode = "" if let dCode = Constants.depCodeMapping[department] { departmentCode = dCode } let url = "\(Constants.baseURL)/cgi/enr/schedule2.contentpage" Alamofire.request(url, parameters: ["abv": department, "inl": "\(departmentCode)", "crsno": "\(courseNo)", "prog": "1", "crd": "3", "cyer": "2016", "csms": semester]) .validate() .responseString { response in if response.result.error == nil { self.parseResult(html: response.result.value!, index: index, course: thisCourse) } else { self.showAlert(title: "Error", msg: (response.result.error?.localizedDescription)!) } } } func parseResult(html: String, index: Int, course: String) { var allSections = [Section]() for section in UOBParser.parseSections(html) { if section.timing.count > 0 { // if it has a time (some sections come without time e.g for College of education) var sec = section sec.note = course allSections.append(sec) } } if allSections.count > 0 { courseSectionDict[course] = allSections // update dictinary } else { showAlert(title: "Course not found", msg: "Course [\(course)] not found") } // load others recuresvly if index + 1 < self.addedCourses.count { self.getNextCourseData(index + 1) } else { self.checkForFinalExamClashes() self.createTimeTable() self.updatePossibleCombinations() } } /// check if there is final exam clash between any 2 courses and alert the user func checkForFinalExamClashes() { let lazyMapCollection = courseSectionDict.keys let keysArray = Array(lazyMapCollection.map { String($0)! }) for i in 0..<keysArray.count { for j in i+1..<keysArray.count { let courseA = courseSectionDict[keysArray[i]]!.last! let courseB = courseSectionDict[keysArray[j]]!.last! if let finalDateA = courseA.finalExam.date, let finalDateB = courseB.finalExam.date { if finalDateA == finalDateB { if courseA.finalExam.startTime == courseB.finalExam.startTime { // clash self.showAlert(title: "Final exam clash", msg: "There is a clash in the final exam between \(keysArray[i]) and \(keysArray[j])") } } } } } } /// stupid function name. we just store the original courses/sections for later use func createTimeTable() { filteredCourseSectionDict = courseSectionDict } /// function will be called whenever the user change one of the options /// /// - Parameter sender: option segment control @IBAction func segmetChangeEvent(_ sender: UISegmentedControl) { if filterChanged { filterChanged = false self.filterChangedImageView.isHidden = true showAlert(title: "Reset", msg: "Filter has beed reset. Please use [Sections Filter] at last") } filteredCourseSectionDict = [:] // reset filtered for (course, sections) in courseSectionDict { filteredCourseSectionDict[course] = [] for section in sections { var passSection = false for timing in section.timing { if workingDaysSegmentedControl.selectedSegmentIndex > 0 { let workingDays = workingDaysSegmentedControl.titleForSegment(at: workingDaysSegmentedControl.selectedSegmentIndex)! for day in timing.day.characters { if (workingDays.range(of: "\(day)") == nil) { passSection = true // the section contain a day not in the user's selected working days break } } if passSection {break} // go for next section } if startAtSegmentedControl.selectedSegmentIndex > 0 { let startTime = startAtSegmentedControl.selectedSegmentIndex + 8 // 9,10,11,12 let timeArr = timing.timeFrom.components(separatedBy: ":") if timeArr.count > 1 { let sectionStartTime = Float(Float(timeArr[0])! + (Float(timeArr[1])! / 60.0)) if Float(startTime) > sectionStartTime { passSection = true break } } } if finishAtSegmentedControl.selectedSegmentIndex > 0 { let finishTime = finishAtSegmentedControl.selectedSegmentIndex + 11 // 12,1,2,3 let timeArr = timing.timeTo.components(separatedBy: ":") if timeArr.count > 1 { let sectionFinishTime = Float(Float(timeArr[0])! + (Float(timeArr[1])! / 60.0)) if Float(finishTime) < sectionFinishTime { passSection = true break } } } if lecturesLocationsSegmentedControl.selectedSegmentIndex > 0 { let room = timing.room var location = 0 // 0 = Sakheer, 1 = Isa Town if room.characters.count > 1 { if room.range(of: "-") != nil { let roomArr = room.components(separatedBy: "-") if let number = Int(roomArr[0]) { if number > 0 && number < 38 { location = 1 } } else if roomArr[0] == "A27" { location = 1 } } } if lecturesLocationsSegmentedControl.selectedSegmentIndex == 1 && location != 0 { passSection = true break } else if lecturesLocationsSegmentedControl.selectedSegmentIndex == 2 && location != 1 { passSection = true break } } } if passSection { continue } else { filteredCourseSectionDict[course]?.append(section) } } } updatePossibleCombinations() } func updatePossibleCombinations() { var totalCombinations = 1 for (_, sections) in filteredCourseSectionDict { totalCombinations *= sections.count } totalCombinationsLabel.text = "\(totalCombinations)" enableAll() if totalCombinations > 0 && totalCombinations < 20000 { nextButtonOutlet.isEnabled = true } else { nextButtonOutlet.isEnabled = false } if totalCombinations > 20000 { tooMuchLabel.text = "should be less than 20000" } else { tooMuchLabel.text = "" } } @IBAction func combinationsInfoButton(_ sender: Any) { showAlert(title: "Info", msg: "Number of possible combinations is the number of MAXIMUM possible combinations for the courses you entered. It should be less than 20000 in order to continue to the next page which will show you the TRUE number of combinations. You can minimize the number of possible combinations by selecting different options below.") } @IBAction func filterInfoButton(_ sender: Any) { // Filter has beed reset. Please use [Sections Filter] at last showAlert(title: "Info", msg: "Use [Section Filter] for extra options. You can choose what section you want to be included individually. Please use [Section Filter] after selecting the Working Days/Times/Location.") } func showAlert(title: String, msg: String) { let alertViewController = NYAlertViewController() alertViewController.title = title alertViewController.message = msg alertViewController.buttonCornerRadius = 20.0 alertViewController.view.tintColor = self.view.tintColor //alertViewController.cancelButtonColor = UIColor.redColor() alertViewController.destructiveButtonColor = UIColor(netHex:0xFFA739) alertViewController.swipeDismissalGestureEnabled = true alertViewController.backgroundTapDismissalGestureEnabled = true let cancelAction = NYAlertAction( title: "Close", style: .cancel, handler: { (action: NYAlertAction?) -> Void in self.dismiss(animated: true, completion: nil) } ) alertViewController.addAction(cancelAction) // Present the alert view controller self.present(alertViewController, animated: true, completion: nil) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "SectionsFilterSegue" { let destinationNavigationController = segue.destination as! UINavigationController let nextScene = destinationNavigationController.topViewController as? SectionsFilterVC nextScene!.courseSectionDict = courseSectionDict nextScene!.filteredCourseSectionDict = filteredCourseSectionDict } else if segue.identifier == "SummarySegue" { let nextScene = segue.destination as? SummaryVC nextScene!.filteredCourseSectionDict = filteredCourseSectionDict } } @IBAction func unwindToOptionsVC(segue: UIStoryboardSegue) { if let sectionsFilterVC = segue.source as? SectionsFilterVC { self.filteredCourseSectionDict = sectionsFilterVC.filteredCourseSectionDict self.filterChanged = sectionsFilterVC.filterChanged if self.filterChanged { self.filterChangedImageView.isHidden = false } else { self.filterChangedImageView.isHidden = true } updatePossibleCombinations() } } }
mit
12181651e083dc3625fa816d61fd0038
36.910959
359
0.521349
5.902951
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/Extensions/String+Pluralize.swift
1
3498
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /// Extensions on String for Science Journal used for formatting localized strings. extension String { /// Returns the claim experiments claim all confirmation message, singular or plural based on item /// count, with the item count and email address included in the string. /// /// - Parameters: /// - itemCount: The item count. /// - email: The email address of the user. /// - Returns: The confirmation message. static func claimExperimentsClaimAllConfirmationMessage(withItemCount itemCount: Int, email: String) -> String { if itemCount == 1 { return String(format: String.claimAllExperimentsConfirmationMessage, email) } else { return String(format: String.claimAllExperimentsConfirmationMessagePlural, String(itemCount), email) } } /// Returns the claim experiments delete all confirmation message, singular or plural based on /// item count, with the item count included in the string. /// /// - Parameter itemCount: The item count. /// - Returns: The confirmation message. static func claimExperimentsDeleteAllConfirmationMessage(withItemCount itemCount: Int) -> String { if itemCount == 1 { return String.claimExperimentsDeleteAllConfirmationMessage } else { return String(format: String.claimExperimentsDeleteAllConfirmationMessagePlural, itemCount) } } /// Returns the claim experiment confirmation message with the email address included in the /// string. /// /// - Parameter email: The email address. /// - Returns: The confirmation message. static func claimExperimentConfirmationMessage(withEmail email: String) -> String { return String(format: String.claimExperimentConfirmationMessage, email) } /// Returns the number of notes in an experiment in a localized string, singular or plural, /// or empty string if none. /// e.g. "1 note", "42 notes", "". /// /// - Parameter count: The note count. /// - Returns: The localized string. static func notesDescription(withCount count: Int) -> String { if count == 0 { return "" } else if count == 1 { return String.experimentOneNote } else { return String(format: String.experimentManyNotes, count) } } /// Returns the number of recordings in an experiment in a localized string, singular or plural, /// or empty string if none. /// e.g. "1 recording", "42 recordings", "". /// /// - Parameter count: The recording count. /// - Returns: The localized string. static func trialsDescription(withCount count: Int) -> String { if count == 0 { return "" } else if count == 1 { return String.experimentOneRecording } else { return String(format: String.experimentManyRecordings, count) } } }
apache-2.0
96bd2bd01d1c43eda110f93905f3c162
36.612903
100
0.683248
4.620872
false
false
false
false
yangyu2010/DouYuZhiBo
DouYuZhiBo/DouYuZhiBo/Class/Home/Controller/FunnyViewController.swift
1
946
// // FunnyViewController.swift // DouYuZhiBo // // Created by Young on 2017/2/28. // Copyright © 2017年 YuYang. All rights reserved. // import UIKit fileprivate let kFunnyContentViewMaggin : CGFloat = 8 class FunnyViewController: BaseRoomViewController { fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel() override func setupUI() { super.setupUI() let layout = baseCollec.collectionViewLayout as! UICollectionViewFlowLayout layout.headerReferenceSize = CGSize.zero baseCollec.contentInset = UIEdgeInsets(top: kFunnyContentViewMaggin, left: 0, bottom: 0, right: 0) } override func loadData() { viewModel = funnyVM funnyVM.requestFunnyData { self.baseCollec.reloadData() //请求数据完成,调用父类的,取消动画 self.loadDataFinished() } } }
mit
ae2f66165151fd631dffffd2646bc63b
23.026316
106
0.633078
4.805263
false
false
false
false
sonnygauran/trailer
Shared/Repo.swift
1
4540
import CoreData final class Repo: DataItem { @NSManaged var dirty: NSNumber? @NSManaged var fork: NSNumber? @NSManaged var fullName: String? @NSManaged var hidden: NSNumber? @NSManaged var inaccessible: NSNumber? @NSManaged var lastDirtied: NSDate? @NSManaged var webUrl: String? @NSManaged var displayPolicyForPrs: NSNumber? @NSManaged var displayPolicyForIssues: NSNumber? @NSManaged var pullRequests: Set<PullRequest> @NSManaged var issues: Set<Issue> class func repoWithInfo(info: [NSObject : AnyObject], fromServer: ApiServer) -> Repo { let r = DataItem.itemWithInfo(info, type: "Repo", fromServer: fromServer) as! Repo if r.postSyncAction?.integerValue != PostSyncAction.DoNothing.rawValue { r.fullName = N(info, "full_name") as? String r.fork = (N(info, "fork") as? NSNumber)?.boolValue r.webUrl = N(info, "html_url") as? String r.dirty = true r.inaccessible = false r.lastDirtied = NSDate() } return r } func shouldSync() -> Bool { return (self.displayPolicyForPrs?.integerValue ?? 0) > 0 || (self.displayPolicyForIssues?.integerValue ?? 0) > 0 } override func resetSyncState() { super.resetSyncState() dirty = true lastDirtied = never() } class func visibleReposInMoc(moc: NSManagedObjectContext) -> [Repo] { let f = NSFetchRequest(entityName: "Repo") f.returnsObjectsAsFaults = false f.predicate = NSPredicate(format: "displayPolicyForPrs > 0 or displayPolicyForIssues > 0") return try! moc.executeFetchRequest(f) as! [Repo] } class func countVisibleReposInMoc(moc: NSManagedObjectContext) -> Int { let f = NSFetchRequest(entityName: "Repo") f.predicate = NSPredicate(format: "displayPolicyForPrs > 0 or displayPolicyForIssues > 0") return moc.countForFetchRequest(f, error: nil) } class func interestedInIssues() -> Bool { for r in Repo.allItemsOfType("Repo", inMoc: mainObjectContext) as! [Repo] { if r.displayPolicyForIssues?.integerValue > 0 { return true } } return false } class func interestedInPrs() -> Bool { for r in Repo.allItemsOfType("Repo", inMoc: mainObjectContext) as! [Repo] { if r.displayPolicyForPrs?.integerValue > 0 { return true } } return false } class func syncableReposInMoc(moc: NSManagedObjectContext) -> [Repo] { let f = NSFetchRequest(entityName: "Repo") f.returnsObjectsAsFaults = false f.predicate = NSPredicate(format: "dirty = YES and (displayPolicyForPrs > 0 or displayPolicyForIssues > 0) and inaccessible != YES") return try! moc.executeFetchRequest(f) as! [Repo] } class func reposNotRecentlyDirtied(moc: NSManagedObjectContext) -> [Repo] { let f = NSFetchRequest(entityName: "Repo") f.predicate = NSPredicate(format: "dirty != YES and lastDirtied < %@ and postSyncAction != %d and (displayPolicyForPrs > 0 or displayPolicyForIssues > 0)", NSDate(timeInterval: -3600, sinceDate: NSDate()), PostSyncAction.Delete.rawValue) f.includesPropertyValues = false f.returnsObjectsAsFaults = false return try! moc.executeFetchRequest(f) as! [Repo] } class func unsyncableReposInMoc(moc: NSManagedObjectContext) -> [Repo] { let f = NSFetchRequest(entityName: "Repo") f.returnsObjectsAsFaults = false f.predicate = NSPredicate(format: "(not (displayPolicyForPrs > 0 or displayPolicyForIssues > 0)) or inaccessible = YES") return try! moc.executeFetchRequest(f) as! [Repo] } class func markDirtyReposWithIds(ids: NSSet, inMoc: NSManagedObjectContext) { let f = NSFetchRequest(entityName: "Repo") f.returnsObjectsAsFaults = false f.predicate = NSPredicate(format: "serverId IN %@", ids) for repo in try! inMoc.executeFetchRequest(f) as! [Repo] { repo.dirty = repo.shouldSync() } } class func reposForFilter(filter: String?) -> [Repo] { let f = NSFetchRequest(entityName: "Repo") f.returnsObjectsAsFaults = false if let filterText = filter where !filterText.isEmpty { f.predicate = NSPredicate(format: "fullName contains [cd] %@", filterText) } f.sortDescriptors = [ NSSortDescriptor(key: "fork", ascending: true), NSSortDescriptor(key: "fullName", ascending: true) ] return try! mainObjectContext.executeFetchRequest(f) as! [Repo] } class func countParentRepos(filter: String?) -> Int { let f = NSFetchRequest(entityName: "Repo") if let fi = filter where !fi.isEmpty { f.predicate = NSPredicate(format: "fork == NO and fullName contains [cd] %@", fi) } else { f.predicate = NSPredicate(format: "fork == NO") } return mainObjectContext.countForFetchRequest(f, error:nil) } }
mit
5f71ccd3ff9ef0a91333f2742b09255b
35.031746
239
0.719383
3.7031
false
false
false
false
optimistapp/optimistapp
Optimist/SunBar.swift
1
1363
// // SunBar.swift // Optimist // // Created by Jacob Johannesen on 1/31/15. // Copyright (c) 2015 Optimist. All rights reserved. // import Foundation import UIKit import CoreGraphics public class SunBar: UIView { let STATUS_BAR_PADDING: CGFloat = 8.0 public override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(netHex:0xffb242) let outerRingImage = UIImage(named: "outerRing") let outerRingImageView = UIImageView(image: outerRingImage) outerRingImageView.frame = CGRect(x: self.frame.width / 2 - outerRingImageView.frame.width / 2, y: self.frame.height / 2 - outerRingImageView.frame.height / 2 + STATUS_BAR_PADDING, width: outerRingImageView.frame.width, height: outerRingImageView.frame.height) self.addSubview(outerRingImageView) let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") rotateAnimation.fromValue = 0.0 rotateAnimation.toValue = CGFloat(M_PI * 2.0) rotateAnimation.duration = 15 rotateAnimation.repeatCount = Float.infinity rotateAnimation.delegate = self outerRingImageView.layer.addAnimation(rotateAnimation, forKey: nil) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
aa9a6adc6be1d61091bc1c9a3e45cbc6
33.974359
268
0.693324
4.155488
false
false
false
false
tkester/swift-algorithm-club
Fixed Size Array/FixedSizeArray.playground/Contents.swift
1
1236
//: Playground - noun: a place where people can play // last checked with Xcode 9.0b4 #if swift(>=4.0) print("Hello, Swift 4!") #endif /* An unordered array with a maximum size. Performance is always O(1). */ struct FixedSizeArray<T> { private var maxSize: Int private var defaultValue: T private var array: [T] private (set) var count = 0 init(maxSize: Int, defaultValue: T) { self.maxSize = maxSize self.defaultValue = defaultValue self.array = [T](repeating: defaultValue, count: maxSize) } subscript(index: Int) -> T { assert(index >= 0) assert(index < count) return array[index] } mutating func append(_ newElement: T) { assert(count < maxSize) array[count] = newElement count += 1 } mutating func removeAt(index: Int) -> T { assert(index >= 0) assert(index < count) count -= 1 let result = array[index] array[index] = array[count] array[count] = defaultValue return result } mutating func removeAll() { for i in 0..<count { array[i] = defaultValue } count = 0 } } var array = FixedSizeArray(maxSize: 5, defaultValue: 0) array.append(4) array.append(2) array[1] array.removeAt(index: 0) array.removeAll()
mit
a7a4908204a1573d002bcd92556222dc
19.262295
61
0.642395
3.551724
false
false
false
false
VernonVan/SmartClass
SmartClass/Paper/Create Paper/Model/Question.swift
1
3830
// // Question.swift // SmartClass // // Created by Vernon on 16/8/4. // Copyright © 2016年 Vernon. All rights reserved. // import Foundation import RealmSwift fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } class Question: Object { /// 题目序号 dynamic var index = 0 /// 题目类型 (0--单选题 1--多选题 2--判断题) dynamic var type = 0 /// 题目描述 dynamic var topic: String? /// 选项A dynamic var choiceA: String? /// 选项B dynamic var choiceB: String? /// 选项C dynamic var choiceC: String? /// 选项D dynamic var choiceD: String? /// 答案 dynamic var answers: String? /// 分值 let score = RealmOptional<Int>() /// 所属的试卷 // let paper = LinkingObjects(fromType: Paper.self, property: "questions") /// Transient:题目是否完成的标记 var isCompleted: Bool { switch type { case 0: return isCompletedSingleChoice() case 1: return isCompletedMultipleChoice() case 2: return isCompletedTrueOrFalse() default: return false } } func isCompletedSingleChoice() -> Bool { let validTopic = !(topic?.isEmpty ?? true) let validChoices = !(choiceA?.isEmpty ?? true) && !(choiceB?.isEmpty ?? true) && !(choiceC?.isEmpty ?? true) && !(choiceD?.isEmpty ?? true) let validAnswer = answers==nil ? false : answers!.characters.count==1 let validScore = score.value>0 && score.value<=100 return validTopic && validChoices && validAnswer && validScore } func isCompletedMultipleChoice() -> Bool { let validTopic = !(topic?.isEmpty ?? true) let validChoices = !(choiceA?.isEmpty ?? true) && !(choiceB?.isEmpty ?? true) && !(choiceC?.isEmpty ?? true) && !(choiceD?.isEmpty ?? true) let validAnswers = answers==nil ? false : (answers!.characters.count>1 && answers!.characters.count<=4) let validScore = score.value>0 && score.value<=100 return validTopic && validChoices && validAnswers && validScore } func isCompletedTrueOrFalse() -> Bool { let validTopic = !(topic?.isEmpty ?? true) let validChoices = !(choiceA?.isEmpty ?? true) && !(choiceB?.isEmpty ?? true) let validAnswer = answers==nil ? false : answers!.characters.count==1 let validScore = score.value>0 && score.value<=100 return validTopic && validChoices && validAnswer && validScore } } enum QuestionType: Int, CustomStringConvertible { /// 单选题 case singleChoice = 0 /// 多选题 case multipleChoice = 1 /// 判断题 case trueOrFalse = 2 init?(typeNum: Int) { switch typeNum { case 0: self = .singleChoice case 1: self = .multipleChoice case 2: self = .trueOrFalse default: return nil } } var description: String { switch self { case .singleChoice: return NSLocalizedString("单选题", comment: "") case .multipleChoice: return NSLocalizedString("多选题", comment: "") case .trueOrFalse: return NSLocalizedString("判断题", comment: "") } } }
mit
0b248301dd59683fcc00241e835baaa7
24.631944
147
0.56841
3.930777
false
false
false
false
daggmano/photo-management-studio
src/Client/OSX/Photo Management Studio/Photo Management Studio/PubSub.swift
1
1960
import Foundation // ===================================================== enum LogLevel: Int { case Debug = 1, Info, Error } let log_level = LogLevel.Debug protocol Loggable { func log() func log_error() func log_debug() } extension String: Loggable { func log() { if log_level.rawValue <= LogLevel.Info.rawValue { print("[info]\t\(self)") } } func log_error() { if log_level.rawValue <= LogLevel.Error.rawValue { print("[error]\t\(self)") } } func log_debug() { if log_level.rawValue <= LogLevel.Debug.rawValue { print("[debug]\t\(self)") } } } // ===================================================== typealias Callback = (AnyObject) -> Void struct Event { static var events = Dictionary<String, Array<Callback>>() static func register(event: String, callback: Callback) { if (self.events[event] == nil) { "Initializing list for event '\(event)'".log_debug() self.events[event] = Array<Callback>() } if var callbacks = self.events[event] { callbacks.append(callback) self.events[event] = callbacks "Registered callback for event '\(event)'".log_debug() } else { "Failed to register callback for event \(event)".log_error() } } static func emit(event: String, obj: AnyObject) { "Emitting event '\(event)'".log_debug() if let events = self.events[event] { "Found list for event '\(event)', of length \(events.count)".log_debug() for callback in events { callback(obj) } } else { "Could not find callbacks for event '\(event)'".log_error() } } } // ===================================================== //protocol Evented { // func emit(message: String) -> Bool //}
mit
45c4423a4955f2b16a4afd78b1d97de8
24.789474
84
0.493878
4.414414
false
false
false
false
newlix/swift-less-sql-api
Carthage/Checkouts/swift-less-api/LessAPI.swift
1
1837
import Foundation public class LessAPI { public let URL:NSURL public var JWT:JSONWebToken? public init(server:String) { let suffix = server.hasSuffix("/") ? "" : "/" self.URL = NSURL(string: server + suffix)! self.JWT = try! JSONWebToken.fromNSUserDefaults() } public func call(path:String, params: [String:AnyObject], progress: NSProgress? = nil) throws -> AnyObject? { let URL = NSURL(string: path, relativeToURL: self.URL)! let headers:[String:String]? = JWT == nil ? nil : ["Authorization":"Bearer \(JWT!.raw)"] let http = try HTTP.post(URL, json: params, headers: headers, progress: progress) return try parseJSON(http) } public func upload(path:String, data: NSData, progress:NSProgress? = nil) throws -> AnyObject? { let URL = NSURL(string: path, relativeToURL: self.URL)! let headers:[String:String]? = JWT == nil ? nil : ["Authorization":"Bearer \(JWT!.raw)"] let http = HTTP.upload(URL, data: data, headers: headers, progress: progress) return try parseJSON(http) } public func upload(path:String, file: NSURL, progress:NSProgress? = nil) throws -> AnyObject? { let URL = NSURL(string: path, relativeToURL: self.URL)! let headers:[String:String]? = JWT == nil ? nil : ["Authorization":"Bearer \(JWT!.raw)"] let http = HTTP.upload(URL, file: file, headers: headers, progress: progress) return try parseJSON(http) } } private func parseJSON(http:HTTP) throws -> AnyObject? { if http.statusCode == 200 { if http.result.length > 0 { return try? NSJSONSerialization.JSONObjectWithData(http.result, options: NSJSONReadingOptions()) } else { return nil } } throw Error.HTTPRequest(http) }
mit
8459828095dff390cc0357c73f08f64b
38.085106
113
0.626565
4.194064
false
false
false
false
Norod/Filterpedia
Filterpedia/customFilters/MercurializeFilter.swift
1
8533
// // MercurializeFilter.swift // Filterpedia // // Created by Simon Gladman on 19/01/2016. // Copyright © 2016 Simon Gladman. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import CoreImage import SceneKit class MercurializeFilter: CIFilter { // MARK: Filter parameters var inputImage: CIImage? var inputEdgeThickness: CGFloat = 5 var inputScale: CGFloat = 10 // MARK: Shading image attributes var inputLightColor = CIColor(red: 1, green: 1, blue: 0.75) { didSet { sphereImage = nil } } var inputLightPosition = CIVector(x: 0, y: 1) { didSet { sphereImage = nil } } var inputAmbientLightColor = CIColor(red: 0.5, green: 0.5, blue: 0.75) { didSet { sphereImage = nil } } var inputShininess: CGFloat = 0.05 { didSet { sphereImage = nil } } // MARK: SceneKit Objects var sphereImage: CIImage? let material = SCNMaterial() let sceneKitView = SCNView() let omniLightNode = LightNode(type: .Omni) let ambientLightNode = LightNode(type: .Ambient) // MARK: Attributes override func setDefaults() { inputEdgeThickness = 5 inputLightColor = CIColor(red: 1, green: 1, blue: 0.75) inputLightPosition = CIVector(x: 0, y: 1) inputAmbientLightColor = CIColor(red: 0.5, green: 0.5, blue: 0.75) inputShininess = 0.05 inputScale = 10 } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Mercurialize Filter", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputLightColor": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIColor", kCIAttributeDisplayName: "Light Color", kCIAttributeDefault: CIColor(red: 1, green: 1, blue: 0.75), kCIAttributeType: kCIAttributeTypeColor], "inputLightPosition": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIVector", kCIAttributeDisplayName: "Light Position", kCIAttributeDefault: CIVector(x: 0, y: 1), kCIAttributeDescription: "Vector defining normalised light position. (0, 0) is bottom left, (1, 1) is top right.", kCIAttributeType: kCIAttributeTypeColor], "inputAmbientLightColor": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIColor", kCIAttributeDisplayName: "Ambient Light Color", kCIAttributeDefault: CIColor(red: 0.5, green: 0.5, blue: 0.75), kCIAttributeType: kCIAttributeTypeColor], "inputShininess": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDisplayName: "Shininess", kCIAttributeDefault: 0.05, kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 0.5, kCIAttributeType: kCIAttributeTypeScalar], "inputEdgeThickness": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDisplayName: "Edge Thickness", kCIAttributeDefault: 5, kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar], "inputScale": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDisplayName: "Scale", kCIAttributeDefault: 10, kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar] ] } // MARK: Initialisation override init() { super.init() setUpSceneKit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Output Image override var outputImage: CIImage! { guard let inputImage = inputImage else { return nil } if sphereImage == nil { material.shininess = inputShininess omniLightNode.color = inputLightColor omniLightNode.position.x = Float(-50 + (inputLightPosition.x * 100)) omniLightNode.position.y = Float(-50 + (inputLightPosition.y * 100)) ambientLightNode.color = inputAmbientLightColor sceneKitView.prepare(sceneKitView.scene!, shouldAbortBlock: {false}) sphereImage = CIImage(image: sceneKitView.snapshot()) } let edgeWork = CIFilter(name: "CIEdgeWork", withInputParameters: [kCIInputImageKey: inputImage, kCIInputRadiusKey: inputEdgeThickness])! let heightField = CIFilter(name: "CIHeightFieldFromMask", withInputParameters: [ kCIInputRadiusKey: inputScale, kCIInputImageKey: edgeWork.outputImage!])! let shadedMaterial = CIFilter(name: "CIShadedMaterial", withInputParameters: [ kCIInputScaleKey: inputScale, kCIInputImageKey: heightField.outputImage!, kCIInputShadingImageKey: sphereImage!])! return shadedMaterial.outputImage } // MARK: SceneKit set up func setUpSceneKit() { sceneKitView.frame = CGRect(x: 0, y: 0, width: 320, height: 320) sceneKitView.backgroundColor = UIColor.black let scene = SCNScene() sceneKitView.scene = scene let camera = SCNCamera() camera.usesOrthographicProjection = true camera.orthographicScale = 1 let cameraNode = SCNNode() cameraNode.camera = camera cameraNode.position = SCNVector3(x: 0, y: 0, z: 2) scene.rootNode.addChildNode(cameraNode) // sphere... let sphere = SCNSphere(radius: 1) let sphereNode = SCNNode(geometry: sphere) sphereNode.position = SCNVector3(x: 0, y: 0, z: 0) scene.rootNode.addChildNode(sphereNode) // Lights scene.rootNode.addChildNode(ambientLightNode) scene.rootNode.addChildNode(omniLightNode) // Material material.lightingModel = SCNMaterial.LightingModel.phong material.specular.contents = UIColor.white material.diffuse.contents = UIColor.darkGray material.shininess = 0.15 sphere.materials = [material] } } /// LightNode class - SceneKit node with light class LightNode: SCNNode { required init(type: LightType) { super.init() light = SCNLight() light!.type = SCNLight.LightType(rawValue: type.rawValue) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var color: CIColor = CIColor(red: 0, green: 0, blue: 0) { didSet { light?.color = UIColor(ciColor: color) } } } enum LightType: String { case Ambient = "ambient" case Omni = "omni" case Directional = "directional" case Spot = "spot" }
gpl-3.0
363fd09c37acf21a1284be4829b2cacb
28.832168
130
0.574543
5.139759
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/TrimThree.swift
1
1199
// // TrimThree.swift // RsyncUI // // Created by Thomas Evensen on 05/05/2021. // import Combine import Foundation final class TrimThree: Errors { var subscriptions = Set<AnyCancellable>() var trimmeddata = [String]() var maxnumber: Int = 0 var errordiscovered: Bool = false init(_ data: [String]) { data.publisher .sink(receiveCompletion: { completion in switch completion { case .finished: return case let .failure(error): let error = error as NSError self.error(errordescription: error.description, errortype: .readerror) } }, receiveValue: { [unowned self] line in let substr = line.dropFirst(10).trimmingCharacters(in: .whitespacesAndNewlines) let str = substr.components(separatedBy: " ").dropFirst(3).joined(separator: " ") if str.isEmpty == false { if str.contains(".DS_Store") == false { trimmeddata.append(str) } } }) .store(in: &subscriptions) } }
mit
a2c6d494a0467ac76148afcd84d6a207
29.74359
97
0.527106
4.854251
false
false
false
false
jmfieldman/Brisk
Brisk/BriskSync2Async.swift
1
22896
// // BriskSync2Async.swift // Brisk // // Copyright (c) 2016-Present Jason Fieldman - https://github.com/jmfieldman/Brisk // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // MARK: - Routing Object public class __BriskRoutingObj<I, O> { // ---------- Properties ---------- // The dispatch group used in various synchronizing routines fileprivate let dispatchGroup = DispatchGroup() // This is the actual function that we are routing fileprivate let wrappedFunction: (I) -> O // If we are routing the response, this catches the value fileprivate var response: O? = nil // This is the queue that the function will be executed on fileprivate var opQueue: DispatchQueue? = nil // This is the queue that the handler will execute on (if needed) fileprivate var handlerQueue: DispatchQueue? = nil // The lock used to synchronize various accesses fileprivate var lock: NSLock = NSLock() // Is this routing object available to perform its operation? // The routing objects may only perform their operations once, they should // NOT be retained and called a second time. fileprivate var operated: Bool = false // ---------- Init ------------ // Instantiate ourselves with a function public init(function: @escaping (I) -> O, defaultOpQueue: DispatchQueue? = nil) { wrappedFunction = function opQueue = defaultOpQueue } // ---------- Queue Adjustments ------------- /// Returns the current routing object set to execute its /// function on the main queue public var main: __BriskRoutingObj<I, O> { self.opQueue = mainQueue return self } /// Returns the current routing object set to execute its /// function on the generic concurrent background queue public var background: __BriskRoutingObj<I, O> { self.opQueue = backgroundQueue return self } /// Returns the current routing object set to execute its /// function on the specified queue public func on(_ queue: DispatchQueue) -> __BriskRoutingObj<I, O> { self.opQueue = queue return self } // ----------- Execution ------------- /// The sync property returns a function with the same input/output /// parameters of the original function. It is executed asynchronously /// on the specified queue. The calling thread is blocked until the /// called function completes. Not compatible with functions that throw /// errors. public var sync: (I) -> O { guard let opQ = opQueue else { brisk_raise("You must specify a queue for this function to operate on") } // If we're synchronous on the main thread already, just run the function immediately. if opQ === mainQueue && Thread.current.isMainThread { return { i in return self.wrappedFunction(i) } } guard !synchronized(lock, block: { let o = self.operated; self.operated = false; return o }) else { brisk_raise("You may not retain or use this routing object in a way that it can be executed more than once.") } return { i in self.dispatchGroup.enter() opQ.async { self.response = self.wrappedFunction(i) self.dispatchGroup.leave() } _ = self.dispatchGroup.wait(timeout: DispatchTime.distantFuture) return self.response! // Will be set in the async call above } } /// Processes the async handler applied to this routing object. fileprivate func processAsyncHandler(_ handler: @escaping (O) -> Void) { guard let hQ = self.handlerQueue else { brisk_raise("The handler queue was not specified before routing the async response") } backgroundQueue.async { _ = self.dispatchGroup.wait(timeout: DispatchTime.distantFuture) hQ.async { handler(self.response!) // Will be set in the async call before wait completes } } } } public final class __BriskRoutingObjVoid<I>: __BriskRoutingObj<I, Void> { // Instantiate ourselves with a function override public init(function: @escaping (I) -> Void, defaultOpQueue: DispatchQueue? = nil) { super.init(function: function, defaultOpQueue: defaultOpQueue) } /// The async property returns a function that takes the parameters /// from the original function, executes the function with those /// parameters in the desired queue, then returns Void back to the /// originating thread. (for functions that originally return Void) /// /// When calling the wrapped function, the internal dispatchQueue /// is not exited until the wrapped function completes. This /// internal dispatchQueue can be waited on to funnel the response /// of the wrapped function to yet another async dispatch. public var async: (I) -> Void { guard let opQ = opQueue else { brisk_raise("You must specify a queue for this function to operate on") } guard !synchronized(lock, block: { let o = self.operated; self.operated = false; return o }) else { brisk_raise("You may not retain or use this routing object in a way that it can be executed more than once.") } return { i in self.dispatchGroup.enter() opQ.async { self.response = self.wrappedFunction(i) self.dispatchGroup.leave() } } } } public final class __BriskRoutingObjNonVoid<I, O>: __BriskRoutingObj<I, O> { // Instantiate ourselves with a function override public init(function: @escaping (I) -> O, defaultOpQueue: DispatchQueue? = nil) { super.init(function: function, defaultOpQueue: defaultOpQueue) } /// The async property returns a function that takes the parameters /// from the original function, executes the function with those /// parameters in the desired queue, then returns the original /// routing object back to the originating thread. /// /// When calling the wrapped function, the internal dispatchQueue /// is not exited until the wrapped function completes. This /// internal dispatchQueue can be waited on to funnel the response /// of the wrapped function to yet another async dispatch. public var async: (I) -> __BriskRoutingObjNonVoid<I, O> { guard let opQ = opQueue else { brisk_raise("You must specify a queue for this function to operate on") } guard !synchronized(lock, block: { let o = self.operated; self.operated = false; return o }) else { brisk_raise("You may not retain or use this routing object in a way that it can be executed more than once.") } return { i in self.dispatchGroup.enter() opQ.async { self.response = self.wrappedFunction(i) self.dispatchGroup.leave() } return self } } } // MARK: - Operators postfix operator ->> postfix operator ~>> postfix operator +>> //postfix operator ?->> //postfix operator ?~>> //postfix operator ?+>> /// The ```->>``` postfix operator generates an internal routing object that /// requires you to specify the operation queue. An example of this /// would be: /// /// ```handler->>.main.async(result: nil)``` @inline(__always) public postfix func ->><I>(function: @escaping (I) -> Void) -> __BriskRoutingObjVoid<I> { return __BriskRoutingObjVoid(function: function) } /// The ```->>``` postfix operator generates an internal routing object that /// requires you to specify the operation queue. An example of this /// would be: /// /// ```handler->>.main.async(result: nil)``` @inline(__always) public postfix func ->><I, O>(function: @escaping (I) -> O) -> __BriskRoutingObjNonVoid<I,O> { return __BriskRoutingObjNonVoid(function: function) } /// The ```->>``` postfix operator generates an internal routing object that /// requires you to specify the operation queue. An example of this /// would be: /// /// ```handler->>.main.async(result: nil)``` //@inline(__always) public postfix func ?->><I>(function: ((I) -> Void)?) -> __BriskRoutingObjVoid<I>? { // return (function == nil) ? nil : __BriskRoutingObjVoid(function: function!) //} /// The ```->>``` postfix operator generates an internal routing object that /// requires you to specify the operation queue. An example of this /// would be: /// /// ```handler->>.main.async(result: nil)``` //@inline(__always) public postfix func ?->><I, O>(function: ((I) -> O)?) -> __BriskRoutingObjNonVoid<I,O>? { // return (function == nil) ? nil : __BriskRoutingObjNonVoid(function: function!) //} /// The ```~>>``` postfix operator generates an internal routing object that /// defaults to the concurrent background queue. An example of this /// would be: /// /// ```handler~>>.async(result: nil)``` public postfix func ~>><I>(function: @escaping (I) -> Void) -> __BriskRoutingObjVoid<I> { return __BriskRoutingObjVoid(function: function, defaultOpQueue: backgroundQueue) } /// The ```~>>``` postfix operator generates an internal routing object that /// defaults to the concurrent background queue. An example of this /// would be: /// /// ```handler~>>.async(result: nil)``` public postfix func ~>><I, O>(function: @escaping (I) -> O) -> __BriskRoutingObjNonVoid<I,O> { return __BriskRoutingObjNonVoid(function: function, defaultOpQueue: backgroundQueue) } /// The ```~>>``` postfix operator generates an internal routing object that /// defaults to the concurrent background queue. An example of this /// would be: /// /// ```handler~>>.async(result: nil)``` //@inline(__always) public postfix func ?~>><I>(function: ((I) -> Void)?) -> __BriskRoutingObjVoid<I>? { // return (function == nil) ? nil : __BriskRoutingObjVoid(function: function!, defaultOpQueue: backgroundQueue) //} /// The ```~>>``` postfix operator generates an internal routing object that /// defaults to the concurrent background queue. An example of this /// would be: /// /// ```handler~>>.async(result: nil)``` //@inline(__always) public postfix func ?~>><I, O>(function: ((I) -> O)?) -> __BriskRoutingObjNonVoid<I,O>? { // return (function == nil) ? nil : __BriskRoutingObjNonVoid(function: function!, defaultOpQueue: backgroundQueue) //} /// The ```+>>``` postfix operator generates an internal routing object that /// defaults to the main queue. An example of this would be: /// /// ```handler+>>.async(result: nil)``` public postfix func +>><I>(function: @escaping (I) -> Void) -> __BriskRoutingObjVoid<I> { return __BriskRoutingObjVoid(function: function, defaultOpQueue: mainQueue) } /// The ```+>>``` postfix operator generates an internal routing object that /// defaults to the main queue. An example of this would be: /// /// ```handler+>>.async(result: nil)``` public postfix func +>><I, O>(function: @escaping (I) -> O) -> __BriskRoutingObjNonVoid<I,O> { return __BriskRoutingObjNonVoid(function: function, defaultOpQueue: mainQueue) } /// The ```+>>``` postfix operator generates an internal routing object that /// defaults to the main queue. An example of this would be: /// /// ```handler+>>.async(result: nil)``` //@inline(__always) public postfix func ?+>><I>(function: ((I) -> Void)?) -> __BriskRoutingObjVoid<I>? { // return (function == nil) ? nil : __BriskRoutingObjVoid(function: function!, defaultOpQueue: mainQueue) //} /// The ```+>>``` postfix operator generates an internal routing object that /// defaults to the main queue. An example of this would be: /// /// ```handler+>>.async(result: nil)``` //@inline(__always) public postfix func ?+>><I, O>(function: ((I) -> O)?) -> __BriskRoutingObjNonVoid<I,O>? { // return (function == nil) ? nil : __BriskRoutingObjNonVoid(function: function!, defaultOpQueue: mainQueue) //} /* -- old precendence = 140 -- */ precedencegroup AsyncRedirectPrecendence { higherThan: RangeFormationPrecedence lowerThan: MultiplicationPrecedence associativity: left } infix operator +>> : AsyncRedirectPrecendence infix operator ~>> : AsyncRedirectPrecendence infix operator ?+>> : AsyncRedirectPrecendence infix operator ?~>> : AsyncRedirectPrecendence /// The ```~>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the global concurrent background queue. /// /// - e.g.: ```handler~>>(param: nil)``` public func ~>><I>(lhs: @escaping (I) -> Void, rhs: I) -> Void { return __BriskRoutingObjVoid(function: lhs, defaultOpQueue: backgroundQueue).async(rhs) } /// The ```~>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the global concurrent background queue. /// /// - e.g.: ```handler~>>(param: nil)``` @discardableResult public func ~>><I, O>(lhs: @escaping (I) -> O, rhs: I) -> __BriskRoutingObjNonVoid<I, O> { return __BriskRoutingObjNonVoid(function: lhs, defaultOpQueue: backgroundQueue).async(rhs) } /// The ```~>>``` infix operator allows for shorthand execution of the wrapped function /// on its defined operation queue. /// /// - e.g.: ```handler~>>(param: nil)``` public func ~>><I>(lhs: __BriskRoutingObjVoid<I>, rhs: I) -> Void { return lhs.async(rhs) } /// The ```~>>``` infix operator allows for shorthand execution of the wrapped function /// on its defined operation queue. /// /// - e.g.: ```handler~>>(param: nil)``` @discardableResult public func ~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>, rhs: I) -> __BriskRoutingObjNonVoid<I, O> { return lhs.async(rhs) } /// The ```~>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the global concurrent background queue. /// /// - e.g.: ```handler~>>(param: nil)``` public func ?~>><I>(lhs: ((I) -> Void)?, rhs: I) -> Void { if let lhs = lhs { __BriskRoutingObjVoid(function: lhs, defaultOpQueue: backgroundQueue).async(rhs) } } /// The ```~>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the global concurrent background queue. /// /// - e.g.: ```handler~>>(param: nil)``` @discardableResult public func ?~>><I, O>(lhs: ((I) -> O)?, rhs: I) -> __BriskRoutingObjNonVoid<I, O>? { return (lhs == nil) ? nil : __BriskRoutingObjNonVoid(function: lhs!, defaultOpQueue: backgroundQueue).async(rhs) } /// The ```~>>``` infix operator allows for shorthand execution of the wrapped function /// on its defined operation queue. /// /// - e.g.: ```handler~>>(param: nil)``` public func ?~>><I>(lhs: __BriskRoutingObjVoid<I>?, rhs: I) -> Void { lhs?.async(rhs) } /// The ```~>>``` infix operator allows for shorthand execution of the wrapped function /// on its defined operation queue. /// /// - e.g.: ```handler~>>(param: nil)``` @discardableResult public func ?~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>?, rhs: I) -> __BriskRoutingObjNonVoid<I, O>? { return lhs?.async(rhs) } /// The ```+>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the main queue. /// /// - e.g.: ```handler+>>(param: nil)``` public func +>><I>(lhs: @escaping (I) -> Void, rhs: I) -> Void { return __BriskRoutingObjVoid(function: lhs, defaultOpQueue: mainQueue).async(rhs) } /// The ```+>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the main queue. /// /// - e.g.: ```handler+>>(param: nil)``` @discardableResult public func +>><I, O>(lhs: @escaping (I) -> O, rhs: I) -> __BriskRoutingObjNonVoid<I, O> { return __BriskRoutingObjNonVoid(function: lhs, defaultOpQueue: mainQueue).async(rhs) } /// The ```+>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the main queue. /// /// - e.g.: ```handler+>>(param: nil)``` public func ?+>><I>(lhs: ((I) -> Void)?, rhs: I) -> Void { if let lhs = lhs { __BriskRoutingObjVoid(function: lhs, defaultOpQueue: mainQueue).async(rhs) } } /// The ```+>>``` infix operator allows for shorthand creation of a routing object /// that operates asynchronously on the main queue. /// /// - e.g.: ```handler+>>(param: nil)``` @discardableResult public func ?+>><I, O>(lhs: ((I) -> O)?, rhs: I) -> __BriskRoutingObjNonVoid<I, O>? { return (lhs == nil) ? nil : __BriskRoutingObjNonVoid(function: lhs!, defaultOpQueue: mainQueue).async(rhs) } /// The special ```~>>``` infix operator between a function and a queue creates a /// routing object that will call its operation on that queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ~>><I>(lhs: @escaping (I) -> Void, rhs: DispatchQueue) -> __BriskRoutingObjVoid<I> { return __BriskRoutingObjVoid(function: lhs, defaultOpQueue: rhs) } /// The special ```~>>``` infix operator between a function and a queue creates a /// routing object that will call its operation on that queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ~>><I, O>(lhs: @escaping (I) -> O, rhs: DispatchQueue) -> __BriskRoutingObjNonVoid<I, O> { return __BriskRoutingObjNonVoid(function: lhs, defaultOpQueue: rhs) } /// The special ```~>>``` infix operator allows you to specify the queues for the /// routing operations. This sets the initial operation queue if it hasn't already /// been defined by on(). If the initial operation queue has already been defined, /// this sets the response handler queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>, rhs: DispatchQueue) -> __BriskRoutingObjNonVoid<I, O> { lhs.handlerQueue = rhs return lhs } /// The special ```~>>``` infix operator between a function and a queue creates a /// routing object that will call its operation on that queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ?~>><I>(lhs: ((I) -> Void)?, rhs: DispatchQueue) -> __BriskRoutingObjVoid<I>? { return (lhs == nil) ? nil : __BriskRoutingObjVoid(function: lhs!, defaultOpQueue: rhs) } /// The special ```~>>``` infix operator between a function and a queue creates a /// routing object that will call its operation on that queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ?~>><I, O>(lhs: ((I) -> O)?, rhs: DispatchQueue) -> __BriskRoutingObjNonVoid<I, O>? { return (lhs == nil) ? nil : __BriskRoutingObjNonVoid(function: lhs!, defaultOpQueue: rhs) } /// The special ```~>>``` infix operator allows you to specify the queues for the /// routing operations. This sets the initial operation queue if it hasn't already /// been defined by on(). If the initial operation queue has already been defined, /// this sets the response handler queue. /// /// - e.g.: ```handler +>> (param: nil) ~>> myQueue ~>> { result in ... }``` /// - e.g.: ```handler ~>> myQueue ~>> (param: nil) ~>> myOtherQueue ~>> { result in ... }``` public func ~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>?, rhs: DispatchQueue) -> __BriskRoutingObjNonVoid<I, O>? { lhs?.handlerQueue = rhs return lhs } /// The ```~>>``` infix operator routes the result of your asynchronous operation /// to a completion handler that is executed on the predefined queue, or the global /// concurrent background queue by default if none was specified. /// /// -e.g.: ```handler~>>(param: nil) ~>> { result in ... }``` public func ~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>, rhs: @escaping (O) -> Void) { if lhs.handlerQueue == nil { lhs.handlerQueue = backgroundQueue } lhs.processAsyncHandler(rhs) } /// The ```+>>``` infix operator routes the result of your asynchronous operation /// to a completion handler that is executed on the main queue. /// /// -e.g.: ```handler~>>(param: nil) +>> { result in ... }``` public func +>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>, rhs: @escaping (O) -> Void) { lhs.handlerQueue = mainQueue lhs.processAsyncHandler(rhs) } /// The ```~>>``` infix operator routes the result of your asynchronous operation /// to a completion handler that is executed on the predefined queue, or the global /// concurrent background queue by default if none was specified. /// /// -e.g.: ```handler~>>(param: nil) ~>> { result in ... }``` public func ~>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>?, rhs: @escaping (O) -> Void) { if let lhs = lhs { if lhs.handlerQueue == nil { lhs.handlerQueue = backgroundQueue } lhs.processAsyncHandler(rhs) } } /// The ```+>>``` infix operator routes the result of your asynchronous operation /// to a completion handler that is executed on the main queue. /// /// -e.g.: ```handler~>>(param: nil) +>> { result in ... }``` public func +>><I, O>(lhs: __BriskRoutingObjNonVoid<I, O>?, rhs: @escaping (O) -> Void) { lhs?.handlerQueue = mainQueue lhs?.processAsyncHandler(rhs) }
mit
ca2c48e301cc147451e8c1fc90904e6a
39.098074
124
0.642339
3.915854
false
false
false
false
KyoheiG3/RxSwift
RxExample/RxExample/Examples/TableViewWithEditingCommands/TableViewWithEditingCommandsViewController.swift
1
6412
// // TableViewWithEditingCommandsViewController.swift // RxExample // // Created by carlos on 26/5/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif /** Another way to do "MVVM". There are different ideas what does MVVM mean depending on your background. It's kind of similar like FRP. In the end, it doesn't really matter what jargon are you using. This would be the ideal case, but it's really hard to model complex views this way because it's not possible to observe partial model changes. */ struct TableViewEditingCommandsViewModel { let favoriteUsers: [User] let users: [User] func executeCommand(_ command: TableViewEditingCommand) -> TableViewEditingCommandsViewModel { switch command { case let .setUsers(users): return TableViewEditingCommandsViewModel(favoriteUsers: favoriteUsers, users: users) case let .setFavoriteUsers(favoriteUsers): return TableViewEditingCommandsViewModel(favoriteUsers: favoriteUsers, users: users) case let .deleteUser(indexPath): var all = [self.favoriteUsers, self.users] all[indexPath.section].remove(at: indexPath.row) return TableViewEditingCommandsViewModel(favoriteUsers: all[0], users: all[1]) case let .moveUser(from, to): var all = [self.favoriteUsers, self.users] let user = all[from.section][from.row] all[from.section].remove(at: from.row) all[to.section].insert(user, at: to.row) return TableViewEditingCommandsViewModel(favoriteUsers: all[0], users: all[1]) } } } enum TableViewEditingCommand { case setUsers(users: [User]) case setFavoriteUsers(favoriteUsers: [User]) case deleteUser(indexPath: IndexPath) case moveUser(from: IndexPath, to: IndexPath) } class TableViewWithEditingCommandsViewController: ViewController, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! let dataSource = TableViewWithEditingCommandsViewController.configureDataSource() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = self.editButtonItem let superMan = User( firstName: "Super", lastName: "Man", imageURL: "http://nerdreactor.com/wp-content/uploads/2015/02/Superman1.jpg" ) let watMan = User(firstName: "Wat", lastName: "Man", imageURL: "http://www.iri.upc.edu/files/project/98/main.GIF" ) let loadFavoriteUsers = RandomUserAPI.sharedAPI .getExampleUserResultSet() .map(TableViewEditingCommand.setUsers) let initialLoadCommand = Observable.just(TableViewEditingCommand.setFavoriteUsers(favoriteUsers: [superMan, watMan])) .concat(loadFavoriteUsers) .observeOn(MainScheduler.instance) let deleteUserCommand = tableView.rx.itemDeleted.map(TableViewEditingCommand.deleteUser) let moveUserCommand = tableView .rx.itemMoved .map(TableViewEditingCommand.moveUser) let initialState = TableViewEditingCommandsViewModel(favoriteUsers: [], users: []) let viewModel = Observable.of(initialLoadCommand, deleteUserCommand, moveUserCommand) .merge() .scan(initialState) { $0.executeCommand($1) } .shareReplay(1) viewModel .map { [ SectionModel(model: "Favorite Users", items: $0.favoriteUsers), SectionModel(model: "Normal Users", items: $0.users) ] } .bindTo(tableView.rx.items(dataSource: dataSource)) .addDisposableTo(disposeBag) tableView.rx.itemSelected .withLatestFrom(viewModel) { i, viewModel in let all = [viewModel.favoriteUsers, viewModel.users] return all[i.section][i.row] } .subscribe(onNext: { [weak self] user in self?.showDetailsForUser(user) }) .addDisposableTo(disposeBag) // customization using delegate // RxTableViewDelegateBridge will forward correct messages tableView.rx.setDelegate(self) .addDisposableTo(disposeBag) } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.isEditing = editing } // MARK: Table view delegate ;) func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let title = dataSource[section] let label = UILabel(frame: CGRect.zero) // hacky I know :) label.text = " \(title)" label.textColor = UIColor.white label.backgroundColor = UIColor.darkGray label.alpha = 0.9 return label } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } // MARK: Navigation private func showDetailsForUser(_ user: User) { let storyboard = UIStoryboard(name: "TableViewWithEditingCommands", bundle: Bundle(identifier: "RxExample-iOS")) let viewController = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController viewController.user = user self.navigationController?.pushViewController(viewController, animated: true) } // MARK: Work over Variable static func configureDataSource() -> RxTableViewSectionedReloadDataSource<SectionModel<String, User>> { let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, User>>() dataSource.configureCell = { (_, tv, ip, user: User) in let cell = tv.dequeueReusableCell(withIdentifier: "Cell")! cell.textLabel?.text = user.firstName + " " + user.lastName return cell } dataSource.titleForHeaderInSection = { dataSource, sectionIndex in return dataSource[sectionIndex].model } dataSource.canEditRowAtIndexPath = { (ds, ip) in return true } dataSource.canMoveRowAtIndexPath = { _ in return true } return dataSource } }
mit
1aa3d58b98362a5bd16ba6c75fe5f3f2
34.032787
130
0.651692
4.845805
false
false
false
false
rrunfa/StreamRun
Libraries/Alamofire/ParameterEncoding.swift
3
9075
// Alamofire.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // 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 /** HTTP method definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Method: String { case OPTIONS = "OPTIONS" case GET = "GET" case HEAD = "HEAD" case POST = "POST" case PUT = "PUT" case PATCH = "PATCH" case DELETE = "DELETE" case TRACE = "TRACE" case CONNECT = "CONNECT" } // MARK: - ParameterEncoding /** Used to specify the way in which a set of parameters are applied to a URL request. */ public enum ParameterEncoding { /** A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). */ case URL /** Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. */ case JSON /** Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. */ case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) /** Uses the associated closure value to construct a new request given an existing request and parameters. */ case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) /** Creates a URL request by encoding parameters and applying them onto an existing request. :param: URLRequest The request to have parameters applied :param: parameters The parameters to apply :returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) { var mutableURLRequest: NSMutableURLRequest = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest if parameters == nil { return (mutableURLRequest, nil) } var error: NSError? = nil switch self { case .URL: func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in sorted(Array(parameters.keys), <) { let value: AnyObject! = parameters[key] components += self.queryComponents(key, value) } return join("&", components.map{ "\($0)=\($1)" } as [String]) } func encodesParametersInURL(method: Method) -> Bool { switch method { case .GET, .HEAD, .DELETE: return true default: return false } } let method = Method(rawValue: mutableURLRequest.HTTPMethod) if let method = method where encodesParametersInURL(method) { if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters!) mutableURLRequest.URL = URLComponents.URL } } else { if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") } mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) } case .JSON: let options = NSJSONWritingOptions.allZeros if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) { mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } case .PropertyList(let (format, options)): if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) { mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } case .Custom(let closure): (mutableURLRequest, error) = closure(mutableURLRequest, parameters) } return (mutableURLRequest, error) } func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.extend([(escape(key), escape("\(value)"))]) } return components } /** Returns a percent escaped string following RFC 3986 for query string formatting. RFC 3986 states that the following characters are "reserved" characters. - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" Core Foundation interprets RFC 3986 in terms of legal and illegal characters. - Legal Numbers: "0123456789" - Legal Letters: "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - Legal Characters: "!", "$", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "=", "?", "@", "_", "~", "\"" - Illegal Characters: All characters not listed as Legal While the Core Foundation `CFURLCreateStringByAddingPercentEscapes` documentation states that it follows RFC 3986, the headers actually point out that it follows RFC 2396. This explains why it does not consider "[", "]" and "#" to be "legal" characters even though they are specified as "reserved" characters in RFC 3986. The following rdar has been filed to hopefully get the documentation updated. - https://openradar.appspot.com/radar?id=5058257274011648 In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" should be percent escaped in the query string. :param: string The string to be percent escaped. :returns: The percent escaped string. */ func escape(string: String) -> String { let generalDelimiters = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimiters = "!$&'()*+,;=" let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String } }
mit
2876d95b8b424f400e0232f83bfdf76f
45.768041
555
0.642786
5.178653
false
false
false
false
migueloruiz/la-gas-app-swift
lasgasmx/CalcResultCell.swift
1
1908
// // CalcResultCell.swift // lasgasmx // // Created by Desarrollo on 4/7/17. // Copyright © 2017 migueloruiz. All rights reserved. // import UIKit class CalcResultCell: CollectionDatasourceCell { override var datasourceItem: Any? { didSet { guard let item = datasourceItem as? CalcPrice else { return } setColor(by: item.price.type) resultLable.text = item.calculate() } } let fuelLabel: UILabel = { let l = UILabel() l.font = UIFont.systemFont(ofSize: 18, weight: 500) l.textAlignment = .center l.textColor = .white l.backgroundColor = .clear return l }() let resultLable: UILabel = { let l = UILabel() l.font = UIFont.systemFont(ofSize: 18) l.textAlignment = .center l.tintColor = .black l.backgroundColor = .white l.layer.cornerRadius = 10 l.clipsToBounds = true return l }() override func setupViews() { addSubview(fuelLabel) addSubview(resultLable) fuelLabel.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: resultLable.leftAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0) resultLable.anchor(top: topAnchor, left: fuelLabel.rightAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 15, leftConstant: 0, bottomConstant: 15, rightConstant: 15, widthConstant: frame.width * 0.6, heightConstant: 0) } func setColor(by type: FuelType) { fuelLabel.text = type.rawValue switch type { case .Magna: self.backgroundColor = UIColor.magna case .Premium: self.backgroundColor = UIColor.premium case .Diesel: self.backgroundColor = UIColor.diesel } } }
mit
d96bde9baba01d0173d6f8c3bc8ae1da
30.262295
239
0.615102
4.343964
false
false
false
false
ZhaoBingDong/EasySwifty
EasySwifty/Classes/Easy+CollectionView.swift
1
3087
// // Easy+CollectionView.swift // EaseSwifty // // Created by 董招兵 on 2017/8/6. // Copyright © 2017年 大兵布莱恩特. All rights reserved. // import Foundation import UIKit public extension UICollectionView { // //MARK: Reload Cell // func reload(at item : Int, inSection section : Int) { // reload(at : IndexPath(item: item, section: section)) // } // func reload(at indexPath : IndexPath) { // reloadItems(at: [indexPath]) // } // func reload(atSections section : Int) { // reloadSections(IndexSet(integer: section)) // } // // //MARK: Insert Cell // func insert(at item : Int, inSection section : Int) { // insert(at: IndexPath(item: item, section: section)) // } // func insert(at indexPath : IndexPath) { // insertItems(at: [indexPath]) // } // func insert(atSections section : Int) { // insertSections(IndexSet(integer: section)) // } // // //MARK: Delete Cell // func delete(at item : Int, inSection section : Int) { // delete(at: IndexPath(item: item, section: section)) // } // func delete(at indexPath : IndexPath) { // deleteItems(at: [indexPath]) // } // func delete(atSections section : Int) { // deleteSections(IndexSet(integer: section)) // } // @discardableResult func dequeueReusableCell<T : UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T { guard let cell = self.dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)") } return cell } func registerCell<T : UICollectionViewCell>(_ t : T.Type) { if let xib = t.xib { register(xib, forCellWithReuseIdentifier: t.reuseIdentifier) } else { register(t, forCellWithReuseIdentifier: t.reuseIdentifier) } } } /// 添加上拉下拉刷新的 protocol MJCollectionViewRefreshable where Self : UIViewController { var collectionView : UICollectionView { get set } var pageNo : Int { get set} func beginRefresh(_ page : Int) //刷新后 } // //extension MJCollectionViewRefreshable { // // /// 默认实现 下拉刷新 // func addHeaderRefresh() { // self.collectionView.mj_header = MiaoTuHeader(refreshingBlock: { [weak self] in // self?.pageNo = 1 // self?.beginRefresh(self?.pageNo ?? 1) // }) // } // // /// 默认实现 上拉加载更多 // func addFooterRefresh() { // self.collectionView.mj_footer = MiaoTuFooter(refreshingBlock: { [weak self] in // self?.pageNo += 1 // self?.beginRefresh(self?.pageNo ?? 1) // }) // } // // func endRefresh() { // if self.collectionView.mj_header != nil { // self.collectionView.mj_header.endRefreshing() // } // if self.collectionView.mj_footer != nil { // self.collectionView.mj_footer.endRefreshing() // } // } //} // //
apache-2.0
e9613d6acc5252dbdb7af780765b5d31
28.470588
119
0.595476
3.853846
false
false
false
false
tinrobots/Mechanica
Sources/Foundation/NSMutableAttributedString+Utils.swift
1
3812
#if canImport(Foundation) import Foundation extension NSMutableAttributedString { // MARK: - Attributes /// **Mechanica** /// /// Removes all the attributes from `self`. public func removeAllAttributes() { setAttributes([:], range: NSRange(location: 0, length: string.count)) } /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString removing all the attributes. public func removingAllAttributes() -> NSMutableAttributedString { return NSMutableAttributedString(string: string) } // MARK: - Operators /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString appending the right NSMutableAttributedString to the left NSMutableAttributedString. public static func + (lhs: NSMutableAttributedString, rhs: NSMutableAttributedString) -> NSMutableAttributedString { // swiftlint:disable force_cast let leftMutableAttributedString = lhs.mutableCopy() as! NSMutableAttributedString let rightMutableAttributedString = rhs.mutableCopy() as! NSMutableAttributedString // swiftlint:enable force_cast leftMutableAttributedString.append(rightMutableAttributedString) return leftMutableAttributedString } /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString appending the right NSAttributedString to the left NSMutableAttributedString. public static func + (lhs: NSMutableAttributedString, rhs: NSAttributedString) -> NSMutableAttributedString { // swiftlint:disable:next force_cast let leftMutableAttributedString = lhs.mutableCopy() as! NSMutableAttributedString // swiftlint:enable force_cast leftMutableAttributedString.append(rhs) return leftMutableAttributedString } /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString appending the right NSMutableAttributedString to the left NSAttributedString. public static func + (lhs: NSAttributedString, rhs: NSMutableAttributedString) -> NSMutableAttributedString { let mutableAttributedString = NSMutableAttributedString(attributedString: lhs) return mutableAttributedString + rhs } /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString appending the right String to the left NSMutableAttributedString. public static func + (lhs: NSMutableAttributedString, rhs: String) -> NSMutableAttributedString { // swiftlint:disable:next force_cast let leftMutableAttributedString = lhs.mutableCopy() as! NSMutableAttributedString let rightMutableAttributedString = NSMutableAttributedString(string: rhs) return leftMutableAttributedString + rightMutableAttributedString } /// **Mechanica** /// /// Returns a `new` NSMutableAttributedString appending the right NSMutableAttributedString to the left String. public static func + (lhs: String, rhs: NSMutableAttributedString) -> NSMutableAttributedString { let leftMutableAttributedString = NSMutableAttributedString(string: lhs) // swiftlint:disable:next force_cast let rightMutableAttributedString = rhs.mutableCopy() as! NSMutableAttributedString return leftMutableAttributedString + rightMutableAttributedString } /// **Mechanica** /// /// Appends the right NSMutableAttributedString to the left NSMutableAttributedString. public static func += (lhs: NSMutableAttributedString, rhs: NSMutableAttributedString) { lhs.append(rhs) } /// **Mechanica** /// /// Appends the right NSAttributedString to the left NSMutableAttributedString. public static func += (lhs: NSMutableAttributedString, rhs: NSAttributedString) { lhs.append(rhs) } /// **Mechanica** /// /// Appends the right String to the left NSMutableAttributedString. public static func += (lhs: NSMutableAttributedString, rhs: String) { lhs.append(NSAttributedString(string: rhs)) } } #endif
mit
c5e0635bfbb428385a2032626c37a353
38.298969
132
0.756296
5.846626
false
false
false
false
KrishMunot/swift
test/Generics/slice_test.swift
1
2281
// RUN: %target-parse-verify-swift -parse-stdlib import Swift infix operator < { associativity none precedence 170 } infix operator == { associativity none precedence 160 } infix operator != { associativity none precedence 160 } func testslice(_ s: Array<Int>) { for i in 0..<s.count { print(s[i]+1) } for i in s { print(i+1) } _ = s[0..<2] _ = s[0...1] } @_silgen_name("malloc") func c_malloc(_ size: Int) -> UnsafeMutablePointer<Void> @_silgen_name("free") func c_free(_ p: UnsafeMutablePointer<Void>) class Vector<T> { var length : Int var capacity : Int var base : UnsafeMutablePointer<T> init() { length = 0 capacity = 0 base = nil } func push_back(_ elem: T) { if length == capacity { let newcapacity = capacity * 2 + 2 let size = Int(Builtin.sizeof(T.self)) let newbase = UnsafeMutablePointer<T>(c_malloc(newcapacity * size)) for i in 0..<length { (newbase + i).initialize(with: (base+i).move()) } c_free(base) base = newbase capacity = newcapacity } (base+length).initialize(with: elem) length += 1 } func pop_back() -> T { length -= 1 return (base + length).move() } subscript (i : Int) -> T { get { if i >= length { Builtin.int_trap() } return (base + i).pointee } set { if i >= length { Builtin.int_trap() } (base + i).pointee = newValue } } deinit { for i in 0..<length { (base + i).deinitialize() } c_free(base) } } protocol Comparable { func <(lhs: Self, rhs: Self) -> Bool } func sort<T : Comparable>(_ array: inout [T]) { for i in 0..<array.count { for j in i+1..<array.count { if array[j] < array[i] { let temp = array[i] array[i] = array[j] array[j] = temp } } } } func find<T : Eq>(_ array: [T], value: T) -> Int { var idx = 0 for elt in array { if (elt == value) { return idx } idx += 1 } return -1 } func findIf<T>(_ array: [T], fn: (T) -> Bool) -> Int { var idx = 0 for elt in array { if (fn(elt)) { return idx } idx += 1 } return -1 } protocol Eq { func ==(lhs: Self, rhs: Self) -> Bool func !=(lhs: Self, rhs: Self) -> Bool }
apache-2.0
4ddb1ad523f9b4cc27ebdd872d964627
17.696721
80
0.543621
3.208158
false
false
false
false
connienguyen/volunteers-iOS
VOLA/VOLA/Helpers/Extensions/UIKit/UIViewController.swift
1
5898
// // UIViewController.swift // VOLA // // Created by Connie Nguyen on 6/6/17. // Copyright © 2017 Systers-Opensource. All rights reserved. // import UIKit // Apply StoryboardIdentifiable protocol to all UIViewControllers extension UIViewController: StoryboardIdentifiable {} extension UIViewController { /** Perform one of available segues - Parameters: - segue: Segue to perform */ func performSegue(_ segue: Segue, sender: Any?) { performSegue(withIdentifier: segue.identifier, sender: sender) } /// Currently active indicator, nil if there is no indicator var currentActivityIndicator: UIActivityIndicatorView? { return view.subviews.first(where: { $0 is UIActivityIndicatorView }) as? UIActivityIndicatorView } /// Display activity indicator if there is not one already active func displayActivityIndicator() { guard currentActivityIndicator == nil else { // Make sure there isn't already an activity indicator Logger.error(UIError.existingActivityIndicator) return } let indicator = UIActivityIndicatorView(frame: view.frame) indicator.activityIndicatorViewStyle = .gray indicator.center = view.center indicator.backgroundColor = ThemeColors.lightGrey indicator.isHidden = false indicator.startAnimating() self.view.addSubview(indicator) } /// Remove current activity indicator if there is one func removeActivityIndicator() { if let indicator = currentActivityIndicator { indicator.removeFromSuperview() } } /** Display error in an alert view controller - Parameters: - errorTitle: Title to display on error alert - errorMessage: Message to display on error alert */ func showErrorAlert(errorTitle: String, errorMessage: String) { let alert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: DictKeys.ok.rawValue, style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } /// Current login upsell view if there is one var loginUpsellView: LoginUpsellView? { return view.subviews.first(where: {$0 is LoginUpsellView }) as? LoginUpsellView } /** Shows login upsell view if there is already not one on the view controller and sets up target for the button on the upsell */ func showUpsell() { // Guard against showing multiple upsells on the same view controller guard loginUpsellView == nil else { return } let newUpsell = LoginUpsellView.instantiateFromXib() let viewFrame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) newUpsell.frame = viewFrame newUpsell.layer.zPosition += 1 newUpsell.loginButton.addTarget(self, action: #selector(presentLoginFromUpsell), for: .touchUpInside) view.addSubview(newUpsell) addNotificationObserver(NotificationName.userLogin, selector: #selector(removeUpsell)) } /// Remove login upsell if there is one active on view controller func removeUpsell() { // Guard against removing upsell view from view controller when there is none guard let upsellView = loginUpsellView else { return } upsellView.removeFromSuperview() removeNotificationObserver(NotificationName.userLogin) } /// Present login flow where use can log in through a social network or manually with email func presentLoginFromUpsell() { let loginNavVC: LoginNavigationController = UIStoryboard(.login).instantiateViewController() present(loginNavVC, animated: true, completion: nil) } /** Show alert that user can dismiss or use as a shortcut to the login flow in order to complete an action that requires a user account (e.g. event registration) */ func showLoginAlert() { let alert = UIAlertController(title: UIDisplay.loginRequiredTitle.localized, message: UIDisplay.loginRequiredPrompt.localized, preferredStyle: .alert) let loginAction = UIAlertAction(title: UIDisplay.loginPrompt.localized, style: .default) { _ in let loginNavVC: LoginNavigationController = UIStoryboard(.login).instantiateViewController() self.present(loginNavVC, animated: true, completion: nil) } let cancelAction = UIAlertAction(title: UIDisplay.cancel.localized, style: .cancel, handler: nil) alert.addAction(loginAction) alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } /** Show alert that user can dismiss or use as a shortcut to Settings to edit app permissions - Parameters: - title: Title of the alert (suggested to use title of permission that needs access) - message: Message of the alert (suggested to use an explaination for permission access) */ func showEditSettingsAlert(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let openSettingsAction = UIAlertAction(title: UIDisplay.editSettings.localized, style: .default, handler: { (_) in guard let settingsURL = URL(string: UIApplicationOpenSettingsURLString) else { return } URL.applicationOpen(url: settingsURL) }) let cancelAction = UIAlertAction(title: UIDisplay.cancel.localized, style: .cancel, handler: nil) alert.addAction(openSettingsAction) alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } }
gpl-2.0
a85875c8dbd5953bf259cdc7cb358eea
39.115646
122
0.674411
5.02728
false
false
false
false
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/SettingsFeature/SettingsView.swift
1
7473
import AcknowList import ComposableArchitecture import Helpers import L10n import Styleguide import SwiftUI import SwiftUIHelpers /// A view to render the app settings. public struct SettingsView: View { public typealias State = SettingsFeature.State public typealias Action = SettingsFeature.Action @Environment(\.colorSchemeContrast) var colorSchemeContrast let store: Store<State, Action> @ObservedObject var viewStore: ViewStore<State, Action> public init(store: Store<State, Action>) { self.store = store viewStore = ViewStore(store, removeDuplicates: ==) } public var body: some View { SettingsForm { Spacer(minLength: 28) VStack { SettingsSection(title: "") { SettingsNavigationLink( destination: RideEventSettingsView( store: store.scope( state: \.userSettings.rideEventSettings, action: SettingsFeature.Action.rideevent ) ), title: L10n.Settings.eventSettings ) SettingsRow { observationModeRow .accessibilityValue( viewStore.userSettings.enableObservationMode ? Text(L10n.A11y.General.on) : Text(L10n.A11y.General.off) ) .accessibilityAction { viewStore.send(.setObservationMode(!viewStore.userSettings.enableObservationMode)) } } SettingsNavigationLink( destination: AppearanceSettingsView( store: store.scope( state: \SettingsFeature.State.userSettings.appearanceSettings, action: SettingsFeature.Action.appearance ) ), title: L10n.Settings.Theme.appearance ) } supportSection infoSection } } .navigationTitle(L10n.Settings.title) .frame( maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading ) .onAppear { viewStore.send(.onAppear) } } var observationModeRow: some View { HStack { VStack(alignment: .leading, spacing: .grid(1)) { Text(L10n.Settings.Observationmode.title) .font(.titleOne) Text(L10n.Settings.Observationmode.detail) .foregroundColor(colorSchemeContrast.isIncreased ? Color(.textPrimary) : Color(.textSilent)) .font(.bodyOne) } Spacer() Toggle( isOn: viewStore.binding( get: { $0.userSettings.enableObservationMode }, send: SettingsFeature.Action.setObservationMode ), label: { EmptyView() } ) .labelsHidden() } .accessibilityElement(children: .combine) } var supportSection: some View { SettingsSection(title: L10n.Settings.support) { VStack(alignment: .leading, spacing: .grid(4)) { Button( action: { viewStore.send(.supportSectionRowTapped(.github)) }, label: { SupportSettingsRow( title: L10n.Settings.programming, subTitle: L10n.Settings.Opensource.detail, link: L10n.Settings.Opensource.action, textStackForegroundColor: Color(.textPrimaryLight), backgroundColor: Color(.brand500), bottomImage: Image(uiImage: Asset.ghLogo.image) ) } ) .accessibilityAddTraits(.isLink) Button( action: { viewStore.send(.supportSectionRowTapped(.crowdin)) }, label: { SupportSettingsRow( title: L10n.Settings.Translate.title, subTitle: L10n.Settings.Translate.subtitle, link: L10n.Settings.Translate.link, textStackForegroundColor: .white, backgroundColor: Color(.translateRowBackground), bottomImage: Image(uiImage: Asset.translate.image) ) } ) .accessibilityAddTraits(.isLink) Button( action: { viewStore.send(.supportSectionRowTapped(.criticalMassDotIn)) }, label: { SupportSettingsRow( title: L10n.Settings.CriticalMassDotIn.title, subTitle: L10n.Settings.CriticalMassDotIn.detail, link: L10n.Settings.CriticalMassDotIn.action, textStackForegroundColor: Color(.textPrimaryLight), backgroundColor: Color(.cmInRowBackground), bottomImage: Image(uiImage: Asset.cmDotInLogo.image) ) } ) .accessibilityAddTraits(.isLink) } .padding(.horizontal, .grid(4)) } } var infoSection: some View { SettingsSection(title: L10n.Settings.Section.info) { SettingsRow { Button( action: { viewStore.send(.infoSectionRowTapped(.website)) }, label: { SettingsInfoLink(title: L10n.Settings.website) } ) .accessibilityAddTraits(.isLink) } SettingsRow { Button( action: { viewStore.send(.infoSectionRowTapped(.twitter)) }, label: { SettingsInfoLink(title: L10n.Settings.twitter) } ) .accessibilityAddTraits(.isLink) } SettingsRow { Button( action: { viewStore.send(.infoSectionRowTapped(.privacy)) }, label: { SettingsInfoLink(title: L10n.Settings.privacyPolicy) } ) .accessibilityAddTraits(.isLink) } if let acknowledgementsPlistPath = viewStore.acknowledgementsPlistPath { SettingsNavigationLink( destination: AcknowListSwiftUIView(plistPath: acknowledgementsPlistPath), title: "Acknowledgements" ) } appVersionAndBuildView } } var appVersionAndBuildView: some View { HStack(spacing: .grid(4)) { ZStack { RoundedRectangle(cornerRadius: 12.5) .foregroundColor(.white) .frame(width: 56, height: 56, alignment: .center) .overlay( RoundedRectangle(cornerRadius: 12.5) .strokeBorder(Color(.border), lineWidth: 1) ) Image(uiImage: Asset.cmLogoC.image) .resizable() .aspectRatio(contentMode: .fit) .frame(width: 48, height: 48, alignment: .center) } .accessibilityHidden(true) VStack(alignment: .leading) { Text(viewStore.versionNumber) .font(.titleTwo) .foregroundColor(Color(.textPrimary)) Text(viewStore.buildNumber) .font(.bodyTwo) .foregroundColor(colorSchemeContrast.isIncreased ? Color(.textPrimary) : Color(.textSilent)) } .accessibilityElement(children: .combine) } .padding(.grid(4)) } } struct SettingsInfoLink: View { let title: String var body: some View { HStack { Text(title) .font(.titleOne) Spacer() Image(systemName: "arrow.up.right") .font(.titleOne) .accessibilityHidden(true) } } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { Preview { NavigationView { SettingsView( store: .init( initialState: .init(), reducer: SettingsFeature()._printChanges() ) ) } } } }
mit
a55b2c8fce6aa3aea1547be8c7b8c1a0
28.654762
102
0.583032
4.756843
false
false
false
false
ParsaTeam/track-manager-ios
TrackManager/TrackManager.swift
1
2052
// // TrackManager.swift // TrackManager // // Created by Thiago Magalhães on 22/02/17. // Copyright © 2017 NET. All rights reserved. // import Foundation @objc public final class TrackManager: NSObject { //MARK: Singleton override private init() { } public static let shared = TrackManager() //MARK: Properties public var showLogs = true private var connectors: [Connector] = [] //MARK: Tracking methods public func track(_ trackable: Trackable, excluding: [String] = []) { DispatchQueue.global(qos: .background).async { for connector in self.connectors { if !excluding.contains(connector.id()) { connector.track(trackable) self.log("Event sent to connector with id \"\(connector.id())\"") } } } } //MARK: Connector handling methods public func add(_ connector: Connector) { guard (self.connectors.index { $0 == connector }) == nil else { log("Connector with id \"\(connector.id())\" already added") return } self.connectors.append(connector) log("Added connector with id \"\(connector.id())\"") } func remove(_ connector: Connector) { if let index = (self.connectors.index { $0 == connector }) { self.connectors.remove(at: index) log("Removed connector with id \"\(connector.id())\"") } else { log("Connector with id \"\(connector.id())\" not found") } } //MARK: Logging methods private func log(_ text: String) { guard self.showLogs else { return } print(text) } } func ==(lhs: Connector, rhs: Connector) -> Bool { return lhs.id() == rhs.id() }
mit
d736855816341aa9bb9d8573e469463c
22.837209
85
0.495122
4.975728
false
false
false
false
yyny1789/KrMediumKit
Source/Network/NetworkManager.swift
1
7965
// // NetworkManager.swift // Client // // Created by aidenluo on 7/26/16. // Copyright © 2016 36Kr. All rights reserved. // import Foundation import Moya import ObjectMapper import ReachabilitySwift import AdSupport public final class NetworkManager { public class var manager: NetworkManager { struct SingletonWrapper { static let singleton = NetworkManager() } return SingletonWrapper.singleton } public let userAgent: String = NetworkManagerSettings.userAgent ?? "未设置 ua" fileprivate var customHTTPHeader: [String: String] { return NetworkManagerSettings.customHTTPHeader ?? ["User-Agent": userAgent] } public let reachability: Reachability? = { return Reachability() }() public func requestCacheAPI<T: TargetType, O: Mappable>( _ target: T, ignoreCache: Bool = true, loadCacheFirstWhenIgnoreCache: Bool = true, stub: Bool = false, log: Bool = true, success: @escaping (_ result: O, _ dataFromCache: Bool) -> Void, failure: @escaping (_ error: MoyaError) -> Void) -> Cancellable? { let url = target.baseURL.appendingPathComponent(target.path).absoluteString if ignoreCache { if loadCacheFirstWhenIgnoreCache { if let cache = DatabaseManager.manager.objectWithPrimaryKey(NetworkCacheEntity.self, primaryKey: url as AnyObject)?.cacheData { if let JSONString = NSString(data: cache, encoding: String.Encoding.utf8.rawValue), let result = Mapper<O>().map(JSONObject: JSONString) { success(result, true) } } } return request(target, stub: stub, log: log, success: { (result: O) in DatabaseManager.manager.saveObjects({ () -> [NetworkCacheEntity] in let cache = NetworkCacheEntity() cache.cacheName = url cache.cacheData = result.toJSONString()?.data(using: String.Encoding.utf8) return [cache] }) success(result, false) }, failure: failure) } else { if let cache = DatabaseManager.manager.objectWithPrimaryKey(NetworkCacheEntity.self, primaryKey: url as AnyObject)?.cacheData { if let JSONString = NSString(data: cache, encoding: String.Encoding.utf8.rawValue), let result = Mapper<O>().map(JSONObject: JSONString) { success(result, true) } else { failure(MoyaError.underlying(NSError(domain: "NetworkManager", code: 1, userInfo: [NSLocalizedDescriptionKey : "缓存的JSON字符串Map至对象失败"]))) } return nil } else { return request(target, stub: stub, log: log, success: { (result: O) in DatabaseManager.manager.saveObjects({ () -> [NetworkCacheEntity] in let cache = NetworkCacheEntity() cache.cacheName = url cache.cacheData = result.toJSONString()?.data(using: String.Encoding.utf8) return [cache] }) success(result, false) }, failure: failure) } } } public func request<T: TargetType, O: Mappable>(_ target: T, stub: Bool = false, log: Bool = true, success: @escaping (_ result: O) -> Void, failure: @escaping (_ error: MoyaError) -> Void) -> Cancellable? { var provider: MoyaProvider<T> if NetworkManagerSettings.consolelogEnable && log { provider = MoyaProvider<T>(endpointClosure: endpointGenerator(), stubClosure: stubGenerator(stub), plugins: [NetworkLoggerPlugin(verbose: true)]) } else { provider = MoyaProvider<T>(endpointClosure: endpointGenerator(), stubClosure: stubGenerator(stub)) } return provider.request(target, completion: { (result) in switch result { case .success(let response): do { if response.statusCode == 200 { let JSON = try response.mapJSON() as? NSDictionary if let code = JSON?["code"] as? Int, let loseCode = NetworkManagerSettings.loseLoginStatusCode, code == loseCode { NetworkManagerSettings.loseLoginStatusHandle() return } let mapper = Mapper<O>() if let object = mapper.map(JSONObject: JSON) { success(object) } else { failure(MoyaError.jsonMapping(response)) } } else { failure(MoyaError.statusCode(response)) } } catch { failure(MoyaError.jsonMapping(response)) } case .failure(let error): failure(error) } }) } public func request<T: TargetType>(_ target: T, stub: Bool = false, log: Bool = true, success: @escaping (_ result: Data) -> Void, failure: @escaping (_ error: MoyaError) -> Void) -> Cancellable? { var provider: MoyaProvider<T> if NetworkManagerSettings.consolelogEnable && log { provider = MoyaProvider<T>(endpointClosure: endpointGenerator(), stubClosure: stubGenerator(stub), plugins: [NetworkLoggerPlugin(verbose: true)]) } else { provider = MoyaProvider<T>(endpointClosure: endpointGenerator(), stubClosure: stubGenerator(stub)) } return provider.request(target, completion: { (result) in switch result { case .success(let response): if response.statusCode == 200 { success(response.data) } else { failure(MoyaError.statusCode(response)) } case .failure(let error): failure(error) } }) } fileprivate func endpointGenerator<T: TargetType>() -> (_ target: T) -> Endpoint<T> { let generator = { (target: T) -> Endpoint<T> in let URL = target.baseURL.appendingPathComponent(target.path).absoluteString let endpoint: Endpoint<T> = Endpoint<T>(url: URL, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters) return endpoint.adding(newHTTPHeaderFields: self.customHTTPHeader) } return generator } fileprivate func stubGenerator<T>(_ stub: Bool) -> (_ target: T) -> StubBehavior { let stubClosure = { (target: T) -> StubBehavior in if stub { return .immediate } else { return .never } } return stubClosure } public func generalRequest<T: TargetType>(_ target: T, completion: @escaping Completion) -> Cancellable? { let endpointClosure = { (target: T) -> Endpoint<T> in let URL = target.baseURL.appendingPathComponent(target.path).absoluteString let endpoint: Endpoint<T> = Endpoint<T>(url: URL, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters) return endpoint.adding(newHTTPHeaderFields: self.customHTTPHeader) } let provider = MoyaProvider<T>(endpointClosure: endpointClosure) return provider.request(target, completion: completion) } }
mit
a745f8921d3204c4c97d2d245400e810
44.872832
211
0.555822
5.283622
false
false
false
false
Ryce/Convrt
Convrt/Convrt/AppDelegate.swift
1
3106
// // AppDelegate.swift // Convrt // // Created by Hamon Riazy on 16/05/15. // Copyright (c) 2015 ryce. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @available(iOS 9.0, *) func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) { print("shortcut call") if shortcutItem.type == "com.ryce.convrt.openhundredeur" { guard let viewController = self.window?.rootViewController as? ViewController, let shortcutCurrency = shortcutItem.userInfo?["currency"] as? String, let currency = ConvrtSession.sharedInstance.savedCurrencyConfiguration.filter({ $0.code == shortcutCurrency }).first, let shortcutAmount = shortcutItem.userInfo?["amount"] as? String, let currentAmount = Double(shortcutAmount) else { completionHandler(false) return } viewController.updateView(currentAmount, currency: currency) } completionHandler(true) } }
gpl-2.0
17e69fb6013bb70cdbd27ac8d66e481d
46.784615
285
0.715712
5.507092
false
false
false
false
ming1016/smck
smck/Lib/RxSwift/BehaviorSubject.swift
15
4343
// // BehaviorSubject.swift // RxSwift // // Created by Krunoslav Zaher on 5/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /// Represents a value that changes over time. /// /// Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. public final class BehaviorSubject<Element> : Observable<Element> , SubjectType , ObserverType , SynchronizedUnsubscribeType , Disposable { public typealias SubjectObserverType = BehaviorSubject<Element> typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType /// Indicates whether the subject has any observers public var hasObservers: Bool { _lock.lock() let value = _observers.count > 0 _lock.unlock() return value } let _lock = RecursiveLock() // state private var _isDisposed = false private var _value: Element private var _observers = Bag<(Event<Element>) -> ()>() private var _stoppedEvent: Event<Element>? /// Indicates whether the subject has been disposed. public var isDisposed: Bool { return _isDisposed } /// Initializes a new instance of the subject that caches its last value and starts with the specified value. /// /// - parameter value: Initial value sent to observers when no other value has been received by the subject yet. public init(value: Element) { _value = value } /// Gets the current value or throws an error. /// /// - returns: Latest value. public func value() throws -> Element { _lock.lock(); defer { _lock.unlock() } // { if _isDisposed { throw RxError.disposed(object: self) } if let error = _stoppedEvent?.error { // intentionally throw exception throw error } else { return _value } //} } /// Notifies all subscribed observers about next event. /// /// - parameter event: Event to send to the observers. public func on(_ event: Event<E>) { _lock.lock() dispatch(_synchronized_on(event), event) _lock.unlock() } func _synchronized_on(_ event: Event<E>) -> Bag<(Event<Element>) -> ()> { if _stoppedEvent != nil || _isDisposed { return Bag() } switch event { case .next(let value): _value = value case .error, .completed: _stoppedEvent = event } return _observers } /// Subscribes an observer to the subject. /// /// - parameter observer: Observer to subscribe to the subject. /// - returns: Disposable object that can be used to unsubscribe the observer from the subject. public override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { _lock.lock() let subscription = _synchronized_subscribe(observer) _lock.unlock() return subscription } func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { if _isDisposed { observer.on(.error(RxError.disposed(object: self))) return Disposables.create() } if let stoppedEvent = _stoppedEvent { observer.on(stoppedEvent) return Disposables.create() } let key = _observers.insert(observer.on) observer.on(.next(_value)) return SubscriptionDisposable(owner: self, key: key) } func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock() _synchronized_unsubscribe(disposeKey) _lock.unlock() } func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { if _isDisposed { return } _ = _observers.removeKey(disposeKey) } /// Returns observer interface for subject. public func asObserver() -> BehaviorSubject<Element> { return self } /// Unsubscribe all observers and release resources. public func dispose() { _lock.lock() _isDisposed = true _observers.removeAll() _stoppedEvent = nil _lock.unlock() } }
apache-2.0
b07084b957459fcb617ccc853131fbb6
28.537415
116
0.587748
4.934091
false
false
false
false
J3D1-WARR10R/WikiRaces
WikiRaces/Shared/Menu View Controllers/Connect View Controllers/CustomRaceViewController/CustomRaceNumericalViewController.swift
2
7663
// // CustomRaceNumericalViewController.swift // WikiRaces // // Created by Andrew Finke on 5/3/20. // Copyright © 2020 Andrew Finke. All rights reserved. // import UIKit import WKRKit final class CustomRaceNumericalViewController: CustomRaceController { // MARK: - Types - private class Cell: UITableViewCell { // MARK: - Properties - static let reuseIdentifier = "reuseIdentifier" let stepper = UIStepper() let valueLabel: UILabel = { let label = UILabel() label.textAlignment = .right return label }() // MARK: - Initalization - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(stepper) contentView.addSubview(valueLabel) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle - override func layoutSubviews() { super.layoutSubviews() stepper.center = CGPoint( x: contentView.frame.width - contentView.layoutMargins.right - stepper.frame.width / 2, y: contentView.frame.height / 2) let labelX = stepper.frame.minX - stepper.layoutMargins.left * 2 valueLabel.frame = CGRect( x: labelX - 50, y: 0, width: 50, height: frame.height) } } enum SettingsType { case points, timing } // MARK: - Properties - var points: WKRGameSettings.Points? { didSet { guard let value = points else { fatalError() } didUpdatePoints?(value) } } var timing: WKRGameSettings.Timing? { didSet { guard let value = timing else { fatalError() } didUpdateTiming?(value) } } var didUpdatePoints: ((WKRGameSettings.Points) -> Void)? var didUpdateTiming: ((WKRGameSettings.Timing) -> Void)? let type: SettingsType // MARK: - Initalization - init(settingsType: SettingsType, currentValue: Any) { self.type = settingsType super.init(style: .grouped) switch type { case .points: guard let points = currentValue as? WKRGameSettings.Points else { fatalError() } self.points = points title = "Points".uppercased() case .timing: guard let timing = currentValue as? WKRGameSettings.Timing else { fatalError() } self.timing = timing title = "Timing".uppercased() } tableView.allowsSelection = false tableView.register(Cell.self, forCellReuseIdentifier: Cell.reuseIdentifier) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UITableViewDataSource - override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return type == .points ? "Bonus Points" : nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: Cell.reuseIdentifier, for: indexPath) as? Cell else { fatalError() } cell.stepper.tag = indexPath.row cell.stepper.addTarget(self, action: #selector(stepperChanged(stepper:)), for: .valueChanged) switch type { case .points: guard let points = points else { fatalError() } if indexPath.row == 0 { cell.textLabel?.text = "Award Interval" cell.stepper.minimumValue = 5 cell.stepper.maximumValue = 360 cell.stepper.stepValue = 5 cell.stepper.value = points.bonusPointsInterval cell.valueLabel.text = Int(points.bonusPointsInterval).description + " S" } else { cell.textLabel?.text = "Award Amount" cell.stepper.minimumValue = 0 cell.stepper.maximumValue = 20 cell.stepper.stepValue = 1 cell.stepper.value = Double(points.bonusPointReward) cell.valueLabel.text = points.bonusPointReward.description } case .timing: guard let timing = timing else { fatalError() } if indexPath.row == 0 { cell.textLabel?.text = "Voting Time" cell.stepper.minimumValue = 5 cell.stepper.maximumValue = 120 cell.stepper.stepValue = 1 cell.stepper.value = Double(timing.votingTime) cell.valueLabel.text = timing.votingTime.description + " S" } else { cell.textLabel?.text = "Results Time" cell.stepper.minimumValue = 15 cell.stepper.maximumValue = 360 cell.stepper.stepValue = 5 cell.stepper.value = Double(timing.resultsTime) cell.valueLabel.text = timing.resultsTime.description + " S" } } return cell } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if type == .points { let title = """ The award interval is the frequency at which bonus points are added to the total points awarded. If set to 60, then every 60 seconds, the total points awarded to the race winner will increase by the amount specified. Stats Effect: Prevents improving points per race average and total number of races. """ return title } else { return nil } } // MARK: - Helpers - @objc func stepperChanged(stepper: UIStepper) { let indexPath = IndexPath(row: stepper.tag, section: 0) guard let cell = tableView.cellForRow(at: indexPath) as? Cell else { fatalError() } switch type { case .points: guard let points = points else { fatalError() } if indexPath.row == 0 { self.points = WKRGameSettings.Points( bonusPointReward: points.bonusPointReward, bonusPointsInterval: stepper.value) cell.valueLabel.text = Int(stepper.value).description + " S" } else { self.points = WKRGameSettings.Points( bonusPointReward: Int(stepper.value), bonusPointsInterval: points.bonusPointsInterval) cell.valueLabel.text = Int(stepper.value).description } case .timing: guard let timing = timing else { fatalError() } if indexPath.row == 0 { self.timing = WKRGameSettings.Timing( votingTime: Int(stepper.value), resultsTime: timing.resultsTime) cell.valueLabel.text = Int(stepper.value).description + " S" } else { self.timing = WKRGameSettings.Timing( votingTime: timing.votingTime, resultsTime: Int(stepper.value)) cell.valueLabel.text = Int(stepper.value).description + " S" } } } }
mit
310dc2a990da1cd326874176fc83cd71
34.472222
216
0.57622
4.988281
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom II Tests/Skills_Tests.swift
2
2070
// // Skills_Tests.swift // Neocom II Tests // // Created by Artem Shimanski on 10/26/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import XCTest @testable import Neocom import EVEAPI import Futures class Skills_Tests: TestCase { override func setUp() { super.setUp() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testSkillQueue() { let exp = expectation(description: "end") let skillPlan = Services.storage.viewContext.currentAccount?.activeSkillPlan let controller = try! SkillQueue.default.instantiate().get() controller.loadViewIfNeeded() controller.presenter.interactor = SkillQueueInteractorMock(presenter: controller.presenter) controller.viewWillAppear(true) controller.viewDidAppear(true) DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { let type = Services.sde.viewContext.invType("Navigation")! let tq = TrainingQueue(character: controller.presenter.content!.value) tq.add(type, level: 1) skillPlan?.add(tq) try! Services.storage.viewContext.save() DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { exp.fulfill() } } wait(for: [exp], timeout: 10) } } class SkillQueueInteractorMock: SkillQueueInteractor { override func load(cachePolicy: URLRequest.CachePolicy) -> Future<SkillQueueInteractor.Content> { var character = Neocom.Character.empty let skill = Neocom.Character.Skill(type: Services.sde.viewContext.invType("Navigation")!)! let queuedSkill = ESI.Skills.SkillQueueItem.init(finishDate: Date.init(timeIntervalSinceNow: 60), finishedLevel: 1, levelEndSP: skill.skillPoints(at: 1), levelStartSP: 0, queuePosition: 0, skillID: skill.typeID, startDate: Date.init(timeIntervalSinceNow: -60), trainingStartSP: 0) character.skillQueue.append(Neocom.Character.SkillQueueItem(skill: skill, queuedSkill: queuedSkill)) let result = ESI.Result(value: character, expires: nil, metadata: nil) return .init(result) } }
lgpl-2.1
f80fd84b8ba2a07e3557a9772b222c0f
33.483333
282
0.738038
3.775547
false
true
false
false
bcesur/FitPocket
FitPocket/FitPocket/ChronometerViewController.swift
1
3046
// // ChronometerViewController.swift // FitPocket // // Created by Berkay Cesur on 23/12/14. // Copyright (c) 2014 Berkay Cesur. All rights reserved. // import UIKit class ChronometerViewController: UIViewController { @IBOutlet weak var cmLabel: UILabel! @IBAction func backButtonTapped(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } var startTime = NSTimeInterval() var timer: NSTimer = NSTimer() var elapsedTime = NSTimeInterval() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { } @IBAction func pauseButtonTapped() { //timer = NSTimer.scheduledTimerWithTimeInterval(0.00, target: self, selector: "sacmasapan", userInfo: nil, repeats: false) } @IBAction func resetButtonTapped() { timer.invalidate() cmLabel.text = "00:00:00" timer = nil } @IBAction func startButtonTapped() { if (!timer.valid) { timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTime", userInfo: nil, repeats: true) startTime = NSDate.timeIntervalSinceReferenceDate() } } func updateTime() { var currentTime = NSDate.timeIntervalSinceReferenceDate() //Find the difference between current time and start time. elapsedTime = currentTime - startTime //calculate the minutes in elapsed time. let minutes = UInt8(elapsedTime / 60.0) elapsedTime -= (NSTimeInterval(minutes) * 60) //calculate the seconds in elapsed time. let seconds = UInt8(elapsedTime) elapsedTime -= NSTimeInterval(seconds) //find out the fraction of milliseconds to be displayed. let fraction = UInt8(elapsedTime * 100) //add the leading zero for minutes, seconds and millseconds and store them as string constants let strMinutes = minutes > 9 ? String(minutes):"0" + String(minutes) let strSeconds = seconds > 9 ? String(seconds):"0" + String(seconds) let strFraction = fraction > 9 ? String(fraction):"0" + String(fraction) //concatenate minuets, seconds and milliseconds as assign it to the UILabel cmLabel.text = "\(strMinutes):\(strSeconds):\(strFraction)" } 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. } */ }
gpl-2.0
2165fb31f241596db2a5dedc20f4b170
31.063158
132
0.640184
4.993443
false
false
false
false
iOSWizards/AwesomeMedia
AwesomeMedia/Classes/Custom Class/AMAVPlayerItem.swift
1
1904
import AVFoundation // MARK: - Responsible for handling the KVO operations that happen on the AVPlayerItem. public enum AwesomeMediaPlayerItemKeyPaths: String { case playbackLikelyToKeepUp case playbackBufferFull case playbackBufferEmpty case status case timeControlStatus } public class AMAVPlayerItem: AVPlayerItem { private var observersKeyPath = [String: NSObject?]() private var keysPathArray: [AwesomeMediaPlayerItemKeyPaths] = [.playbackLikelyToKeepUp, .playbackBufferFull, .playbackBufferEmpty, .status, .timeControlStatus] deinit { for (keyPath, observer) in observersKeyPath { if let observer = observer { self.removeObserver(observer, forKeyPath: keyPath) } } } override public func addObserver(_ observer: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions = [], context: UnsafeMutableRawPointer?) { super.addObserver(observer, forKeyPath: keyPath, options: options, context: context) if let keyPathRaw = AwesomeMediaPlayerItemKeyPaths(rawValue: keyPath), keysPathArray.contains(keyPathRaw) { if let obj = observersKeyPath[keyPath] as? NSObject { self.removeObserver(obj, forKeyPath: keyPath) observersKeyPath[keyPath] = observer } else { observersKeyPath[keyPath] = observer } } } override public func removeObserver(_ observer: NSObject, forKeyPath keyPath: String, context: UnsafeMutableRawPointer?) { super.removeObserver(observer, forKeyPath: keyPath, context: context) observersKeyPath[keyPath] = nil } public override func removeObserver(_ observer: NSObject, forKeyPath keyPath: String) { super.removeObserver(observer, forKeyPath: keyPath) observersKeyPath[keyPath] = nil } }
mit
2dff2df1acca71a3a0e81eb145cdcdd6
39.510638
165
0.690651
5.348315
false
false
false
false
starhoshi/pi-chan
pi-chan/ViewControllers/Preview/PreviewViewController.swift
1
2775
// // PreviewViewController.swift // pi-chan // // Created by Kensuke Hoshikawa on 2016/04/12. // Copyright © 2016年 star__hoshi. All rights reserved. // import UIKit import SVProgressHUD import SafariServices import Cent class PreviewViewController: UIViewController, UIWebViewDelegate { var postNumber:Int! let localHtml = NSBundle.mainBundle().pathForResource("md", ofType: "html")! var post:Post? @IBOutlet weak var webView: UIWebView! @IBOutlet weak var rightBarButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() rightBarButton.setFAIcon(.FAEdit, iconSize: 22) let req = NSURLRequest(URL: NSURL(string: localHtml)!) webView.delegate = self; webView.loadRequest(req) } override func viewDidAppear(animated: Bool) { if Global.fromLogin || Global.posted { loadApi() Global.fromLogin = false Global.posted = false } } func loadApi(){ SVProgressHUD.showWithStatus("Loading...") Esa(token: KeychainManager.getToken()!, currentTeam: KeychainManager.getTeamName()!).post(postNumber){ result in SVProgressHUD.dismiss() switch result { case .Success(let post): self.post = post self.navigationItem.title = post.name let md = post.bodyMd.replaceNewLine() let js = "insert('\(md.stringByReplacingOccurrencesOfString("'",withString: "\\'"))');" log?.debug("\(js)") self.webView.stringByEvaluatingJavaScriptFromString(js) case .Failure(let error): ErrorHandler.errorAlert(error, controller: self) } } } func webViewDidFinishLoad(webView: UIWebView) { loadApi() } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if request.URL!.absoluteString =~ "file:///posts" { goPreviewToPreview(request.URL!) return false } if navigationType == .Other{ return true }else{ let safari = SFSafariViewController(URL: request.URL!, entersReaderIfAvailable: true) presentViewController(safari, animated: true, completion: nil) return false } } func goPreviewToPreview(url:NSURL){ let nextPostNumber = Int(url.absoluteString.stringByReplacingOccurrencesOfString("file:///posts/",withString: ""))! performSegueWithIdentifier("PreviewToPreview", sender: nextPostNumber) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let previewViewController:PreviewViewController = segue.destinationViewController as! PreviewViewController previewViewController.postNumber = sender as! Int } @IBAction func openEditor(sender: AnyObject) { Window.openEditor(self, post: post) } }
mit
60d363468d6a5c10736bf40d670b0395
30.862069
135
0.702381
4.722317
false
false
false
false
ymesika/Kitura-HTTP2
Sources/KituraHTTP2/HTTP2ConnectionUpgradeFactory.swift
1
2685
/* * Copyright IBM Corporation 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import KituraNet import LoggerAPI public class HTTP2ConnectionUpgradeFactory: ConnectionUpgradeFactory { /// The name of the protocol supported by this `ConnectionUpgradeFactory`. public let name = "h2c" /// Create an instance of this 'ConnectionUpgradeFactory' init() { ConnectionUpgrader.register(factory: self) } /// "Upgrade" a connection to the HTTP/2 protocol. /// /// - Parameter handler: The `IncomingSocketHandler` that is handling the connection being upgraded. /// - Parameter request: The `ServerRequest` object of the incoming "upgrade" request. /// - Parameter response: The `ServerResponse` object that will be used to send the response of the "upgrade" request. /// /// - Returns: A tuple of the created `IncomingSocketProcessor` and a message to send as the body of the response to /// the upgrade request. The `IncomingSocketProcessor` should be nil if the upgrade request wasn't successful. /// If the message is nil, the response will not contain a body. public func upgrade(handler: IncomingSocketHandler, request: ServerRequest, response: ServerResponse) -> (IncomingSocketProcessor?, String?) { guard let settings = request.headers["HTTP2-Settings"] else { return (nil, "Upgrade request MUST include exactly one 'HTTP2-Settings' header field.") } guard settings.count == 1 else { return (nil, "Upgrade request MUST include exactly one 'HTTP2-Settings' header field.") } guard let decodedSettings = Data(base64Encoded: HTTP2Utils.base64urlToBase64(base64url: settings[0])) else { return (nil, "Value for 'HTTP2-Settings' is not Base64 URL encoded") } response.statusCode = .switchingProtocols let session = HTTP2Session(settingsPayload: decodedSettings, with: request) let processor = HTTP2SocketProcessor(session: session, upgrade: true) session.processor = processor return (processor, nil) } }
apache-2.0
bcafa62c9122f41dda8334b3c390fcf6
41.619048
143
0.696834
4.475
false
false
false
false
developerY/Swift2_Playgrounds
Swift2LangRef.playground/Pages/Advanced Operations.xcplaygroundpage/Contents.swift
1
10508
//: [Previous](@previous) //: ------------------------------------------------------------------------------------------------ //: Things to know: //: //: * Arithmetic operators in Swift do not automatically overflow. Adding two values that overflow //: their type (for example, storing 300 in a UInt8) will cause an error. There are special //: operators that allow overflow, including dividing by zero. //: //: * Swift allows developers to define their own operators, including those that Swift doesn't //: currently define. You can even specify the associativity and precedence for operators. //: ------------------------------------------------------------------------------------------------ //: ------------------------------------------------------------------------------------------------ //: Bitwise Operators //: //: The Bitwise operators (AND, OR, XOR, etc.) in Swift effeectively mirror the functionality that //: you're used to with C++ and Objective-C. //: //: We'll cover them briefly. The odd formatting is intended to help show the results: var andResult: UInt8 = 0b00101111 & 0b11110100 //: 0b00100100 <- result var notResult: UInt8 = ~0b11110000 //: 0b00001111 <- result var orResult: UInt8 = 0b01010101 | 0b11110000 //: 0b11110101 <- result var xorResult: UInt8 = 0b01010101 ^ 0b11110000 //: 0b10100101 <- result //: Shifting in Swift is slightly different than in C++. //: //: A lesser-known fact about C++ is that the signed right-shift of a signed value is //: implementation specific. Most compilers do what most programmers expect, which is an arithmetic //: shift (which maintains the sign bit and shifts 1's into the word from the right.) //: //: Swift defines this behavior to be what you expect, shifting signed values to the right will //: perform an arithmetic shift using two's compilment. var leftShiftUnsignedResult: UInt8 = 32 << 1 var leftShiftSignedResult: Int8 = 32 << 1 var leftShiftSignedNegativeResult: Int8 = -32 << 1 var rightShiftUnsignedResult: UInt8 = 32 >> 1 var rightShiftSignedResult: Int8 = 32 >> 1 var rightShiftSignedNegativeResult: Int8 = -32 >> 1 //: ------------------------------------------------------------------------------------------------ //: Overflow operators //: //: If an arithmetic operation (specifically addition (+), subtraction (-) and multiplication (*)) //: results in a value too large or too small for the constant or variable that the result is //: intended for, Swift will produce an overflow/underflow error. //: //: The last two lines of this code block will trigger an overflow/underflow: //: //: var positive: Int8 = 120 //: var negative: Int8 = -120 //: var overflow: Int8 = positive + positive //: var underflow: Int8 = negative + negative //: //: This is also true for division by zero, which can be caused with the division (/) or remainder //: (%) operators. //: //: Sometimes, however, overflow and underflow behavior is exactly what the programmer may intend, //: so Swift provides specific overflow/underflow operators which will not trigger an error and //: allow the overflow/underflow to perform as we see in C++/Objective-C. //: //: Special operators for division by zero are also provided, which return 0 in the case of a //: division by zero. //: //: Here they are, in all their glory: var someValue: Int8 = 120 var aZero: Int8 = someValue - someValue var overflowAdd: Int8 = someValue &+ someValue var underflowSub: Int8 = -someValue &- someValue var overflowMul: Int8 = someValue &* someValue // removed - var divByZero: Int8 = 100 &/ aZero // removed - var remainderDivByZero: Int8 = 100 &% aZero //: ------------------------------------------------------------------------------------------------ //: Operator Functions (a.k.a., Operator Overloading) //: //: Most C++ programmers should be familiar with the concept of operator overloading. Swift offers //: the same kind of functionality as well as additional functionality of specifying the operator //: precednce and associativity. //: //: The most common operators will usually take one of the following forms: //: //: * prefix: the operator appears before a single identifier as in "-a" or "++i" //: * postfix: the operator appears after a single identifier as in "i++" //: * infix: the operator appears between two identifiers as in "a + b" or "c / d" //: //: These are specified with the three attributes, @prefix, @postfix and @infix. //: //: There are more types of operators (which use different attributes, which we'll cover shortly. //: //: Let's define a Vector2D class to work with: struct Vector2D { var x = 0.0 var y = 0.0 } //: Next, we'll define a simple vector addition (adding the individual x & y components to create //: a new vector.) //: //: Since we're adding two Vector2D instances, we'll use operator "+". We want our addition to take //: the form "vectorA + vectorB", which means we'll be defining an infix operator. //: //: Here's what that looks like: func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } //: Let's verify our work: var a = Vector2D(x: 1.0, y: 2.0) var b = Vector2D(x: 3.0, y: 4.0) var c = a + b //: We've seen the infix operator at work so let's move on to the prefix and postfix operators. //: We'll define a prefix operator that negates the vector taking the form (result = -value): prefix func - (vector: Vector2D) -> Vector2D { return Vector2D(x: -vector.x, y: -vector.y) } //: Check our work: c = -a //: Next, let's consider the common prefix increment operator (++a) and postfix increment (a++) //: operations. Each of these performs the operation on a single value whle also returning the //: appropriate result (either the original value before the increment or the value after the //: increment.) //: //: Each will either use the @prefix or @postfix attribute, but since they also modify the value //: they are also @assigmnent operators (and make use of inout for the parameter.) //: //: Let's take a look: prefix func ++ (inout vector: Vector2D) -> Vector2D { vector = vector + Vector2D(x: 1.0, y: 1.0) return vector } postfix func ++ (inout vector: Vector2D) -> Vector2D { var previous = vector; vector = vector + Vector2D(x: 1.0, y: 1.0) return previous } //: And we can check our work: ++c c++ c //: Equivalence Operators allow us to define a means for checking if two values are the same //: or equivalent. They can be "equal to" (==) or "not equal to" (!=). These are simple infix //: opertors that return a Bool result. //: //: Let's also take a moment to make sure we do this right. When comparing floating point values //: you can either check for exact bit-wise equality (a == b) or you can compare values that are //: "very close" by using an epsilon. It's important to recognize the difference, as there are //: cases when IEEE floating point values should be equal, but are actually represented differently //: in their bit-wise format because they were calculated differently. In these cases, a simple //: equality comparison will not suffice. //: //: So here are our more robust equivalence operators: let Epsilon = 0.1e-7 func == (left: Vector2D, right: Vector2D) -> Bool { if abs(left.x - right.x) > Epsilon { return false } if abs(left.y - right.y) > Epsilon { return false } return true } func != (left: Vector2D, right: Vector2D) -> Bool { // Here, we'll use the inverted result of the "==" operator: return !(left == right) } //: ------------------------------------------------------------------------------------------------ //: Custom Operators //: //: So far, we've been defining operator functions for operators that Swift understands and //: for which Swift provides defined behaviors. We can also define our own custom operators for //: doing other interestig things. //: //: For example, Swift doesn't support the concept of a "vector normalization" or "cross product" //: because this functionality doesn't apply to any of the types Swift offers. //: //: Let's keep it simple, though. How about an operator that adds a vector to itself. Let's make //: this a prefix operator that takes the form "+++value" //: //: First, we we must introduce Swift to our new operator. The syntax takes the form of the //: 'operator' keyword, folowed by either 'prefix', 'postfix' or 'infix': //: //: Swift meet operator, operator meet swift: prefix operator +++ {} //: Now we can declare our new operator: prefix func +++ (inout vector: Vector2D) -> Vector2D { vector = vector + vector return vector } //: Let's check our work: var someVector = Vector2D(x: 5.0, y: 9.0) +++someVector //: ------------------------------------------------------------------------------------------------ //: Precedence and Associativity for Custom Infix Operators //: //: Custom infix operators can define their own associativity (left-to-right or right-to-left or //: none) as well as a precedence for determining the order of operations. //: //: Associativity values are 'left' or 'right' or 'none'. //: //: Precedence values are ranked with a numeric value. If not specified, the default value is 100. //: Operations are performed in order of precedence, with higher values being performed first. The //: precedence values are relative to all other precedence values for other operators. The following //: are the default values for operator precedence in the Swift standard library: //: //: 160 (none): Operators << >> //: 150 (left): Operators * / % &* &/ &% & //: 140 (left): Operators + - &+ &- | ^ //: 135 (none): Operators .. ... //: 132 (none): Operators is as //: 130 (none): Operators < <= > >= == != === !== ~= //: 120 (left): Operators && //: 110 (left): Operators || //: 100 (right): Operators ?: //: 90 (right): Operators = *= /= %= += -= <<= >>= &= ^= |= &&= ||= //: //: Let's take a look at how we define a new custom infix operator with left associativity and a //: precedence of 140. //: //: We'll define a function that adds the 'x' components of two vectors, but subtracts the 'y' //: components. We'll call this the "+-" operator: infix operator +- { associativity left precedence 140 } func +- (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y - right.y) } //: Check our work. Let's setup a couple vectors that result in a value of (0, 0): var first = Vector2D(x: 5.0, y: 5.0) var second = Vector2D(x: -5.0, y: 5.0) first +- second //: [Next](@next)
mit
a840bc3dae21f45070d4d3eb01a94cf1
38.954373
100
0.649791
3.984831
false
false
false
false
brentdax/swift
test/Sanitizers/tsan.swift
1
1450
// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=thread -o %t_tsan-binary // RUN: %target-codesign %t_tsan-binary // RUN: not env %env-TSAN_OPTIONS="abort_on_error=0" %target-run %t_tsan-binary 2>&1 | %FileCheck %s // REQUIRES: executable_test // REQUIRES: tsan_runtime // UNSUPPORTED: OS=tvos // FIXME: This should be covered by "tsan_runtime"; older versions of Apple OSs // don't support TSan. // UNSUPPORTED: remote_run // https://bugs.swift.org/browse/SR-6622 // XFAIL: linux #if os(macOS) || os(iOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) import Glibc #endif // Make sure we can handle swifterror and don't bail during the LLVM // threadsanitizer pass. enum MyError : Error { case A } public func foobar(_ x: Int) throws { if x == 0 { throw MyError.A } } public func call_foobar() { do { try foobar(1) } catch(_) { } } // Test ThreadSanitizer execution end-to-end. var threads: [pthread_t] = [] var racey_x: Int; for _ in 1...5 { #if os(macOS) || os(iOS) var t : pthread_t? #else var t : pthread_t = 0 #endif pthread_create(&t, nil, { _ in print("pthread ran") racey_x = 5; return nil }, nil) #if os(macOS) || os(iOS) threads.append(t!) #else threads.append(t) #endif } for t in threads { if t == nil { print("nil thread") continue } pthread_join(t, nil) } // CHECK: ThreadSanitizer: data race
apache-2.0
3f13aa2200765b9ff201d042c803c6fe
19.138889
104
0.643448
2.929293
false
false
false
false
guillermo-ag-95/App-Development-with-Swift-for-Students
2 - Introduction to UIKit/Guided Project - Apple Pie/Apple Pie/Apple Pie/ViewController.swift
1
2433
// // ViewController.swift // Apple Pie // // Created by Guillermo Alcalá Gamero on 21/12/2018. // Copyright © 2018 Guillermo Alcalá Gamero. All rights reserved. // import UIKit class ViewController: UIViewController { var listOfWords = ["buccaneer", "swift", "glorious", "incandescent", "bug", "program"] var incorrectMovesAllowed = 7 var totalWins = 0 { didSet { newRound() } } var totalLoses = 0 { didSet { newRound() } } var currentGame: Game! @IBOutlet weak var treeImageView: UIImageView! @IBOutlet weak var correctWordLabel: UILabel! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet var letterButtons: [UIButton]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. newRound() } @IBAction func buttonPressed(_ sender: UIButton) { sender.isEnabled = false let letterString = sender.title(for: .normal)! let letter = Character(letterString.lowercased()) currentGame.playerGuessed(letter: letter) updateGameState() } func newRound() { if !listOfWords.isEmpty { let newWord = listOfWords.removeFirst() currentGame = Game(word: newWord, incorrectMovesRemaining: incorrectMovesAllowed, guessedLetters: []) enableLetterButtons(true) updateUI() } else { enableLetterButtons(false) } } func updateUI() { var letters = [String]() for letter in currentGame.formattedWord { letters.append(String(letter)) } let wordWithSpacing = letters.joined(separator: " ") correctWordLabel.text = wordWithSpacing scoreLabel.text = "Wins: \(totalWins), Loses: \(totalLoses)" treeImageView.image = UIImage(named: "Tree \(currentGame.incorrectMovesRemaining)") } func updateGameState() { if currentGame.incorrectMovesRemaining == 0 { totalLoses += 1 } else if currentGame.word == currentGame.formattedWord { totalWins += 1 } else { updateUI() } } func enableLetterButtons(_ enable: Bool) { for button in letterButtons { button.isEnabled = enable } } }
mit
566645f268ef08313e02a4bd13d7dff4
26.613636
113
0.593004
4.611006
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/Graphic/ArcGraphic.swift
1
4766
// // ArcGraphic.swift // SwiftyEcharts // // Created by Pluto Y on 12/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// 圆弧类型的 `Graphic` public final class ArcGraphic: Graphic { /// 圆弧的大小和位置 public final class Shape { public var cx: Float? public var cy: Float? public var r: Float? public var r0: Float? public var startAngle: Float? public var endAngle: Float? public var clockwise: Float? public init() {} } /// MARK: Graphic public var type: GraphicType { return .arc } public var id: String? public var action: GraphicAction? public var left: Position? public var right: Position? public var top: Position? public var bottom: Position? public var bounding: GraphicBounding? public var z: Float? public var zlevel: Float? public var silent: Bool? public var invisible: Bool? public var cursor: String? public var draggable: Bool? public var progressive: Bool? /// 圆弧的大小和位置 public var shape: Shape? /// 圆弧的样式 public var style: CommonGraphicStyle? public init() {} } extension ArcGraphic.Shape: Enumable { public enum Enums { case cx(Float), cy(Float), r(Float), r0(Float), startAngle(Float), endAngle(Float), clockwise(Float) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .cx(cx): self.cx = cx case let .cy(cy): self.cy = cy case let .r(r): self.r = r case let .r0(r0): self.r0 = r0 case let .startAngle(startAngle): self.startAngle = startAngle case let .endAngle(endAngle): self.endAngle = endAngle case let .clockwise(clockwise): self.clockwise = clockwise } } } } extension ArcGraphic.Shape: Mappable { public func mapping(_ map: Mapper) { map["cx"] = cx map["cy"] = cy map["r"] = r map["r0"] = r0 map["startAngle"] = startAngle map["endAngle"] = endAngle map["clockwise"] = clockwise } } extension ArcGraphic: Enumable { public enum Enums { case id(String), action(GraphicAction), left(Position), right(Position), top(Position), bottom(Position), bounding(GraphicBounding), z(Float), zlevel(Float), silent(Bool), invisible(Bool), cursor(String), draggable(Bool), progressive(Bool), shape(Shape), style(CommonGraphicStyle) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .id(id): self.id = id case let .action(action): self.action = action case let .left(left): self.left = left case let .right(right): self.right = right case let .top(top): self.top = top case let .bottom(bottom): self.bottom = bottom case let .bounding(bounding): self.bounding = bounding case let .z(z): self.z = z case let .zlevel(zlevel): self.zlevel = zlevel case let .silent(silent): self.silent = silent case let .invisible(invisible): self.invisible = invisible case let .cursor(cursor): self.cursor = cursor case let .draggable(draggable): self.draggable = draggable case let .progressive(progressive): self.progressive = progressive case let .shape(shape): self.shape = shape case let .style(style): self.style = style } } } } extension ArcGraphic: Mappable { public func mapping(_ map: Mapper) { map["type"] = type map["id"] = id map["$action"] = action map["left"] = left map["right"] = right map["top"] = top map["bottom"] = bottom map["bounding"] = bounding map["z"] = z map["zlevel"] = zlevel map["silent"] = silent map["invisible"] = invisible map["cursor"] = cursor map["draggable"] = draggable map["progressive"] = progressive map["shape"] = shape map["style"] = style } }
mit
53c68b92dab4052e4e0c6413ffff4575
28.092593
288
0.531933
4.505736
false
false
false
false
lorentey/swift
test/SILOptimizer/prespecialize.swift
13
1392
// RUN: %target-swift-frontend %s -Onone -Xllvm -sil-inline-generics=false -emit-sil | %FileCheck %s // REQUIRES: optimized_stdlib // Check that pre-specialization works at -Onone. // This test requires the standard library to be compiled with pre-specializations! // CHECK-LABEL: sil [noinline] @$s13prespecialize4test_4sizeySaySiGz_SitF // // function_ref specialized Collection<A where ...>.makeIterator() -> IndexingIterator<A> // CHECK: function_ref @$sSlss16IndexingIteratorVyxG0B0RtzrlE04makeB0ACyFSnySiG_Tg5 // // function_ref specialized IndexingIterator.next() -> A.Element? // CHECK: function_ref @$ss16IndexingIteratorV4next7ElementQzSgyFSnySiG_Tg5 // // Look for generic specialization <Swift.Int> of Swift.Array.subscript.getter : (Swift.Int) -> A // CHECK: function_ref @$sSayxSicigSi_Tg5 // CHECK: return @inline(never) public func test(_ a: inout [Int], size: Int) { for i in 0..<size { for j in 0..<size { a[i] = a[j] } } } // CHECK-LABEL: sil [noinline] @$s13prespecialize3runyyF // Look for generic specialization <Swift.Int> of Swift.Array.init (repeating : A, count : Swift.Int) -> Swift.Array<A> // CHECK: function_ref @$sSa9repeating5countSayxGx_SitcfCSi_Tg5 // CHECK: return @inline(never) public func run() { let size = 10000 var p = [Int](repeating: 0, count: size) for i in 0..<size { p[i] = i } test(&p, size: size) } run()
apache-2.0
e9735f7f7c61daa6cb16e427f37e5b11
31.372093
119
0.704741
3.185355
false
true
false
false
felipedemetrius/AppSwift3
AppSwift3/TasksViewController.swift
1
4003
// // TasksViewController.swift // AppSwift3 // // Created by Felipe Silva on 2/14/17. // Copyright © 2017 Felipe Silva . All rights reserved. // import UIKit /// Responsible for controlling the screen that shows the user a list of task ID's class TasksViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var label: UILabel! private var refreshControl:UIRefreshControl! /// ViewModel for this ViewController var viewModel: TasksViewModel? { didSet { observerViewModel() } } /// Controls UI components for user feedback private var isLoadingDataSource = false { didSet{ if isLoadingDataSource { activityIndicator.startAnimating() label.isHidden = true tableView.separatorStyle = UITableViewCellSeparatorStyle.none } else { refreshControl.endRefreshing() activityIndicator.stopAnimating() if viewModel?.dataSource.value == nil || viewModel?.dataSource.value?.count == 0 { label.isHidden = false tableView.separatorStyle = UITableViewCellSeparatorStyle.none } else { tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine } } tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() observerViewModel() setTableView() setPullToRefresh() } private func setTableView(){ tableView.register(UINib(nibName: "TasksTableViewCell", bundle: nil), forCellReuseIdentifier: "TasksTableViewCell") tableView.estimatedRowHeight = 66 } fileprivate func observerViewModel(){ if !isViewLoaded { return } guard let viewModel = viewModel else { return } title = viewModel.title viewModel.isLoadingDatasource.bindAndFire { [unowned self] in self.isLoadingDataSource = $0 } } @objc private func setPullToRefresh(){ refreshControl = UIRefreshControl() refreshControl.addTarget(viewModel, action: #selector(TasksViewModel.setDatasource), for: UIControlEvents.valueChanged) refreshControl.tintColor = UIColor.black tableView.addSubview(refreshControl) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "goToTaskDetail" { let vc = segue.destination as! TaskDetailViewController if let id = sender as? String { let viewModel = TaskDetailViewModel(id: id) vc.viewModel = viewModel } } } } extension TasksViewController : UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel?.dataSource.value?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let id = viewModel?.dataSource.value?[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "TasksTableViewCell") as! TasksTableViewCell cell.label.text = id return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "goToTaskDetail", sender: viewModel?.dataSource.value?[indexPath.row]) } }
mit
e9fba1d2c222fa37aeec8a76a3ccb2c9
28.426471
127
0.608696
6.045317
false
false
false
false
yonat/MultiSelectSegmentedControl
Sources/MultiSelectSegmentedControl.swift
1
14929
// // MultiSelectSegmentedControl.swift // MultiSelectSegmentedControl // // Created by Yonat Sharon on 2019-08-19. // import SweeterSwift import UIKit @objc public protocol MultiSelectSegmentedControlDelegate { func multiSelect(_ multiSelectSegmentedControl: MultiSelectSegmentedControl, didChange value: Bool, at index: Int) } @IBDesignable open class MultiSelectSegmentedControl: UIControl { @objc public weak var delegate: MultiSelectSegmentedControlDelegate? // MARK: - UISegmentedControl Enhancements /// Items shown in segments. Each item can be a `String`, a `UIImage`, or an array of strings and images. @objc public var items: [Any] { get { return segments .map { $0.contents } .map { $0.count == 1 ? $0[0] : $0 } } set { removeAllSegments() for item in newValue { let arrayItem = item as? [Any] ?? [item] insertSegment(contents: arrayItem) } } } /// Indexes of selected segments (can be more than one if `allowsMultipleSelection` is `true`. @objc public var selectedSegmentIndexes: IndexSet { get { return IndexSet(segments.enumerated().filter { $1.isSelected }.map { $0.offset }) } set { for (i, segment) in segments.enumerated() { segment.isSelected = newValue.contains(i) showDividersBetweenSelectedSegments() } } } @objc public var selectedSegmentTitles: [String] { return segments.filter { $0.isSelected }.compactMap { $0.title } } /// Allow use to select multiple segments (default: `true`). @IBInspectable open dynamic var allowsMultipleSelection: Bool = true { didSet { if !allowsMultipleSelection { selectedSegmentIndex = { selectedSegmentIndex }() } } } /// Select or deselect all segments /// - Parameter selected: `true` to select (default), `false` to deselect. @objc public func selectAllSegments(_ selected: Bool = true) { selectedSegmentIndexes = selected ? IndexSet(0 ..< segments.count) : [] } /// Add segment to the control. /// - Parameter contents: An array of 1 or more strings and images /// - Parameter index: Where to insert the segment (default: at the end) /// - Parameter animated: Animate the insertion (default: false) @objc open func insertSegment(contents: [Any], at index: Int = UISegmentedControl.noSegment, animated: Bool = false) { let segment = MultiSelectSegment(contents: contents, parent: self) segment.tintColor = tintColor segment.isHidden = true perform(animated: animated) { [stackView] in if index >= 0 && index < stackView.arrangedSubviews.count { stackView.insertArrangedSubview(segment, at: index) self.removeDivider(at: index - 1) self.insertDivider(afterSegment: index - 1) self.insertDivider(afterSegment: index) } else { stackView.addArrangedSubview(segment) self.insertDivider(afterSegment: stackView.arrangedSubviews.count - 2) } segment.isHidden = false self.showDividersBetweenSelectedSegments() self.invalidateIntrinsicContentSize() } } // MARK: - Appearance /// Width of the dividers between segments and the border around the view. @IBInspectable open dynamic var borderWidth: CGFloat = 1 { didSet { stackView.spacing = borderWidth borderView.layer.borderWidth = borderWidth for divider in dividers { constrainDividerToControl(divider: divider) } constrain(stackView, at: .left, to: borderView, diff: borderWidth) constrain(stackView, at: .right, to: borderView, diff: -borderWidth) invalidateIntrinsicContentSize() } } /// Corner radius of the view. @IBInspectable open dynamic var borderRadius: CGFloat = 4 { didSet { layer.cornerRadius = borderRadius borderView.layer.cornerRadius = borderRadius } } /// Stack the segments vertically. (default: `false`) @IBInspectable open dynamic var isVertical: Bool { get { return stackView.axis == .vertical } set { removeAllDividers() stackView.axis = newValue ? .vertical : .horizontal DispatchQueue.main.async { // wait for new layout to take effect, to prevent auto layout error self.addAllDividers() } invalidateIntrinsicContentSize() } } /// Stack each segment contents vertically when it contains both text and image. (default: `false`) @IBInspectable open dynamic var isVerticalSegmentContents: Bool = false { didSet { segments.forEach { $0.updateContentsAxis() } invalidateIntrinsicContentSize() } } public dynamic var titleTextAttributes: [UIControl.State: [NSAttributedString.Key: Any]] = [:] { didSet { segments.forEach { $0.updateTitleAttributes() } invalidateIntrinsicContentSize() } } /// Configure additional properties of segments titles. For example: `multiSegment.titleConfigurationHandler = { $0.numberOfLines = 0 }` @objc open dynamic var titleConfigurationHandler: ((UILabel) -> Void)? { didSet { for segment in segments { segment.updateLabelConfiguration() } invalidateIntrinsicContentSize() } } /// Optional selected background color, if different than tintColor @IBInspectable open dynamic var selectedBackgroundColor: UIColor? { didSet { segments.forEach { $0.updateColors() } } } // MARK: - UISegmentedControl Compatibility @objc public convenience init(items: [Any]? = nil) { self.init(frame: .zero) if let items = items { self.items = items } } @objc public var selectedSegmentIndex: Int { get { return selectedSegmentIndexes.first ?? UISegmentedControl.noSegment } set { selectedSegmentIndexes = newValue >= 0 && newValue < segments.count ? [newValue] : [] } } @objc public var numberOfSegments: Int { return segments.count } /// Use different size for each segment, depending on its content size. (default: `false`) @IBInspectable public dynamic var apportionsSegmentWidthsByContent: Bool { get { return stackView.distribution != .fillEqually } set { stackView.distribution = newValue ? .fill : .fillEqually invalidateIntrinsicContentSize() } } @objc public func setImage(_ image: UIImage?, forSegmentAt index: Int) { guard index >= 0 && index < segments.count else { return } segments[index].image = image invalidateIntrinsicContentSize() } @objc public func imageForSegment(at index: Int) -> UIImage? { guard index >= 0 && index < segments.count else { return nil } return segments[index].image } @objc public func setTitle(_ title: String?, forSegmentAt index: Int) { guard index >= 0 && index < segments.count else { return } segments[index].title = title invalidateIntrinsicContentSize() } @objc public func titleForSegment(at index: Int) -> String? { guard index >= 0 && index < segments.count else { return nil } return segments[index].title } @objc public func setTitleTextAttributes(_ attributes: [NSAttributedString.Key: Any]?, for state: UIControl.State) { titleTextAttributes[state] = attributes invalidateIntrinsicContentSize() } @objc public func titleTextAttributes(for state: UIControl.State) -> [NSAttributedString.Key: Any]? { return titleTextAttributes[state] } @objc public func insertSegment(with image: UIImage, at index: Int = UISegmentedControl.noSegment, animated: Bool = false) { insertSegment(contents: [image], at: index, animated: animated) } @objc public func insertSegment(withTitle title: String, at index: Int = UISegmentedControl.noSegment, animated: Bool = false) { insertSegment(contents: [title], at: index, animated: animated) } @objc public func removeAllSegments() { removeAllDividers() stackView.removeAllArrangedSubviewsCompletely() invalidateIntrinsicContentSize() } @objc public func removeSegment(at index: Int, animated: Bool) { guard index >= 0 && index < segments.count else { return } let segment = segments[index] perform(animated: animated) { segment.isHidden = true self.removeDivider(at: index) // after removed segment self.removeDivider(at: index - 1) // before removed segment } perform(animated: animated) { self.stackView.removeArrangedSubviewCompletely(segment) self.insertDivider(afterSegment: index - 1) // before removed segment self.showDividersBetweenSelectedSegments() self.invalidateIntrinsicContentSize() } } @objc public func setEnabled(_ enabled: Bool, forSegmentAt index: Int) { guard index >= 0 && index < segments.count else { return } segments[index].isEnabled = enabled } @objc public func isEnabledForSegment(at index: Int) -> Bool { guard index >= 0 && index < segments.count else { return false } return segments[index].isEnabled } // MARK: - Overrides public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder: NSCoder) { super.init(coder: coder) setup() } open override var backgroundColor: UIColor? { didSet { segments.forEach { $0.updateColors() } } } open override func tintColorDidChange() { super.tintColorDidChange() let newTint = actualTintColor borderView.layer.borderColor = newTint.cgColor dividers.forEach { $0.backgroundColor = newTint } segments.forEach { $0.tintColor = tintColor } } open override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() items = ["Lorem", "Ipsum", "Sit"] } open override var intrinsicContentSize: CGSize { // to pacify Interface Builder frame calculations let stackViewSize = stackView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) return CGRect(origin: .zero, size: stackViewSize).insetBy(dx: -borderWidth, dy: -borderWidth).size } // MARK: - Internals public var segments: [MultiSelectSegment] { return stackView.arrangedSubviews.compactMap { $0 as? MultiSelectSegment } } let stackView = UIStackView() let borderView = UIView() var dividers: [UIView] = [] private func setup() { addConstrainedSubview(borderView, constrain: .top, .bottom, .left, .right) addConstrainedSubview(stackView, constrain: .top, .bottom) constrain(stackView, at: .left, to: borderView, diff: 1) constrain(stackView, at: .right, to: borderView, diff: -1) clipsToBounds = true stackView.distribution = .fillEqually borderWidth = { borderWidth }() borderRadius = { borderRadius }() tintColorDidChange() borderView.isUserInteractionEnabled = false addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTap))) accessibilityIdentifier = "MultiSelectSegmentedControl" } @objc open func didTap(gesture: UITapGestureRecognizer) { let location = gesture.location(in: self) guard let segment = hitTest(location, with: nil) as? MultiSelectSegment else { return } guard let index = segments.firstIndex(of: segment) else { return } perform(animated: true) { if self.allowsMultipleSelection { segment.isSelected.toggle() self.showDividersBetweenSelectedSegments() } else { if segment.isSelected { return } self.selectedSegmentIndex = index } self.sendActions(for: [.valueChanged, .primaryActionTriggered]) self.delegate?.multiSelect(self, didChange: segment.isSelected, at: index) } } // MARK: - Dividers private func showDividersBetweenSelectedSegments() { for i in 0 ..< dividers.count { let isHidden = segments[i].isSelected && segments[i + 1].isSelected dividers[i].alpha = isHidden ? 0 : 1 } } private func insertDivider(afterSegment index: Int) { guard index >= 0 && index < segments.count - 1 else { return } let segment = segments[index] let divider = UIView() divider.backgroundColor = actualTintColor dividers.insert(divider, at: index) addConstrainedSubview(divider) constrainDividerToControl(divider: divider) if isVertical { constrain(divider, at: .top, to: segment, at: .bottom) constrain(divider, at: .bottom, to: segments[index + 1], at: .top) } else { constrain(divider, at: .leading, to: segment, at: .trailing) constrain(divider, at: .trailing, to: segments[index + 1], at: .leading) } } private func removeDivider(at index: Int) { guard index >= 0 && index < dividers.count else { return } dividers[index].removeFromSuperview() dividers.remove(at: index) } private func removeAllDividers() { dividers.forEach { $0.removeFromSuperview() } dividers.removeAll() } private func addAllDividers() { guard dividers.count < segments.count else { return } for i in dividers.count ..< segments.count - 1 { insertDivider(afterSegment: i) } showDividersBetweenSelectedSegments() } private func constrainDividerToControl(divider: UIView) { if isVertical { constrain(divider, at: .left, diff: borderWidth) constrain(divider, at: .right, diff: -borderWidth) } else { constrain(divider, at: .top, diff: borderWidth) constrain(divider, at: .bottom, diff: -borderWidth) } } } extension UIView { func perform(animated: Bool, action: @escaping () -> Void) { if animated { UIView.animate(withDuration: 0.25, animations: action) } else { action() } } } extension UIControl.State: Hashable {}
mit
71bf72a865a76114b50f952629509ef9
35.68059
140
0.624489
4.941741
false
false
false
false
contentful-labs/Cube
Scripts/Sync.swift
1
3911
#!/usr/bin/env cato 2.1 /* A script for syncing data between Sphere.IO and Contentful. */ let ContentfulContentTypeId = "F94etMpd2SsI2eSq4QsiG" let ContentfulSphereIOFieldId = "nJpobh9I3Yle0lnN" let ContentfulSpaceId = "jx9s8zvjjls9" let SphereIOProject = "ecomhack-demo-67" import AFNetworking import Alamofire import AppKit import Chores import ContentfulDeliveryAPI import ContentfulManagementAPI import Cube // Note: has to be added manually as a development Pod import ISO8601DateFormatter import Result func env(variable: String) -> String { return NSProcessInfo.processInfo().environment[variable] ?? "" } func key(name: String, project: String = "WatchButton") -> String { return (>["pod", "keys", "get", name, project]).stdout } NSApplicationLoad() let contentfulToken = env("CONTENTFUL_MANAGEMENT_API_ACCESS_TOKEN") let contentfulClient = CMAClient(accessToken: contentfulToken) var clientId = env("SPHERE_IO_CLIENT_ID") if clientId == "" { clientId = key("SphereIOClientId") } var clientSecret = env("SPHERE_IO_CLIENT_SECRET") if clientSecret == "" { clientSecret = key("SphereIOClientSecret") } if clientId == "" || clientSecret == "" { print("Missing commercetools credentials, please refer to the README.") exit(1) } let sphereClient = SphereIOClient(clientId: clientId, clientSecret: clientSecret, project: SphereIOProject) extension String { var floatValue: Float { return (self as NSString).floatValue } } func createEntry(space: CMASpace, type: CMAContentType, product: Product, exitAfter: Bool = false) { var fields: [NSObject : AnyObject] = [ ContentfulSphereIOFieldId: [ "en-US": product.identifier ], "name": [ "en-US": product.name ], "productDescription": [ "en-US": product.productDescription ], "price": [ "en-US": (product.price["amount"]!).floatValue ], ] space.createAssetWithTitle([ "en-US": product.name ], description: [ "en-US": product.productDescription ], fileToUpload: [ "en-US": product.imageUrl ], success: { (_, asset) in asset.processWithSuccess(nil, failure: nil) fields["productImage"] = [ "en-US": asset ] space.createEntryOfContentType(type, withFields: fields, success: { (_, entry) in print(entry) if (exitAfter) { exit(0) } }) { (_, error) in print(error) if (exitAfter) { exit(1) } } }) { (_, error) in print(error) } } func handleSpace(space: CMASpace, products: [Product]) { space.fetchEntriesMatching(["content_type": ContentfulContentTypeId], success: { (_, entries) in let importedProductIds = entries.items.map() { $0.fields[ContentfulSphereIOFieldId] as! String } space.fetchContentTypeWithIdentifier(ContentfulContentTypeId, success: { (_, type) in for (index, product) in products.enumerate() { let exitAfter = (index + 1) == products.count if importedProductIds.contains(product.identifier) { if exitAfter { exit(0) } continue } createEntry(space, type: type, product: product, exitAfter: exitAfter) } }) { (_, error) in print(error) } }) { (_, error) in print(error) } } sphereClient.fetchProductData() { (result) in if let value = result.value, results = value["results"] as? [[String:AnyObject]] { let products = results.map { (res) in Product(res) } contentfulClient.fetchSpaceWithIdentifier(ContentfulSpaceId, success: { (_, space) in handleSpace(space, products: products) }) { (_, error) in print(error) } } else { fatalError("Failed to retrieve products from commercetools.") } } NSApp.run()
mit
6abaa3d7e150c5bac5f3db6f4441aca5
30.288
101
0.633342
3.914915
false
false
false
false
visenze/visearch-sdk-swift
ViSearchSDK/Carthage/Checkouts/visenze-tracking-swift/ViSenzeAnalytics/ViSenzeAnalytics/Classes/Response/VaEventResponse.swift
1
1424
// // VaEventResponse.swift // ViSenzeAnalytics // // Created by Hung on 9/9/20. // Copyright © 2020 ViSenze. All rights reserved. // import UIKit public class VaEventResponse: NSObject { /// request ID public var reqid: String = "" /// the request status : OK, warning or fail public var status: String = "" public var error: VaError? = nil public init?(data: Data) { super.init() do{ let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! Dictionary<String, Any> self.parseJson(json) } catch { print("\(type(of: self)).\(#function)[line:\(#line)] - error: Json response might be invalid. Error during processing:") print ("\(error)\n") return nil } } public func parseJson(_ json: [String : Any]) { if let status = json["status"] as? String { self.status = status } if let errorCode = json["error"] as? [String: Any] { if let error = errorCode["message"] as? String, let code = errorCode["code"] as? Int { self.error = VaError(code: code, message: error) } } if let requestId = json["reqid"] as? String { self.reqid = requestId } } }
mit
e808b59b9652747fd77fe7b649581821
25.351852
133
0.518623
4.474843
false
false
false
false
RylynnLai/V2EX_sf
V2EX/RLTopicContent.swift
1
6235
// // RLTopicContent.swift // V2EX // // Created by LLZ on 16/4/29. // Copyright © 2016年 LLZ. All rights reserved. // import UIKit class RLTopicContent: UIViewController, UITableViewDelegate, UITableViewDataSource { var replyListHeight:CGFloat = 0.0 var tempCell:RLReplyCell? = nil var topicModel:Topic? lazy var replyModels:[Reply] = [Reply]() lazy var replyList:UITableView = { let list = UITableView() list.bounces = false list.scrollEnabled = false list.alpha = 0.0 list.dataSource = self list.delegate = self return list }() private lazy var footer:MJRefreshAutoNormalFooter = { let refleshFooter = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(RLTopicContent.loadRepliesData)) refleshFooter.refreshingTitleHidden = true refleshFooter.stateLabel.textColor = UIColor.lightGrayColor() refleshFooter.stateLabel.alpha = 0.4 refleshFooter.setTitle("点击或上拉显示评论列表", forState: .Idle) return refleshFooter }() @IBOutlet weak var loadingAIV: UIActivityIndicatorView! @IBOutlet weak var authorLable: UILabel! @IBOutlet weak var titleLable: UILabel! @IBOutlet weak var createdTimeLable: UILabel! @IBOutlet weak var authorBtn: UIButton! @IBOutlet weak var replieNumLable: UILabel! @IBOutlet weak var contentWbV: UIWebView! override func viewDidLoad() { super.viewDidLoad() initUI() initData() self.replyList.estimatedRowHeight = 100; } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIView.animateWithDuration(0.1, animations: { [weak self] in if let strongSelf = self { strongSelf.navigationController?.navigationBar.mj_y = 20; } }) } //MARK: -私有方法 private func initUI() { guard (topicModel != nil) else { return } //导航栏标题 self.title = topicModel!.title //帖子内容 let htmlStr = String.HTMLstringWithBody(topicModel!.content_rendered ?? "") contentWbV.loadHTMLString(htmlStr, baseURL: nil) //头像 let iconURL = NSURL.init(string: "https:\(topicModel!.member!.avatar_normal!)") authorBtn.sd_setBackgroundImageWithURL(iconURL, forState: .Normal, placeholderImage: UIImage.init(named: "blank")) //标题 titleLable.text = topicModel!.title titleLable.adjustsFontSizeToFitWidth = true//固定lable大小,内容自适应,还有个固定字体大小,lable自适应的方法sizeToFit //作者名称 authorLable.text = "\(topicModel!.member!.username!) ●" //创建时间 if topicModel!.createdTime != nil { createdTimeLable.text = "\(topicModel!.createdTime!) ●" } else { createdTimeLable.text = String.creatTimeByTimeIntervalSince1970(Double(topicModel!.created!)) } //回复个数 replieNumLable.text = "\(topicModel!.replies!)个回复" } private func initData() { /*这里规则是 *检查数据是否完整,完整就直接显示帖子内容,不重新请求;不完整就发起网络请求,并更新内存缓存保存新的数据 *用户可以手动下拉刷新话题列表刷新或下拉刷新帖子刷新,需要更新缓存数据 */ guard topicModel != nil else { return } if topicModel!.content_rendered == nil { loadingAIV.startAnimating() RLTopicsHelper.shareTopicsHelper.topicWithTopicID(topicModel!.id!, completion: {[weak self] (topic) in if let strongSelf = self { strongSelf.topicModel = topic strongSelf.initUI() } }) } } @objc private func loadRepliesData() { if let topic = topicModel { RLTopicsHelper.shareTopicsHelper.repliesWithTopicID(topic.id!, completion: { [weak self] (replies) in if let strongSelf = self { strongSelf.replyModels = replies if replies.count > 0 { strongSelf.replyList.reloadData() strongSelf.replyList.alpha = 1.0 strongSelf.replyList.mj_h = strongSelf.replyList.contentSize.height let scrollView = strongSelf.view as! UIScrollView scrollView.contentSize = CGSizeMake(strongSelf.contentWbV.frame.maxX, strongSelf.contentWbV.mj_h + 64 + strongSelf.replyList.contentSize.height) strongSelf.footer.setTitle("点击或上拉刷新评论列表", forState: .Idle) } else { strongSelf.footer.setTitle("目前还没有人发表评论", forState: .Idle) } strongSelf.footer.endRefreshing() } }) } } //MARK: - UIWebViewDelegate func webViewDidStartLoad(webView: UIWebView) { loadingAIV.startAnimating() } func webViewDidFinishLoad(webView: UIWebView) { if webView.loading { return } else { loadingAIV.stopAnimating() //根据内容改变webView的高度(有些奇怪,约束不起作用了),webView不可以滑动 webView.mj_h = webView.scrollView.contentSize.height webView.scrollView.scrollEnabled = false //本控制器的scrollView可以滑动,改变contentSize let scrollView = self.view as! UIScrollView scrollView.contentSize = CGSizeMake(webView.frame.maxX, webView.mj_h + 64)//加上导航栏高度+评论列表初始高度 replyList.frame = CGRectMake(0, webView.frame.maxY, webView.frame.maxX, 20) scrollView.addSubview(replyList) //MJRefresh(加载评论,第一次添加footer默认会拉一次数据) scrollView.mj_footer = footer } } }
mit
e032dbe1e4ea7514b2c3152f4e1112ce
36.51634
168
0.602787
4.599359
false
false
false
false
aunnnn/CreativeSwift
CreativeSwift/Misc/Grid.swift
1
3983
// // Grid.swift // CreativeSwift // // Created by Wirawit Rueopas on 1/21/2560 BE. // Copyright © 2560 Wirawit Rueopas. All rights reserved. // import Foundation /// An abstraction for grid. Useful for getting a frame in grid coordinate. public class Grid { public let nRows: Int public let nCols: Int public let fRows: CGFloat public let fCols: CGFloat private var cachedAllBlocks: [CGRect]? = nil public var targetRect: CGRect { didSet { cachedAllBlocks = nil blockSize = CGSize.init(width: targetRect.width/CGFloat(nRows), height: targetRect.height/CGFloat(nCols)) } } public var targetRectInset: UIEdgeInsets = .zero { didSet { cachedAllBlocks = nil blockSize = CGSize.init(width: (targetRect.width-targetRectInset.left-targetRectInset.right)/CGFloat(nRows), height: (targetRect.height-targetRectInset.top-targetRectInset.bottom)/CGFloat(nCols)) } } /// Cache of block size. Recomputed when targetRect is changed. public private(set) var blockSize: CGSize = .zero public init(rows: Int, cols: Int, targetRect: CGRect = .zero) { if rows <= 0 || cols <= 0 { fatalError("Grid cannot have less than zero rows or cols.") } self.nRows = rows self.nCols = cols self.fRows = CGFloat(rows) self.fCols = CGFloat(cols) self.targetRect = targetRect self.blockSize = CGSize.init(width: targetRect.width/CGFloat(nRows), height: targetRect.height/CGFloat(nCols)) } public func origin(row: Int, col: Int) -> CGPoint { return CGPoint.init(x: targetRect.originX + targetRectInset.left + col.asCGFloat * blockSize.width, y: targetRect.originY + targetRectInset.top + row.asCGFloat * blockSize.height) } /// Is the specified coordinate valid. E.g., is it "in" the grid. public func valid(row: Int, col: Int) -> Bool { return !(row < 0 || col < 0 || row >= nRows || col >= nCols) } /// Return a frame for single block at (row, col). public func block(row: Int, col: Int) -> CGRect { if !valid(row: row, col: col) { return .zero } return CGRect.init(origin: origin(row: row, col: col), size: blockSize) } /// Returns a frame of grid. public func frame(startRow: Int, startCol: Int, endRow: Int, endCol: Int) -> CGRect { if !valid(row: startRow, col: startCol) { return .zero } if !valid(row: endRow, col: endCol) { return .zero } if endRow < startRow || endCol < startCol { return .zero } let o = origin(row: startRow, col: startCol) let size = CGSize.init(width: blockSize.width * (endCol-startCol+1).asCGFloat, height: blockSize.height * (endRow-startRow+1).asCGFloat) return CGRect.init(origin: o, size: size) } /// Returns a frame of 'row'. public func row(_ row: Int, startCol: Int?=nil, endCol: Int?=nil) -> CGRect { let c1 = startCol ?? 0 let c2 = endCol ?? (nCols - 1) return frame(startRow: row, startCol: c1, endRow: row, endCol: c2) } /// Returns a frame of entire column. public func col(_ col: Int, startRow: Int?=nil, endRow: Int?=nil) -> CGRect { let r1 = startRow ?? 0 let r2 = endRow ?? nRows - 1 return frame(startRow: r1, startCol: col, endRow: r2, endCol: col) } /// Returns all blocks for this grid. It is cached and invalidated automatically. public func allBlocks() -> [CGRect] { if let cached = cachedAllBlocks { return cached } var res: [CGRect] = [CGRect].init(repeating: .zero, count: nRows * nCols) for i in 0..<nRows { for j in 0..<nCols { res[i*(nCols) + j] = block(row: i, col: j) } } // cache if nil cachedAllBlocks = res return res } }
mit
4dc37aa78621df8afc2c93cc2b29357f
36.214953
207
0.600201
3.839923
false
false
false
false
hughbe/ui-components
src/MenuDisabled/MenuDisabledTextField.swift
1
1016
// // MenuDisabledTextField.swift // UIComponents // // Created by Hugh Bellamy on 05/09/2015. // Copyright (c) 2015 Hugh Bellamy. All rights reserved. // @IBDesignable public class MenuDisabledTextField: UITextField { @IBInspectable public var menuEnabled: Bool = false @IBInspectable public var canPositionCaretAtStart: Bool = true @IBInspectable public var editingRectDeltaY: CGFloat = 0 public override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { return menuEnabled } public override func caretRectForPosition(position: UITextPosition) -> CGRect { if (position == beginningOfDocument && !canPositionCaretAtStart) { return super.caretRectForPosition(positionFromPosition(position, offset: 1)!) } return super.caretRectForPosition(position) } public override func editingRectForBounds(bounds: CGRect) -> CGRect { return bounds.insetBy(dx: 0, dy: editingRectDeltaY) } }
mit
5d232d90669f19220f21156f39cfd154
32.9
100
0.709646
4.861244
false
false
false
false
AbelSu131/ios-charts
Charts/Classes/Charts/BarChartView.swift
2
11668
// // BarChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics /// Chart that draws bars. public class BarChartView: BarLineChartViewBase, BarChartRendererDelegate { /// flag that enables or disables the highlighting arrow private var _drawHighlightArrowEnabled = false /// if set to true, all values are drawn above their bars, instead of below their top private var _drawValueAboveBarEnabled = true /// if set to true, all values of a stack are drawn individually, and not just their sum private var _drawValuesForWholeStackEnabled = true /// if set to true, a grey area is darawn behind each bar that indicates the maximum value private var _drawBarShadowEnabled = false internal override func initialize() { super.initialize(); renderer = BarChartRenderer(delegate: self, animator: _animator, viewPortHandler: _viewPortHandler); _xAxisRenderer = ChartXAxisRendererBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self); _chartXMin = -0.5; } internal override func calcMinMax() { super.calcMinMax(); if (_data === nil) { return; } var barData = _data as! BarChartData; // increase deltax by 1 because the bars have a width of 1 _deltaX += 0.5; // extend xDelta to make space for multiple datasets (if ther are one) _deltaX *= CGFloat(_data.dataSetCount); var maxEntry = 0; for (var i = 0, count = barData.dataSetCount; i < count; i++) { var set = barData.getDataSetByIndex(i); if (maxEntry < set!.entryCount) { maxEntry = set!.entryCount; } } var groupSpace = barData.groupSpace; _deltaX += CGFloat(maxEntry) * groupSpace; _chartXMax = Double(_deltaX) - _chartXMin; } /// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart. public override func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight! { if (_dataNotSet || _data === nil) { println("Can't select by touch. No data set."); return nil; } _leftAxisTransformer.pixelToValue(&pt); if (pt.x < CGFloat(_chartXMin) || pt.x > CGFloat(_chartXMax)) { return nil; } return getHighlight(xPosition: pt.x, yPosition: pt.y); } /// Returns the correct Highlight object (including xIndex and dataSet-index) for the specified touch position. internal func getHighlight(#xPosition: CGFloat, yPosition: CGFloat) -> ChartHighlight! { if (_dataNotSet || _data === nil) { return nil; } var barData = _data as! BarChartData!; var setCount = barData.dataSetCount; var valCount = barData.xValCount; var dataSetIndex = 0; var xIndex = 0; if (!barData.isGrouped) { // only one dataset exists xIndex = Int(round(xPosition)); // check bounds if (xIndex < 0) { xIndex = 0; } else if (xIndex >= valCount) { xIndex = valCount - 1; } } else { // if this bardata is grouped into more datasets // calculate how often the group-space appears var steps = Int(xPosition / (CGFloat(setCount) + CGFloat(barData.groupSpace))); var groupSpaceSum = barData.groupSpace * CGFloat(steps); var baseNoSpace = xPosition - groupSpaceSum; dataSetIndex = Int(baseNoSpace) % setCount; xIndex = Int(baseNoSpace) / setCount; // check bounds if (xIndex < 0) { xIndex = 0; dataSetIndex = 0; } else if (xIndex >= valCount) { xIndex = valCount - 1; dataSetIndex = setCount - 1; } // check bounds if (dataSetIndex < 0) { dataSetIndex = 0; } else if (dataSetIndex >= setCount) { dataSetIndex = setCount - 1; } } var dataSet = barData.getDataSetByIndex(dataSetIndex) as! BarChartDataSet!; if (!dataSet.isStacked) { return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex); } else { return getStackedHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex, yValue: Double(yPosition)); } } /// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected. internal func getStackedHighlight(#xIndex: Int, dataSetIndex: Int, yValue: Double) -> ChartHighlight! { var dataSet = _data.getDataSetByIndex(dataSetIndex); var entry = dataSet.entryForXIndex(xIndex) as! BarChartDataEntry!; if (entry !== nil) { var stackIndex = entry.getClosestIndexAbove(yValue); return ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex, stackIndex: stackIndex); } else { return nil; } } /// Returns the bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data. public func getBarBounds(e: BarChartDataEntry) -> CGRect! { var set = _data.getDataSetForEntry(e) as! BarChartDataSet!; if (set === nil) { return nil; } var barspace = set.barSpace; var y = CGFloat(e.value); var x = CGFloat(e.xIndex); var barWidth: CGFloat = 0.5; var spaceHalf = barspace / 2.0; var left = x - barWidth + spaceHalf; var right = x + barWidth - spaceHalf; var top = y >= 0.0 ? y : 0.0; var bottom = y <= 0.0 ? y : 0.0; var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top); getTransformer(set.axisDependency).rectValueToPixel(&bounds); return bounds; } public override var lowestVisibleXIndex: Int { var step = CGFloat(_data.dataSetCount); var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace; var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom); getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt); return Int((pt.x <= CGFloat(chartXMin)) ? 0.0 : (pt.x / div) + 1.0); } public override var highestVisibleXIndex: Int { var step = CGFloat(_data.dataSetCount); var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace; var pt = CGPoint(x: _viewPortHandler.contentRight, y: _viewPortHandler.contentBottom); getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt); return Int((pt.x >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.x / div)); } // MARK: Accessors /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled: Bool { get { return _drawHighlightArrowEnabled; } set { _drawHighlightArrowEnabled = newValue; setNeedsDisplay(); } } /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled: Bool { get { return _drawValueAboveBarEnabled; } set { _drawValueAboveBarEnabled = newValue; setNeedsDisplay(); } } /// if set to true, all values of a stack are drawn individually, and not just their sum public var drawValuesForWholeStackEnabled: Bool { get { return _drawValuesForWholeStackEnabled; } set { _drawValuesForWholeStackEnabled = newValue; setNeedsDisplay(); } } /// if set to true, a grey area is drawn behind each bar that indicates the maximum value public var drawBarShadowEnabled: Bool { get { return _drawBarShadowEnabled; } set { _drawBarShadowEnabled = newValue; setNeedsDisplay(); } } /// returns true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled; } /// returns true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled; } /// returns true if all values of a stack are drawn, and not just their sum public var isDrawValuesForWholeStackEnabled: Bool { return drawValuesForWholeStackEnabled; } /// returns true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled; } // MARK: - BarChartRendererDelegate public func barChartRendererData(renderer: BarChartRenderer) -> BarChartData! { return _data as! BarChartData!; } public func barChartRenderer(renderer: BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! { return getTransformer(which); } public func barChartRendererMaxVisibleValueCount(renderer: BarChartRenderer) -> Int { return maxVisibleValueCount; } public func barChartDefaultRendererValueFormatter(renderer: BarChartRenderer) -> NSNumberFormatter! { return valueFormatter; } public func barChartRendererChartYMax(renderer: BarChartRenderer) -> Double { return chartYMax; } public func barChartRendererChartYMin(renderer: BarChartRenderer) -> Double { return chartYMin; } public func barChartRendererChartXMax(renderer: BarChartRenderer) -> Double { return chartXMax; } public func barChartRendererChartXMin(renderer: BarChartRenderer) -> Double { return chartXMin; } public func barChartIsDrawHighlightArrowEnabled(renderer: BarChartRenderer) -> Bool { return drawHighlightArrowEnabled; } public func barChartIsDrawValueAboveBarEnabled(renderer: BarChartRenderer) -> Bool { return drawValueAboveBarEnabled; } public func barChartIsDrawValuesForWholeStackEnabled(renderer: BarChartRenderer) -> Bool { return drawValuesForWholeStackEnabled; } public func barChartIsDrawBarShadowEnabled(renderer: BarChartRenderer) -> Bool { return drawBarShadowEnabled; } public func barChartIsInverted(renderer: BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool { return getAxis(axis).isInverted; } }
apache-2.0
95c5da2dfd03fe32286adc991cb5e3cb
31.057692
150
0.594961
5.357208
false
false
false
false
drewcrawford/DCAKit
DCAKit/Foundation Additions/KVOHelp.swift
1
7179
// // KVOHelp.swift // DCAKit // // Created by Drew Crawford on 4/9/15. // Copyright (c) 2015 DrewCrawfordApps. // This file is part of DCAKit. It is subject to the license terms in the LICENSE // file found in the top level of this distribution and at // https://github.com/drewcrawford/DCAKit/blob/master/LICENSE. // No part of DCAKit, including this file, may be copied, modified, // propagated, or distributed except according to the terms contained // in the LICENSE file. import Foundation private struct ObserversMap { /** [observed : [String : [KVOHelpObserver]]]] */ private static var map = NSMapTable.weakToStrongObjectsMapTable() private static func KVOHelpsForPair(#observed: NSObject, keyPath: String) -> [KVOHelpObserver] { if let o = ObserversMap.map.objectForKey(observed) as? [String: [KVOHelpObserver]] { if o[keyPath] != nil { return o[keyPath]! } } return [] } private static func KVOHelpForTriple(#observed: NSObject, keyPath: String, referenceObject: AnyObject) -> KVOHelpObserver? { let haystack = KVOHelpsForPair(observed: observed, keyPath: keyPath) for needle in haystack { if needle.referenceObject === referenceObject { return needle } } return nil } private static func setNewHelps(#helps: [KVOHelpObserver], observed: NSObject, keyPath: String, referenceObject: AnyObject) { var newStringMap = ObserversMap.map.objectForKey(observed) as? [String: [KVOHelpObserver]] ?? [:] as [String: [KVOHelpObserver]] newStringMap[keyPath] = helps map.setObject(newStringMap, forKey: observed) } private static func setKVOHelpForTriple(#newHelp: KVOHelpObserver, observed: NSObject, keyPath: String, referenceObject: AnyObject) { removeKVOHelpForTriple(observed: observed, keyPath: keyPath, referenceObject: referenceObject) var helps = KVOHelpsForPair(observed: observed, keyPath: keyPath) helps.append(newHelp) setNewHelps(helps: helps, observed: observed, keyPath: keyPath, referenceObject: referenceObject) } /**Removes the KVOHelp for the given triple. :note: This function does remove the KVOHelp from the KVO system itself, unlike the other functions, which do not really interact with the KVO system. */ private static func removeKVOHelpForTriple(#observed: NSObject, keyPath: String, referenceObject: AnyObject) { var haystack = KVOHelpsForPair(observed: observed, keyPath: keyPath) for (i, needle) in enumerate(haystack) { if needle.referenceObject === referenceObject { observed.removeObserver(needle, forKeyPath: keyPath) haystack.removeAtIndex(i) break } } setNewHelps(helps: haystack, observed: observed, keyPath: keyPath, referenceObject: referenceObject) } } public typealias KVOHelpClosureType = (keyPath: String, observedObject: AnyObject, change: [NSObject: AnyObject], context: AnyObject?) -> () class KVOHelpObserver : NSObject { private weak var referenceObject : AnyObject? = nil private let keyPath : String private let closure: KVOHelpClosureType private let strongContext : AnyObject? init(referenceObject: AnyObject, keyPath: String, context: AnyObject?, closure: KVOHelpClosureType) { self.keyPath = keyPath self.referenceObject = referenceObject self.closure = closure self.strongContext = context } private static var danglingSelf : KVOHelpObserver? = nil override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if referenceObject == nil { //I theorize that there is some problem here where the line below //causes self to be released. //solution: create a random dangling reference to self! KVOHelpObserver.danglingSelf = self object.removeObserver(self, forKeyPath: keyPath) //eventually, we'll clean it up dispatch_after(interval: 0.01, dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), { () -> Void in KVOHelpObserver.danglingSelf = nil }) return } closure(keyPath: keyPath, observedObject: object, change: change, context: strongContext) } } public extension NSObject { /** Blocks-based KVO. :param: referenceObject a reference object, typically self. When this object gets deallocated, the observer is automatically cleaned up. :param: keyPath the key path to observe :param: options. See the documentation for KVO :param: context. An arbitrary object passed to the block. A strong pointer to the context is acquired, so choose carefully. :param: closure a closure to run to be notified about changes. You want this to be weak/unowned self. :note: Only one (observed, observer, key) triple is allowed at a time. If you try to create a new one, we will replace the existing one. */ @availability(*, deprecated=8.1,renamed="beginObservingValue") public func addObserver(#referenceObject: AnyObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions, context: AnyObject?, closure: KVOHelpClosureType) { let kvoObserver = KVOHelpObserver(referenceObject: referenceObject, keyPath: keyPath, context: context, closure: closure) ObserversMap.setKVOHelpForTriple(newHelp: kvoObserver, observed: self, keyPath: keyPath, referenceObject: referenceObject) self.addObserver(kvoObserver, forKeyPath: keyPath, options: options, context:nil) } /** Blocks-based KVO. A variant with no referenceObject. In this case you must manually remove the observer. :param: referenceObject a reference object, typically self. When this object gets deallocated, the observer is automatically cleaned up. :param: keyPath the key path to observe :param: options. See the documentation for KVO :param: context. An arbitrary object passed to the block. A strong pointer to the context is acquired, so choose carefully. :param: closure a closure to run to be notified about changes. You want this to be weak/unowned self. :note: Only one (observed, observer, key) triple is allowed at a time. If you try to create a new one, we will replace the existing one. */ @availability(*, deprecated=8.1,renamed="beginObservingValue") public func addObserver(forKeyPath keyPath: String, options: NSKeyValueObservingOptions, context: AnyObject?, closure: KVOHelpClosureType) { self.addObserver(referenceObject: NSNull(), forKeyPath: keyPath, options: options, context: context, closure: closure) } @availability(*, deprecated=8.1) public func removeObserver(#referenceObject: AnyObject, forKeyPath keyPath: String) { let object = ObserversMap.KVOHelpForTriple(observed: self, keyPath: keyPath, referenceObject: referenceObject)! self.removeObserver(object, forKeyPath: keyPath) } }
mit
fb80730e27f36651e4c96596c2461023
50.654676
173
0.702466
4.532197
false
false
false
false
alfishe/mooshimeter-osx
mooshimeter-osx/UI/Views/LargeIndicatorView.swift
1
1030
// // LargeIndicator.swift // mooshimeter-osx // // Created by Dev on 5/24/17. // Copyright © 2017 alfishe. All rights reserved. // import Cocoa import QuartzCore @IBDesignable class LargeIndicatorView: NSView { @IBOutlet weak var lblMode: NSTextField! @IBOutlet weak var lblSign: NSTextField! @IBOutlet weak var lblValue: NSTextField! required init(coder: NSCoder) { super.init(coder: coder)! var topLevelObjects: NSArray? = nil var view: NSView? = nil let frameworkBundle = Bundle(for: classForCoder) if frameworkBundle.loadNibNamed("LargeIndicatorView", owner: self, topLevelObjects: &topLevelObjects) { view = topLevelObjects!.first(where: { $0 is NSView }) as? NSView } // Use bounds not frame or it'll be offset view?.frame = bounds // Make the view stretch with containing view view?.autoresizingMask = [NSView.AutoresizingMask.width, NSView.AutoresizingMask.height] if view != nil { self.addSubview(view!) } } }
mit
7ade988db7fe3633b2e5f30a5beb212e
23.5
105
0.680272
4.149194
false
false
false
false
Yalantis/AppearanceNavigationController
AppearanceNavigationController/RootViewController.swift
1
1501
import UIKit class RootViewController: UITableViewController, NavigationControllerAppearanceContext { private let values: [Appearance] = (0..<10).map { _ in Appearance.random() } // mark: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return values.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! // fine for sample app let appearance = values[indexPath.row] cell.contentView.backgroundColor = appearance.navigationBar.backgroundColor cell.textLabel?.textColor = appearance.navigationBar.tintColor cell.textLabel?.text = "Sample #\(indexPath.row + 1)" cell.textLabel?.backgroundColor = .clear return cell } // mark: - AppearanceNavigationControllerContext func preferredAppearance(for navigationController: UINavigationController) -> Appearance? { return Appearance.lightAppearance } // mark: - Segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cell = sender as? UITableViewCell, let target = segue.destination as? ContentViewController, let index = tableView.indexPath(for: cell)?.row { target.appearance = values[index] } } }
mit
d6b895e3f1c0ff21466fe722f5bcbc30
33.906977
109
0.666889
5.579926
false
false
false
false
octo-technology/IQKeyboardManager
Demo/Swift_Demo/ViewController/SpecialCaseViewController.swift
1
4695
// // SpecialCaseViewController.swift // IQKeyboard // // Created by Iftekhar on 23/09/14. // Copyright (c) 2014 Iftekhar. All rights reserved. // import Foundation import UIKit class CustomSubclassView : UIScrollView {} class SpecialCaseViewController: UIViewController, UISearchBarDelegate, UITextFieldDelegate, UITextViewDelegate { @IBOutlet private var customWorkTextField : UITextField! @IBOutlet private var textField6 : UITextField! @IBOutlet private var textField7 : UITextField! @IBOutlet private var textField8 : UITextField! @IBOutlet private var switchInteraction1 : UISwitch! @IBOutlet private var switchInteraction2 : UISwitch! @IBOutlet private var switchInteraction3 : UISwitch! @IBOutlet private var switchEnabled1 : UISwitch! @IBOutlet private var switchEnabled2 : UISwitch! @IBOutlet private var switchEnabled3 : UISwitch! override func viewDidLoad() { super.viewDidLoad() textField6.userInteractionEnabled = switchInteraction1.on textField7.userInteractionEnabled = switchInteraction2.on textField8.userInteractionEnabled = switchInteraction3.on textField6.enabled = switchEnabled1.on textField7.enabled = switchEnabled2.on textField8.enabled = switchEnabled3.on updateUI() IQKeyboardManager.sharedManager().considerToolbarPreviousNextInViewClass(CustomSubclassView) } @IBAction func showAlertClicked (barButton : UIBarButtonItem!) { let alertView : UIAlertView = UIAlertView(title: "IQKeyboardManager", message: "It doesn't affect UIAlertView (Doesn't add IQToolbar on it's textField", delegate: nil, cancelButtonTitle: "OK") alertView.alertViewStyle = UIAlertViewStyle.LoginAndPasswordInput alertView.show() } func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(true, animated: true) } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchBar.setShowsCancelButton(false, animated: true) } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } func updateUI() { textField6.placeholder = (textField6.enabled ? "enabled" : "" ) + "," + (textField6.userInteractionEnabled ? "userInteractionEnabled" : "" ) textField7.placeholder = (textField7.enabled ? "enabled" : "" ) + "," + (textField7.userInteractionEnabled ? "userInteractionEnabled" : "" ) textField8.placeholder = (textField8.enabled ? "enabled" : "" ) + "," + (textField8.userInteractionEnabled ? "userInteractionEnabled" : "" ) } func switch1UserInteractionAction(sender: UISwitch) { textField6.userInteractionEnabled = sender.on updateUI() } func switch2UserInteractionAction(sender: UISwitch) { textField7.userInteractionEnabled = sender.on updateUI() } func switch3UserInteractionAction(sender: UISwitch) { textField8.userInteractionEnabled = sender.on updateUI() } func switch1Action(sender: UISwitch) { textField6.enabled = sender.on updateUI() } func switch2Action(sender: UISwitch) { textField7.enabled = sender.on updateUI() } func switch3Action(sender: UISwitch) { textField8.enabled = sender.on updateUI() } func textFieldShouldBeginEditing(textField: UITextField) -> Bool { if (textField == customWorkTextField) { if(textField.isAskingCanBecomeFirstResponder == false) { let alertView : UIAlertView = UIAlertView(title: "IQKeyboardManager", message: "Do your custom work here", delegate: nil, cancelButtonTitle: "OK") alertView.show() } return false } else { return true } } func textFieldDidBeginEditing(textField: UITextField) { switchEnabled1.enabled = false switchEnabled2.enabled = false switchEnabled3.enabled = false switchInteraction1.enabled = false switchInteraction2.enabled = false switchInteraction3.enabled = false } func textFieldDidEndEditing(textField: UITextField) { switchEnabled1.enabled = true switchEnabled2.enabled = true switchEnabled3.enabled = true switchInteraction1.enabled = true switchInteraction2.enabled = true switchInteraction3.enabled = true } override func shouldAutorotate() -> Bool { return true } }
mit
eec007c81555662f104de7f2b369c87f
33.270073
200
0.671778
5.287162
false
false
false
false
andychase/classwork
cs496/final/finalProject/ListViewController.swift
1
1213
// // FirstViewController.swift // finalProject // // Created by Andy Chase on 12/5/15. // Copyright © 2015 Andy Chase. All rights reserved. // import UIKit class ListViewController: UIViewController { var userId:String! var listType:Bool! var dataSource:ListModel! @IBOutlet var table: UITableView! @IBOutlet weak var inputField: UITextField! override func viewDidLoad() { self.dataSource = ListModel( table: table, isGlobalListType: self.restorationIdentifier == "globalList", userId: userId ) table.dataSource = self.dataSource table.delegate = self.dataSource } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.dataSource!.loadRows() } override func viewDidAppear(animated: Bool) { table.setEditing(true, animated: true) } @IBAction func addButtonPress(sender: AnyObject) { if let text = inputField.text { if text != "" { self.dataSource.addItem(text) self.dataSource.saveRows() inputField.text = "" } } } }
mit
03ea19acb6a0322e2a5d89bee84a1948
23.24
73
0.59901
4.752941
false
false
false
false
jbruce2112/cutlines
Cutlines/AppDelegate.swift
1
4328
// // AppDelegate.swift // Cutlines // // Created by John on 1/30/17. // Copyright © 2017 Bruce32. All rights reserved. // import CloudKit import UIKit class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private let photoManager = PhotoManager() private var tabBarController: UITabBarController? private var navigationControllers: [UINavigationController]? private var collectionViewController: CollectionViewController? private var searchViewController: SearchViewController? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { tabBarController = window!.rootViewController as? UITabBarController navigationControllers = tabBarController?.viewControllers as? [UINavigationController] collectionViewController = navigationControllers?.first?.viewControllers.first as? CollectionViewController searchViewController = navigationControllers?[1].viewControllers.first as? SearchViewController // Inject the manager into the initial view controllers collectionViewController?.photoManager = photoManager searchViewController?.photoManager = photoManager // Handle updating the network indicator in the status bar photoManager.cloudManager.networkStatusDelegate = self // Tell the photo manager to set everything up // required for cloud communication, syncing and storage photoManager.setup() // Listen for push events application.registerForRemoteNotifications() // Set initial theme setTheme() return true } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { guard let dict = userInfo as? [String: NSObject], let notification = CKNotification(fromRemoteNotificationDictionary: dict), notification.subscriptionID == photoManager.cloudManager.subscriptionID else { completionHandler(.noData) return } photoManager.cloudManager.fetchChanges { completionHandler(UIBackgroundFetchResult.newData) } } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { log("Failed to register for notifications with \(error)") } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, // and store enough application state information to restore your application to its // current state in case it is terminated later. If your application supports // background execution, this method is called instead of applicationWillTerminate: when the user quits. photoManager.cloudManager.saveSyncState() searchViewController?.saveRecent() } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; // here you can undo many of the changes made on entering the background. collectionViewController?.refresh() } func setTheme() { // We're settings these properties in the AppDelegate since it already knows // about the navigation and tab controllers, and we don't currently have any // custom classes to implement their own viewWillAppear()/setTheme() behavior tabBarController?.tabBar.setTheme() for controller in navigationControllers ?? [] { controller.navigationBar.setTheme() } } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { completionHandler(quickAction(for: shortcutItem)) } private func quickAction(for shortcutItem: UIApplicationShortcutItem) -> Bool { let name = shortcutItem.type.components(separatedBy: ".").last! if name == "Search" { tabBarController?.selectedIndex = 1 return true } return false } } // MARK: NetworkStatusDelegate conformance extension AppDelegate: NetworkStatusDelegate { func statusChanged(busy: Bool) { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = busy } } }
mit
cbc9b72cbee419f3674c3976a51b4c7a
32.804688
195
0.758955
5.322263
false
false
false
false
charmaex/JDTransition
JDTransition/JDAnimationScale.swift
1
1606
// // JDAnimationScale.swift // JDTransition // // Created by Jan Dammshäuser on 26.09.16. // Copyright © 2016 Jan Dammshäuser. All rights reserved. // import Foundation struct JDAnimationScale { static func out(inWindow window: UIView, fromVC: UIViewController, toVC: UIViewController, duration: TimeInterval, options opt: UIViewAnimationOptions?, completion: @escaping (Bool) -> Void) { window.addSubview(toVC.view) window.sendSubview(toBack: toVC.view) toVC.view.frame = fromVC.view.frame let options = opt ?? .curveEaseOut UIView.animate(withDuration: duration, delay: 0, options: options, animations: { fromVC.view.transform = CGAffineTransform(scaleX: 0.05, y: 0.05) }) { finished in completion(finished) fromVC.view.transform = CGAffineTransform(scaleX: 1, y: 1) } } static func `in`(inWindow window: UIView, fromVC: UIViewController, toVC: UIViewController, duration: TimeInterval, options opt: UIViewAnimationOptions?, completion: @escaping (Bool) -> Void) { window.addSubview(toVC.view) toVC.view.frame = fromVC.view.frame let destCenter = fromVC.view.center let options = opt ?? .curveEaseIn toVC.view.transform = CGAffineTransform(scaleX: 0.05, y: 0.05) UIView.animate(withDuration: duration, delay: 0, options: options, animations: { toVC.view.transform = CGAffineTransform(scaleX: 1, y: 1) toVC.view.center = destCenter }) { finished in completion(finished) } } }
mit
58d4dd8151260073f563aa0e253fcc1c
32.395833
197
0.657517
4.332432
false
false
false
false
Xinext/RemainderCalc
src/RemainderCalc/MainViewController.swift
1
24507
// // MainViewController.swift // RemainderCalc // import UIKit import AVFoundation class MainViewController: UIViewController { // MARK: - IBOutlet @IBOutlet weak var outletMainContentsView: UIView! @IBOutlet weak var outletMainContentsBottomLayoutConstraint: NSLayoutConstraint! // タイトルエリア @IBOutlet weak var outletNavigationItem: UINavigationItem! // アプリタイトル @IBOutlet weak var outletHistoryButton: UIBarButtonItem! // 履歴ボタン @IBOutlet weak var outletPreferenceButton: UIBarButtonItem! // 設定ボタン // 表示エリア @IBOutlet weak var outletInputValueLabel: XIPaddingLabel! // 入力値テキストラベル @IBOutlet weak var outletExpressionLabel: XIPaddingLabel! // 式タイトルラベル @IBOutlet weak var outletExpressionValueLabel: XIPaddingLabel! // 式テキストラベル @IBOutlet weak var outletAnswerLabel: XIPaddingLabel! // 答えタイトルラベル @IBOutlet weak var outletAnswerValueLabel: XIPaddingLabel! // 答えテキストラベル @IBOutlet weak var outletDecimalPointTitleLabel: XIPaddingLabel! // 小数点位置タイトルラベル @IBOutlet weak var outletDecimalPointDownButton: XIPaddingButton! // 小数点Downボタン @IBOutlet weak var outletDecimalPointValueLabel: XIPaddingLabel! // 小数点位置テキスト @IBOutlet weak var outletDecimalPointUpButton: XIPaddingButton! // 小数点Upボタン // 入力エリア @IBOutlet weak var outletKey0Button: XIPaddingButton! // 0キーボタン @IBOutlet weak var outletKey00Button: XIPaddingButton! // 00キーボタン @IBOutlet weak var outletKey1Button: XIPaddingButton! // 1キーボタン @IBOutlet weak var outletKey2Button: XIPaddingButton! // 2キーボタン @IBOutlet weak var outletKey3Button: XIPaddingButton! // 3キーボタン @IBOutlet weak var outletKey4Button: XIPaddingButton! // 4キーボタン @IBOutlet weak var outletKey5Button: XIPaddingButton! // 5キーボタン @IBOutlet weak var outletKey6Button: XIPaddingButton! // 6キーボタン @IBOutlet weak var outletKey7Button: XIPaddingButton! // 7キーボタン @IBOutlet weak var outletKey8Button: XIPaddingButton! // 8キーボタン @IBOutlet weak var outletKey9Button: XIPaddingButton! // 9キーボタン @IBOutlet weak var outletKeyDotButton: XIPaddingButton! // 小数点キーボタン @IBOutlet weak var outletKeyACButton: XIPaddingButton! // AC(All Clear)キーボタン @IBOutlet weak var outletKeyBSButton: XIPaddingButton! // BS(Back space)キーボタン @IBOutlet weak var outletKeyDivideButton: XIPaddingButton! // ÷キーボタン @IBOutlet weak var outletKeyEqualButton: XIPaddingButton! // =キーボタン // MARK: - Private variable private var adMgr = AdModMgr() private var firstAppear: Bool = false var seTapButtonAudio : AVAudioPlayer! = nil // MARK: - ViewController Override override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // 表示アイテムの初期化 initEachItem() // 表示アイテムのローカライズ localizeEachItem() // SE(効果音)の初期化 initSEAudio() // 広告マネージャーの初期化 adMgr.InitManager(pvc:self, cv:outletMainContentsView, lc: outletMainContentsBottomLayoutConstraint) } /** Viewが表示される直前に呼び出されるイベントハンドラー */ override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // 最初に表示される時の処理 if (firstAppear != true) { outletMainContentsView.isHidden = true // メインコンテンツの準備ができるまで非表示 } } /** Viewが表示された直後に呼び出されるイベントハンドラー */ override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // 最初に表示される時の処理 if (firstAppear != true) { procStateMgr(.INIT) // メインコンテンツを初期化 outletMainContentsView.isHidden = false // メインコンテンツの準備が完了したので表示 adMgr.DispAdView(pos: AdModMgr.DISP_POSITION.BOTTOM) // 広告の表示 firstAppear = true } } /** メモリー警告 */ override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** initialize each item */ private func initEachItem() { // Navibar right button outletPreferenceButton.width = 0 let settingIcon = UIImage(named: "icon_preference")?.ResizeUIImage(width: 20, height: 20) outletPreferenceButton.image = settingIcon } /** localize each item */ private func localizeEachItem() { outletNavigationItem.title = NSLocalizedString("STR_MAIN_VIEW_TITLE", comment: "") outletHistoryButton.title = NSLocalizedString("STR_MAIN_HISTORY_BUTTON", comment: "") outletPreferenceButton.title = "" outletExpressionLabel.text = NSLocalizedString("STR_MAIN_EXP_LABEL", comment: "") outletAnswerLabel.text = NSLocalizedString("STR_MAIN_ANS_LABEL", comment: "") outletDecimalPointTitleLabel.text = NSLocalizedString("STR_MAIN_DECPOS_LABEL", comment: "") } /** initialize each se audio */ private func initSEAudio() { // for Tap the button let soundFilePath = Bundle.main.path(forResource: "SE_TapButton", ofType: "mp3")! let sound:URL = URL(fileURLWithPath: soundFilePath) // AVAudioPlayerのインスタンスを作成 do { seTapButtonAudio = try AVAudioPlayer(contentsOf: sound, fileTypeHint:nil) } catch { seTapButtonAudio = nil print("AVAudioPlayerインスタンス作成失敗") } // バッファに保持していつでも再生できるようにする seTapButtonAudio.prepareToPlay() } // MARK: - Action method /** [Action] 小数点位置ダウンボタン 押下 */ @IBAction func Action_DecimalPointDownButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_DECPOS_DOWN) } /** [Action] 小数点位置アップボタン 押下 */ @IBAction func Action_DecimalPointUpButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_DECPOS_UP) } /** [Action] 0ボタン 押下 */ @IBAction func Action_Key0Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 0 as AnyObject) } /** [Action] 00ボタン 押下 */ @IBAction func Action_Key00Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 0 as AnyObject) procStateMgr(.TAP_NUM, 0 as AnyObject) } /** [Action] 1ボタン 押下 */ @IBAction func Action_Key1Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 1 as AnyObject) } /** [Action] 2ボタン 押下 */ @IBAction func Action_Key2Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 2 as AnyObject) } /** [Action] 3ボタン 押下 */ @IBAction func Action_Key3Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 3 as AnyObject) } /** [Action] 4ボタン 押下 */ @IBAction func Action_Key4Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 4 as AnyObject) } /** [Action] 5ボタン 押下 */ @IBAction func Action_Key5Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 5 as AnyObject) } /** [Action] 6ボタン 押下 */ @IBAction func Action_Key6Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 6 as AnyObject) } /** [Action] 7ボタン 押下 */ @IBAction func Action_Key7Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 7 as AnyObject) } /** [Action] 8ボタン 押下 */ @IBAction func Action_Key8Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 8 as AnyObject) } /** [Action] 9ボタン 押下 */ @IBAction func Action_Key9Button_TouchDown(_ sender: Any) { procStateMgr(.TAP_NUM, 9 as AnyObject) } /** [Action] ACボタン 押下 */ @IBAction func Action_KeyACButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_AC) } /** [Action] 小数点ボタン 押下 */ @IBAction func Action_DotButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_DP) } /** [Action] BSボタン 押下 */ @IBAction func Action_KeyBSButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_BS) } /** [Action] ÷ボタン 押下 */ @IBAction func Action_KeyDivideButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_DIV) } /** [Action] =ボタン 押下 */ @IBAction func Action_KeyEqualButton_TouchDown(_ sender: Any) { procStateMgr(.TAP_EQ) } // MARK: - State Procedure // MARK: - State Procedure (変数・定義) /** ステート定義 */ private enum PROC_STATE { case WAIT_DIVIDEND // 割られる値入力待ち 状態 (IDLE) case WAIT_DIVISOR // 割る値入力待ち 状態 case VIEW_ANSWER // 答え表示 状態 case MAXNUM // イリーガル状態チェック用 } private var procState: PROC_STATE = PROC_STATE.WAIT_DIVIDEND /** イベント定義 */ private enum PROC_EVENT { case INIT // 初期化 case TAP_DECPOS_UP // 小数点位置Upボタン押下 case TAP_DECPOS_DOWN // 小数点位置Downボタン押下 case TAP_NUM // 数字ボタン(0,00,1,2,3,4,5,6,7,8,9)押下 case TAP_DP // 小数点ボタン case TAP_AC // ACボタン押下 case TAP_BS // ←ボタン押下 case TAP_DIV // ÷ボタン押下 case TAP_EQ // =ボタン押下 case MAXNUM // イリーガルイベントチェック用 } /** あまり割算計算マネージャー */ private let remCalcMgr = RemainderCalculationManager() // MARK: - State Procedure (ステートマネージャー処理) /** Initialization of processing - parameter event: Occurred Event - parameter param: The parameter of event - returns: nothing */ private func procStateMgr( _ event: PROC_EVENT, _ param: AnyObject? = nil) { // The common event processing for all state. switch event { case .INIT: // Viewの初期化 initConfigOfEachView() localizeEachItem() remCalcMgr.SetDecimalPosition(AppPreference.GetDecimalPoint()) initStateMgr() case .TAP_AC: playTapButtonSound() initStateMgr() default: // no action break; } // Event driven processing switch procState { case .WAIT_DIVIDEND: procstatemgr_Evt_WaitDividend( event, param: param ) case .WAIT_DIVISOR: procstatemgr_Evt_WaitDivisor( event, param: param ) case .VIEW_ANSWER: procstatemgr_Evt_ViewAnswer( event, param: param ) default: // Illegal state initStateMgr() break; } // State driven processing changeViewItemColorForState(state: procState) } /** [Event Driven] State: Wait dividend - parameter event: Occurred Event - parameter param: The parameter of event - returns: nothing */ private func procstatemgr_Evt_WaitDividend( _ event: PROC_EVENT, param: AnyObject?) { switch event { case .INIT: // common processing event break case .TAP_DECPOS_UP: evt_TAP_DECPOS_UP() case .TAP_DECPOS_DOWN: evt_TAP_DECPOS_DOWN() case .TAP_NUM: evt_TAP_NUM(param as! Int) break case .TAP_DP: evt_TAP_DP() break case .TAP_AC: // common processing event // common processing event break case .TAP_BS: evt_TAP_BS() break case .TAP_DIV: playTapButtonSound() remCalcMgr.DecideDividend() updateTextInDisplayArea() procState = .WAIT_DIVISOR break case .TAP_EQ: // ignore break default: // Illegal event evt_ErrorHandling() procState = .WAIT_DIVIDEND break; } } /** [Event Driven] State: Wait divisor - parameter event: Occurred Event - parameter param: The parameter of event - returns: nothing */ private func procstatemgr_Evt_WaitDivisor( _ event: PROC_EVENT, param: AnyObject?) { switch event { case .INIT: // common processing event break case .TAP_DECPOS_UP: evt_TAP_DECPOS_UP() case .TAP_DECPOS_DOWN: evt_TAP_DECPOS_DOWN() case .TAP_NUM: evt_TAP_NUM(param as! Int) break case .TAP_DP: evt_TAP_DP() break case .TAP_AC: // common processing event // common processing event break case .TAP_BS: evt_TAP_BS() break case .TAP_DIV: // ignore break case .TAP_EQ: playTapButtonSound() remCalcMgr.DecideDiviSor() saveDataForHistory() procState = .VIEW_ANSWER updateTextInDisplayArea() break default: // Illegal event evt_ErrorHandling() procState = .WAIT_DIVIDEND break; } } /** [Event Driven] State: View answer - parameter event: Occurred Event - parameter param: The parameter of event - returns: nothing */ private func procstatemgr_Evt_ViewAnswer( _ event: PROC_EVENT, param: AnyObject?) { switch event { case .INIT: // common processing event break case .TAP_DECPOS_UP: // ignore break case .TAP_DECPOS_DOWN: // ignore break case .TAP_NUM: // ignore break case .TAP_DP: // ignore break case .TAP_AC: // common processing event // common processing event break case .TAP_BS: // ignore break case .TAP_DIV: // ignore break case .TAP_EQ: // ignore break default: // Illegal event evt_ErrorHandling() procState = .WAIT_DIVIDEND break; } } // MARK: - State Procedure (イベント共通処理) /** TAP_DECPOS_UP */ func evt_TAP_DECPOS_UP() { playTapButtonSound() remCalcMgr.UpDecimalPosition() AppPreference.SetDecimalPoint(value: remCalcMgr.P_DecimalPosition) updateTextInDisplayArea() } /** TAP_DECPOS_DOWN */ func evt_TAP_DECPOS_DOWN() { playTapButtonSound() remCalcMgr.DownDecimalPosition() AppPreference.SetDecimalPoint(value: remCalcMgr.P_DecimalPosition) updateTextInDisplayArea() } /** TAP_NUM */ func evt_TAP_NUM(_ number: Int) { playTapButtonSound() remCalcMgr.InputNumber(number) updateTextInDisplayArea() } /** TAP_BS */ func evt_TAP_BS() { playTapButtonSound() remCalcMgr.ExecuteBackSpace() updateTextInDisplayArea() } /** TAP_DP */ func evt_TAP_DP() { playTapButtonSound() remCalcMgr.InputDecimalPoint() updateTextInDisplayArea() } /** Error Handling */ func evt_ErrorHandling() { initStateMgr() updateTextInDisplayArea() } // MARK: - State Procedure (サブルーチン処理) /** Initialization state procedures */ private func initStateMgr() { remCalcMgr.InitValuesForCalc() procState = .WAIT_DIVIDEND updateTextInDisplayArea() } /** Update text in display area */ private func updateTextInDisplayArea() { outletDecimalPointValueLabel.text = remCalcMgr.P_DecPosString // 小数点位置 outletInputValueLabel.text = remCalcMgr.P_InputValuesString // 入力値 outletExpressionValueLabel.text = remCalcMgr.P_ExpressionString // 式 outletExpressionValueLabel.FontSizeToFit() outletAnswerValueLabel.text = remCalcMgr.P_AnswerString // 答え outletAnswerValueLabel.FontSizeToFit() } /** Initialize the configuration of each view */ private func initConfigOfEachView() { // 表示エリア outletInputValueLabel.text = "888888888888" // 12桁 outletInputValueLabel.FontSizeToFit() outletInputValueLabel.text = "" outletExpressionLabel.FontSizeToFit() outletAnswerLabel.FontSizeToFit() outletDecimalPointTitleLabel.FontSizeToFit() outletDecimalPointDownButton.FontSizeToFit() outletDecimalPointValueLabel.FontSizeToFit() outletDecimalPointUpButton.FontSizeToFit() // 入力エリア outletKey0Button.FontSizeToFit() outletKey00Button.FontSizeToFit() outletKey1Button.FontSizeToFit() outletKey2Button.FontSizeToFit() outletKey3Button.FontSizeToFit() outletKey4Button.FontSizeToFit() outletKey5Button.FontSizeToFit() outletKey6Button.FontSizeToFit() outletKey7Button.FontSizeToFit() outletKey8Button.FontSizeToFit() outletKey9Button.FontSizeToFit() outletKeyACButton.FontSizeToFit() outletKeyBSButton.FontSizeToFit() outletKeyDotButton.FontSizeToFit() outletKeyDivideButton.FontSizeToFit() outletKeyEqualButton.FontSizeToFit() } /** Change the color of each view item color for each state. */ private func changeViewItemColorForState(state: PROC_STATE) { switch state { case .WAIT_DIVIDEND: outletInputValueLabel.backgroundColor = UIColor.white outletExpressionValueLabel.backgroundColor = UIColor.lightGray outletAnswerValueLabel.backgroundColor = UIColor.lightGray outletDecimalPointDownButton.tintColor = UIColor.white outletDecimalPointUpButton.tintColor = UIColor.white outletKey0Button.tintColor = UIColor.white outletKey00Button.tintColor = UIColor.white outletKey1Button.tintColor = UIColor.white outletKey2Button.tintColor = UIColor.white outletKey3Button.tintColor = UIColor.white outletKey4Button.tintColor = UIColor.white outletKey5Button.tintColor = UIColor.white outletKey6Button.tintColor = UIColor.white outletKey7Button.tintColor = UIColor.white outletKey8Button.tintColor = UIColor.white outletKey9Button.tintColor = UIColor.white outletKeyDotButton.tintColor = UIColor.white outletKeyACButton.tintColor = UIColor.white outletKeyBSButton.tintColor = UIColor.white outletKeyDivideButton.tintColor = UIColor.white outletKeyEqualButton.tintColor = UIColor.lightGray case .WAIT_DIVISOR: outletInputValueLabel.backgroundColor = UIColor.white outletExpressionValueLabel.backgroundColor = UIColor.hexStr(hexStr: "A5D1F4", alpha: 1.0) outletAnswerValueLabel.backgroundColor = UIColor.lightGray outletDecimalPointDownButton.tintColor = UIColor.white outletDecimalPointUpButton.tintColor = UIColor.white outletKey0Button.tintColor = UIColor.white outletKey00Button.tintColor = UIColor.white outletKey1Button.tintColor = UIColor.white outletKey2Button.tintColor = UIColor.white outletKey3Button.tintColor = UIColor.white outletKey4Button.tintColor = UIColor.white outletKey5Button.tintColor = UIColor.white outletKey6Button.tintColor = UIColor.white outletKey7Button.tintColor = UIColor.white outletKey8Button.tintColor = UIColor.white outletKey9Button.tintColor = UIColor.white outletKeyDotButton.tintColor = UIColor.white outletKeyACButton.tintColor = UIColor.white outletKeyBSButton.tintColor = UIColor.white outletKeyDivideButton.tintColor = UIColor.lightGray outletKeyEqualButton.tintColor = UIColor.white case .VIEW_ANSWER: outletInputValueLabel.backgroundColor = UIColor.lightGray outletExpressionValueLabel.backgroundColor = UIColor.hexStr(hexStr: "A5D1F4", alpha: 1.0) outletAnswerValueLabel.backgroundColor = UIColor.hexStr(hexStr: "EAC7CD", alpha: 1.0) outletDecimalPointDownButton.tintColor = UIColor.lightGray outletDecimalPointUpButton.tintColor = UIColor.lightGray outletKey0Button.tintColor = UIColor.lightGray outletKey00Button.tintColor = UIColor.lightGray outletKey1Button.tintColor = UIColor.lightGray outletKey2Button.tintColor = UIColor.lightGray outletKey3Button.tintColor = UIColor.lightGray outletKey4Button.tintColor = UIColor.lightGray outletKey5Button.tintColor = UIColor.lightGray outletKey6Button.tintColor = UIColor.lightGray outletKey7Button.tintColor = UIColor.lightGray outletKey8Button.tintColor = UIColor.lightGray outletKey9Button.tintColor = UIColor.lightGray outletKeyDotButton.tintColor = UIColor.lightGray outletKeyACButton.tintColor = UIColor.white outletKeyBSButton.tintColor = UIColor.lightGray outletKeyDivideButton.tintColor = UIColor.lightGray outletKeyEqualButton.tintColor = UIColor.lightGray default: break } } /** 履歴用データの保存 */ private func saveDataForHistory() { ModelMgr.Save_D_History(setModel: { (data: D_History) -> Void in data.m_i_answer = remCalcMgr.P_AnswerString data.m_i_expression = remCalcMgr.P_ExpressionString data.m_i_decimal_position = Int16(remCalcMgr.P_DecimalPosition) data.m_i_divisor = remCalcMgr.P_DivisorValue data.m_i_dividend = remCalcMgr.P_DividendValue data.m_k_update_time = Date() }) ModelMgr.DeleteDataWithOffset(offset: 50) } /** Play tap the button. */ private func playTapButtonSound() { if ( AppPreference.GetButtonPushedSound() == true ) { if ( self.seTapButtonAudio != nil ) { self.seTapButtonAudio.play() } } } }
mit
a97327f96707d4a76dfb482551194e1a
30.842541
108
0.59096
4.307549
false
false
false
false
yanfeng0107/ios-charts
Charts/Classes/Data/ChartData.swift
59
24664
// // ChartData.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartData: NSObject { internal var _yMax = Double(0.0) internal var _yMin = Double(0.0) internal var _leftAxisMax = Double(0.0) internal var _leftAxisMin = Double(0.0) internal var _rightAxisMax = Double(0.0) internal var _rightAxisMin = Double(0.0) private var _yValueSum = Double(0.0) private var _yValCount = Int(0) /// the last start value used for calcMinMax internal var _lastStart: Int = 0 /// the last end value used for calcMinMax internal var _lastEnd: Int = 0 /// the average length (in characters) across all x-value strings private var _xValAverageLength = Double(0.0) internal var _xVals: [String?]! internal var _dataSets: [ChartDataSet]! public override init() { super.init() _xVals = [String?]() _dataSets = [ChartDataSet]() } public init(xVals: [String?]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : xVals _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public init(xVals: [NSObject]?, dataSets: [ChartDataSet]?) { super.init() _xVals = xVals == nil ? [String?]() : ChartUtils.bridgedObjCGetStringArray(objc: xVals!) _dataSets = dataSets == nil ? [ChartDataSet]() : dataSets self.initialize(_dataSets) } public convenience init(xVals: [String?]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [NSObject]?) { self.init(xVals: xVals, dataSets: [ChartDataSet]()) } public convenience init(xVals: [String?]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } public convenience init(xVals: [NSObject]?, dataSet: ChartDataSet?) { self.init(xVals: xVals, dataSets: dataSet === nil ? nil : [dataSet!]) } internal func initialize(dataSets: [ChartDataSet]) { checkIsLegal(dataSets) calcMinMax(start: _lastStart, end: _lastEnd) calcYValueSum() calcYValueCount() calcXValAverageLength() } // calculates the average length (in characters) across all x-value strings internal func calcXValAverageLength() { if (_xVals.count == 0) { _xValAverageLength = 1 return } var sum = 1 for (var i = 0; i < _xVals.count; i++) { sum += _xVals[i] == nil ? 0 : count(_xVals[i]!) } _xValAverageLength = Double(sum) / Double(_xVals.count) } // Checks if the combination of x-values array and DataSet array is legal or not. // :param: dataSets internal func checkIsLegal(dataSets: [ChartDataSet]!) { if (dataSets == nil) { return } for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].yVals.count > _xVals.count) { println("One or more of the DataSet Entry arrays are longer than the x-values array of this Data object.") return } } } public func notifyDataChanged() { initialize(_dataSets) } /// calc minimum and maximum y value over all datasets internal func calcMinMax(#start: Int, end: Int) { if (_dataSets == nil || _dataSets.count < 1) { _yMax = 0.0 _yMin = 0.0 } else { _lastStart = start _lastEnd = end _yMin = DBL_MAX _yMax = -DBL_MAX for (var i = 0; i < _dataSets.count; i++) { _dataSets[i].calcMinMax(start: start, end: end) if (_dataSets[i].yMin < _yMin) { _yMin = _dataSets[i].yMin } if (_dataSets[i].yMax > _yMax) { _yMax = _dataSets[i].yMax } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } // left axis var firstLeft = getFirstLeft() if (firstLeft !== nil) { _leftAxisMax = firstLeft!.yMax _leftAxisMin = firstLeft!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { if (dataSet.yMin < _leftAxisMin) { _leftAxisMin = dataSet.yMin } if (dataSet.yMax > _leftAxisMax) { _leftAxisMax = dataSet.yMax } } } } // right axis var firstRight = getFirstRight() if (firstRight !== nil) { _rightAxisMax = firstRight!.yMax _rightAxisMin = firstRight!.yMin for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { if (dataSet.yMin < _rightAxisMin) { _rightAxisMin = dataSet.yMin } if (dataSet.yMax > _rightAxisMax) { _rightAxisMax = dataSet.yMax } } } } // in case there is only one axis, adjust the second axis handleEmptyAxis(firstLeft, firstRight: firstRight) } } /// calculates the sum of all y-values in all datasets internal func calcYValueSum() { _yValueSum = 0 if (_dataSets == nil) { return } for (var i = 0; i < _dataSets.count; i++) { _yValueSum += fabs(_dataSets[i].yValueSum) } } /// Calculates the total number of y-values across all ChartDataSets the ChartData represents. internal func calcYValueCount() { _yValCount = 0 if (_dataSets == nil) { return } var count = 0 for (var i = 0; i < _dataSets.count; i++) { count += _dataSets[i].entryCount } _yValCount = count } /// returns the number of LineDataSets this object contains public var dataSetCount: Int { if (_dataSets == nil) { return 0 } return _dataSets.count } /// returns the smallest y-value the data object contains. public var yMin: Double { return _yMin } public func getYMin() -> Double { return _yMin } public func getYMin(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMin } else { return _rightAxisMin } } /// returns the greatest y-value the data object contains. public var yMax: Double { return _yMax } public func getYMax() -> Double { return _yMax } public func getYMax(axis: ChartYAxis.AxisDependency) -> Double { if (axis == .Left) { return _leftAxisMax } else { return _rightAxisMax } } /// returns the average length (in characters) across all values in the x-vals array public var xValAverageLength: Double { return _xValAverageLength } /// returns the total y-value sum across all DataSet objects the this object represents. public var yValueSum: Double { return _yValueSum } /// Returns the total number of y-values across all DataSet objects the this object represents. public var yValCount: Int { return _yValCount } /// returns the x-values the chart represents public var xVals: [String?] { return _xVals } ///Adds a new x-value to the chart data. public func addXValue(xVal: String?) { _xVals.append(xVal) } /// Removes the x-value at the specified index. public func removeXValue(index: Int) { _xVals.removeAtIndex(index) } /// Returns the array of ChartDataSets this object holds. public var dataSets: [ChartDataSet] { get { return _dataSets } set { _dataSets = newValue } } /// Retrieve the index of a ChartDataSet with a specific label from the ChartData. Search can be case sensitive or not. /// IMPORTANT: This method does calculations at runtime, do not over-use in performance critical situations. /// /// :param: dataSets the DataSet array to search /// :param: type /// :param: ignorecase if true, the search is not case-sensitive /// :returns: internal func getDataSetIndexByLabel(label: String, ignorecase: Bool) -> Int { if (ignorecase) { for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].label == nil) { continue } if (label.caseInsensitiveCompare(dataSets[i].label!) == NSComparisonResult.OrderedSame) { return i } } } else { for (var i = 0; i < dataSets.count; i++) { if (label == dataSets[i].label) { return i } } } return -1 } /// returns the total number of x-values this ChartData object represents (the size of the x-values array) public var xValCount: Int { return _xVals.count } /// Returns the labels of all DataSets as a string array. internal func dataSetLabels() -> [String] { var types = [String]() for (var i = 0; i < _dataSets.count; i++) { if (dataSets[i].label == nil) { continue } types[i] = _dataSets[i].label! } return types } /// Get the Entry for a corresponding highlight object /// /// :param: highlight /// :returns: the entry that is highlighted public func getEntryForHighlight(highlight: ChartHighlight) -> ChartDataEntry? { if highlight.dataSetIndex >= dataSets.count { return nil } else { return _dataSets[highlight.dataSetIndex].entryForXIndex(highlight.xIndex) } } /// Returns the DataSet object with the given label. /// sensitive or not. /// IMPORTANT: This method does calculations at runtime. Use with care in performance critical situations. /// /// :param: label /// :param: ignorecase public func getDataSetByLabel(label: String, ignorecase: Bool) -> ChartDataSet? { var index = getDataSetIndexByLabel(label, ignorecase: ignorecase) if (index < 0 || index >= _dataSets.count) { return nil } else { return _dataSets[index] } } public func getDataSetByIndex(index: Int) -> ChartDataSet! { if (_dataSets == nil || index < 0 || index >= _dataSets.count) { return nil } return _dataSets[index] } public func addDataSet(d: ChartDataSet!) { if (_dataSets == nil) { return } _yValCount += d.entryCount _yValueSum += d.yValueSum if (_dataSets.count == 0) { _yMax = d.yMax _yMin = d.yMin if (d.axisDependency == .Left) { _leftAxisMax = d.yMax _leftAxisMin = d.yMin } else { _rightAxisMax = d.yMax _rightAxisMin = d.yMin } } else { if (_yMax < d.yMax) { _yMax = d.yMax } if (_yMin > d.yMin) { _yMin = d.yMin } if (d.axisDependency == .Left) { if (_leftAxisMax < d.yMax) { _leftAxisMax = d.yMax } if (_leftAxisMin > d.yMin) { _leftAxisMin = d.yMin } } else { if (_rightAxisMax < d.yMax) { _rightAxisMax = d.yMax } if (_rightAxisMin > d.yMin) { _rightAxisMin = d.yMin } } } _dataSets.append(d) handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) } public func handleEmptyAxis(firstLeft: ChartDataSet?, firstRight: ChartDataSet?) { // in case there is only one axis, adjust the second axis if (firstLeft === nil) { _leftAxisMax = _rightAxisMax _leftAxisMin = _rightAxisMin } else if (firstRight === nil) { _rightAxisMax = _leftAxisMax _rightAxisMin = _leftAxisMin } } /// Removes the given DataSet from this data object. /// Also recalculates all minimum and maximum values. /// /// :returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSet(dataSet: ChartDataSet!) -> Bool { if (_dataSets == nil || dataSet === nil) { return false } for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return removeDataSetByIndex(i) } } return false } /// Removes the DataSet at the given index in the DataSet array from the data object. /// Also recalculates all minimum and maximum values. /// /// :returns: true if a DataSet was removed, false if no DataSet could be removed. public func removeDataSetByIndex(index: Int) -> Bool { if (_dataSets == nil || index >= _dataSets.count || index < 0) { return false } var d = _dataSets.removeAtIndex(index) _yValCount -= d.entryCount _yValueSum -= d.yValueSum calcMinMax(start: _lastStart, end: _lastEnd) return true } /// Adds an Entry to the DataSet at the specified index. Entries are added to the end of the list. public func addEntry(e: ChartDataEntry, dataSetIndex: Int) { if (_dataSets != nil && _dataSets.count > dataSetIndex && dataSetIndex >= 0) { var val = e.value var set = _dataSets[dataSetIndex] if (_yValCount == 0) { _yMin = val _yMax = val if (set.axisDependency == .Left) { _leftAxisMax = e.value _leftAxisMin = e.value } else { _rightAxisMax = e.value _rightAxisMin = e.value } } else { if (_yMax < val) { _yMax = val } if (_yMin > val) { _yMin = val } if (set.axisDependency == .Left) { if (_leftAxisMax < e.value) { _leftAxisMax = e.value } if (_leftAxisMin > e.value) { _leftAxisMin = e.value } } else { if (_rightAxisMax < e.value) { _rightAxisMax = e.value } if (_rightAxisMin > e.value) { _rightAxisMin = e.value } } } _yValCount += 1 _yValueSum += val handleEmptyAxis(getFirstLeft(), firstRight: getFirstRight()) set.addEntry(e) } else { println("ChartData.addEntry() - dataSetIndex our of range.") } } /// Removes the given Entry object from the DataSet at the specified index. public func removeEntry(entry: ChartDataEntry!, dataSetIndex: Int) -> Bool { // entry null, outofbounds if (entry === nil || dataSetIndex >= _dataSets.count) { return false } // remove the entry from the dataset var removed = _dataSets[dataSetIndex].removeEntry(xIndex: entry.xIndex) if (removed) { var val = entry.value _yValCount -= 1 _yValueSum -= val calcMinMax(start: _lastStart, end: _lastEnd) } return removed } /// Removes the Entry object at the given xIndex from the ChartDataSet at the /// specified index. Returns true if an entry was removed, false if no Entry /// was found that meets the specified requirements. public func removeEntryByXIndex(xIndex: Int, dataSetIndex: Int) -> Bool { if (dataSetIndex >= _dataSets.count) { return false } var entry = _dataSets[dataSetIndex].entryForXIndex(xIndex) if (entry?.xIndex != xIndex) { return false } return removeEntry(entry, dataSetIndex: dataSetIndex) } /// Returns the DataSet that contains the provided Entry, or null, if no DataSet contains this entry. public func getDataSetForEntry(e: ChartDataEntry!) -> ChartDataSet? { if (e == nil) { return nil } for (var i = 0; i < _dataSets.count; i++) { var set = _dataSets[i] for (var j = 0; j < set.entryCount; j++) { if (e === set.entryForXIndex(e.xIndex)) { return set } } } return nil } /// Returns the index of the provided DataSet inside the DataSets array of /// this data object. Returns -1 if the DataSet was not found. public func indexOfDataSet(dataSet: ChartDataSet) -> Int { for (var i = 0; i < _dataSets.count; i++) { if (_dataSets[i] === dataSet) { return i } } return -1 } public func getFirstLeft() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Left) { return dataSet } } return nil } public func getFirstRight() -> ChartDataSet? { for dataSet in _dataSets { if (dataSet.axisDependency == .Right) { return dataSet } } return nil } /// Returns all colors used across all DataSet objects this object represents. public func getColors() -> [UIColor]? { if (_dataSets == nil) { return nil } var clrcnt = 0 for (var i = 0; i < _dataSets.count; i++) { clrcnt += _dataSets[i].colors.count } var colors = [UIColor]() for (var i = 0; i < _dataSets.count; i++) { var clrs = _dataSets[i].colors for clr in clrs { colors.append(clr) } } return colors } /// Generates an x-values array filled with numbers in range specified by the parameters. Can be used for convenience. public func generateXVals(from: Int, to: Int) -> [String] { var xvals = [String]() for (var i = from; i < to; i++) { xvals.append(String(i)) } return xvals } /// Sets a custom ValueFormatter for all DataSets this data object contains. public func setValueFormatter(formatter: NSNumberFormatter!) { for set in dataSets { set.valueFormatter = formatter } } /// Sets the color of the value-text (color in which the value-labels are drawn) for all DataSets this data object contains. public func setValueTextColor(color: UIColor!) { for set in dataSets { set.valueTextColor = color ?? set.valueTextColor } } /// Sets the font for all value-labels for all DataSets this data object contains. public func setValueFont(font: UIFont!) { for set in dataSets { set.valueFont = font ?? set.valueFont } } /// Enables / disables drawing values (value-text) for all DataSets this data object contains. public func setDrawValues(enabled: Bool) { for set in dataSets { set.drawValuesEnabled = enabled } } /// Enables / disables highlighting values for all DataSets this data object contains. public var highlightEnabled: Bool { get { for set in dataSets { if (!set.highlightEnabled) { return false } } return true } set { for set in dataSets { set.highlightEnabled = newValue } } } /// if true, value highlightning is enabled public var isHighlightEnabled: Bool { return highlightEnabled } /// Clears this data object from all DataSets and removes all Entries. /// Don't forget to invalidate the chart after this. public func clearValues() { dataSets.removeAll(keepCapacity: false) notifyDataChanged() } /// Checks if this data object contains the specified Entry. Returns true if so, false if not. public func contains(#entry: ChartDataEntry) -> Bool { for set in dataSets { if (set.contains(entry)) { return true } } return false } /// Checks if this data object contains the specified DataSet. Returns true if so, false if not. public func contains(#dataSet: ChartDataSet) -> Bool { for set in dataSets { if (set.isEqual(dataSet)) { return true } } return false } /// MARK: - ObjC compatibility /// returns the average length (in characters) across all values in the x-vals array public var xValsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _xVals); } }
apache-2.0
44ad11ea7196c51843de5984ad10325c
25.37861
128
0.47247
5.224317
false
false
false
false
alessiobrozzi/firefox-ios
Client/Frontend/Browser/ThirdPartySearchAlerts.swift
9
2900
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared class ThirdPartySearchAlerts: UIAlertController { /** Allows the keyboard to pop back up after an alertview. **/ override var canBecomeFirstResponder: Bool { return false } /** Builds the Alert view that asks if the users wants to add a third party search engine. - parameter okayCallback: Okay option handler. - returns: UIAlertController for asking the user to add a search engine **/ static func addThirdPartySearchEngine(_ okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController { let alert = ThirdPartySearchAlerts( title: Strings.ThirdPartySearchAddTitle, message: Strings.ThirdPartySearchAddMessage, preferredStyle: UIAlertControllerStyle.alert ) let noOption = UIAlertAction( title: Strings.ThirdPartySearchCancelButton, style: UIAlertActionStyle.cancel, handler: nil ) let okayOption = UIAlertAction( title: Strings.ThirdPartySearchOkayButton, style: UIAlertActionStyle.default, handler: okayCallback ) alert.addAction(okayOption) alert.addAction(noOption) return alert } /** Builds the Alert view that shows the user an error in case a search engine could not be added. - returns: UIAlertController with an error dialog **/ static func failedToAddThirdPartySearch() -> UIAlertController { return searchAlertWithOK(title: Strings.ThirdPartySearchFailedTitle, message: Strings.ThirdPartySearchFailedMessage) } static func incorrectCustomEngineForm() -> UIAlertController { return searchAlertWithOK(title: Strings.CustomEngineFormErrorTitle, message: Strings.CustomEngineFormErrorMessage) } static func duplicateCustomEngine() -> UIAlertController { return searchAlertWithOK(title: Strings.CustomEngineDuplicateErrorTitle, message: Strings.CustomEngineDuplicateErrorMessage) } private static func searchAlertWithOK(title: String, message: String) -> UIAlertController { let alert = ThirdPartySearchAlerts( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert ) let okayOption = UIAlertAction( title: Strings.ThirdPartySearchOkayButton, style: UIAlertActionStyle.default, handler: nil ) alert.addAction(okayOption) return alert } }
mpl-2.0
660bc89955ad57924fec5275fbf94694
31.954545
115
0.649655
5.894309
false
false
false
false
furuya02/ProvisioningProfileExplorer
ProvisioningProfileExplorer/Certificate.swift
1
455
// // ertificate.swift // ProvisioningProfileExplorer // // Created by hirauchi.shinichi on 2016/04/16. // Copyright © 2016年 SAPPOROWORKS. All rights reserved. // import Cocoa class Certificate: NSObject { var summary: String = "" var expires: NSDate? = nil var lastDays = 0 init(summary:String,expires:NSDate?,lastDays:Int){ self.summary = summary self.expires = expires self.lastDays = lastDays } }
mit
35400dd8a6c7545b813ce4bd7043e063
20.52381
56
0.661504
3.559055
false
false
false
false