repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
Bauer312/ProjectEuler
Sources/Multiples/Multiples.swift
1
2746
/* Copyright (c) 2016 Brian Bauer Licensed under the MIT License (MIT) - Please see License.txt in the top level of this repository for additional information. */ import Foundation public class Multiples { public init () { //Don't need to do anything... } // Create a complete set of numbers, all of which are: // Multiples of number // Below the maximum func multiple(_ number: Int, _ maximum: Int) -> Set<Int> { var result = Set<Int>() for i in 1..<maximum { if i % number == 0 { result.insert(i) } } return result } func setSum(_ setToSum: Set<Int>) -> Int { var sum: Int = 0 for i in setToSum { sum = sum + i } return sum } public func setGroups(components: Set<Int>, maximum: Int) -> Int { var masterSet = Set<Int>() for component in components { masterSet = masterSet.union(multiple(component, maximum)) } return setSum(masterSet) } public func smallestMultiple(_ multiples: [Int64]) -> Int64 { var num: Int64 = 1 var noRemainder: Bool = true while num < Int64.max { for i in multiples { if num % i != 0 { noRemainder = false break } } if noRemainder == true { return num } num = num + 1 noRemainder = true } return -1 } public func largestAdjacentProduct(_ numbers: [Int], digits: Int) -> [Int] { var result : [Int] = Array(repeating: 0, count: digits + 1) var index: Int = 0 while index < numbers.count - digits { var product: Int = 1 for iterator in 0..<digits { product = product * numbers[index + iterator] } if product > result[0] { result[0] = product for iterator in 1...digits { result[iterator] = numbers[index + iterator] } } index = index + 1 } return result } public func numberArrayFromFile(_ fileName: String) -> [Int] { var result : [Int] = Array<Int>() guard fileName.characters.count > 0 else { return result } do { #if os(Linux) let numberString = try String(contentsOfFile: fileName, encoding: String.Encoding.utf8) #else let numberString = try String(contentsOfFile: fileName) #endif for digit in numberString.characters { if let value = Int(String(digit)) { result.append(value) } } } catch { print("Unable to read \(fileName)") return result } return result } public func isPythagoreanTriplet(a: Int, b: Int, c: Int) -> Bool { guard a < b && b < c else { return false } if a * a + b * b == c * c { return true } return false } }
mit
devincoughlin/swift
test/SILGen/property_wrappers.swift
1
19834
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t -enable-library-evolution %S/Inputs/property_wrapper_defs.swift // RUN: %target-swift-emit-silgen -primary-file %s -I %t | %FileCheck %s import property_wrapper_defs @propertyWrapper struct Wrapper<T> { var wrappedValue: T init(value: T) { wrappedValue = value } } @propertyWrapper struct WrapperWithInitialValue<T> { var wrappedValue: T } protocol DefaultInit { init() } extension Int: DefaultInit { } struct HasMemberwiseInit<T: DefaultInit> { @Wrapper(value: false) var x: Bool @WrapperWithInitialValue var y: T = T() @WrapperWithInitialValue(wrappedValue: 17) var z: Int } func forceHasMemberwiseInit() { _ = HasMemberwiseInit(x: Wrapper(value: true), y: 17, z: WrapperWithInitialValue(wrappedValue: 42)) _ = HasMemberwiseInit<Int>(x: Wrapper(value: true)) _ = HasMemberwiseInit(y: 17) _ = HasMemberwiseInit<Int>(z: WrapperWithInitialValue(wrappedValue: 42)) _ = HasMemberwiseInit<Int>() } // CHECK: sil_global private @$s17property_wrappers9UseStaticV13_staticWibble33_{{.*}}AA4LazyOySaySiGGvpZ : $Lazy<Array<Int>> // HasMemberwiseInit.x.setter // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1xSbvs : $@convention(method) <T where T : DefaultInit> (Bool, @inout HasMemberwiseInit<T>) -> () { // CHECK: bb0(%0 : $Bool, %1 : $*HasMemberwiseInit<T>): // CHECK: [[MODIFY_SELF:%.*]] = begin_access [modify] [unknown] %1 : $*HasMemberwiseInit<T> // CHECK: [[X_BACKING:%.*]] = struct_element_addr [[MODIFY_SELF]] : $*HasMemberwiseInit<T>, #HasMemberwiseInit._x // CHECK: [[X_BACKING_VALUE:%.*]] = struct_element_addr [[X_BACKING]] : $*Wrapper<Bool>, #Wrapper.wrappedValue // CHECK: assign %0 to [[X_BACKING_VALUE]] : $*Bool // CHECK: end_access [[MODIFY_SELF]] : $*HasMemberwiseInit<T> // variable initialization expression of HasMemberwiseInit._x // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2_x33_{{.*}}AA7WrapperVySbGvpfi : $@convention(thin) <T where T : DefaultInit> () -> Wrapper<Bool> { // CHECK: integer_literal $Builtin.Int1, 0 // CHECK-NOT: return // CHECK: function_ref @$sSb22_builtinBooleanLiteralSbBi1__tcfC : $@convention(method) (Builtin.Int1, @thin Bool.Type) -> Bool // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers7WrapperV5valueACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin Wrapper<τ_0_0>.Type) -> @out Wrapper<τ_0_0> // user: %9 // CHECK: return {{%.*}} : $Wrapper<Bool> // variable initialization expression of HasMemberwiseInit.$y // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2_y33_{{.*}}23WrapperWithInitialValueVyxGvpfi : $@convention(thin) <T where T : DefaultInit> () -> @out // CHECK: bb0(%0 : $*T): // CHECK-NOT: return // CHECK: witness_method $T, #DefaultInit.init!allocator.1 : <Self where Self : DefaultInit> (Self.Type) -> () -> Self : $@convention(witness_method: DefaultInit) <τ_0_0 where τ_0_0 : DefaultInit> (@thick τ_0_0.Type) -> @out τ_0_0 // variable initialization expression of HasMemberwiseInit._z // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2_z33_{{.*}}23WrapperWithInitialValueVySiGvpfi : $@convention(thin) <T where T : DefaultInit> () -> WrapperWithInitialValue<Int> { // CHECK: bb0: // CHECK-NOT: return // CHECK: integer_literal $Builtin.IntLiteral, 17 // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers23WrapperWithInitialValueV07wrappedF0ACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin WrapperWithInitialValue<τ_0_0>.Type) -> @out WrapperWithInitialValue<τ_0_0> // default argument 0 of HasMemberwiseInit.init(x:y:z:) // CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA_ : $@convention(thin) <T where T : DefaultInit> () -> Wrapper<Bool> // default argument 1 of HasMemberwiseInit.init(x:y:z:) // CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA0_ : $@convention(thin) <T where T : DefaultInit> () -> @out T { // default argument 2 of HasMemberwiseInit.init(x:y:z:) // CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA1_ : $@convention(thin) <T where T : DefaultInit> () -> WrapperWithInitialValue<Int> { // HasMemberwiseInit.init() // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitVACyxGycfC : $@convention(method) <T where T : DefaultInit> (@thin HasMemberwiseInit<T>.Type) -> @out HasMemberwiseInit<T> { // Initialization of x // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2_x33_{{.*}}7WrapperVySbGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> Wrapper<Bool> // Initialization of y // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2_y33_{{.*}}23WrapperWithInitialValueVyxGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> @out τ_0_0 // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV1yxvpfP : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> (@in τ_0_0) -> @out WrapperWithInitialValue<τ_0_0> // Initialization of z // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2_z33_{{.*}}23WrapperWithInitialValueVySiGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> WrapperWithInitialValue<Int> // CHECK: return // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers9HasNestedV2_y33_{{.*}}14PrivateWrapperAELLVyx_SayxGGvpfi : $@convention(thin) <T> () -> @owned Array<T> { // CHECK: bb0: // CHECK: function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF struct HasNested<T> { @propertyWrapper private struct PrivateWrapper<U> { var wrappedValue: U } @PrivateWrapper private var y: [T] = [] static func blah(y: [T]) -> HasNested<T> { return HasNested<T>() } } // FIXME: For now, we are only checking that we don't crash. struct HasDefaultInit { @Wrapper(value: true) var x @WrapperWithInitialValue var y = 25 static func defaultInit() -> HasDefaultInit { return HasDefaultInit() } static func memberwiseInit(x: Bool, y: Int) -> HasDefaultInit { return HasDefaultInit(x: Wrapper(value: x), y: y) } } struct WrapperWithAccessors { @Wrapper var x: Int // Synthesized setter // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers20WrapperWithAccessorsV1xSivs : $@convention(method) (Int, @inout WrapperWithAccessors) -> () // CHECK-NOT: return // CHECK: struct_element_addr {{%.*}} : $*WrapperWithAccessors, #WrapperWithAccessors._x mutating func test() { x = 17 } } func consumeOldValue(_: Int) { } func consumeNewValue(_: Int) { } struct WrapperWithDidSetWillSet { // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivs // CHECK: function_ref @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivw // CHECK: struct_element_addr {{%.*}} : $*WrapperWithDidSetWillSet, #WrapperWithDidSetWillSet._x // CHECK-NEXT: struct_element_addr {{%.*}} : $*Wrapper<Int>, #Wrapper.wrappedValue // CHECK-NEXT: assign %0 to {{%.*}} : $*Int // CHECK: function_ref @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivW @Wrapper var x: Int { didSet { consumeNewValue(oldValue) } willSet { consumeOldValue(newValue) } } mutating func test(x: Int) { self.x = x } } @propertyWrapper struct WrapperWithStorageValue<T> { var wrappedValue: T var projectedValue: Wrapper<T> { return Wrapper(value: wrappedValue) } } struct UseWrapperWithStorageValue { // UseWrapperWithStorageValue._x.getter // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers26UseWrapperWithStorageValueV2$xAA0D0VySiGvg : $@convention(method) (UseWrapperWithStorageValue) -> Wrapper<Int> // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers23WrapperWithStorageValueV09projectedF0AA0C0VyxGvg @WrapperWithStorageValue(wrappedValue: 17) var x: Int } @propertyWrapper enum Lazy<Value> { case uninitialized(() -> Value) case initialized(Value) init(wrappedValue initialValue: @autoclosure @escaping () -> Value) { self = .uninitialized(initialValue) } var wrappedValue: Value { mutating get { switch self { case .uninitialized(let initializer): let value = initializer() self = .initialized(value) return value case .initialized(let value): return value } } set { self = .initialized(newValue) } } } struct UseLazy<T: DefaultInit> { @Lazy var foo = 17 @Lazy var bar = T() @Lazy var wibble = [1, 2, 3] // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers7UseLazyV3foo3bar6wibbleACyxGSi_xSaySiGtcfC : $@convention(method) <T where T : DefaultInit> (Int, @in T, @owned Array<Int>, @thin UseLazy<T>.Type) -> @out UseLazy<T> // CHECK: function_ref @$s17property_wrappers7UseLazyV3fooSivpfP : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> (Int) -> @owned Lazy<Int> // CHECK: function_ref @$s17property_wrappers7UseLazyV3barxvpfP : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> (@in τ_0_0) -> @out Lazy<τ_0_0> // CHECK: function_ref @$s17property_wrappers7UseLazyV6wibbleSaySiGvpfP : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> (@owned Array<Int>) -> @owned Lazy<Array<Int>> } struct X { } func triggerUseLazy() { _ = UseLazy<Int>() _ = UseLazy<Int>(foo: 17) _ = UseLazy(bar: 17) _ = UseLazy<Int>(wibble: [1, 2, 3]) } struct UseStatic { // CHECK: sil hidden [ossa] @$s17property_wrappers9UseStaticV12staticWibbleSaySiGvgZ // CHECK: sil private [global_init] [ossa] @$s17property_wrappers9UseStaticV13_staticWibble33_{{.*}}4LazyOySaySiGGvau // CHECK: sil hidden [ossa] @$s17property_wrappers9UseStaticV12staticWibbleSaySiGvsZ @Lazy static var staticWibble = [1, 2, 3] } extension WrapperWithInitialValue { func test() { } } class ClassUsingWrapper { @WrapperWithInitialValue var x = 0 } extension ClassUsingWrapper { // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers17ClassUsingWrapperC04testcdE01cyAC_tF : $@convention(method) (@guaranteed ClassUsingWrapper, @guaranteed ClassUsingWrapper) -> () { func testClassUsingWrapper(c: ClassUsingWrapper) { // CHECK: ref_element_addr %1 : $ClassUsingWrapper, #ClassUsingWrapper._x self._x.test() } } // @propertyWrapper struct WrapperWithDefaultInit<T> { private var storage: T? init() { self.storage = nil } init(wrappedValue initialValue: T) { self.storage = initialValue } var wrappedValue: T { get { return storage! } set { storage = newValue } } } class UseWrapperWithDefaultInit { @WrapperWithDefaultInit var name: String } // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers25UseWrapperWithDefaultInitC5_name33_F728088E0028E14D18C6A10CF68512E8LLAA0defG0VySSGvpfi : $@convention(thin) () -> @owned WrapperWithDefaultInit<String> // CHECK: function_ref @$s17property_wrappers22WrapperWithDefaultInitVACyxGycfC // CHECK: return {{%.*}} : $WrapperWithDefaultInit<String> // Property wrapper composition. @propertyWrapper struct WrapperA<Value> { var wrappedValue: Value } @propertyWrapper struct WrapperB<Value> { var wrappedValue: Value } @propertyWrapper struct WrapperC<Value> { var wrappedValue: Value? } struct CompositionMembers { // CompositionMembers.p1.getter // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers18CompositionMembersV2p1SiSgvg : $@convention(method) (@guaranteed CompositionMembers) -> Optional<Int> // CHECK: bb0([[SELF:%.*]] : @guaranteed $CompositionMembers): // CHECK: [[P1:%.*]] = struct_extract [[SELF]] : $CompositionMembers, #CompositionMembers._p1 // CHECK: [[P1_VALUE:%.*]] = struct_extract [[P1]] : $WrapperA<WrapperB<WrapperC<Int>>>, #WrapperA.wrappedValue // CHECK: [[P1_VALUE2:%.*]] = struct_extract [[P1_VALUE]] : $WrapperB<WrapperC<Int>>, #WrapperB.wrappedValue // CHECK: [[P1_VALUE3:%.*]] = struct_extract [[P1_VALUE2]] : $WrapperC<Int>, #WrapperC.wrappedValue // CHECK: return [[P1_VALUE3]] : $Optional<Int> @WrapperA @WrapperB @WrapperC var p1: Int? @WrapperA @WrapperB @WrapperC var p2 = "Hello" // variable initialization expression of CompositionMembers.$p2 // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers18CompositionMembersV3_p233_{{.*}}8WrapperAVyAA0N1BVyAA0N1CVySSGGGvpfi : $@convention(thin) () -> @owned Optional<String> { // CHECK: %0 = string_literal utf8 "Hello" // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers18CompositionMembersV2p12p2ACSiSg_SSSgtcfC : $@convention(method) (Optional<Int>, @owned Optional<String>, @thin CompositionMembers.Type) -> @owned CompositionMembers // CHECK: s17property_wrappers18CompositionMembersV3_p233_{{.*}}8WrapperAVyAA0N1BVyAA0N1CVySSGGGvpfi } func testComposition() { _ = CompositionMembers(p1: nil) } // Observers with non-default mutatingness. @propertyWrapper struct NonMutatingSet<T> { private var fixed: T var wrappedValue: T { get { fixed } nonmutating set { } } init(wrappedValue initialValue: T) { fixed = initialValue } } @propertyWrapper struct MutatingGet<T> { private var fixed: T var wrappedValue: T { mutating get { fixed } set { } } init(wrappedValue initialValue: T) { fixed = initialValue } } struct ObservingTest { // ObservingTest.text.setter // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers13ObservingTestV4textSSvs : $@convention(method) (@owned String, @guaranteed ObservingTest) -> () // CHECK: function_ref @$s17property_wrappers14NonMutatingSetV12wrappedValuexvg @NonMutatingSet var text: String = "" { didSet { } } @NonMutatingSet var integer: Int = 17 { willSet { } } @MutatingGet var text2: String = "" { didSet { } } @MutatingGet var integer2: Int = 17 { willSet { } } } // Tuple initial values. struct WithTuples { // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers10WithTuplesVACycfC : $@convention(method) (@thin WithTuples.Type) -> WithTuples { // CHECK: function_ref @$s17property_wrappers10WithTuplesV10_fractions33_F728088E0028E14D18C6A10CF68512E8LLAA07WrapperC12InitialValueVySd_S2dtGvpfi : $@convention(thin) () -> (Double, Double, Double) // CHECK: function_ref @$s17property_wrappers10WithTuplesV9fractionsSd_S2dtvpfP : $@convention(thin) (Double, Double, Double) -> WrapperWithInitialValue<(Double, Double, Double)> @WrapperWithInitialValue var fractions = (1.3, 0.7, 0.3) static func getDefault() -> WithTuples { return .init() } } // Resilience with DI of wrapperValue assignments. // rdar://problem/52467175 class TestResilientDI { @MyPublished var data: Int? = nil // CHECK: assign_by_wrapper {{%.*}} : $Optional<Int> to {{%.*}} : $*MyPublished<Optional<Int>>, init {{%.*}} : $@callee_guaranteed (Optional<Int>) -> @out MyPublished<Optional<Int>>, set {{%.*}} : $@callee_guaranteed (Optional<Int>) -> () func doSomething() { self.data = Int() } } @propertyWrapper public struct PublicWrapper<T> { public var wrappedValue: T public init(value: T) { wrappedValue = value } } @propertyWrapper public struct PublicWrapperWithStorageValue<T> { public var wrappedValue: T public init(wrappedValue: T) { self.wrappedValue = wrappedValue } public var projectedValue: PublicWrapper<T> { return PublicWrapper(value: wrappedValue) } } public class Container { public init() { } // The accessor cannot be serializable/transparent because it accesses an // internal var. // CHECK-LABEL: sil [ossa] @$s17property_wrappers9ContainerC10$dontCrashAA13PublicWrapperVySiGvg : $@convention(method) (@guaranteed Container) -> PublicWrapper<Int> { // CHECK: bb0(%0 : @guaranteed $Container): // CHECK: ref_element_addr %0 : $Container, #Container._dontCrash @PublicWrapperWithStorageValue(wrappedValue: 0) public var dontCrash : Int { willSet { } didSet { } } } // SR-11303 / rdar://problem/54311335 - crash due to wrong archetype used in generated SIL public protocol TestProtocol {} public class TestClass<T> { @WrapperWithInitialValue var value: T // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers9TestClassC5value8protocolACyxGx_qd__tcAA0C8ProtocolRd__lufc // CHECK: [[BACKING_INIT:%.*]] = function_ref @$s17property_wrappers9TestClassC5valuexvpfP : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out WrapperWithInitialValue<τ_0_0> // CHECK-NEXT: partial_apply [callee_guaranteed] [[BACKING_INIT]]<T>() init<U: TestProtocol>(value: T, protocol: U) { self.value = value } } // Composition with wrappedValue initializers that have default values. @propertyWrapper struct Outer<Value> { var wrappedValue: Value init(a: Int = 17, wrappedValue: Value, s: String = "hello") { self.wrappedValue = wrappedValue } } @propertyWrapper struct Inner<Value> { var wrappedValue: Value init(wrappedValue: @autoclosure @escaping () -> Value, d: Double = 3.14159) { self.wrappedValue = wrappedValue() } } struct ComposedInit { @Outer @Inner var value: Int // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers12ComposedInitV5valueSivpfP : $@convention(thin) (Int) -> Outer<Inner<Int>> { // CHECK: function_ref @$s17property_wrappers12ComposedInitV6_value33_F728088E0028E14D18C6A10CF68512E8LLAA5OuterVyAA5InnerVySiGGvpfiSiycfu_ // CHECK: function_ref @$s17property_wrappers5InnerV12wrappedValue1dACyxGxyXA_SdtcfcfA0_ // CHECK: function_ref @$s17property_wrappers5InnerV12wrappedValue1dACyxGxyXA_SdtcfC // CHECK: function_ref @$s17property_wrappers5OuterV1a12wrappedValue1sACyxGSi_xSStcfcfA_ // CHECK: function_ref @$s17property_wrappers5OuterV1a12wrappedValue1sACyxGSi_xSStcfcfA1_ // CHECK: function_ref @$s17property_wrappers5OuterV1a12wrappedValue1sACyxGSi_xSStcfC init() { self.value = 17 } } // rdar://problem/55982409 - crash due to improperly inferred 'final' @propertyWrapper public struct MyWrapper<T> { public var wrappedValue: T public var projectedValue: Self { self } public init(wrappedValue: T) { self.wrappedValue = wrappedValue } } open class TestMyWrapper { public init() {} @MyWrapper open var useMyWrapper: Int? = nil } // rdar://problem/54352235 - crash due to reference to private backing var extension UsesMyPublished { // CHECK-LABEL: sil hidden [ossa] @$s21property_wrapper_defs15UsesMyPublishedC0A9_wrappersE6setFooyySiF : $@convention(method) (Int, @guaranteed UsesMyPublished) -> () // CHECK: class_method %1 : $UsesMyPublished, #UsesMyPublished.foo!setter.1 // CHECK-NOT: assign_by_wrapper // CHECK: return func setFoo(_ x: Int) { foo = x } } // CHECK-LABEL: sil_vtable ClassUsingWrapper { // CHECK-NEXT: #ClassUsingWrapper.x!getter.1: (ClassUsingWrapper) -> () -> Int : @$s17property_wrappers17ClassUsingWrapperC1xSivg // ClassUsingWrapper.x.getter // CHECK-NEXT: #ClassUsingWrapper.x!setter.1: (ClassUsingWrapper) -> (Int) -> () : @$s17property_wrappers17ClassUsingWrapperC1xSivs // ClassUsingWrapper.x.setter // CHECK-NEXT: #ClassUsingWrapper.x!modify.1: (ClassUsingWrapper) -> () -> () : @$s17property_wrappers17ClassUsingWrapperC1xSivM // ClassUsingWrapper.x.modify // CHECK-NEXT: #ClassUsingWrapper.init!allocator.1: (ClassUsingWrapper.Type) -> () -> ClassUsingWrapper : @$s17property_wrappers17ClassUsingWrapperCACycfC // CHECK-NEXT: #ClassUsingWrapper.deinit!deallocator.1: @$s17property_wrappers17ClassUsingWrapperCfD // CHECK-NEXT: } // CHECK-LABEL: sil_vtable [serialized] TestMyWrapper // CHECK: #TestMyWrapper.$useMyWrapper!getter.1
apache-2.0
jamy0801/LGWeChatKit
LGWeChatKit/LGChatKit/find/LGScanViewController.swift
1
7646
// // LGScanViewController.swift // LGScanViewController // // Created by jamy on 15/9/22. // Copyright © 2015年 jamy. All rights reserved. // import UIKit import AVFoundation class LGScanViewController: UIViewController , AVCaptureMetadataOutputObjectsDelegate{ let screenWidth = UIScreen.mainScreen().bounds.size.width let screenHeight = UIScreen.mainScreen().bounds.size.height let screenSize = UIScreen.mainScreen().bounds.size var traceNumber = 0 var upORdown = false var timer:NSTimer! var device : AVCaptureDevice! var input : AVCaptureDeviceInput! var output : AVCaptureMetadataOutput! var session: AVCaptureSession! var preView: AVCaptureVideoPreviewLayer! var line : UIImageView! // MARK: - init functions init() { super.init(nibName: nil, bundle: nil) hidesBottomBarWhenPushed = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "二维码扫描" if !setupCamera() { return } setupScanLine() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) session.startRunning() timer = NSTimer(timeInterval: 0.02, target: self, selector: "scanLineAnimation", userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode) } override func viewWillDisappear(animated: Bool) { traceNumber = 0 upORdown = false session.stopRunning() timer.invalidate() timer = nil super.viewWillDisappear(animated) } func setupCamera() -> Bool { device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) do { input = try AVCaptureDeviceInput(device: device) } catch let error as NSError { print(error.localizedDescription) return false } output = AVCaptureMetadataOutput() output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) output.rectOfInterest = makeScanReaderInterestRect() session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetHigh if session.canAddInput(input) { session.addInput(input) } if session.canAddOutput(output) { session.addOutput(output) } output.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code] preView = AVCaptureVideoPreviewLayer(session: session) preView.videoGravity = AVLayerVideoGravityResizeAspectFill preView.frame = self.view.bounds let shadowView = makeScanCameraShadowView(makeScanReaderRect()) self.view.layer.insertSublayer(preView, atIndex: 0) self.view.addSubview(shadowView) return true } func setupScanLine() { let rect = makeScanReaderRect() var imageSize: CGFloat = 20.0 let imageX = rect.origin.x let imageY = rect.origin.y let width = rect.size.width let height = rect.size.height + 2 /// 四个边角 let imageViewTL = UIImageView(frame: CGRectMake(imageX, imageY, imageSize, imageSize)) imageViewTL.image = UIImage(named: "scan_tl") imageSize = (imageViewTL.image?.size.width)! self.view.addSubview(imageViewTL) let imageViewTR = UIImageView(frame: CGRectMake(imageX + width - imageSize, imageY, imageSize, imageSize)) imageViewTR.image = UIImage(named: "scan_tr") self.view.addSubview(imageViewTR) let imageViewBL = UIImageView(frame: CGRectMake(imageX, imageY + height - imageSize, imageSize, imageSize)) imageViewBL.image = UIImage(named: "scan_bl") self.view.addSubview(imageViewBL) let imageViewBR = UIImageView(frame: CGRectMake(imageX + width - imageSize, imageY + height - imageSize, imageSize, imageSize)) imageViewBR.image = UIImage(named: "scan_br") self.view.addSubview(imageViewBR) line = UIImageView(frame: CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 2)) line.image = UIImage(named: "scan_line") self.view.addSubview(line) } // MARK: Rect func makeScanReaderRect() -> CGRect { let scanSize = (min(screenWidth, screenHeight) * 3) / 5 var scanRect = CGRectMake(0, 0, scanSize, scanSize) scanRect.origin.x += (screenWidth / 2) - (scanRect.size.width / 2) scanRect.origin.y += (screenHeight / 2) - (scanRect.size.height / 2) return scanRect } func makeScanReaderInterestRect() -> CGRect { let rect = makeScanReaderRect() let x = rect.origin.x / screenWidth let y = rect.origin.y / screenHeight let width = rect.size.width / screenWidth let height = rect.size.height / screenHeight return CGRectMake(x, y, width, height) } func makeScanCameraShadowView(innerRect: CGRect) -> UIView { let referenceImage = UIImageView(frame: self.view.bounds) UIGraphicsBeginImageContext(referenceImage.frame.size) let context = UIGraphicsGetCurrentContext() CGContextSetRGBFillColor(context, 0, 0, 0, 0.5) var drawRect = CGRectMake(0, 0, screenWidth, screenHeight) CGContextFillRect(context, drawRect) drawRect = CGRectMake(innerRect.origin.x - referenceImage.frame.origin.x, innerRect.origin.y - referenceImage.frame.origin.y, innerRect.size.width, innerRect.size.height) CGContextClearRect(context, drawRect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() referenceImage.image = image return referenceImage } // MARK: 定时器 func scanLineAnimation() { let rect = makeScanReaderRect() let lineFrameX = rect.origin.x let lineFrameY = rect.origin.y let downHeight = rect.size.height if upORdown == false { traceNumber++ line.frame = CGRectMake(lineFrameX, lineFrameY + CGFloat(2 * traceNumber), downHeight, 2) if CGFloat(2 * traceNumber) > downHeight - 2 { upORdown = true } } else { traceNumber-- line.frame = CGRectMake(lineFrameX, lineFrameY + CGFloat(2 * traceNumber), downHeight, 2) if traceNumber == 0 { upORdown = false } } } // MARK: AVCaptureMetadataOutputObjectsDelegate func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { if metadataObjects.count == 0 { return } let metadata = metadataObjects[0] as! AVMetadataMachineReadableCodeObject let value = metadata.stringValue showScanCode(value) } // MARK: show result func showScanCode(code: String) { print("\(code)") } }
mit
qq456cvb/DeepLearningKitForiOS
iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/ConvolutionLayer.swift
1
15316
// // ConvolutionLayer.swift // MemkiteMetal // // Created by Amund Tveit on 25/11/15. // Copyright © 2015 memkite. All rights reserved. // import Foundation import Metal func getDataFromBlob(_ blob: NSDictionary) -> ([Float], [Float]) { let shape = blob["shape"] as! NSDictionary let data = blob["data"] as! [Float] var FloatData = createFloatNumbersArray(data.count) for i in 0 ..< data.count { FloatData[i] = data[i] } return (shape["dim"] as! [Float], FloatData) } func createConvolutionLayerCached(_ layer: NSDictionary, inputBuffer: MTLBuffer, inputShape: [Float], metalCommandQueue: MTLCommandQueue, metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice, layer_data_caches: inout [Dictionary<String,MTLBuffer>], blob_cache: inout [Dictionary<String,([Float],[Float])>], layer_number: Int, layer_string: String, caching_mode:Bool) -> (MTLBuffer, MTLCommandBuffer, [Float]) { _ = Date() // let metalCommandBuffer = metalCommandQueue.commandBuffer() let metalCommandBuffer = metalCommandQueue.makeCommandBufferWithUnretainedReferences() var convolution_params_dict:NSDictionary = NSDictionary() var pad:Float = 0.0 var kernel_size:Float = 1.0 var stride:Float = 1.0 var blobs:[NSDictionary] = [] var weights:[Float] = [] var weight_shape:[Float] = [] var bias_data:[Float] = [] var h:Float = 0.0 var w:Float = 0.0 var result_shape:[Float] = [] var outputCount:Int = 0 var input_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var weight_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var result_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var tensor_dimensions:[MetalTensorDimensions] = [] var col_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var col_output:[Float] = [] var convolution_params:MetalConvolutionParameters = MetalConvolutionParameters(pad:0, kernel_size: 0, stride: 0) if(!caching_mode) { print("NOTCACHINGMODE") convolution_params_dict = layer["convolution_param"] as! NSDictionary pad = 0.0 kernel_size = 1.0 stride = 1.0 if let val = convolution_params_dict["pad"] as? Float{ pad = val } else if convolution_params_dict["pad"] != nil { let val = (convolution_params_dict["pad"] as! [Float])[0] pad = val } if let val = convolution_params_dict["kernel_size"] as? Float{ kernel_size = val } else if convolution_params_dict["kernel_size"] != nil { let val = (convolution_params_dict["kernel_size"] as! [Float])[0] kernel_size = val } _ = Date() if let tmpval = blob_cache[layer_number]["0"] { (weight_shape, weights) = tmpval } else { blobs = layer["blobs"] as! [NSDictionary] (weight_shape, weights) = getDataFromBlob(blobs[0]) // print(weights) blob_cache[layer_number]["0"] = (weight_shape, weights) } // assert(weight_shape[2] == kernel_size) // assert(weight_shape[3] == kernel_size) blobs = layer["blobs"] as! [NSDictionary] (_, bias_data) = getDataFromBlob(blobs[1]) h = (inputShape[2] + 2 * pad - kernel_size) / stride + 1 w = (inputShape[3] + 2 * pad - kernel_size) / stride + 1 result_shape = [inputShape[0], weight_shape[0], h, w] outputCount = Int(result_shape.reduce(1, *)) // Create input and output vectors, and corresponding metal buffer input_dimensions = MetalTensorDimensions(n: inputShape[0], channels: inputShape[1], width: inputShape[2], height: inputShape[3]) weight_dimensions = MetalTensorDimensions(n: weight_shape[0], channels: weight_shape[1], width: weight_shape[2], height: weight_shape[3]) col_dimensions = MetalTensorDimensions(n: inputShape[0], channels: inputShape[1] * kernel_size * kernel_size, width: inputShape[2], height: inputShape[3]) result_dimensions = MetalTensorDimensions(n: result_shape[0], channels: result_shape[1], width: result_shape[2], height: result_shape[3]) tensor_dimensions = [input_dimensions, weight_dimensions, col_dimensions, result_dimensions] col_output = createFloatNumbersArray(Int(col_dimensions.n * col_dimensions.channels * col_dimensions.height * col_dimensions.width)) convolution_params = MetalConvolutionParameters(pad: pad, kernel_size: kernel_size, stride: stride) } // let resultBuffer = addConvolutionCommandToCommandBufferCached(metalCommandBuffer, inputBuffer: inputBuffer, im2ColCount: col_output.count, weights: weights, outputCount: outputCount, convolution_params: convolution_params, tensor_dimensions: tensor_dimensions, bias: bias_data, metalDefaultLibrary: metalDefaultLibrary, metalDevice:metalDevice, layer_data_caches: &layer_data_caches, layer_number: layer_number,layer_string: layer_string, caching_mode: caching_mode) //metalCommandBuffer.commit() let resultBuffer = addFastConvolutionCommandToCommandBufferCached(metalCommandBuffer, inputBuffer: inputBuffer, weights: weights, outputCount: outputCount, convolution_params: convolution_params, tensor_dimensions: tensor_dimensions, bias: bias_data, metalDefaultLibrary: metalDefaultLibrary, metalDevice:metalDevice, layer_data_caches: &layer_data_caches, layer_number: layer_number,layer_string: layer_string, caching_mode: caching_mode) return (resultBuffer, metalCommandBuffer, result_shape) } func addFastConvolutionCommandToCommandBufferCached(_ commandBuffer: MTLCommandBuffer, inputBuffer: MTLBuffer, weights: [Float], outputCount: Int, convolution_params: MetalConvolutionParameters, tensor_dimensions: [MetalTensorDimensions], bias: [Float], metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice, layer_data_caches: inout [Dictionary<String,MTLBuffer>], layer_number: Int, layer_string: String, caching_mode:Bool) -> MTLBuffer { _ = Date() print("before output and col_output") var output:[Float] = [] if(!caching_mode) { output = createFloatNumbersArray(outputCount) } print("before setupshaderinpipeline") let (_, fastCovComputePipelineState, _) = setupShaderInMetalPipeline("fast_convolution_layer", metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice) let resultMetalBuffer = createOrReuseFloatMetalBuffer("resultMetalBuffer", data: output, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) print("after resultmetalbuffer") let weightMetalBuffer = createOrReuseFloatMetalBuffer("weightMetalBuffer", data: weights, cache: &layer_data_caches, layer_number:layer_number, metalDevice: metalDevice) // let convolutionParamsMetalBuffer = createOrReuseConvolutionParametersMetalBuffer("convolutionParamsMetalBuffer", data: convolution_params, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let tensorDimensionsMetalBuffer = createOrReuseTensorDimensionsVectorMetalBuffer("tensorDimensionsMetalBuffer", data: tensor_dimensions, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let biasMetalBuffer = createOrReuseFloatMetalBuffer("bias", data: bias, cache: &layer_data_caches, layer_number:layer_number, metalDevice: metalDevice) // Create Metal compute command encoder for im2col let metalComputeCommandEncoder = commandBuffer.makeComputeCommandEncoder() metalComputeCommandEncoder.setBuffer(resultMetalBuffer, offset: 0, at: 0) metalComputeCommandEncoder.setBuffer(weightMetalBuffer, offset: 0, at: 1) metalComputeCommandEncoder.setBuffer(tensorDimensionsMetalBuffer, offset: 0, at: 2) metalComputeCommandEncoder.setBuffer(inputBuffer, offset: 0, at: 3) metalComputeCommandEncoder.setBuffer(biasMetalBuffer, offset: 0, at: 4) //metalComputeCommandEncoder.setComputePipelineState(im2colComputePipelineState) metalComputeCommandEncoder.setComputePipelineState(fastCovComputePipelineState!) // Set up thread groups on GPU // TODO: check out http://metalbyexample.com/introduction-to-compute/ let threadsPerGroup = MTLSize(width:(fastCovComputePipelineState?.threadExecutionWidth)!,height:1,depth:1) // ensure at least 1 threadgroup let numThreadgroups = MTLSize(width:(outputCount-1)/(fastCovComputePipelineState?.threadExecutionWidth)! + 1, height:1, depth:1) metalComputeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) // Finalize configuration metalComputeCommandEncoder.endEncoding() return resultMetalBuffer } func addConvolutionCommandToCommandBufferCached(_ commandBuffer: MTLCommandBuffer, inputBuffer: MTLBuffer, im2ColCount: Int, weights: [Float], outputCount: Int, convolution_params: MetalConvolutionParameters, tensor_dimensions: [MetalTensorDimensions], bias: [Float], metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice, layer_data_caches: inout [Dictionary<String,MTLBuffer>], layer_number: Int, layer_string: String, caching_mode:Bool) -> MTLBuffer { _ = Date() print("before output and col_output") var output:[Float] = [] var col_output:[Float] = [] if(!caching_mode) { output = createFloatNumbersArray(outputCount) col_output = createFloatNumbersArray(im2ColCount) } print("before setupshaderinpipeline") let (_, im2colComputePipelineState, _) = setupShaderInMetalPipeline("im2col", metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice) let resultMetalBuffer = createOrReuseFloatMetalBuffer("resultMetalBuffer", data: output, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) print("after resultmetalbuffer") let weightMetalBuffer = createOrReuseFloatMetalBuffer("weightMetalBuffer", data: weights, cache: &layer_data_caches, layer_number:layer_number, metalDevice: metalDevice) let convolutionParamsMetalBuffer = createOrReuseConvolutionParametersMetalBuffer("convolutionParamsMetalBuffer", data: convolution_params, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let tensorDimensionsMetalBuffer = createOrReuseTensorDimensionsVectorMetalBuffer("tensorDimensionsMetalBuffer", data: tensor_dimensions, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let colOutputMetalBuffer = createOrReuseFloatMetalBuffer("colOutputMetalBuffer", data: col_output, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let biasMetalBuffer = createOrReuseFloatMetalBuffer("bias", data: bias, cache: &layer_data_caches, layer_number:layer_number, metalDevice: metalDevice) // Create Metal compute command encoder for im2col var metalComputeCommandEncoder = commandBuffer.makeComputeCommandEncoder() metalComputeCommandEncoder.setBuffer(inputBuffer, offset: 0, at: 0) metalComputeCommandEncoder.setBuffer(tensorDimensionsMetalBuffer, offset: 0, at: 1) metalComputeCommandEncoder.setBuffer(convolutionParamsMetalBuffer, offset: 0, at: 2) metalComputeCommandEncoder.setBuffer(colOutputMetalBuffer, offset: 0, at: 3) //metalComputeCommandEncoder.setComputePipelineState(im2colComputePipelineState) // Set the shader function that Metal will use metalComputeCommandEncoder.setComputePipelineState(im2colComputePipelineState!) // Set up thread groups on GPU // TODO: check out http://metalbyexample.com/introduction-to-compute/ var threadsPerGroup = MTLSize(width:(im2colComputePipelineState?.threadExecutionWidth)!,height:1,depth:1) // ensure at least 1 threadgroup print("before mtlsize 2") var numThreadgroups = MTLSize(width:(col_output.count-1)/(im2colComputePipelineState?.threadExecutionWidth)! + 1, height:1, depth:1) metalComputeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) print("after dispatch") // Finalize configuration metalComputeCommandEncoder.endEncoding() let (_, convolutionComputePipelineState, _) = setupShaderInMetalPipeline("convolution_layer", metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice) metalComputeCommandEncoder = commandBuffer.makeComputeCommandEncoder() // Create Metal Compute Command Encoder and add input and output buffers to it metalComputeCommandEncoder.setBuffer(resultMetalBuffer, offset: 0, at: 0) metalComputeCommandEncoder.setBuffer(weightMetalBuffer, offset: 0, at: 1) metalComputeCommandEncoder.setBuffer(tensorDimensionsMetalBuffer, offset: 0, at: 2) metalComputeCommandEncoder.setBuffer(colOutputMetalBuffer, offset: 0, at: 3) metalComputeCommandEncoder.setBuffer(biasMetalBuffer, offset: 0, at: 4) // Set the shader function that Metal will use metalComputeCommandEncoder.setComputePipelineState(convolutionComputePipelineState!) // Set up thread groups on GPU // TODO: check out http://metalbyexample.com/introduction-to-compute/ threadsPerGroup = MTLSize(width:(convolutionComputePipelineState?.threadExecutionWidth)!,height:1,depth:1) // ensure at least 1 threadgroup numThreadgroups = MTLSize(width:(outputCount-1)/(convolutionComputePipelineState?.threadExecutionWidth)! + 1, height:1, depth:1) metalComputeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) // Finalize configuration metalComputeCommandEncoder.endEncoding() return resultMetalBuffer }
apache-2.0
scoremedia/Fisticuffs
iOS Example/AddItemViewController.swift
1
2235
// The MIT License (MIT) // // Copyright (c) 2015 theScore Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Fisticuffs class AddItemViewController: UITableViewController { let viewModel = AddItemViewModel() @IBOutlet var doneButton: UIBarButtonItem! @IBOutlet var cancelButton: UIBarButtonItem! @IBOutlet var titleField: UITextField! override func viewDidLoad() { super.viewDidLoad() _ = doneButton.b_onTap.subscribe(viewModel.doneTapped) _ = cancelButton.b_onTap.subscribe(viewModel.cancelTapped) titleField.b_text.bind(viewModel.item.title) _ = viewModel.finished.subscribe { [weak self] _, result in switch result { case let .NewToDoItem(item): DataManager.sharedManager.toDoItems.value.append(item) break default: break } self?.dismiss(animated: true, completion: nil) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) titleField.becomeFirstResponder() } }
mit
hulinSun/MyRx
MyRx/Pods/Moya/Source/Response.swift
1
3082
import Foundation public final class Response: CustomDebugStringConvertible, Equatable { public let statusCode: Int public let data: Data public let request: URLRequest? public let response: URLResponse? public init(statusCode: Int, data: Data, request: URLRequest? = nil, response: URLResponse? = nil) { self.statusCode = statusCode self.data = data self.request = request self.response = response } public var description: String { return "Status Code: \(statusCode), Data Length: \(data.count)" } public var debugDescription: String { return description } public static func == (lhs: Response, rhs: Response) -> Bool { return lhs.statusCode == rhs.statusCode && lhs.data == rhs.data && lhs.response == rhs.response } } public extension Response { /// Filters out responses that don't fall within the given range, generating errors when others are encountered. public func filter(statusCodes: ClosedRange<Int>) throws -> Response { guard statusCodes.contains(statusCode) else { throw Error.statusCode(self) } return self } public func filter(statusCode: Int) throws -> Response { return try filter(statusCodes: statusCode...statusCode) } public func filterSuccessfulStatusCodes() throws -> Response { return try filter(statusCodes: 200...299) } public func filterSuccessfulStatusAndRedirectCodes() throws -> Response { return try filter(statusCodes: 200...399) } /// Maps data received from the signal into a UIImage. func mapImage() throws -> Image { guard let image = Image(data: data) else { throw Error.imageMapping(self) } return image } /// Maps data received from the signal into a JSON object. func mapJSON(failsOnEmptyData: Bool = true) throws -> Any { do { return try JSONSerialization.jsonObject(with: data, options: .allowFragments) } catch { if data.count < 1 && !failsOnEmptyData { return NSNull() } throw Error.jsonMapping(self) } } /// Maps data received from the signal into a String. /// /// - parameter atKeyPath: Optional key path at which to parse string. public func mapString(atKeyPath keyPath: String? = nil) throws -> String { if let keyPath = keyPath { // Key path was provided, try to parse string at key path guard let jsonDictionary = try mapJSON() as? NSDictionary, let string = jsonDictionary.value(forKeyPath:keyPath) as? String else { throw Error.stringMapping(self) } return string } else { // Key path was not provided, parse entire response as string guard let string = String(data: data, encoding: .utf8) else { throw Error.stringMapping(self) } return string } } }
mit
zhenghao58/On-the-road
OnTheRoadB/CurrentTripViewController.swift
1
3675
// // ViewController.swift // OnTheRoadB // // Created by Cunqi.X on 14/10/24. // Copyright (c) 2014年 CS9033. All rights reserved. // import UIKit import CoreData class CurrentTripViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView! var selectedTrip:Trip! var detailArr : [TripDetail]! var fileHelper : FileHelper! var databaseHelper : DataBaseHelper! override func viewDidLoad() { super.viewDidLoad() fileHelper = FileHelper() databaseHelper = DataBaseHelper() self.title = selectedTrip.name fileHelper.setCurrentFolderPath(selectedTrip.name) refreshData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) refreshData() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "addNewTripDetail") { let viewController = segue.destinationViewController as AddNewTripDetailViewController viewController.navigationItem.title = "Add New Day" viewController.currentTrip = self.selectedTrip viewController.currentDay = detailArr.count + 1 println(selectedTrip.masterDetail.count) } if(segue.identifier == "showEachDetail"){ let index = self.tableView.indexPathForSelectedRow()!.row let viewController = segue.destinationViewController as DetailTableViewController viewController.selectedTripDetail = self.detailArr[index] viewController.fileHelper = self.fileHelper viewController.navigationItem.title = detailArr[index].name } } /* The code below here are the simple code to show what I want the current trip screen looks like, we can use the first row as an indicator, and rest rows to show the records of current trip. change the row hight to make the first row and the rest rows diffierent. */ func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return detailArr.count } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 198 } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete){ let data = detailArr[indexPath.row] databaseHelper.deleteData(data) refreshData() tableView.reloadData() } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("tripDetails", forIndexPath: indexPath) as CardTableViewCell cell.useMember(detailArr[indexPath.row], fileHelper: fileHelper) return cell } func refreshData(){ detailArr = selectedTrip.masterDetail.allObjects as [TripDetail] detailArr.sort { (TripDetail A, TripDetail B) -> Bool in return A.name > B.name } tableView.reloadData() } }
mit
mspvirajpatel/SwiftyBase
SwiftyBase/Classes/Extensions/NSFileManagerExtension.swift
1
20729
// // NSFileManagerExtension.swift // Pods // // Created by MacMini-2 on 13/09/17. // // import Foundation /// This extension adds some useful functions to NSFileManager public extension FileManager { // MARK: - Enums - static func createDirectory(at directoryURL: URL) throws { return try self.default.createDirectory(at: directoryURL) } func createDirectory(at directoryUrl: URL) throws { let fileManager = FileManager.default var isDir: ObjCBool = false let fileExists = fileManager.fileExists(atPath: directoryUrl.path, isDirectory: &isDir) if fileExists == false || isDir.boolValue != false { try fileManager.createDirectory(at: directoryUrl, withIntermediateDirectories: true, attributes: nil) } } static func removeTemporaryFiles(at path: String) throws { return try self.default.removeTemporaryFiles() } static var document: URL { return self.default.document } var document: URL { #if os(OSX) // On OS X it is, so put files in Application Support. If we aren't running // in a sandbox, put it in a subdirectory based on the bundle identifier // to avoid accidentally sharing files between applications var defaultURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first if ProcessInfo.processInfo.environment["APP_SANDBOX_CONTAINER_ID"] == nil { var identifier = Bundle.main.bundleIdentifier if identifier?.length == 0 { identifier = Bundle.main.executableURL?.lastPathComponent } defaultURL = defaultURL?.appendingPathComponent(identifier ?? "", isDirectory: true) } return defaultURL ?? URL(fileURLWithPath: "") #else // On iOS the Documents directory isn't user-visible, so put files there return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] #endif } func removeTemporaryFiles() throws { let contents = try contentsOfDirectory(atPath: NSTemporaryDirectory()) for file in contents { try removeItem(atPath: NSTemporaryDirectory() + file) } } static func removeDocumentFiles(at path: String) throws { return try self.default.removeDocumentFiles() } func removeDocumentFiles() throws { let documentPath = document.path let contents = try contentsOfDirectory(atPath: documentPath) for file in contents { try removeItem(atPath: documentPath + file) } } /** Directory type enum - MainBundle: Main bundle directory - Library: Library directory - Documents: Documents directory - Cache: Cache directory */ enum DirectoryType : Int { case MainBundle case Library case Documents case Cache } // MARK: - Class functions - /** Read a file an returns the content as String - parameter file: File name - parameter ofType: File type - returns: Returns the content of the file a String */ static func readTextFile(file: String, ofType: String) throws -> String? { return try String(contentsOfFile: Bundle.main.path(forResource: file, ofType: ofType)!, encoding: String.Encoding.utf8) } /** Save a given array into a PLIST with the given filename - parameter directory: Path of the PLIST - parameter filename: PLIST filename - parameter array: Array to save into PLIST - returns: Returns true if the operation was successful, otherwise false */ static func saveArrayToPath(directory: DirectoryType, filename: String, array: Array<AnyObject>) -> Bool { var finalPath: String switch directory { case .MainBundle: finalPath = self.getBundlePathForFile(file: "\(filename).plist") case .Library: finalPath = self.getLibraryDirectoryForFile(file: "\(filename).plist") case .Documents: finalPath = self.getDocumentsDirectoryForFile(file: "\(filename).plist") case .Cache: finalPath = self.getCacheDirectoryForFile(file: "\(filename).plist") } return NSKeyedArchiver.archiveRootObject(array, toFile: finalPath) } /** Load array from a PLIST with the given filename - parameter directory: Path of the PLIST - parameter filename: PLIST filename - returns: Returns the loaded array */ static func loadArrayFromPath(directory: DirectoryType, filename: String) -> AnyObject? { var finalPath: String switch directory { case .MainBundle: finalPath = self.getBundlePathForFile(file: filename) case .Library: finalPath = self.getLibraryDirectoryForFile(file: filename) case .Documents: finalPath = self.getDocumentsDirectoryForFile(file: filename) case .Cache: finalPath = self.getCacheDirectoryForFile(file: filename) } return NSKeyedUnarchiver.unarchiveObject(withFile: finalPath) as AnyObject? } /** Get the Bundle path for a filename - parameter file: Filename - returns: Returns the path as a String */ static func getBundlePathForFile(file: String) -> String { let fileExtension = file.pathExtension var stringdata = "" do { stringdata = try Bundle.main.path(forResource: file.stringByReplacingWithRegex(regexString: String(format: ".%@", file) as NSString, withString: "") as String, ofType: fileExtension)! } catch _ { // Error handling } return stringdata } /** Get the Documents directory for a filename - parameter file: Filename - returns: Returns the directory as a String */ static func getDocumentsDirectoryForFile(file: String) -> String { let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] return documentsDirectory.stringByAppendingPathComponent(path: String(format: "%@/", file)) } /** Get the Library directory for a filename - parameter file: Filename - returns: Returns the directory as a String */ static func getLibraryDirectoryForFile(file: String) -> String { let libraryDirectory = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] return libraryDirectory.stringByAppendingPathComponent(path: String(format: "%@/", file)) } /** Get the Cache directory for a filename - parameter file: Filename - returns: Returns the directory as a String */ static func getCacheDirectoryForFile(file: String) -> String { let cacheDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] return cacheDirectory.stringByAppendingPathComponent(path: String(format: "%@/", file)) } /** Returns the size of the file - parameter file: Filename - parameter directory: Directory of the file - returns: Returns the file size */ static func fileSize(file: String, fromDirectory directory: DirectoryType) throws -> NSNumber? { if file.count != 0 { var path: String switch directory { case .MainBundle: path = self.getBundlePathForFile(file: file) case .Library: path = self.getLibraryDirectoryForFile(file: file) case .Documents: path = self.getDocumentsDirectoryForFile(file: file) case .Cache: path = self.getCacheDirectoryForFile(file: file) } if FileManager.default.fileExists(atPath: path) { let fileAttributes: NSDictionary? = try FileManager.default.attributesOfItem(atPath: file) as NSDictionary? if let _fileAttributes = fileAttributes { return NSNumber(value: _fileAttributes.fileSize()) } } } return nil } /** Delete a file with the given filename - parameter file: Filename to delete - parameter directory: Directory of the file - returns: Returns true if the operation was successful, otherwise false */ static func deleteFile(file: String, fromDirectory directory: DirectoryType) throws -> Bool { if file.count != 0 { var path: String switch directory { case .MainBundle: path = self.getBundlePathForFile(file: file) case .Library: path = self.getLibraryDirectoryForFile(file: file) case .Documents: path = self.getDocumentsDirectoryForFile(file: file) case .Cache: path = self.getCacheDirectoryForFile(file:file) } if FileManager.default.fileExists(atPath: path) { do { try FileManager.default.removeItem(atPath: path) return true } catch { return false } } } return false } /** Move a file from a directory to another - parameter file: Filename to move - parameter origin: Origin directory of the file - parameter destination: Destination directory of the file - parameter folderName: Folder name where to move the file. If folder not exist it will be created automatically - returns: Returns true if the operation was successful, otherwise false */ static func moveLocalFile(file: String, fromDirectory origin: DirectoryType, toDirectory destination: DirectoryType, withFolderName folderName: String? = nil) throws -> Bool { var originPath: String switch origin { case .MainBundle: originPath = self.getBundlePathForFile(file: file) case .Library: originPath = self.getLibraryDirectoryForFile(file: file) case .Documents: originPath = self.getDocumentsDirectoryForFile(file: file) case .Cache: originPath = self.getCacheDirectoryForFile(file: file) } var destinationPath: String = "" if folderName != nil { destinationPath = String(format: "%@/%@", destinationPath, folderName!) } else { destinationPath = file } switch destination { case .MainBundle: destinationPath = self.getBundlePathForFile(file: destinationPath) case .Library: destinationPath = self.getLibraryDirectoryForFile(file: destinationPath) case .Documents: destinationPath = self.getDocumentsDirectoryForFile(file: destinationPath) case .Cache: destinationPath = self.getCacheDirectoryForFile(file: destinationPath) } if folderName != nil { let folderPath: String = String(format: "%@/%@", destinationPath, folderName!) if !FileManager.default.fileExists(atPath: originPath) { try FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: false, attributes: nil) } } var copied: Bool = false, deleted: Bool = false if FileManager.default.fileExists(atPath: originPath) { do { try FileManager.default.copyItem(atPath: originPath, toPath: destinationPath) copied = true } catch { copied = false } } if destination != .MainBundle { if FileManager.default.fileExists(atPath: originPath) { do { try FileManager.default.removeItem(atPath: originPath) deleted = true } catch { deleted = false } } } if copied && deleted { return true } return false } /** Move a file from a directory to another - parameter file: Filename to move - parameter origin: Origin directory of the file - parameter destination: Destination directory of the file - returns: Returns true if the operation was successful, otherwise false */ static func moveLocalFile(file: String, fromDirectory origin: DirectoryType, toDirectory destination: DirectoryType) throws -> Bool { return try self.moveLocalFile(file: file, fromDirectory: origin, toDirectory: destination, withFolderName: nil) } /** Duplicate a file into another directory - parameter origin: Origin path - parameter destination: Destination path - returns: Returns true if the operation was successful, otherwise false */ static func duplicateFileAtPath(origin: String, toNewPath destination: String) -> Bool { if FileManager.default.fileExists(atPath: origin) { do { try FileManager.default.copyItem(atPath: origin, toPath: destination) return true } catch { return false } } return false } /** Rename a file with another filename - parameter origin: Origin path - parameter path: Subdirectory path - parameter oldName: Old filename - parameter newName: New filename - returns: Returns true if the operation was successful, otherwise false */ static func renameFileFromDirectory(origin: DirectoryType, atPath path: String, withOldName oldName: String, andNewName newName: String) -> Bool { var originPath: String switch origin { case .MainBundle: originPath = self.getBundlePathForFile(file: path) case .Library: originPath = self.getLibraryDirectoryForFile(file: path) case .Documents: originPath = self.getDocumentsDirectoryForFile(file: path) case .Cache: originPath = self.getCacheDirectoryForFile(file: path) } if FileManager.default.fileExists(atPath: originPath) { var newNamePath: String = "" do { newNamePath = try originPath.stringByReplacingWithRegex(regexString: oldName as NSString, withString: newName as NSString) as String try FileManager.default.copyItem(atPath: originPath, toPath: newNamePath) do { try FileManager.default.removeItem(atPath: originPath) return true } catch { return false } } catch { return false } } return false } /** Get the given settings for a given key - parameter settings: Settings filename - parameter objectForKey: Key to set the object - returns: Returns the object for the given key */ static func getSettings(settings: String, objectForKey: String) -> AnyObject? { var path: String = self.getLibraryDirectoryForFile(file: "") path = path.stringByAppendingPathExtension(ext: "/Preferences/")! path = path.stringByAppendingPathExtension(ext: "\(settings)-Settings.plist")! var loadedPlist: NSMutableDictionary if FileManager.default.fileExists(atPath: path) { loadedPlist = NSMutableDictionary(contentsOfFile: path)! } else { return nil } return loadedPlist.object(forKey: objectForKey) as AnyObject? } /** Set the given settings for a given object and key. The file will be saved in the Library directory - parameter settings: Settings filename - parameter object: Object to set - parameter objKey: Key to set the object - returns: Returns true if the operation was successful, otherwise false */ static func setSettings(settings: String, object: AnyObject, forKey objKey: String) -> Bool { var path: String = self.getLibraryDirectoryForFile(file: "") path = path.stringByAppendingPathExtension(ext: "/Preferences/")! path = path.stringByAppendingPathExtension(ext: "\(settings)-Settings.plist")! var loadedPlist: NSMutableDictionary if FileManager.default.fileExists(atPath: path) { loadedPlist = NSMutableDictionary(contentsOfFile: path)! } else { loadedPlist = NSMutableDictionary() } loadedPlist[objKey] = object return loadedPlist.write(toFile: path, atomically: true) } /** Set the App settings for a given object and key. The file will be saved in the Library directory - parameter object: Object to set - parameter objKey: Key to set the object - returns: Returns true if the operation was successful, otherwise false */ static func setAppSettingsForObject(object: AnyObject, forKey objKey: String) -> Bool { return self.setSettings(settings: App.name, object: object, forKey: objKey) } /** Get the App settings for a given key - parameter objKey: Key to get the object - returns: Returns the object for the given key */ static func getAppSettingsForObjectWithKey(objKey: String) -> AnyObject? { return self.getSettings(settings: App.name, objectForKey: objKey) } /** Get URL of Document directory. - returns: Document directory URL. */ class func ts_documentURL() -> URL { return ts_URLForDirectory(.documentDirectory)! } /** Get String of Document directory. - returns: Document directory String. */ class func ts_documentPath() -> String { return ts_pathForDirectory(.documentDirectory)! } /** Get URL of Library directory - returns: Library directory URL */ class func ts_libraryURL() -> URL { return ts_URLForDirectory(.libraryDirectory)! } /** Get String of Library directory - returns: Library directory String */ class func ts_libraryPath() -> String { return ts_pathForDirectory(.libraryDirectory)! } /** Get URL of Caches directory - returns: Caches directory URL */ class func ts_cachesURL() -> URL { return ts_URLForDirectory(.cachesDirectory)! } /** Get String of Caches directory - returns: Caches directory String */ class func ts_cachesPath() -> String { return ts_pathForDirectory(.cachesDirectory)! } /** Adds a special filesystem flag to a file to avoid iCloud backup it. - parameter filePath: Path to a file to set an attribute. */ class func ts_addSkipBackupAttributeToFile(_ filePath: String) { let url: URL = URL(fileURLWithPath: filePath) do { try (url as NSURL).setResourceValue(NSNumber(value: true as Bool), forKey: URLResourceKey.isExcludedFromBackupKey) } catch {} } /** Check available disk space in MB - returns: Double in MB */ class func ts_availableDiskSpaceMb() -> Double { let fileAttributes = try? `default`.attributesOfFileSystem(forPath: ts_documentPath()) if let fileSize = (fileAttributes![FileAttributeKey.systemSize] as AnyObject).doubleValue { return fileSize / Double(0x100000) } return 0 } fileprivate class func ts_URLForDirectory(_ directory: FileManager.SearchPathDirectory) -> URL? { return `default`.urls(for: directory, in: .userDomainMask).last } fileprivate class func ts_pathForDirectory(_ directory: FileManager.SearchPathDirectory) -> String? { return NSSearchPathForDirectoriesInDomains(directory, .userDomainMask, true)[0] } }
mit
catloafsoft/AudioKit
AudioKit/OSX/AudioKit/Playgrounds/Helpers/AKParametricEQWindow.swift
1
4630
// // AKParametricEQWindow.swift // AudioKit // // Autogenerated by scripts by Aurelius Prochazka. Do not edit directly. // Copyright (c) 2015 Aurelius Prochazka. All rights reserved. // import Foundation import Cocoa /// A Window to control AKParametricEQ in Playgrounds public class AKParametricEQWindow: NSWindow { private let windowWidth = 400 private let padding = 30 private let sliderHeight = 20 private let numberOfComponents = 3 /// Slider to control centerFreq public let centerFreqSlider: NSSlider /// Slider to control q public let qSlider: NSSlider /// Slider to control gain public let gainSlider: NSSlider private let centerFreqTextField: NSTextField private let qTextField: NSTextField private let gainTextField: NSTextField private var parametricEQ: AKParametricEQ /// Initiate the AKParametricEQ window public init(_ control: AKParametricEQ) { parametricEQ = control let sliderWidth = windowWidth - 2 * padding centerFreqSlider = newSlider(sliderWidth) qSlider = newSlider(sliderWidth) gainSlider = newSlider(sliderWidth) centerFreqTextField = newTextField(sliderWidth) qTextField = newTextField(sliderWidth) gainTextField = newTextField(sliderWidth) let titleHeightApproximation = 50 let windowHeight = padding * 2 + titleHeightApproximation + numberOfComponents * 3 * sliderHeight super.init(contentRect: NSRect(x: padding, y: padding, width: windowWidth, height: windowHeight), styleMask: NSTitledWindowMask, backing: .Buffered, `defer`: false) self.hasShadow = true self.styleMask = NSBorderlessWindowMask | NSResizableWindowMask self.movableByWindowBackground = true self.level = 7 self.title = "AKParametricEQ" let viewRect = NSRect(x: 0, y: 0, width: windowWidth, height: windowHeight) let view = NSView(frame: viewRect) let topTitle = NSTextField() topTitle.stringValue = "AKParametricEQ" topTitle.editable = false topTitle.drawsBackground = false topTitle.bezeled = false topTitle.alignment = NSCenterTextAlignment topTitle.font = NSFont(name: "Lucida Grande", size: 24) topTitle.sizeToFit() topTitle.frame.origin.x = CGFloat(windowWidth / 2) - topTitle.frame.width / 2 topTitle.frame.origin.y = CGFloat(windowHeight - padding) - topTitle.frame.height view.addSubview(topTitle) makeTextField(centerFreqTextField, view: view, below: topTitle, distance: 2, stringValue: "Center Frequency: \(parametricEQ.centerFrequency) Hz") makeSlider(centerFreqSlider, view: view, below: topTitle, distance: 3, target: self, action: "updateCenterfreq", currentValue: parametricEQ.centerFrequency, minimumValue: 20, maximumValue: 22050) makeTextField(qTextField, view: view, below: topTitle, distance: 5, stringValue: "Q: \(parametricEQ.q) Hz") makeSlider(qSlider, view: view, below: topTitle, distance: 6, target: self, action: "updateQ", currentValue: parametricEQ.q, minimumValue: 0.1, maximumValue: 20) makeTextField(gainTextField, view: view, below: topTitle, distance: 8, stringValue: "Gain: \(parametricEQ.gain) dB") makeSlider(gainSlider, view: view, below: topTitle, distance: 9, target: self, action: "updateGain", currentValue: parametricEQ.gain, minimumValue: -20, maximumValue: 20) self.contentView!.addSubview(view) self.makeKeyAndOrderFront(nil) } internal func updateCenterfreq() { parametricEQ.centerFrequency = centerFreqSlider.doubleValue centerFreqTextField.stringValue = "Center Frequency \(String(format: "%0.4f", parametricEQ.centerFrequency)) Hz" } internal func updateQ() { parametricEQ.q = qSlider.doubleValue qTextField.stringValue = "Q \(String(format: "%0.4f", parametricEQ.q)) Hz" } internal func updateGain() { parametricEQ.gain = gainSlider.doubleValue gainTextField.stringValue = "Gain \(String(format: "%0.4f", parametricEQ.gain)) dB" } /// Required initializer required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
SmallElephant/FESwiftDemo
11-FMDBDemo/11-FMDBDemo/DataManager.swift
1
724
// // DataManager.swift // 11-FMDBDemo // // Created by keso on 2017/3/25. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class DataManager { static let shareIntance:DataManager = DataManager() var db:FMDatabase = FMDatabase() func createDataBase(dataName:String) { let path:String = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] let finalPath:String = path.appending("/\(dataName)") print("数据存储地址:\(finalPath)") db = FMDatabase(path: finalPath) if db.open() { print("数据库打开成功") } } }
mit
eCrowdMedia/MooApi
Sources/network/StoreApi.swift
1
1373
// // StoreApi.swift // MooApi // // Created by Apple on 2017/11/21. // Copyright © 2017年 ecrowdmedia.com. All rights reserved. // import Foundation public enum StoreApi: ApiProtocol { case home case collection(String) case block(String) case category(String) case contributor(String) case ranks(String) case publisher(String) case books(String) case searchKeyword case searchSuggest case searchTopKeyword public var developURI: String { return "https://api.readmoo.tw/v2" } public var baseURI: String { return "https://api.readmoo.com/v2" } public var path: String { switch self { case .home: return "/navigation/home?version=2&banner_type=mobile" case .collection(let id): return "/navigation/collection/\(id)" case .block(let id): return "/navigation/block/\(id)" case let .category(id): return "/navigation/category/\(id)" case .contributor(let id): return "/navigation/contributor/\(id)" case .ranks(let id): return "/navigation/ranks/\(id)" case .publisher(let id): return "/navigation/publisher/\(id)" case .books(let id): return "/books/\(id)" case .searchKeyword: return "/books" case .searchSuggest: return "/books" case .searchTopKeyword: return "/navigation/top_keyword" } } }
mit
RoRoche/iOSSwiftStarter
iOSSwiftStarter/iOSSwiftStarter/Resources/UIColor+SwiftGen.swift
1
1478
// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen import UIKit extension UIColor { convenience init(rgbaValue: UInt32) { let red = CGFloat((rgbaValue >> 24) & 0xff) / 255.0 let green = CGFloat((rgbaValue >> 16) & 0xff) / 255.0 let blue = CGFloat((rgbaValue >> 8) & 0xff) / 255.0 let alpha = CGFloat((rgbaValue ) & 0xff) / 255.0 self.init(red: red, green: green, blue: blue, alpha: alpha) } } extension UIColor { enum Name { /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#e67e22"></span> /// Alpha: 100% <br/> (0xe67e22ff) case Carrot /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#2ecc71"></span> /// Alpha: 100% <br/> (0x2ecc71ff) case Emerland /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#3498db"></span> /// Alpha: 100% <br/> (0x3498dbff) case Peterriver /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#c0392b"></span> /// Alpha: 100% <br/> (0xc0392bff) case Pomegranate var rgbaValue: UInt32! { switch self { case .Carrot: return 0xe67e22ff case .Emerland: return 0x2ecc71ff case .Peterriver: return 0x3498dbff case .Pomegranate: return 0xc0392bff } } } convenience init(named name: Name) { self.init(rgbaValue: name.rgbaValue) } }
apache-2.0
460467069/smzdm
什么值得买7.1.1版本/什么值得买(5月12日)/Classes/HaoJia(好价)/秒杀/View/ZZMiaoShaCell.swift
1
498
// // ZZMiaoShaCell.swift // 什么值得买 // // Created by Wang_ruzhou on 2017/1/2. // Copyright © 2017年 Wang_ruzhou. All rights reserved. // import UIKit class ZZMiaoShaCell: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
aojet/Aojet
Sources/Aojet/actors/dispatch/queue/Queue.swift
1
351
// // Queue.swift // Aojet // // Created by Qihe Bian on 6/6/16. // Copyright © 2016 Qihe Bian. All rights reserved. // class Queue<T>: Equatable { final let id: Int final var queue = Array<T>() var isLocked = false init(id: Int) { self.id = id } } func ==<T>(lhs: Queue<T>, rhs: Queue<T>) -> Bool { return lhs.id == rhs.id }
mit
blockchain/My-Wallet-V3-iOS
Modules/FeatureWithdrawalLocks/Sources/FeatureWithdrawalLocksDomain/Service/NoOpWithdrawalLocksService.swift
1
314
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation public final class NoOpWithdrawalLocksService: WithdrawalLocksServiceAPI { public var withdrawalLocks: AnyPublisher<WithdrawalLocks, Never> { Empty().eraseToAnyPublisher() } public init() {} }
lgpl-3.0
harlanhaskins/swift
test/Driver/PrivateDependencies/one-way-provides-after-fine.swift
1
3576
/// other | main /// other +==> main // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/one-way-provides-after-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/one-way-provides-after-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST-NOT: Handled // RUN: touch -t 201401240006 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // CHECK-SECOND-DAG: Handled other.swift // CHECK-SECOND-DAG: Handled main.swift // RUN: touch -t 201401240007 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/one-way-provides-after-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/one-way-provides-after-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: touch -t 201401240007 %t/main.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s // RUN: touch -t 201401240008 %t/main.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s // CHECK-THIRD-NOT: Handled other.swift // CHECK-THIRD: Handled main.swift // CHECK-THIRD-NOT: Handled other.swift
apache-2.0
gouyz/GYZBaking
baking/Classes/Home/View/GYZCategoryHeaderView.swift
1
1703
// // GYZCategoryHeaderView.swift // baking // 商品分类header // Created by gouyz on 2017/3/30. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit class GYZCategoryHeaderView: UITableViewHeaderFooterView { override init(reuseIdentifier: String?){ super.init(reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ bgView.backgroundColor = kBackgroundColor contentView.addSubview(bgView) bgView.addSubview(nameLab) bgView.addSubview(clearLab) bgView.snp.makeConstraints { (make) in make.edges.equalTo(0) } nameLab.snp.makeConstraints { (make) in make.left.equalTo(kMargin) make.top.bottom.equalTo(bgView) make.right.equalTo(clearLab.snp.left).offset(-kMargin) } clearLab.snp.makeConstraints { (make) in make.right.equalTo(-kMargin) make.top.bottom.equalTo(nameLab) make.width.equalTo(60) } } fileprivate lazy var bgView : UIView = UIView() /// 商品分类名称 lazy var nameLab : UILabel = { let lab = UILabel() lab.font = k13Font lab.textColor = kHeightGaryFontColor return lab }() /// lazy var clearLab : UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kHeightGaryFontColor lab.text = "清空" lab.textAlignment = .right lab.isHidden = true return lab }() }
mit
myhyazid/WordPress-iOS
WordPress/WordPressTest/PushAuthenticationManagerTests.swift
13
6488
import Foundation import XCTest import WordPress class PushAuthenticationManagerTests : XCTestCase { class MockUIAlertViewProxy : UIAlertViewProxy { var titlePassedIn:String? var messagePassedIn:String? var cancelButtonTitlePassedIn:String? var otherButtonTitlesPassedIn:[AnyObject]? var tapBlockPassedIn:UIAlertViewCompletionBlock? var showWithTitleCalled = false override func showWithTitle(title: String!, message: String!, cancelButtonTitle: String!, otherButtonTitles: [AnyObject]!, tapBlock: UIAlertViewCompletionBlock!) -> UIAlertView! { showWithTitleCalled = true titlePassedIn = title messagePassedIn = message cancelButtonTitlePassedIn = cancelButtonTitle otherButtonTitlesPassedIn = otherButtonTitles tapBlockPassedIn = tapBlock return UIAlertView() } } class MockPushAuthenticationService : PushAuthenticationService { var tokenPassedIn:String? var completionBlockPassedIn:((Bool) -> ())? var authorizedLoginCalled = false var numberOfTimesAuthorizedLoginCalled = 0 override func authorizeLogin(token: String, completion: ((Bool) -> ())) { authorizedLoginCalled = true numberOfTimesAuthorizedLoginCalled++ tokenPassedIn = token completionBlockPassedIn = completion } } var mockPushAuthenticationService = MockPushAuthenticationService(managedObjectContext: TestContextManager().mainContext) var mockAlertViewProxy = MockUIAlertViewProxy() var pushAuthenticationManager:PushAuthenticationManager? override func setUp() { super.setUp() pushAuthenticationManager = PushAuthenticationManager(pushAuthenticationService: mockPushAuthenticationService) pushAuthenticationManager?.alertViewProxy = mockAlertViewProxy; } func testIsPushAuthenticationNotificationReturnsTrueWhenPassedTheCorrectPushAuthenticationNoteType() { let result = pushAuthenticationManager!.isPushAuthenticationNotification(["type": "push_auth"]) XCTAssertTrue(result, "Should be true when the type is 'push_auth'") } func testIsPushAuthenticationNotificationReturnsFalseWhenPassedIncorrectPushAuthenticationNoteType() { let result = pushAuthenticationManager!.isPushAuthenticationNotification(["type": "not_push"]) XCTAssertFalse(result, "Should be false when the type is not 'push_auth'") } func expiredPushNotificationDictionary() -> NSDictionary { return ["expires": NSTimeInterval(3)] } func validPushAuthenticationDictionary() -> NSMutableDictionary { return ["push_auth_token" : "token", "aps" : [ "alert" : "an alert"]] } func testHandlePushAuthenticationNotificationShowsTheLoginExpiredAlertIfNotificationHasExpired(){ pushAuthenticationManager!.handlePushAuthenticationNotification(expiredPushNotificationDictionary()) XCTAssertTrue(mockAlertViewProxy.showWithTitleCalled, "Should show the login expired alert if the notification has expired") XCTAssertEqual(mockAlertViewProxy.titlePassedIn!, NSLocalizedString("Login Request Expired", comment:""), "") } func testHandlePushAuthenticationNotificationDoesNotShowTheLoginExpiredAlertIfNotificationHasNotExpired(){ pushAuthenticationManager!.handlePushAuthenticationNotification([:]) XCTAssertFalse(mockAlertViewProxy.showWithTitleCalled, "Should not show the login expired alert if the notification hasn't expired") } func testHandlePushAuthenticationNotificationWithBlankTokenDoesNotShowLoginVerificationAlert(){ var pushNotificationDictionary = validPushAuthenticationDictionary() pushNotificationDictionary.removeObjectForKey("push_auth_token") pushAuthenticationManager!.handlePushAuthenticationNotification(pushNotificationDictionary) XCTAssertFalse(mockAlertViewProxy.showWithTitleCalled, "Should not show the login verification") } func testHandlePushAuthenticationNotificationWithBlankMessageDoesNotShowLoginVerificationAlert(){ pushAuthenticationManager!.handlePushAuthenticationNotification(["push_auth_token" : "token"]) XCTAssertFalse(mockAlertViewProxy.showWithTitleCalled, "Should not show the login verification") } func testHandlePushAuthenticationNotificationWithValidDataShouldShowLoginVerification() { pushAuthenticationManager!.handlePushAuthenticationNotification(validPushAuthenticationDictionary()) XCTAssertTrue(mockAlertViewProxy.showWithTitleCalled, "Should show the login verification") XCTAssertEqual(mockAlertViewProxy.titlePassedIn!, NSLocalizedString("Verify Sign In", comment: ""), "") } func testHandlePushAuthenticationNotificationShouldAttemptToAuthorizeTheLoginIfTheUserIndicatesTheyWantTo() { pushAuthenticationManager!.handlePushAuthenticationNotification(validPushAuthenticationDictionary()) let alertView = UIAlertView() mockAlertViewProxy.tapBlockPassedIn?(alertView, 1) XCTAssertTrue(mockPushAuthenticationService.authorizedLoginCalled, "Should have attempted to authorize the login") } func testHandlePushAuthenticationNotificationWhenAttemptingToLoginShouldAttemptToRetryTheLoginIfItFailed() { pushAuthenticationManager!.handlePushAuthenticationNotification(validPushAuthenticationDictionary()) let alertView = UIAlertView() mockAlertViewProxy.tapBlockPassedIn?(alertView, 1) mockPushAuthenticationService.completionBlockPassedIn?(false) XCTAssertEqual(mockPushAuthenticationService.numberOfTimesAuthorizedLoginCalled, 2, "Should have attempted to retry a failed login") } func testHandlePushAuthenticationNotificationShouldNotAttemptToAuthorizeTheLoginIfTheUserIndicatesTheyDontWantTo() { pushAuthenticationManager!.handlePushAuthenticationNotification(validPushAuthenticationDictionary()) let alertView = UIAlertView() mockAlertViewProxy.tapBlockPassedIn?(alertView, alertView.cancelButtonIndex) XCTAssertFalse(mockPushAuthenticationService.authorizedLoginCalled, "Should not have attempted to authorize the login") } }
gpl-2.0
zhugejunwei/LeetCode
7. Reverse Integer.swift
1
778
import UIKit func reverse(x: Int) -> Int { var myX = x var myOutput:Double = 0 while ((myX > 9 || myX < -9) && myX % 10 == 0) { myX = myX / 10 } while myX != 0 { myOutput = myOutput * 10 + Double(myX % 10) myX = myX / 10 } if myOutput > Double(Int32.max) || myOutput < Double(Int32.min) { return 0 }else { return Int(myOutput) } } reverse(-12120) /* func reverse(x: Int) -> Int { var sign = 1 var mx = x if mx < 0 { sign = -1 mx *= -1 } while mx % 10 == 0 && mx != 0 { mx /= 10 } var rx = 0.0 var stop = 0 while stop == 0 { if mx < 10 { stop = 1 } rx = rx * 10 + Double(mx) % 10 mx /= 10 } if rx > Double(INT32_MAX) { return 0 }else { return Int(rx) * sign } } */
mit
arttuperala/kmbmpdc
kmbmpdc/Preferences.swift
1
3859
import Cocoa class Preferences: NSViewController { @IBOutlet weak var hostField: NSTextField! @IBOutlet weak var portField: NSTextField! @IBOutlet weak var passwordField: NSSecureTextField! @IBOutlet weak var musicDirectoryPath: NSPathControl! @IBOutlet weak var notificationEnableButton: NSButton! var owner: AppDelegate? let defaults = UserDefaults.standard var mpdHost: String { get { return defaults.string(forKey: Constants.Preferences.mpdHost) ?? "" } set(stringValue) { defaults.set(stringValue, forKey: Constants.Preferences.mpdHost) } } var mpdPassword: String { get { return defaults.string(forKey: Constants.Preferences.mpdPass) ?? "" } set(stringValue) { if stringValue.isEmpty { defaults.set(nil, forKey: Constants.Preferences.mpdPass) } else { defaults.set(stringValue, forKey: Constants.Preferences.mpdPass) } } } var mpdPort: String { get { let port = defaults.integer(forKey: Constants.Preferences.mpdPort) if port > 0 { return String(port) } else { return "" } } set(stringValue) { if let port = Int(stringValue) { defaults.set(port, forKey: Constants.Preferences.mpdPort) } else { portField.stringValue = "" defaults.set(0, forKey: Constants.Preferences.mpdPort) } } } var musicDirectory: URL { get { if let url = defaults.url(forKey: Constants.Preferences.musicDirectory) { return url } else { return URL(fileURLWithPath: NSHomeDirectory()) } } set(url) { defaults.set(url, forKey: Constants.Preferences.musicDirectory) } } var notificationsDisabled: NSControl.StateValue { get { let disabled = defaults.bool(forKey: Constants.Preferences.notificationsDisabled) return disabled ? .off : .on } set(state) { let disabled = state == .off ? true : false defaults.set(disabled, forKey: Constants.Preferences.notificationsDisabled) } } override func viewDidLoad() { super.viewDidLoad() hostField.stringValue = mpdHost portField.stringValue = mpdPort passwordField.stringValue = mpdPassword musicDirectoryPath.url = musicDirectory notificationEnableButton.state = notificationsDisabled } override func viewWillDisappear() { mpdHost = hostField.stringValue mpdPort = portField.stringValue mpdPassword = passwordField.stringValue } override func viewDidDisappear() { super.viewDidDisappear() owner?.preferenceWindow = nil } @IBAction func changedHost(_ sender: NSTextField) { mpdHost = sender.stringValue } @IBAction func changedPassword(_ sender: NSTextField) { mpdPassword = sender.stringValue } @IBAction func changedPort(_ sender: NSTextField) { mpdPort = sender.stringValue } @IBAction func notificationsToggled(_ sender: NSButton) { notificationsDisabled = sender.state } @IBAction func openMusicDirectorySelector(_ sender: Any) { let panel = NSOpenPanel() panel.allowsMultipleSelection = false panel.canChooseDirectories = true panel.canChooseFiles = false panel.directoryURL = musicDirectoryPath.url let panelAction = panel.runModal() if panelAction == .OK { musicDirectoryPath.url = panel.url musicDirectory = panel.url! } } }
apache-2.0
steryokhin/AsciiArtPlayer
src/AsciiArtPlayer/AsciiArtPlayer/Classes/Presentation/User Stories/Home/View/HomeViewOutput.swift
1
377
// // HomeHomeViewOutput.swift // AsciiArtPlayer // // Created by Sergey Teryokhin on 19/12/2016. // Copyright © 2016 iMacDev. All rights reserved. // protocol HomeViewOutput { /** @author Sergey Teryokhin Notify presenter that view is ready */ func viewIsReady() func viewShowAssetLoader() func viewShowCameraRecorder() }
mit
AnRanScheme/MagiRefresh
MagiRefresh/Classes/Extension/CALayer+MagiRefresh.swift
3
2983
// // CALayer+Magi.swift // magiLoadingPlaceHolder // // Created by 安然 on 2018/8/10. // Copyright © 2018年 anran. All rights reserved. // import UIKit extension CALayer { //frame.origin.x var magi_left: CGFloat { get { return self.frame.origin.x } set { var frame = self.frame frame.origin.x = newValue self.frame = frame } } //frame.origin.y var magi_top: CGFloat { get { return self.frame.origin.y } set { var frame = self.frame frame.origin.y = newValue self.frame = frame } } //frame.origin.x + frame.size.width var magi_right: CGFloat { get { return self.frame.origin.x + self.frame.size.width } set { var frame = self.frame frame.origin.x = newValue - frame.size.width self.frame = frame } } //frame.origin.y + frame.size.height var magi_bottom: CGFloat { get { return self.frame.origin.y + self.frame.size.height } set { var frame = self.frame frame.origin.y = newValue - frame.origin.y self.frame = frame } } //frame.size.width var magi_width: CGFloat { get { return self.frame.size.width } set { var frame = self.frame frame.size.width = newValue self.frame = frame } } //frame.size.height var magi_height: CGFloat { get { return self.frame.size.height } set { var frame = self.frame frame.size.height = newValue self.frame = frame } } //center.x var magi_positionX: CGFloat { get { return self.position.x } set { self.position = CGPoint(x: newValue, y: self.position.y) } } //center.y var magi_positionY: CGFloat { get { return self.position.y } set { self.position = CGPoint(x: self.position.x, y: newValue) } } //frame.origin var magi_origin: CGPoint { get { return self.frame.origin } set { var frame = self.frame frame.origin = newValue self.frame = frame } } //frame.size var magi_size: CGSize { get { return self.frame.size } set { var frame = self.frame frame.size = newValue self.frame = frame } } //maxX var magi_maxX: CGFloat { get { return self.frame.origin.x + self.frame.size.width } } //maxY var magi_maxY: CGFloat { get { return self.frame.origin.y + self.frame.size.height } } }
mit
k-thorat/Dotzu
Framework/Dotzu/Dotzu/DotzuManager.swift
1
2077
// // Manager.swift // exampleWindow // // Created by Remi Robert on 02/12/2016. // Copyright © 2016 Remi Robert. All rights reserved. // import UIKit public class Dotzu: NSObject { public static let sharedManager = Dotzu() private var window: ManagerWindow? fileprivate var controller: ManagerViewController? private let cache = NSCache<AnyObject, AnyObject>() private let userDefault = UserDefaults.standard var displayedList = false func initLogsManager() { if LogsSettings.shared.resetLogsStart { let _ = StoreManager<Log>(store: .log).reset() let _ = StoreManager<LogRequest>(store: .network).reset() } } public func enable() { initLogsManager() if LogsSettings.shared.showBubbleHead { self.window = ManagerWindow(frame: UIScreen.main.bounds) self.controller = ManagerViewController() } self.window?.rootViewController = self.controller self.window?.makeKeyAndVisible() self.window?.delegate = self LoggerNetwork.shared.enable = LogsSettings.shared.network Logger.shared.enable = true LoggerCrash.shared.enable = true } public func disable() { self.window?.rootViewController = nil self.window?.resignKey() self.window?.removeFromSuperview() Logger.shared.enable = false LoggerCrash.shared.enable = false LoggerNetwork.shared.enable = false } public func addLogger(session: URLSessionConfiguration) { session.protocolClasses?.insert(LoggerNetwork.self, at: 0) } public func viewController () -> UIViewController? { let storyboard = UIStoryboard(name: "Manager", bundle: Bundle(for: ManagerViewController.self)) return storyboard.instantiateInitialViewController() } override init() { super.init() } } extension Dotzu: ManagerWindowDelegate { func isPointEvent(point: CGPoint) -> Bool { return self.controller?.shouldReceive(point: point) ?? false } }
mit
arevaloarboled/Moviles
Proyecto/iOS/Messages/Messages/SharedFiles.swift
1
568
// // OneMessage.swift // Messages // // Created by Estudiantes on 3/06/16. // Copyright © 2016 Estudiantes. All rights reserved. // import Foundation import JSONHelper struct SharedFiles:Deserializable { var id: Int? var name: String? var contentType: String? var from: Int? var to: Int? var date: String? init(data: [String: AnyObject]) { id <-- data["id"] name <-- data["name"] contentType <-- data["contentType"] from <-- data["from"] to <-- data["to"] date <-- data["date"] } }
mit
kaojohnny/CoreStore
CoreStoreTests/StorageInterfaceTests.swift
1
9241
// // StorageInterfaceTests.swift // CoreStore // // Copyright © 2016 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import XCTest @testable import CoreStore //MARK: - StorageInterfaceTests final class StorageInterfaceTests: XCTestCase { @objc dynamic func test_ThatDefaultInMemoryStores_ConfigureCorrectly() { let store = InMemoryStore() XCTAssertEqual(store.dynamicType.storeType, NSInMemoryStoreType) XCTAssertNil(store.configuration) XCTAssertNil(store.storeOptions) } @objc dynamic func test_ThatCustomInMemoryStores_ConfigureCorrectly() { let store = InMemoryStore(configuration: "config1") XCTAssertEqual(store.dynamicType.storeType, NSInMemoryStoreType) XCTAssertEqual(store.configuration, "config1") XCTAssertNil(store.storeOptions) } @objc dynamic func test_ThatSQLiteStoreDefaultDirectories_AreCorrect() { #if os(tvOS) let systemDirectorySearchPath = NSSearchPathDirectory.CachesDirectory #else let systemDirectorySearchPath = NSSearchPathDirectory.ApplicationSupportDirectory #endif let defaultSystemDirectory = NSFileManager .defaultManager() .URLsForDirectory(systemDirectorySearchPath, inDomains: .UserDomainMask).first! let defaultRootDirectory = defaultSystemDirectory.URLByAppendingPathComponent( NSBundle.mainBundle().bundleIdentifier ?? "com.CoreStore.DataStack", isDirectory: true ) let applicationName = (NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String) ?? "CoreData" let defaultFileURL = defaultRootDirectory .URLByAppendingPathComponent(applicationName, isDirectory: false) .URLByAppendingPathExtension("sqlite") XCTAssertEqual(SQLiteStore.defaultRootDirectory, defaultRootDirectory) XCTAssertEqual(SQLiteStore.defaultFileURL, defaultFileURL) } @objc dynamic func test_ThatDefaultSQLiteStores_ConfigureCorrectly() { let store = SQLiteStore() XCTAssertEqual(store.dynamicType.storeType, NSSQLiteStoreType) XCTAssertNil(store.configuration) XCTAssertEqual(store.storeOptions, [NSSQLitePragmasOption: ["journal_mode": "WAL"]] as NSDictionary) XCTAssertEqual(store.fileURL, SQLiteStore.defaultFileURL) XCTAssertEqual(store.mappingModelBundles, NSBundle.allBundles()) XCTAssertEqual(store.localStorageOptions, [.None]) } @objc dynamic func test_ThatFileURLSQLiteStores_ConfigureCorrectly() { let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) .URLByAppendingPathComponent(NSUUID().UUIDString, isDirectory: false) .URLByAppendingPathExtension("db") let bundles = [NSBundle(forClass: self.dynamicType)] let store = SQLiteStore( fileURL: fileURL, configuration: "config1", mappingModelBundles: bundles, localStorageOptions: .RecreateStoreOnModelMismatch ) XCTAssertEqual(store.dynamicType.storeType, NSSQLiteStoreType) XCTAssertEqual(store.configuration, "config1") XCTAssertEqual(store.storeOptions, [NSSQLitePragmasOption: ["journal_mode": "WAL"]] as NSDictionary) XCTAssertEqual(store.fileURL, fileURL) XCTAssertEqual(store.mappingModelBundles, bundles) XCTAssertEqual(store.localStorageOptions, [.RecreateStoreOnModelMismatch]) } @objc dynamic func test_ThatFileNameSQLiteStores_ConfigureCorrectly() { let fileName = NSUUID().UUIDString + ".db" let bundles = [NSBundle(forClass: self.dynamicType)] let store = SQLiteStore( fileName: fileName, configuration: "config1", mappingModelBundles: bundles, localStorageOptions: .RecreateStoreOnModelMismatch ) XCTAssertEqual(store.dynamicType.storeType, NSSQLiteStoreType) XCTAssertEqual(store.configuration, "config1") XCTAssertEqual(store.storeOptions, [NSSQLitePragmasOption: ["journal_mode": "WAL"]] as NSDictionary) XCTAssertEqual(store.fileURL.URLByDeletingLastPathComponent, SQLiteStore.defaultRootDirectory) XCTAssertEqual(store.fileURL.lastPathComponent, fileName) XCTAssertEqual(store.mappingModelBundles, bundles) XCTAssertEqual(store.localStorageOptions, [.RecreateStoreOnModelMismatch]) } @objc dynamic func test_ThatLegacySQLiteStoreDefaultDirectories_AreCorrect() { #if os(tvOS) let systemDirectorySearchPath = NSSearchPathDirectory.CachesDirectory #else let systemDirectorySearchPath = NSSearchPathDirectory.ApplicationSupportDirectory #endif let legacyDefaultRootDirectory = NSFileManager.defaultManager().URLsForDirectory( systemDirectorySearchPath, inDomains: .UserDomainMask ).first! let legacyDefaultFileURL = legacyDefaultRootDirectory .URLByAppendingPathComponent(DataStack.applicationName, isDirectory: false) .URLByAppendingPathExtension("sqlite") XCTAssertEqual(LegacySQLiteStore.defaultRootDirectory, legacyDefaultRootDirectory) XCTAssertEqual(LegacySQLiteStore.defaultFileURL, legacyDefaultFileURL) } @objc dynamic func test_ThatDefaultLegacySQLiteStores_ConfigureCorrectly() { let store = LegacySQLiteStore() XCTAssertEqual(store.dynamicType.storeType, NSSQLiteStoreType) XCTAssertNil(store.configuration) XCTAssertEqual(store.storeOptions, [NSSQLitePragmasOption: ["journal_mode": "WAL"]] as NSDictionary) XCTAssertEqual(store.fileURL, LegacySQLiteStore.defaultFileURL) XCTAssertEqual(store.mappingModelBundles, NSBundle.allBundles()) XCTAssertEqual(store.localStorageOptions, [.None]) } @objc dynamic func test_ThatFileURLLegacySQLiteStores_ConfigureCorrectly() { let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) .URLByAppendingPathComponent(NSUUID().UUIDString, isDirectory: false) .URLByAppendingPathExtension("db") let bundles = [NSBundle(forClass: self.dynamicType)] let store = LegacySQLiteStore( fileURL: fileURL, configuration: "config1", mappingModelBundles: bundles, localStorageOptions: .RecreateStoreOnModelMismatch ) XCTAssertEqual(store.dynamicType.storeType, NSSQLiteStoreType) XCTAssertEqual(store.configuration, "config1") XCTAssertEqual(store.storeOptions, [NSSQLitePragmasOption: ["journal_mode": "WAL"]] as NSDictionary) XCTAssertEqual(store.fileURL, fileURL) XCTAssertEqual(store.mappingModelBundles, bundles) XCTAssertEqual(store.localStorageOptions, [.RecreateStoreOnModelMismatch]) } @objc dynamic func test_ThatFileNameLegacySQLiteStores_ConfigureCorrectly() { let fileName = NSUUID().UUIDString + ".db" let bundles = [NSBundle(forClass: self.dynamicType)] let store = LegacySQLiteStore( fileName: fileName, configuration: "config1", mappingModelBundles: bundles, localStorageOptions: .RecreateStoreOnModelMismatch ) XCTAssertEqual(store.dynamicType.storeType, NSSQLiteStoreType) XCTAssertEqual(store.configuration, "config1") XCTAssertEqual(store.storeOptions, [NSSQLitePragmasOption: ["journal_mode": "WAL"]] as NSDictionary) XCTAssertEqual(store.fileURL.URLByDeletingLastPathComponent, LegacySQLiteStore.defaultRootDirectory) XCTAssertEqual(store.fileURL.lastPathComponent, fileName) XCTAssertEqual(store.mappingModelBundles, bundles) XCTAssertEqual(store.localStorageOptions, [.RecreateStoreOnModelMismatch]) } }
mit
apple/swift-corelibs-foundation
Tests/Foundation/Tests/TestNSNull.swift
4
1294
// 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 // class TestNSNull : XCTestCase { static var allTests: [(String, (TestNSNull) -> () throws -> Void)] { return [ ("test_alwaysEqual", test_alwaysEqual), ("test_description", test_description), ] } func test_alwaysEqual() { let null_1 = NSNull() let null_2 = NSNull() let null_3: NSNull? = NSNull() let null_4: NSNull? = nil //Check that any two NSNull's are == XCTAssertEqual(null_1, null_2) //Check that any two NSNull's are ===, preserving the singleton behavior XCTAssertTrue(null_1 === null_2) //Check that NSNull() == .Some(NSNull) XCTAssertEqual(null_1, null_3) //Make sure that NSNull() != .None XCTAssertNotEqual(null_1, null_4) } func test_description() { XCTAssertEqual(NSNull().description, "<null>") } }
apache-2.0
TrustWallet/trust-wallet-ios
Trust/EtherClient/ENS/ENSRecord.swift
1
864
// Copyright DApps Platform Inc. All rights reserved. import Foundation import RealmSwift final class ENSRecord: Object { @objc dynamic var name: String = "" @objc dynamic var owner: String = "" @objc dynamic var resolver: String = "" @objc dynamic var address: String = "" @objc dynamic var ttl: Int = 0 @objc dynamic var updatedAt: Date = Date() @objc dynamic var isReverse: Bool = false convenience init(name: String, address: String, owner: String = "", resolver: String = "", isReverse: Bool = false, updatedAt: Date = Date()) { self.init() self.name = name self.owner = owner self.address = address self.resolver = resolver self.updatedAt = updatedAt self.isReverse = isReverse } override class func primaryKey() -> String? { return "name" } }
gpl-3.0
nathawes/swift
test/IRGen/objc_runtime_name_attr.swift
19
547
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s // REQUIRES: objc_interop //import Foundation class NormalEverydayClass {} // CHECK: @"$s22objc_runtime_name_attr19NormalEverydayClassCMm" = hidden global %objc_class // CHECK: @_DATA__TtC22objc_runtime_name_attr19NormalEverydayClass = internal constant @_objcRuntimeName(RenamedClass) class ThisWillBeRenamed {} // CHECK: @"$s22objc_runtime_name_attr17ThisWillBeRenamedCMm" = hidden global %objc_class // CHECK: @_DATA_RenamedClass = internal constant
apache-2.0
conversant/conversant-ios-sdk
ConversantSDKSampleAppSwift/ConversantSDKSampleAppSwift/ViewController.swift
1
5134
// // ViewController.swift // ConversantSDKSampleAppSwift // // Created by Daniel Kanaan on 4/14/17. // Copyright © 2017 Daniel Kanaan. All rights reserved. // import UIKit import ConversantSDK class ViewController: UIViewController, ConversantInterstitialAdDelegate, ConversantBannerAdDelegate { @IBOutlet weak var feedbackTextView: UITextView! @IBOutlet weak var bannerButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func loadAd () { //Create an Interstitial Ad let interstitialAd = ConversantInterstitialAd(delegate: self) //Fetch the interstitial Ad interstitialAd.fetch() appendFeedback(text: "Fetching interstitial") } @IBAction func bannerAd(_ sender: UIButton) { ConversantConfiguration.defaultConfiguration.autoDisplay = false var adView:ConversantAdView! //Check if the ad already exists if let currentAd = view.viewWithTag(9) as? ConversantAdView { adView = currentAd if adView.isReady { adView.display() sender.setTitle("Fetch again", for: .normal) return } } else { //If there is no ad, create an ad adView = ConversantAdView(adFormat: .mobileBannerAd, delegate: self) //Add it to the view heirarchy view.addSubview(adView) //Give it a tag so we can get it later adView.tag = 9 } //Set the frame of the ad to center below the button let newFrame = CGRect(x:sender.frame.origin.x + (sender.frame.width / 2) - (ConversantAdFormat.mobileBannerAd.width / 2), y:sender.frame.origin.y + sender.frame.height + 5, width: ConversantAdFormat.mobileBannerAd.width, height: ConversantAdFormat.mobileBannerAd.height) adView.frame = newFrame //fetch the ad adView.fetch() appendFeedback(text: "Fetching banner") //set the button to new text sender.setTitle("Display", for: .normal) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Delegate function for successful load func interstitialAdLoadComplete(ad: ConversantInterstitialAd) { //Present the interstitial ad from this view controller ad.present(from: self) appendFeedback(text: "Interstitial Loaded") } //Delegate function for load failure. Here we will present an Alert func interstitialAdLoadFailed(ad: ConversantInterstitialAd, error: ConversantError) { //Create a message using the error.description property let alert = UIAlertController(title: "Failed", message: "Ad Load Failed with error: \(error.description)", preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default) { (_) in alert.dismiss(animated: true, completion: nil) } alert.addAction(ok) present(alert, animated: true, completion: nil) } func bannerAdLoadComplete(ad: ConversantAdView) { appendFeedback(text: "Banner Loaded") if ad.isReady { ad.display() bannerButton.setTitle("Fetch again", for: .normal) } else { bannerButton.setTitle("Display", for:.normal) } } //Delegate function for banner load failure. Here we will present an Alert func bannerAdLoadFailed(ad: ConversantAdView, error: ConversantError) { //Create a message using the error.description property let alert = UIAlertController(title: "Failed", message: "Ad Load Failed with error: \(error.description)", preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default) { (_) in alert.dismiss(animated: true, completion: nil) } alert.addAction(ok) present(alert, animated: true, completion: nil) } //Other Delegate Functions func bannerAdWillPresentScreen(ad: ConversantAdView) { appendFeedback(text: "\(#function)") } func bannerAdDidDismissScreen(ad: ConversantAdView) { appendFeedback(text: "\(#function)") } func bannerAdWillDismissScreen(ad: ConversantAdView) { appendFeedback(text: "\(#function)") } func interstitialAdWillAppear(ad: ConversantInterstitialAd) { appendFeedback(text: "\(#function)") } func interstitialAdWillDisappear(ad: ConversantInterstitialAd) { appendFeedback(text: "\(#function)") } func interstitialAdDidDisappear(ad: ConversantInterstitialAd) { appendFeedback(text: "\(#function)") } //Helper functions func appendFeedback(text:String) { feedbackTextView.text = feedbackTextView.text + text + "\n" let bottom = feedbackTextView.contentSize.height - feedbackTextView.bounds.size.height feedbackTextView.setContentOffset(CGPoint(x: 0, y: bottom), animated: true) } }
apache-2.0
IngmarStein/swift
stdlib/public/core/Mirror.swift
3
35536
//===--- Mirror.swift -----------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // FIXME: ExistentialCollection needs to be supported before this will work // without the ObjC Runtime. /// Representation of the sub-structure and optional "display style" /// of any arbitrary subject instance. /// /// Describes the parts---such as stored properties, collection /// elements, tuple elements, or the active enumeration case---that /// make up a particular instance. May also supply a "display style" /// property that suggests how this structure might be rendered. /// /// Mirrors are used by playgrounds and the debugger. public struct Mirror { /// Representation of descendant classes that don't override /// `customMirror`. /// /// Note that the effect of this setting goes no deeper than the /// nearest descendant class that overrides `customMirror`, which /// in turn can determine representation of *its* descendants. internal enum _DefaultDescendantRepresentation { /// Generate a default mirror for descendant classes that don't /// override `customMirror`. /// /// This case is the default. case generated /// Suppress the representation of descendant classes that don't /// override `customMirror`. /// /// This option may be useful at the root of a class cluster, where /// implementation details of descendants should generally not be /// visible to clients. case suppressed } /// Representation of ancestor classes. /// /// A `CustomReflectable` class can control how its mirror will /// represent ancestor classes by initializing the mirror with a /// `AncestorRepresentation`. This setting has no effect on mirrors /// reflecting value type instances. public enum AncestorRepresentation { /// Generate a default mirror for all ancestor classes. /// /// This case is the default. /// /// - Note: This option generates default mirrors even for /// ancestor classes that may implement `CustomReflectable`'s /// `customMirror` requirement. To avoid dropping an ancestor class /// customization, an override of `customMirror` should pass /// `ancestorRepresentation: .Customized(super.customMirror)` when /// initializing its `Mirror`. case generated /// Use the nearest ancestor's implementation of `customMirror` to /// create a mirror for that ancestor. Other classes derived from /// such an ancestor are given a default mirror. /// /// The payload for this option should always be /// "`{ super.customMirror }`": /// /// var customMirror: Mirror { /// return Mirror( /// self, /// children: ["someProperty": self.someProperty], /// ancestorRepresentation: .Customized({ super.customMirror })) // <== /// } case customized(() -> Mirror) /// Suppress the representation of all ancestor classes. The /// resulting `Mirror`'s `superclassMirror` is `nil`. case suppressed } /// Reflect upon the given `subject`. /// /// If the dynamic type of `subject` conforms to `CustomReflectable`, /// the resulting mirror is determined by its `customMirror` property. /// Otherwise, the result is generated by the language. /// /// - Note: If the dynamic type of `subject` has value semantics, /// subsequent mutations of `subject` will not observable in /// `Mirror`. In general, though, the observability of such /// mutations is unspecified. public init(reflecting subject: Any) { if case let customized as CustomReflectable = subject { self = customized.customMirror } else { self = Mirror( legacy: _reflect(subject), subjectType: type(of: subject)) } } /// An element of the reflected instance's structure. The optional /// `label` may be used when appropriate, e.g. to represent the name /// of a stored property or of an active `enum` case, and will be /// used for lookup when `String`s are passed to the `descendant` /// method. public typealias Child = (label: String?, value: Any) /// The type used to represent sub-structure. /// /// Depending on your needs, you may find it useful to "upgrade" /// instances of this type to `AnyBidirectionalCollection` or /// `AnyRandomAccessCollection`. For example, to display the last /// 20 children of a mirror if they can be accessed efficiently, you /// might write: /// /// if let b = AnyBidirectionalCollection(someMirror.children) { /// var i = xs.index(b.endIndex, offsetBy: -20, /// limitedBy: b.startIndex) ?? b.startIndex /// while i != xs.endIndex { /// print(b[i]) /// b.formIndex(after: &i) /// } /// } public typealias Children = AnyCollection<Child> /// A suggestion of how a `Mirror`'s `subject` is to be interpreted. /// /// Playgrounds and the debugger will show a representation similar /// to the one used for instances of the kind indicated by the /// `DisplayStyle` case name when the `Mirror` is used for display. public enum DisplayStyle { case `struct`, `class`, `enum`, tuple, optional, collection case dictionary, `set` } static func _noSuperclassMirror() -> Mirror? { return nil } /// Returns the legacy mirror representing the part of `subject` /// corresponding to the superclass of `staticSubclass`. internal static func _legacyMirror( _ subject: AnyObject, asClass targetSuperclass: AnyClass) -> _Mirror? { // get a legacy mirror and the most-derived type var cls: AnyClass = type(of: subject) var clsMirror = _reflect(subject) // Walk up the chain of mirrors/classes until we find staticSubclass while let superclass: AnyClass = _getSuperclass(cls) { guard let superclassMirror = clsMirror._superMirror() else { break } if superclass == targetSuperclass { return superclassMirror } clsMirror = superclassMirror cls = superclass } return nil } internal static func _superclassIterator<Subject>( _ subject: Subject, _ ancestorRepresentation: AncestorRepresentation ) -> () -> Mirror? { if let subjectClass = Subject.self as? AnyClass, let superclass = _getSuperclass(subjectClass) { switch ancestorRepresentation { case .generated: return { self._legacyMirror(_unsafeDowncastToAnyObject(fromAny: subject), asClass: superclass).map { Mirror(legacy: $0, subjectType: superclass) } } case .customized(let makeAncestor): return { Mirror(_unsafeDowncastToAnyObject(fromAny: subject), subjectClass: superclass, ancestor: makeAncestor()) } case .suppressed: break } } return Mirror._noSuperclassMirror } /// Represent `subject` with structure described by `children`, /// using an optional `displayStyle`. /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .customized({ super.customMirror }) /// /// - Note: The traversal protocol modeled by `children`'s indices /// (`ForwardIndex`, `BidirectionalIndex`, or /// `RandomAccessIndex`) is captured so that the resulting /// `Mirror`'s `children` may be upgraded later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject, C : Collection>( _ subject: Subject, children: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) where C.Iterator.Element == Child, // FIXME(ABI)#47 (Associated Types with where clauses): these constraints should be applied to // associated types of Collection. C.SubSequence : Collection, C.SubSequence.Iterator.Element == Child, C.SubSequence.Index == C.Index, C.SubSequence.Indices : Collection, C.SubSequence.Indices.Iterator.Element == C.Index, C.SubSequence.Indices.Index == C.Index, C.SubSequence.Indices.SubSequence == C.SubSequence.Indices, C.SubSequence.SubSequence == C.SubSequence, C.Indices : Collection, C.Indices.Iterator.Element == C.Index, C.Indices.Index == C.Index, C.Indices.SubSequence == C.Indices { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) self.children = Children(children) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Represent `subject` with child values given by /// `unlabeledChildren`, using an optional `displayStyle`. The /// result's child labels will all be `nil`. /// /// This initializer is especially useful for the mirrors of /// collections, e.g.: /// /// extension MyArray : CustomReflectable { /// var customMirror: Mirror { /// return Mirror(self, unlabeledChildren: self, displayStyle: .collection) /// } /// } /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .Customized({ super.customMirror }) /// /// - Note: The traversal protocol modeled by `children`'s indices /// (`ForwardIndex`, `BidirectionalIndex`, or /// `RandomAccessIndex`) is captured so that the resulting /// `Mirror`'s `children` may be upgraded later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject, C : Collection>( _ subject: Subject, unlabeledChildren: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) where // FIXME(ABI)#48 (Associated Types with where clauses): these constraints should be applied to // associated types of Collection. C.SubSequence : Collection, C.SubSequence.SubSequence == C.SubSequence, C.Indices : Collection, C.Indices.Iterator.Element == C.Index, C.Indices.Index == C.Index, C.Indices.SubSequence == C.Indices { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) self.children = Children( unlabeledChildren.lazy.map { Child(label: nil, value: $0) } ) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Represent `subject` with labeled structure described by /// `children`, using an optional `displayStyle`. /// /// Pass a dictionary literal with `String` keys as `children`. Be /// aware that although an *actual* `Dictionary` is /// arbitrarily-ordered, the ordering of the `Mirror`'s `children` /// will exactly match that of the literal you pass. /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .customized({ super.customMirror }) /// /// - Note: The resulting `Mirror`'s `children` may be upgraded to /// `AnyRandomAccessCollection` later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject>( _ subject: Subject, children: DictionaryLiteral<String, Any>, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) } self.children = Children(lazyChildren) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// The static type of the subject being reflected. /// /// This type may differ from the subject's dynamic type when `self` /// is the `superclassMirror` of another mirror. public let subjectType: Any.Type /// A collection of `Child` elements describing the structure of the /// reflected subject. public let children: Children /// Suggests a display style for the reflected subject. public let displayStyle: DisplayStyle? public var superclassMirror: Mirror? { return _makeSuperclassMirror() } internal let _makeSuperclassMirror: () -> Mirror? internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation } /// A type that explicitly supplies its own mirror. /// /// You can create a mirror for any type using the `Mirror(reflect:)` /// initializer, but if you are not satisfied with the mirror supplied for /// your type by default, you can make it conform to `CustomReflectable` and /// return a custom `Mirror` instance. public protocol CustomReflectable { /// The custom mirror for this instance. /// /// If this type has value semantics, the mirror should be unaffected by /// subsequent mutations of the instance. var customMirror: Mirror { get } } /// A type that explicitly supplies its own mirror, but whose /// descendant classes are not represented in the mirror unless they /// also override `customMirror`. public protocol CustomLeafReflectable : CustomReflectable {} //===--- Addressing -------------------------------------------------------===// /// A protocol for legitimate arguments to `Mirror`'s `descendant` /// method. /// /// Do not declare new conformances to this protocol; they will not /// work as expected. // FIXME(ABI)#49 (Sealed Protocols): this protocol should be "non-open" and you shouldn't be able to // create conformances. public protocol MirrorPath {} extension IntMax : MirrorPath {} extension Int : MirrorPath {} extension String : MirrorPath {} extension Mirror { internal struct _Dummy : CustomReflectable { var mirror: Mirror var customMirror: Mirror { return mirror } } /// Return a specific descendant of the reflected subject, or `nil` /// Returns a specific descendant of the reflected subject, or `nil` /// if no such descendant exists. /// /// A `String` argument selects the first `Child` with a matching label. /// An integer argument *n* select the *n*th `Child`. For example: /// /// var d = Mirror(reflecting: x).descendant(1, "two", 3) /// /// is equivalent to: /// /// var d = nil /// let children = Mirror(reflecting: x).children /// if let p0 = children.index(children.startIndex, /// offsetBy: 1, limitedBy: children.endIndex) { /// let grandChildren = Mirror(reflecting: children[p0].value).children /// SeekTwo: for g in grandChildren { /// if g.label == "two" { /// let greatGrandChildren = Mirror(reflecting: g.value).children /// if let p1 = greatGrandChildren.index( /// greatGrandChildren.startIndex, /// offsetBy: 3, limitedBy: greatGrandChildren.endIndex) { /// d = greatGrandChildren[p1].value /// } /// break SeekTwo /// } /// } /// } /// /// As you can see, complexity for each element of the argument list /// depends on the argument type and capabilities of the collection /// used to initialize the corresponding subject's parent's mirror. /// Each `String` argument results in a linear search. In short, /// this function is suitable for exploring the structure of a /// `Mirror` in a REPL or playground, but don't expect it to be /// efficient. public func descendant( _ first: MirrorPath, _ rest: MirrorPath... ) -> Any? { var result: Any = _Dummy(mirror: self) for e in [first] + rest { let children = Mirror(reflecting: result).children let position: Children.Index if case let label as String = e { position = children.index { $0.label == label } ?? children.endIndex } else if let offset = (e as? Int).map({ IntMax($0) }) ?? (e as? IntMax) { position = children.index(children.startIndex, offsetBy: offset, limitedBy: children.endIndex) ?? children.endIndex } else { _preconditionFailure( "Someone added a conformance to MirrorPath; that privilege is reserved to the standard library") } if position == children.endIndex { return nil } result = children[position].value } return result } } //===--- Legacy _Mirror Support -------------------------------------------===// extension Mirror.DisplayStyle { /// Construct from a legacy `_MirrorDisposition` internal init?(legacy: _MirrorDisposition) { switch legacy { case .`struct`: self = .`struct` case .`class`: self = .`class` case .`enum`: self = .`enum` case .tuple: self = .tuple case .aggregate: return nil case .indexContainer: self = .collection case .keyContainer: self = .dictionary case .membershipContainer: self = .`set` case .container: preconditionFailure("unused!") case .optional: self = .optional case .objCObject: self = .`class` } } } internal func _isClassSuperMirror(_ t: Any.Type) -> Bool { #if _runtime(_ObjC) return t == _ClassSuperMirror.self || t == _ObjCSuperMirror.self #else return t == _ClassSuperMirror.self #endif } extension _Mirror { internal func _superMirror() -> _Mirror? { if self.count > 0 { let childMirror = self[0].1 if _isClassSuperMirror(type(of: childMirror)) { return childMirror } } return nil } } /// When constructed using the legacy reflection infrastructure, the /// resulting `Mirror`'s `children` collection will always be /// upgradable to `AnyRandomAccessCollection` even if it doesn't /// exhibit appropriate performance. To avoid this pitfall, convert /// mirrors to use the new style, which only present forward /// traversal in general. internal extension Mirror { /// An adapter that represents a legacy `_Mirror`'s children as /// a `Collection` with integer `Index`. Note that the performance /// characteristics of the underlying `_Mirror` may not be /// appropriate for random access! To avoid this pitfall, convert /// mirrors to use the new style, which only present forward /// traversal in general. internal struct LegacyChildren : RandomAccessCollection { typealias Indices = CountableRange<Int> init(_ oldMirror: _Mirror) { self._oldMirror = oldMirror } var startIndex: Int { return _oldMirror._superMirror() == nil ? 0 : 1 } var endIndex: Int { return _oldMirror.count } subscript(position: Int) -> Child { let (label, childMirror) = _oldMirror[position] return (label: label, value: childMirror.value) } internal let _oldMirror: _Mirror } /// Initialize for a view of `subject` as `subjectClass`. /// /// - parameter ancestor: A Mirror for a (non-strict) ancestor of /// `subjectClass`, to be injected into the resulting hierarchy. /// /// - parameter legacy: Either `nil`, or a legacy mirror for `subject` /// as `subjectClass`. internal init( _ subject: AnyObject, subjectClass: AnyClass, ancestor: Mirror, legacy legacyMirror: _Mirror? = nil ) { if ancestor.subjectType == subjectClass || ancestor._defaultDescendantRepresentation == .suppressed { self = ancestor } else { let legacyMirror = legacyMirror ?? Mirror._legacyMirror( subject, asClass: subjectClass)! self = Mirror( legacy: legacyMirror, subjectType: subjectClass, makeSuperclassMirror: { _getSuperclass(subjectClass).map { Mirror( subject, subjectClass: $0, ancestor: ancestor, legacy: legacyMirror._superMirror()) } }) } } internal init( legacy legacyMirror: _Mirror, subjectType: Any.Type, makeSuperclassMirror: (() -> Mirror?)? = nil ) { if let makeSuperclassMirror = makeSuperclassMirror { self._makeSuperclassMirror = makeSuperclassMirror } else if let subjectSuperclass = _getSuperclass(subjectType) { self._makeSuperclassMirror = { legacyMirror._superMirror().map { Mirror(legacy: $0, subjectType: subjectSuperclass) } } } else { self._makeSuperclassMirror = Mirror._noSuperclassMirror } self.subjectType = subjectType self.children = Children(LegacyChildren(legacyMirror)) self.displayStyle = DisplayStyle(legacy: legacyMirror.disposition) self._defaultDescendantRepresentation = .generated } } //===--- QuickLooks -------------------------------------------------------===// /// The sum of types that can be used as a Quick Look representation. public enum PlaygroundQuickLook { /// Plain text. case text(String) /// An integer numeric value. case int(Int64) /// An unsigned integer numeric value. case uInt(UInt64) /// A single precision floating-point numeric value. case float(Float32) /// A double precision floating-point numeric value. case double(Float64) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// An image. case image(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A sound. case sound(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A color. case color(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A bezier path. case bezierPath(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// An attributed string. case attributedString(Any) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A rectangle. case rectangle(Float64, Float64, Float64, Float64) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A point. case point(Float64, Float64) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A size. case size(Float64, Float64) /// A boolean value. case bool(Bool) // FIXME: Uses explicit values to avoid coupling a particular Cocoa type. /// A range. case range(Int64, Int64) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A GUI view. case view(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A graphical sprite. case sprite(Any) /// A Uniform Resource Locator. case url(String) /// Raw data that has already been encoded in a format the IDE understands. case _raw([UInt8], String) } extension PlaygroundQuickLook { /// Initialize for the given `subject`. /// /// If the dynamic type of `subject` conforms to /// `CustomPlaygroundQuickLookable`, returns the result of calling /// its `customPlaygroundQuickLook` property. Otherwise, returns /// a `PlaygroundQuickLook` synthesized for `subject` by the /// language. Note that in some cases the result may be /// `.Text(String(reflecting: subject))`. /// /// - Note: If the dynamic type of `subject` has value semantics, /// subsequent mutations of `subject` will not observable in /// `Mirror`. In general, though, the observability of such /// mutations is unspecified. public init(reflecting subject: Any) { if let customized = subject as? CustomPlaygroundQuickLookable { self = customized.customPlaygroundQuickLook } else if let customized = subject as? _DefaultCustomPlaygroundQuickLookable { self = customized._defaultCustomPlaygroundQuickLook } else { if let q = _reflect(subject).quickLookObject { self = q } else { self = .text(String(reflecting: subject)) } } } } /// A type that explicitly supplies its own playground Quick Look. /// /// A Quick Look can be created for an instance of any type by using the /// `PlaygroundQuickLook(reflecting:)` initializer. If you are not satisfied /// with the representation supplied for your type by default, you can make it /// conform to the `CustomPlaygroundQuickLookable` protocol and provide a /// custom `PlaygroundQuickLook` instance. public protocol CustomPlaygroundQuickLookable { /// A custom playground Quick Look for this instance. /// /// If this type has value semantics, the `PlaygroundQuickLook` instance /// should be unaffected by subsequent mutations. var customPlaygroundQuickLook: PlaygroundQuickLook { get } } // A workaround for <rdar://problem/26182650> // FIXME(ABI)#50 (Dynamic Dispatch for Class Extensions) though not if it moves out of stdlib. public protocol _DefaultCustomPlaygroundQuickLookable { var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { get } } //===--- General Utilities ------------------------------------------------===// // This component could stand alone, but is used in Mirror's public interface. /// A lightweight collection of key-value pairs. /// /// Use a `DictionaryLiteral` instance when you need an ordered collection of /// key-value pairs and don't require the fast key lookup that the /// `Dictionary` type provides. Unlike key-value pairs in a true dictionary, /// neither the key nor the value of a `DictionaryLiteral` instance must /// conform to the `Hashable` protocol. /// /// You initialize a `DictionaryLiteral` instance using a Swift dictionary /// literal. Besides maintaining the order of the original dictionary literal, /// `DictionaryLiteral` also allows duplicates keys. For example: /// /// let recordTimes: DictionaryLiteral = ["Florence Griffith-Joyner": 10.49, /// "Evelyn Ashford": 10.76, /// "Evelyn Ashford": 10.79, /// "Marlies Gohr": 10.81] /// print(recordTimes.first!) /// // Prints "("Florence Griffith-Joyner", 10.49)" /// /// Some operations that are efficient on a dictionary are slower when using /// `DictionaryLiteral`. In particular, to find the value matching a key, you /// must search through every element of the collection. The call to /// `index(where:)` in the following example must traverse the whole /// collection to make sure that no element matches the given predicate: /// /// let runner = "Marlies Gohr" /// if let index = recordTimes.index(where: { $0.0 == runner }) { /// let time = recordTimes[index].1 /// print("\(runner) set a 100m record of \(time) seconds.") /// } else { /// print("\(runner) couldn't be found in the records.") /// } /// // Prints "Marlies Gohr set a 100m record of 10.81 seconds." /// /// Dictionary Literals as Function Parameters /// ------------------------------------------ /// /// When calling a function with a `DictionaryLiteral` parameter, you can pass /// a Swift dictionary literal without causing a `Dictionary` to be created. /// This capability can be especially important when the order of elements in /// the literal is significant. /// /// For example, you could create an `IntPairs` structure that holds a list of /// two-integer tuples and use an initializer that accepts a /// `DictionaryLiteral` instance. /// /// struct IntPairs { /// var elements: [(Int, Int)] /// /// init(_ elements: DictionaryLiteral<Int, Int>) { /// self.elements = Array(elements) /// } /// } /// /// When you're ready to create a new `IntPairs` instance, use a dictionary /// literal as the parameter to the `IntPairs` initializer. The /// `DictionaryLiteral` instance preserves the order of the elements as /// passed. /// /// let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1]) /// print(pairs.elements) /// // Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]" public struct DictionaryLiteral<Key, Value> : ExpressibleByDictionaryLiteral { /// Creates a new `DictionaryLiteral` instance from the given dictionary /// literal. /// /// The order of the key-value pairs is kept intact in the resulting /// `DictionaryLiteral` instance. public init(dictionaryLiteral elements: (Key, Value)...) { self._elements = elements } internal let _elements: [(Key, Value)] } /// `Collection` conformance that allows `DictionaryLiteral` to /// interoperate with the rest of the standard library. extension DictionaryLiteral : RandomAccessCollection { public typealias Indices = CountableRange<Int> /// The position of the first element in a nonempty collection. /// /// If the `DictionaryLiteral` instance is empty, `startIndex` is equal to /// `endIndex`. public var startIndex: Int { return 0 } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// If the `DictionaryLiteral` instance is empty, `endIndex` is equal to /// `startIndex`. public var endIndex: Int { return _elements.endIndex } // FIXME: a typealias is needed to prevent <rdar://20248032> /// The element type of a `DictionaryLiteral`: a tuple containing an /// individual key-value pair. public typealias Element = (key: Key, value: Value) /// Accesses the element at the specified position. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// - Returns: The key-value pair at position `position`. public subscript(position: Int) -> Element { return _elements[position] } } extension String { /// Creates a string representing the given value. /// /// Use this initializer to convert an instance of any type to its preferred /// representation as a `String` instance. The initializer creates the /// string representation of `instance` in one of the following ways, /// depending on its protocol conformance: /// /// - If `instance` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `instance.write(to: s)` on an empty /// string `s`. /// - If `instance` conforms to the `CustomStringConvertible` protocol, the /// result is `instance.description`. /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `instance.debugDescription`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(describing: p)) /// // Prints "Point(x: 21, y: 30)" /// /// After adding `CustomStringConvertible` conformance by implementing the /// `description` property, `Point` provides its own custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(String(describing: p)) /// // Prints "(21, 30)" /// /// - SeeAlso: `String.init<Subject>(reflecting: Subject)` public init<Subject>(describing instance: Subject) { self.init() _print_unlocked(instance, &self) } /// Creates a string with a detailed representation of the given value, /// suitable for debugging. /// /// Use this initializer to convert an instance of any type to its custom /// debugging representation. The initializer creates the string /// representation of `instance` in one of the following ways, depending on /// its protocol conformance: /// /// - If `subject` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `subject.debugDescription`. /// - If `subject` conforms to the `CustomStringConvertible` protocol, the /// result is `subject.description`. /// - If `subject` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `subject.write(to: s)` on an empty /// string `s`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "p: Point = { /// // x = 21 /// // y = 30 /// // }" /// /// After adding `CustomDebugStringConvertible` conformance by implementing /// the `debugDescription` property, `Point` provides its own custom /// debugging representation. /// /// extension Point: CustomDebugStringConvertible { /// var debugDescription: String { /// return "Point(x: \(x), y: \(y))" /// } /// } /// /// print(String(reflecting: p)) /// // Prints "Point(x: 21, y: 30)" /// /// - SeeAlso: `String.init<Subject>(Subject)` public init<Subject>(reflecting subject: Subject) { self.init() _debugPrint_unlocked(subject, &self) } } /// Reflection for `Mirror` itself. extension Mirror : CustomStringConvertible { public var description: String { return "Mirror for \(self.subjectType)" } } extension Mirror : CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: [:]) } } @available(*, unavailable, renamed: "MirrorPath") public typealias MirrorPathType = MirrorPath
apache-2.0
zhuqling/Dollar.swift
Cent/CentTests/CentTests.swift
1
7925
// // CentTests.swift // CentTests // // Created by Ankur Patel on 10/16/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import XCTest class CentTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } /** Array Test Cases */ func testArrayEach() { var arr: [String] = [] let result = ["A", "B", "C"].each({ arr.append($0) }) XCTAssertEqual(result, ["A", "B", "C"], "Return array itself") XCTAssertEqual(arr.joinWithSeparator(""), "ABC", "Return string concatenated") } func testArrayCycle() { var result = "" [1, 2, 3].cycle(2) { print($0, separator: "", terminator: "", toStream: &result) } XCTAssertEqual("123123", result, "testCycle: Should return cycled pattern") } func testArrayEvery(){ let result = ["angry", "hungry"].every { (a: String) -> (Bool) in a.hasSuffix("gry") } XCTAssertEqual(result, true, "testEvery: Should return true") } func testArrayIndexOf() { let array = ["foo", "spam", "bar", "eggs"] XCTAssertEqual(array.indexOf("spam"), 1, "Should return correct index") } func testArrayIndexOfReturnNill() { XCTAssertNil(["foo", "spam", "bar", "eggs"].indexOf("NONE"), "Should return nill when element not found") } func testArrayFetch(){ let arr = [1, 2, 3, 4, 5, 6, 7, 8] XCTAssertNil(arr.fetch(100),"Should return nill") XCTAssertEqual(arr.fetch(100, orElse: 42), 42, "Should return orElse value") XCTAssertEqual(arr.fetch(-1), 8, "Should return last element") } func testArrayFindIndex(){ let ind: Int? = ["foo", "bar", "spam", "eggs"].findIndex { $0.length == 4 } XCTAssertEqual(2, ind!,"Should return correct index") } func testArrayFindLastIndex() { let ind: Int? = ["foo", "bar", "spam", "eggs"].findLastIndex { $0.length == 4 } XCTAssertEqual(3, ind!,"Should return correct index") } func testArrayFirst() { XCTAssertEqual("foo", ["foo", "bar"].first(), "Should return first element") } func testArrayFlatten() { let unFlattened = ["foo", ["bar"], [["spam"]], [[["eggs"]]] ] let flattened = unFlattened.flatten() XCTAssertEqual(["foo", "bar", "spam", "eggs"], flattened, "Should return flattened array") } func testArrayGet(){ let element = ["foo", "bar"].get(0) XCTAssertEqual("foo",element!, "Should return index element 0") let nothing = ["foo", "bar"].get(1000) XCTAssertNil(nothing, "Should return nill") } func testArrayInitial(){ XCTAssertEqual(["foo", "bar", "spam"].initial(),["foo", "bar"], "Should return all but last") XCTAssertEqual(["foo", "bar", "spam"].initial(2),["foo"], "Should return all but last 2 elements") } func testArrayLast(){ XCTAssertEqual(["foo", "bar"].last(),"bar", "Should return last element") } func testArrayRest(){ XCTAssertEqual(["foo", "bar", "spam"].rest(2),["spam"], "Should return all but first 2 element") XCTAssertEqual(["foo", "bar", "spam"].rest(),["bar", "spam"], "Should return all but first element") } func testArrayMin(){ XCTAssertEqual([1, 0, 2, 3].min(),0, "Should return minimum") } func testArrayMax(){ XCTAssertEqual([1, 3, 0, 2].max(), 3, "Should return maximum") } func testArrayRemove() { var arr = ["A", "B", "C", "D", "E"] arr.remove("B") XCTAssertEqual(arr, ["A", "C", "D", "E"], "Test remove") arr.remove("Z") XCTAssertEqual(arr, ["A", "C", "D", "E"], "Remove element that does not exist") } func testArrayContains() { let arr = ["A", "B", "C", "D", "E"] XCTAssert(arr.contains("C"), "Test if array contains C") XCTAssertFalse(arr.contains("Z"), "Test of failure") } /** String Test Cases */ func testSubscript() { XCTAssertEqual("Dollar and Cent"[0...5], "Dollar", "Return substring") XCTAssertEqual("Dollar and Cent"[7..<10], "and", "Return substring") } /** Regex Test Cases */ func testRegex() { XCTAssertEqual("Dollar and Cent" =~ "and", true, "Should pattern match with regex string") XCTAssertEqual("Dollar and Cent" =~ "and Cent$", true, "Should pattern match with regex string") XCTAssertEqual("Dollar and Cent" =~ "\\sand\\s", true, "Should pattern match with regex string") XCTAssertEqual("Dollar and Cent" =~ "and Cent\\s+", false, "Should pattern match with regex string") } /** Int Test Cases */ func testDateMath() { struct TestDate { let unit: NSCalendarUnit let singleMath: Int.CalendarMath let multipleMath: Int.CalendarMath } let calendar = NSCalendar.autoupdatingCurrentCalendar() let multiple = 2 let tests = [ TestDate(unit: .Second, singleMath: 1.second, multipleMath: multiple.seconds), TestDate(unit: .Minute, singleMath: 1.minute, multipleMath: multiple.minutes), TestDate(unit: .Hour, singleMath: 1.hour, multipleMath: multiple.hours), TestDate(unit: .Day, singleMath: 1.day, multipleMath: multiple.days), TestDate(unit: .WeekOfYear, singleMath: 1.week, multipleMath: multiple.weeks), TestDate(unit: .Month, singleMath: 1.month, multipleMath: multiple.months), TestDate(unit: .Year, singleMath: 1.year, multipleMath: multiple.years) ] tests.each { (test) -> () in func equalIsh(lhs: NSDate!, rhs: NSDate!) -> Bool { return round(lhs.timeIntervalSinceNow) == round(rhs.timeIntervalSinceNow) } let components = NSDateComponents() components.setValue(1, forComponent: test.unit) XCTAssert(equalIsh(test.singleMath.fromNow, rhs: calendar.dateByAddingComponents(components, toDate: NSDate(), options: [])), "formNow single units are equal.") components.setValue(-1, forComponent: test.unit) XCTAssert(equalIsh(test.singleMath.ago, rhs: calendar.dateByAddingComponents(components, toDate: NSDate(), options: [])), "ago single units are equal.") components.setValue(multiple, forComponent: test.unit) XCTAssert(equalIsh(test.multipleMath.fromNow, rhs: calendar.dateByAddingComponents(components, toDate: NSDate(), options: [])), "formNow multiple units are equal.") components.setValue(-multiple, forComponent: test.unit) XCTAssert(equalIsh(test.multipleMath.ago, rhs: calendar.dateByAddingComponents(components, toDate: NSDate(), options: [])), "ago multiple units are equal.") } } /** Dictionary Test Cases */ func testDictionaryMerge() { let eastCoastStateCapitals = ["New York": "Albany", "Maryland":"Annapolis", "Connecticut":"Hartford" ] let westCoastStateCapitals = ["California": "Sacremento", "Washington":"Olympia"] var usStateCapitals: Dictionary<String, String> = [:] usStateCapitals.merge(eastCoastStateCapitals, westCoastStateCapitals) XCTAssertEqual(usStateCapitals, ["New York": "Albany", "Maryland":"Annapolis", "Connecticut":"Hartford" ,"California": "Sacremento", "Washington":"Olympia"]) } func testArrayDifference() { let arr = ["B", "A", "C", "E", "D"] XCTAssertEqual(arr - ["C"], ["B", "A", "E", "D"], "Test removes C") XCTAssertEqual(arr - ["E", "C"], ["B", "A", "D"], "Test removes C and E") } }
mit
wwq0327/iOS9Example
DemoLists/DemoLists/BackTextViewController.swift
1
1546
// // BackTextViewController.swift // DemoLists // // Created by wyatt on 15/12/19. // Copyright © 2015年 Wanqing Wang. All rights reserved. // import UIKit class BackTextViewController: UIViewController { @IBOutlet weak var textLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() addBackgroundColorToText() } func addBackgroundColorToText() { let style = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle style.firstLineHeadIndent = 10.0 style.headIndent = 10 style.tailIndent = 0 style.lineSpacing = 20.0 let attributes = [NSParagraphStyleAttributeName: style] textLabel.attributedText = NSAttributedString(string: textLabel.text!, attributes: attributes) let textbackgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6) textLabel.backgroundColor = textbackgroundColor } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
sandym/swiftpp
tests/2/test.swift
1
316
import Foundation class MySimple : Simple { override func method2() -> String { return "is " + super.method2() } } print( "\u{1B}[32m" ) print( "--> 2. overriden virtual with call to super, swift -> C++ -> swift -> C++" ) let s1 = MySimple() s1.method1() MySimple.method3( s1.text() ) print( "\u{1B}[0m" )
mit
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/Model/UploadItemAsset.swift
1
1739
// // UploadItemAsset.swift // MT_iOS // // Created by CHEEBOW on 2016/02/08. // Copyright © 2016年 Six Apart, Ltd. All rights reserved. // import UIKit class UploadItemAsset: UploadItemImage { private(set) var asset: PHAsset! init(asset: PHAsset) { super.init() self.asset = asset } override func setup(completion: (() -> Void)) { let manager = PHImageManager.defaultManager() manager.requestImageDataForAsset(self.asset, options: nil, resultHandler: {(imageData: NSData?, dataUTI: String?, orientation: UIImageOrientation, info: [NSObject : AnyObject]?) in if let data = imageData { if let image = UIImage(data: data) { let jpeg = Utils.convertJpegData(image, width: self.width, quality: self.quality) self.data = jpeg completion() } } else { completion() } } ) } override func thumbnail(size: CGSize, completion: (UIImage->Void)) { let manager = PHImageManager.defaultManager() manager.requestImageForAsset(self.asset, targetSize: size, contentMode: .Default, options: nil, resultHandler: {image, Info in if let image = image { completion(image) } } ) } override func makeFilename()->String { if let date = asset.creationDate { self._filename = Utils.makeJPEGFilename(date) } else { self._filename = Utils.makeJPEGFilename(NSDate()) } return self._filename } }
mit
stringcode86/SCUtilities
SCUtilitiesCore/Utils.swift
1
1010
// // File.swift // SCUtilities // // Created by Michal Inger on 18/11/2015. // Copyright © 2015 stringCode ltd. All rights reserved. // import Foundation public func dispatch_after(delay:Double, _ closure:(()->())? = nil) { if let closure = closure { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))),dispatch_get_main_queue(), closure) } } public func dispatch_async_on_main_queue(block: ()->()) { dispatch_async(dispatch_get_main_queue()) { block() } } public func saveFileToDocumentsWithName(name: String, contents: NSData) { var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as String! path = path + "/" + name contents.writeToFile(path, atomically: false) } public func testBuildConfiguration() -> String { #if RELEASEF let text = "Release SC " #else let text = "Debug SC" #endif return text }
mit
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/MyImageView.swift
1
676
// // MyImageView.swift // ApiDemo-Swift // // Created by Jacob su on 5/12/16. // Copyright © 2016 suzp1984@gmail.com All rights reserved. // import UIKit class MyImageView: UIView { var image : UIImage! override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { self.setNeedsDisplay() // causes drawRect to be called } override func draw(_ rect: CGRect) { if var im = self.image { if let asset = self.image.imageAsset { let tc = self.traitCollection im = asset.image(with: tc) } im.draw(at: CGPoint.zero) } } }
apache-2.0
tensorflow/swift-apis
Sources/TensorFlow/Core/LazyTensorOperation.swift
1
40853
// Copyright 2019 The TensorFlow Authors. 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 CTensorFlow @usableFromInline class LazyTensorHandle: _AnyTensorHandle { enum Handle { /// Bool indicates if this concrete TFETensorhandle was a result of /// materialization. case concrete(TFETensorHandle, materialized: Bool) /// Bool indicates whether this is a live tensor. This flag is used to /// heuristically determine whether this symbolic tensor should also be /// materialized whenever materialization of any other tensor is triggered. case symbolic(LazyTensorOperation, index: Int, isLive: Bool) } let handle: Handle @usableFromInline var _tfeTensorHandle: TFETensorHandle { switch handle { case .concrete(let h, _): return h case .symbolic(let op, let index, _): return op.materialized(index: index) } } init(_ base: TFETensorHandle) { handle = Handle.concrete(base, materialized: false) } init(_materialized base: TFETensorHandle) { handle = Handle.concrete(base, materialized: true) } init(_lazy op: LazyTensorOperation, index: Int) { precondition( index < op.outputCount, "Symbolic Tensor Index is out-of-bounds") handle = Handle.symbolic(op, index: index, isLive: false) LazyTensorContext.local.operationsTracker.incrementRefCount(op, isLive: false) } init(_lazyLive op: LazyTensorOperation, index: Int) { precondition( index < op.outputCount, "Symbolic Tensor Index is out-of-bounds") handle = Handle.symbolic(op, index: index, isLive: true) LazyTensorContext.local.operationsTracker.incrementRefCount(op, isLive: true) } deinit { if case let .symbolic(op, _, isLive) = handle { LazyTensorContext.local.operationsTracker.decrementRefCount(op, isLive: isLive) } } /// The number of dimensions of the underlying `Tensor`. @usableFromInline var rank: Int { @_semantics("autodiff.nonvarying") get { shape.rank } } /// The shape of the underlying `Tensor`. @usableFromInline var shape: TensorShape { @_semantics("autodiff.nonvarying") get { switch handle { case .symbolic(let op, let index, _): precondition( LazyTensorContext.local.isShapeTrackingEnabled, "Shape tracking is not enabled in this context.") if let shape = op.outputShapes[index] { return shape } // Materialize and get the shape from concrete tensor handle. op.outputShapes[index] = _tfeTensorHandle.shape return op.outputShapes[index]! case .concrete(let tfeHandle, _): return tfeHandle.shape } } } /// Returns the underlying `LazyTensorOperation` if this is a symbolic `LazyTensorHandle`. var lazyTensorOperation: LazyTensorOperation? { switch handle { case .symbolic(let op, _, _): return op case .concrete: return nil } } @usableFromInline var backend: Device.Backend { return .TF_EAGER } // Liveness tracking for LazyTensorOperations // static func isLive(_ op: LazyTensorOperation) -> Bool { return LazyTensorContext.local.operationsTracker.isLive(op) } static func forEachLiveOperation( _ perform: (LazyTensorOperation) throws -> Void ) rethrows { try LazyTensorContext.local.operationsTracker.forEachLiveOperation(perform) } static func forEachOperation( _ perform: (LazyTensorOperation) throws -> Void ) rethrows { try LazyTensorContext.local.operationsTracker.forEachOperation(perform) } @usableFromInline static var _materializationCallback: (String) -> Void = { _ in } } extension _AnyTensorHandle { /// Returns a concrete `LazyTensorHandle` with an additional constraint that the /// underlying concrete `LazyTensorHandle` should be marked to be promoted as an /// input when used in an extracted trace. This provides a **temporary** /// mechanism to promote a concrete lazy tensor to an input in extracted /// traces. (Note that this may trigger materialization.) var _concreteInputLazyTensor: LazyTensorHandle { LazyTensorHandle(_materialized: self._tfeTensorHandle) } } extension TensorHandle { /// Returns `Self` that wraps `_concreteInputLazyTensor` of the underlying /// `_AnyTensorHandle` public var _concreteInputLazyTensor: TensorHandle { TensorHandle(handle: handle._concreteInputLazyTensor) } } extension Tensor { /// Returns `Self` that wraps `_concreteInputLazyTensor` of the underlying /// `_AnyTensorHandle` public var _concreteInputLazyTensor: Tensor { Tensor(handle: handle._concreteInputLazyTensor) } } extension StringTensor { /// Returns `Self` that wraps `_concreteInputLazyTensor` of the underlying /// `_AnyTensorHandle` public var _concreteInputLazyTensor: StringTensor { StringTensor(handle: handle._concreteInputLazyTensor) } } extension VariantHandle { /// Returns `Self` that wraps `_concreteInputLazyTensor` of the underlying /// `_AnyTensorHandle` public var _concreteInputLazyTensor: VariantHandle { VariantHandle(handle: handle._concreteInputLazyTensor) } } extension ResourceHandle { /// Returns `Self` that wraps `_concreteInputLazyTensor` of the underlying /// `_AnyTensorHandle` public var _concreteInputLazyTensor: ResourceHandle { ResourceHandle(handle: handle._concreteInputLazyTensor) } } class LazyTensorOperation: TensorOperation { typealias TensorValueHandle = LazyTensorHandle enum Input { case single(LazyTensorHandle) case list([LazyTensorHandle]) } enum Attribute: Equatable { case boolValue(Bool) case intValue(Int) case floatValue(Float) case doubleValue(Double) case stringValue(String) case boolArray([Bool]) case intArray([Int]) case floatArray([Float]) case doubleArray([Double]) case stringArray([String]) case constTensor(TFETensorHandle) case tensorDataTypeValue(TensorDataType) case tensorFunctionPointer(_TensorFunctionPointer) case tensorDataTypeArray([TensorDataType]) case optionalTensorShape(TensorShape?) case optionalTensorShapeArray([TensorShape?]) } var name: String let outputCount: Int var inputs: [Input] var attributes: [String: Attribute] var outputShapes: [TensorShape?] var deviceName: String? var outputs: [TFETensorHandle]? var id: String? var nameWithID: String { if let id = self.id { return "\(name)_\(id)" } else { return "\(name)_\(ObjectIdentifier(self))" } } func outputName(at index: Int) -> String { precondition( index < outputCount, "Output index out of bounds when getting outputName.") let ssaID = id ?? "\(ObjectIdentifier(self))" var ssaName = "%\(ssaID)" if outputCount > 1 { ssaName += ".\(index)" } return ssaName } var outputName: String { switch outputCount { case 0: return "" case 1: return outputName(at: 0) default: let outputNames = (0..<outputCount).lazy.map { self.outputName(at: $0) } let aggregateName = outputNames.joined(separator: ", ") return "(\(aggregateName))" } } static var liveOperations: Int = 0 init(_id id: String?, name: String, outputCount: Int) { self.name = name self.inputs = [] self.attributes = [:] self.deviceName = _ExecutionContext.global.currentDeviceName self.outputCount = outputCount self.outputShapes = [] self.outputs = nil self.id = id LazyTensorOperation.liveOperations += 1 } required convenience init(_ name: String, _ outputCount: Int) { self.init(_id: nil, name: name, outputCount: outputCount) } deinit { LazyTensorOperation.liveOperations -= 1 } func evaluate() -> [LazyTensorHandle] { if LazyTensorContext.local.isShapeTrackingEnabled { updateOutputShapes() } return (0..<outputCount).map { LazyTensorHandle(_lazyLive: self, index: $0) } } func addInput(_ input: LazyTensorHandle) { inputs.append(Input.single(input)) } func updateAttribute(_ name: String, _ value: Bool) { attributes[name] = Attribute.boolValue(value) } func updateAttribute(_ name: String, _ value: Int) { attributes[name] = Attribute.intValue(value) } func updateAttribute(_ name: String, _ value: Int32) { attributes[name] = Attribute.intValue(Int(value)) } func updateAttribute(_ name: String, _ value: Int64) { attributes[name] = Attribute.intValue(Int(value)) } func updateAttribute(_ name: String, _ value: Float) { attributes[name] = Attribute.floatValue(value) } func updateAttribute(_ name: String, _ value: Double) { attributes[name] = Attribute.doubleValue(value) } func updateAttribute(_ name: String, _ value: String) { attributes[name] = Attribute.stringValue(value) } func updateAttribute(_ name: String, _ value: [Bool]) { attributes[name] = Attribute.boolArray(value) } func updateAttribute(_ name: String, _ value: [Int]) { attributes[name] = Attribute.intArray(value) } func updateAttribute(_ name: String, _ value: [Int32]) { attributes[name] = Attribute.intArray(value.map { Int($0) }) } func updateAttribute(_ name: String, _ value: [Int64]) { attributes[name] = Attribute.intArray(value.map { Int($0) }) } func updateAttribute(_ name: String, _ value: [Float]) { attributes[name] = Attribute.floatArray(value) } func updateAttribute(_ name: String, _ value: [Double]) { attributes[name] = Attribute.doubleArray(value) } func updateAttribute(_ name: String, _ value: [String]) { attributes[name] = Attribute.stringArray(value) } } extension LazyTensorOperation: TFTensorOperation { private func lazyTensorHandle(_ input: _AnyTensorHandle) -> LazyTensorHandle { if let lazyHandle = input as? LazyTensorHandle { if case let LazyTensorHandle.Handle.symbolic( op, index, true) = lazyHandle.handle { // We turn off liveness for the constructed LazyTensorHandle, // because it is only referenced internally as a part // of the LazyTensorOperation input. return LazyTensorHandle(_lazy: op, index: index) } else { return lazyHandle } } else { return LazyTensorHandle(input._tfeTensorHandle) } } func addInput(_ input: _AnyTensorHandle) { addInput(lazyTensorHandle(input)) } func addInput<Scalar: TensorFlowScalar>(_ input: Tensor<Scalar>) { addInput(input.handle.handle) } func addInput(_ input: StringTensor) { addInput(input.handle.handle) } func addInput(_ input: VariantHandle) { addInput(input.handle) } func addInput(_ input: ResourceHandle) { addInput(input.handle) } func addInputList<T: TensorArrayProtocol>(_ input: T) { let lazyHandles = input._tensorHandles.map { lazyTensorHandle($0) } inputs.append(Input.list(lazyHandles)) } func updateAttribute(_ name: String, _ value: TensorDataType) { attributes[name] = Attribute.tensorDataTypeValue(value) } func updateAttribute(_ name: String, _ value: TensorShape) { attributes[name] = Attribute.optionalTensorShape(value) } func updateAttribute(_ name: String, _ value: TensorShape?) { attributes[name] = Attribute.optionalTensorShape(value) } func updateAttribute(_ name: String, _ value: [TensorDataType]) { attributes[name] = Attribute.tensorDataTypeArray(value) } func updateAttribute(_ name: String, _ value: [TensorShape]) { attributes[name] = Attribute.optionalTensorShapeArray(value) } func updateAttribute(_ name: String, _ value: [TensorShape?]) { attributes[name] = Attribute.optionalTensorShapeArray(value) } func updateAttribute(_ name: String, _ value: _TensorFunctionPointer) { attributes[name] = Attribute.tensorFunctionPointer(value) } func updateAttribute(_ name: String, _ value: TFETensorHandle) { attributes[name] = Attribute.constTensor(value) } func updateAttribute<In: TensorGroup, Out: TensorGroup>( _ name: String, _ value: (In) -> Out ) { updateAttribute(name, _TensorFunctionPointer(name: _tffunc(value))) } func execute() { // If we want to stage this, we will need to add control dependencies. // For the time-being, just build a TFE_Op and run it. // // Collect all the unmaterialized inputs. var unmaterializedInputs = [LazyTensorOperation]() unmaterializedInputs.reserveCapacity(inputs.count) for input in inputs { switch input { case .single(let v): if let lazyOperation = v.lazyTensorOperation { unmaterializedInputs.append(lazyOperation) } case .list(let values): unmaterializedInputs.append( contentsOf: values.lazy.compactMap { $0.lazyTensorOperation } ) } } // Materialize the inputs now. LazyTensorOperation.materialize(targets: unmaterializedInputs) // Build the TFEOp and execute. let op = TFE_Op(name, outputCount) for input in inputs { switch input { case .single(let v): op.addInput(v._tfeTensorHandle) case .list(let values): for v in values { op.addInput(v._tfeTensorHandle) } } } for (name, value) in attributes { switch value { case .boolValue(let v): op.updateAttribute(name, v) case .intValue(let v): op.updateAttribute(name, v) case .floatValue(let v): op.updateAttribute(name, v) case .doubleValue(let v): op.updateAttribute(name, v) case .stringValue(let v): op.updateAttribute(name, v) case .boolArray(let v): op.updateAttribute(name, v) case .intArray(let v): op.updateAttribute(name, v) case .floatArray(let v): op.updateAttribute(name, v) case .doubleArray(let v): op.updateAttribute(name, v) case .stringArray(let v): op.updateAttribute(name, v) case .constTensor(_): fatalError("Const Tensor cannot be eager attribute.") case .tensorDataTypeValue(let v): op.updateAttribute(name, v) case .tensorDataTypeArray(let v): op.updateAttribute(name, v) case .optionalTensorShape(let v): op.updateAttribute(name, v) case .optionalTensorShapeArray(let v): op.updateAttribute(name, v) case .tensorFunctionPointer(let v): op.updateAttribute(name, v) } } op.execute() } func execute<T0: TensorArrayProtocol>( _ count0: Int ) -> (T0) { let outputs = evaluate() let offset0 = 0 let result = (T0.init(_handles: outputs[offset0..<count0])) return result } func execute<T0: TensorArrayProtocol, T1: TensorArrayProtocol>( _ count0: Int, _ count1: Int ) -> (T0, T1) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<outputs.count]) ) return result } func execute<T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol>( _ count0: Int, _ count1: Int, _ count2: Int ) -> (T0, T1, T2) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int ) -> (T0, T1, T2, T3) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int ) -> (T0, T1, T2, T3, T4) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int ) -> (T0, T1, T2, T3, T4, T5) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int ) -> (T0, T1, T2, T3, T4, T5, T6) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol, T10: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int, _ count10: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let offset10 = offset9 + count9 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<offset10]), T10.init(_handles: outputs[offset10..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol, T10: TensorArrayProtocol, T11: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int, _ count10: Int, _ count11: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let offset10 = offset9 + count9 let offset11 = offset10 + count10 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<offset10]), T10.init(_handles: outputs[offset10..<offset11]), T11.init(_handles: outputs[offset11..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol, T10: TensorArrayProtocol, T11: TensorArrayProtocol, T12: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int, _ count10: Int, _ count11: Int, _ count12: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let offset10 = offset9 + count9 let offset11 = offset10 + count10 let offset12 = offset11 + count11 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<offset10]), T10.init(_handles: outputs[offset10..<offset11]), T11.init(_handles: outputs[offset11..<offset12]), T12.init(_handles: outputs[offset12..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol, T10: TensorArrayProtocol, T11: TensorArrayProtocol, T12: TensorArrayProtocol, T13: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int, _ count10: Int, _ count11: Int, _ count12: Int, _ count13: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let offset10 = offset9 + count9 let offset11 = offset10 + count10 let offset12 = offset11 + count11 let offset13 = offset12 + count12 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<offset10]), T10.init(_handles: outputs[offset10..<offset11]), T11.init(_handles: outputs[offset11..<offset12]), T12.init(_handles: outputs[offset12..<offset13]), T13.init(_handles: outputs[offset13..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol, T10: TensorArrayProtocol, T11: TensorArrayProtocol, T12: TensorArrayProtocol, T13: TensorArrayProtocol, T14: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int, _ count10: Int, _ count11: Int, _ count12: Int, _ count13: Int, _ count14: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let offset10 = offset9 + count9 let offset11 = offset10 + count10 let offset12 = offset11 + count11 let offset13 = offset12 + count12 let offset14 = offset13 + count13 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<offset10]), T10.init(_handles: outputs[offset10..<offset11]), T11.init(_handles: outputs[offset11..<offset12]), T12.init(_handles: outputs[offset12..<offset13]), T13.init(_handles: outputs[offset13..<offset14]), T14.init(_handles: outputs[offset14..<outputs.count]) ) return result } } extension TFETensorHandle { public var valueDescription: String { let dtype = TFE_TensorHandleDataType(self._cTensorHandle) switch dtype { case TF_FLOAT: return Tensor(handle: TensorHandle<Float>(handle: self)).description case TF_DOUBLE: return Tensor(handle: TensorHandle<Double>(handle: self)).description case TF_BFLOAT16: return Tensor(handle: TensorHandle<BFloat16>(handle: self)).description case TF_INT64: return Tensor(handle: TensorHandle<Int64>(handle: self)).description case TF_INT32: return Tensor(handle: TensorHandle<Int32>(handle: self)).description case TF_INT16: return Tensor(handle: TensorHandle<Int16>(handle: self)).description case TF_INT8: return Tensor(handle: TensorHandle<Int8>(handle: self)).description case TF_UINT64: return Tensor(handle: TensorHandle<UInt64>(handle: self)).description case TF_UINT32: return Tensor(handle: TensorHandle<UInt32>(handle: self)).description case TF_UINT16: return Tensor(handle: TensorHandle<UInt16>(handle: self)).description case TF_UINT8: return Tensor(handle: TensorHandle<UInt8>(handle: self)).description case TF_BOOL: return Tensor(handle: TensorHandle<Bool>(handle: self)).description case TF_STRING: // TODO(https://bugs.swift.org/browse/TF-561): The current // implementation of ShapedArray<String> is not correct, which // causes seg faults. return "\"string\"" default: return TFETensorHandle.tfDataTypeAsString(dtype) } } static func tfDataTypeAsString(_ cDataType: TF_DataType) -> String { switch cDataType { case TF_FLOAT: return "float" case TF_DOUBLE: return "double" case TF_INT32: return "int32" case TF_UINT8: return "uint8" case TF_INT16: return "int16" case TF_INT8: return "int8" case TF_STRING: return "string" case TF_COMPLEX64, TF_COMPLEX: return "complex" case TF_INT64: return "int64" case TF_BOOL: return "bool" case TF_QINT8: return "qint8" case TF_QUINT8: return "quint8" case TF_QINT32: return "qint32" case TF_BFLOAT16: return "bfloat16" case TF_QINT16: return "qint16" case TF_QUINT16: return "quint16" case TF_UINT16: return "uint16" case TF_COMPLEX128: return "complex128" case TF_HALF: return "half" case TF_RESOURCE: return "resource" case TF_VARIANT: return "variant" case TF_UINT32: return "uint32" case TF_UINT64: return "uint64" default: fatalError("Unhandled type: \(cDataType)") } } } extension LazyTensorOperation.Attribute: CustomStringConvertible { var description: String { switch self { case .boolValue(let v): return "\(v)" case .intValue(let v): return "Int(\(v))" case .floatValue(let v): return "Float(\(v))" case .doubleValue(let v): return "Double(\(v))" case .stringValue(let v): return "\"\(v)\"" case .boolArray(let values): return arrayAsString("", values) case .intArray(let values): return arrayAsString("Int", values) case .floatArray(let values): return arrayAsString("Float", values) case .doubleArray(let values): return arrayAsString("Double", values) case .stringArray(let values): return arrayAsString("String", values) case .constTensor(let v): return v.valueDescription case .tensorDataTypeValue(let v): return dataTypeAsString(v) case .tensorFunctionPointer(let v): return "TFFunction(\(v.name))" case .tensorDataTypeArray(let values): let descriptions = values.map { dataTypeAsString($0) } let descString = descriptions.joined(separator: ", ") return "[\(descString)]" case .optionalTensorShape(let t): return String(describing: t) case .optionalTensorShapeArray(let t): return "\(t)" } } private func arrayAsString<T>(_ desc: String, _ values: [T]) -> String { let arrayDesc = (values.map { "\($0)" }).joined(separator: ", ") return "\(desc)[\(arrayDesc)]" } private func dataTypeAsString(_ dataType: TensorDataType) -> String { return TFETensorHandle.tfDataTypeAsString(dataType._cDataType) } } extension LazyTensorHandle: CustomStringConvertible { public var description: String { switch self.handle { case .concrete(let h, let isMaterialized): return isMaterialized ? "\(h.valueDescription)*" : "\(h.valueDescription)" case .symbolic(let op, let index, let isLive): return op.outputName(at: index) + (isLive ? "*" : "") } } } extension LazyTensorOperation: CustomStringConvertible { public var description: String { let attributesDesc = attributes.sorted(by: { $0.key < $1.key }).map { "\($0): \($1)" } let inputsDesc = inputs.map { input -> String in switch input { case Input.single(let lazyTensor): return "\(lazyTensor)" case Input.list(let lazyTensorList): let lazyTensors = lazyTensorList.map { "\($0)" } let lazyTensorsDesc = lazyTensors.joined(separator: ", ") return "[\(lazyTensorsDesc)]" } } var desc = "\(outputName) = \(name)" if !attributes.isEmpty { desc += "[" desc += attributesDesc.joined(separator: ", ") desc += "]" } desc += "(" desc += inputsDesc.joined(separator: ", ") desc += ")" return desc } } extension LazyTensorOperation { /// Returns the materialized value at the given output `index`. func materialized(index: Int) -> TFETensorHandle { precondition(index < outputCount) return materialized()[index] } /// Materializes all the outputs. func materialized() -> [TFETensorHandle] { // Return materialized outputs if any. if let outputs = outputs { return outputs } LazyTensorOperation.materialize(targets: [self]) // Our outputs should have been updated by now. Otherwise, // something terrible happened! precondition(outputs != nil, "Materialization failed!") return outputs! } /// Converts symbolic tensor inputs to concrete inputs if the associated `LazyTensorOperation` /// has been materialized. func maybeMaterializeInputs() { /// If `lazyTensor` is symbolic and the associated `LazyTensorOperation` /// has been materialized, return the corresponding concrete `LazyTensorHandle`. /// Otherwise, return `lazyTensor` untouched. func materializedAsNeeded(lazyTensor: LazyTensorHandle) -> LazyTensorHandle { let handle = lazyTensor.handle if case let .symbolic(lazyOp, index, _) = handle, let outputs = lazyOp.outputs { return LazyTensorHandle(_materialized: outputs[index]) } return lazyTensor } /// Returns an input that is rewritten such that all symbolic values /// that have been materialized have been replaced by the corresponding /// concerete inputs. If no symbolic values have been materialized or if /// there are no symbolic values, return the `input` untouched. func materializedAsNeeded(input: Input) -> Input { switch input { case .single(let h): return .single(materializedAsNeeded(lazyTensor: h)) case .list(let elements): return .list(elements.map { materializedAsNeeded(lazyTensor: $0) }) } } inputs = inputs.map { materializedAsNeeded(input: $0) } } static func materialize(targets: [LazyTensorOperation]) { let traceInfo = LazyTensorTraceBuilder.materializationTraceInfo(targets) debugLog("Extracted trace:\n\(traceInfo.trace)") let function = TFFunction(trace: traceInfo.trace) debugLog("Generated TFFunction:\n\(function)") let allOutputs = function.execute(traceInfo.concreteInputs) // Slice up the outputs to various lazy tensors var start = 0 for lazyOp in traceInfo.lazyOperations { let end = start + lazyOp.outputCount lazyOp.outputs = Array(allOutputs[start..<end]) lazyOp.outputShapes = lazyOp.outputs!.map { $0.shape } start = end } } }
apache-2.0
natecook1000/swift
test/SILGen/same_type_abstraction.swift
3
2504
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s protocol Associated { associatedtype Assoc } struct Abstracted<T: Associated, U: Associated> { let closure: (T.Assoc) -> U.Assoc } struct S1 {} struct S2 {} // CHECK-LABEL: sil hidden @$S21same_type_abstraction28callClosureWithConcreteTypes{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @$S{{.*}}TR : func callClosureWithConcreteTypes<T: Associated, U: Associated>(x: Abstracted<T, U>, arg: S1) -> S2 where T.Assoc == S1, U.Assoc == S2 { return x.closure(arg) } // Problem when a same-type constraint makes an associated type into a tuple protocol MyProtocol { associatedtype ReadData associatedtype Data func readData() -> ReadData } extension MyProtocol where Data == (ReadData, ReadData) { // CHECK-LABEL: sil hidden @$S21same_type_abstraction10MyProtocolPAA8ReadDataQz_AEt0G0RtzrlE07currentG0AE_AEtyF : $@convention(method) <Self where Self : MyProtocol, Self.Data == (Self.ReadData, Self.ReadData)> (@in_guaranteed Self) -> (@out Self.ReadData, @out Self.ReadData) func currentData() -> Data { // CHECK: bb0(%0 : @trivial $*Self.ReadData, %1 : @trivial $*Self.ReadData, %2 : @trivial $*Self): // CHECK: [[READ_FN:%.*]] = witness_method $Self, #MyProtocol.readData!1 : {{.*}} : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: apply [[READ_FN]]<Self>(%0, %2) : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: [[READ_FN:%.*]] = witness_method $Self, #MyProtocol.readData!1 : {{.*}} : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: apply [[READ_FN]]<Self>(%1, %2) : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: return return (readData(), readData()) } } // Problem with protocol typealiases, which are modeled as same-type // constraints protocol Refined : Associated { associatedtype Key typealias Assoc = Key init() } extension Refined { // CHECK-LABEL: sil hidden @$S21same_type_abstraction7RefinedPAAE12withElementsx5AssocQz_tcfC : $@convention(method) <Self where Self : Refined> (@in Self.Assoc, @thick Self.Type) -> @out Self init(withElements newElements: Key) { self.init() } }
apache-2.0
jariz/Noti
Noti/IntroViewController.swift
1
2469
// // IntroViewController.swift // Noti // // Created by Jari on 29/06/16. // Copyright © 2016 Jari Zwarts. All rights reserved. // import Cocoa class IntroViewController: NSViewController { var awc:NSWindowController?; override func viewDidAppear() { if (self.view.window != nil) { self.view.window!.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark) self.view.window!.titlebarAppearsTransparent = true; self.view.window!.isMovableByWindowBackground = true self.view.window!.invalidateShadow() } NotificationCenter.default.addObserver(self, selector: #selector(IntroViewController.authSuccess(_:)), name:NSNotification.Name(rawValue: "AuthSuccess"), object: nil) } @IBOutlet weak var authBtn:NSButton!; @IBOutlet weak var authTxt:NSTextField!; @IBOutlet weak var authImg:NSImageView!; @objc func authSuccess(_ notification: Notification) { authBtn.isEnabled = false self.authTxt.alphaValue = 1 self.authTxt.alphaValue = self.authBtn.alphaValue //self.view.window!.styleMask.subtract(NSClosableWindowMask) NSAnimationContext.runAnimationGroup({ (context) -> Void in context.duration = 0.50 self.authTxt.animator().alphaValue = 0 self.authBtn.animator().alphaValue = 0 }, completionHandler: { () -> Void in self.authTxt.isHidden = true self.authBtn.isHidden = true self.authImg.isHidden = false self.authImg.alphaValue = 0 NSAnimationContext.runAnimationGroup({ (context) -> Void in context.duration = 0.50 self.authImg.animator().alphaValue = 1 }, completionHandler: nil) }) Timer.scheduledTimer(timeInterval: 3, target: BlockOperation(block: self.view.window!.close), selector: #selector(Operation.main), userInfo: nil, repeats: false) } @IBAction func startAuth(_ sender: AnyObject) { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) awc = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "AuthWindowController")) as? NSWindowController print("showWindow") awc!.showWindow(self) } }
mit
nProdanov/FuelCalculator
Fuel economy smart calc./Fuel economy smart calc./CurrentChargeViewController.swift
1
3632
// // CurrentChargeViewController.swift // Fuel economy smart calc. // // Created by Nikolay Prodanow on 3/24/17. // Copyright © 2017 Nikolay Prodanow. All rights reserved. // import UIKit class CurrentChargeViewController: UIViewController { @IBOutlet weak var tripQuantityTextField: UITextField! @IBOutlet weak var journeyQuantityTextField: UITextField! @IBOutlet weak var gasStationNameLabel: UILabel! @IBOutlet weak var dateChargedlabel: UILabel! @IBOutlet weak var fuelChargedQuantityLabel: UILabel! @IBOutlet weak var fuelPriceLabel: UILabel! @IBOutlet weak var fuelChargedUnitLabel: UILabel! @IBOutlet weak var fuelPriceCurrencyUnitLabel: UILabel! @IBOutlet weak var fuelPriceUnitLabel: UILabel! @IBOutlet weak var tripUnitLabel: UILabel! @IBOutlet weak var journeyUnitLabel: UILabel! @IBAction func addTripToJourney() { let trip = Double(tripQuantityTextField.text!) if let currentCharge = self.currentCharge, let tripDistance = trip { self.currentCharge?.journey += tripDistance self.chargesData?.updadeCurrentCharge(with: currentCharge.journey) } tripQuantityTextField.text = "" journeyQuantityTextField.text = self.currentCharge?.journey.description dismissKeyboard() } var chargesData: BaseChargesData? var currentCharge: CurrentCharge? { didSet { self.updateUI() } } override func viewDidLoad() { super.viewDidLoad() addGestureForDismissingKeyboard() addSaveButtonToNavBar() } override func viewWillAppear(_ animated: Bool) { chargesData?.setDelegate(self) if currentCharge == nil { self.chargesData?.getCurrentCharge() } } func save() { if let currentCharge = self.currentCharge { self.chargesData?.createCharge(fromCurrentCharge: currentCharge) } } private func updateUI() { if let charge = currentCharge { gasStationNameLabel.text = charge.gasStation.fullName let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd MMMM YYYY" dateChargedlabel.text = dateFormatter.string(from: charge.chargingDate) fuelChargedQuantityLabel.text = charge.chargedFuel.description fuelChargedUnitLabel.text = charge.fuelunit fuelPriceLabel.text = charge.price.description fuelPriceCurrencyUnitLabel.text = charge.priceUnit fuelPriceUnitLabel.text = charge.fuelunit tripUnitLabel.text = charge.distanceUnit journeyUnitLabel.text = charge.distanceUnit journeyQuantityTextField.text = charge.journey.description } } private func addSaveButtonToNavBar() { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(save)) } } extension CurrentChargeViewController: ChargesDataDelegate { func didReceiveCurrentCharge(_ currentCharge: CurrentCharge?) { if currentCharge != nil { self.currentCharge = currentCharge } else { self.tabBarController?.selectedIndex = 1 } } func didCreateCharge() { self.currentCharge = nil self.chargesData?.deleteCurrentCharge() } func didReceiceDeleteCurrentCharge(){ self.tabBarController?.selectedIndex = 3 } }
mit
gerardogrisolini/Webretail
Sources/Webretail/Authentication/TurnstilePerfectRealm.swift
1
771
// // TurnstilePerfectRealm.swift // Webretail // // Created by Gerardo Grisolini on 26/02/17. // // import Turnstile import TurnstileWeb import PerfectHTTP public class TurnstilePerfectRealm { public var requestFilter: (HTTPRequestFilter, HTTPFilterPriority) public var responseFilter: (HTTPResponseFilter, HTTPFilterPriority) public let turnstile: Turnstile public init(sessionManager: SessionManager = PerfectSessionManager(), realm: Realm = CustomRealm()) { turnstile = Turnstile(sessionManager: sessionManager, realm: realm) let filter = TurnstileFilter(turnstile: turnstile) requestFilter = (filter, HTTPFilterPriority.high) responseFilter = (filter, HTTPFilterPriority.high) } }
apache-2.0
ruilin/RLMap
iphone/Maps/Categories/Bundle+Init.swift
4
203
extension Bundle { func load(viewClass: AnyClass, owner: Any? = nil, options: [AnyHashable : Any]? = nil) -> [Any]? { return loadNibNamed(toString(viewClass), owner: owner, options: options) } }
apache-2.0
roothybrid7/SharedKit
Tests/SharedKitTests/URLExtensionsTests.swift
1
1404
// // URLExtensionsTests.swift // SharedKit // // Created by Satoshi Ohki on 2016/11/20. // // import XCTest import Foundation @testable import SharedKit class URLExtensionsTests: 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() } let targets = [ (url: URL(string: "https://example.com:3000/users/sign_in?user=hoge#link1")!, expect: "https://example.com:3000"), (url: URL(string: "https://user:pass@example.com:3000/users/sign_in?user=hoge#link2")!, expect: "https://user:pass@example.com:3000"), (url: URL(fileURLWithPath: "/foo/bar/buz.png"), expect: "file://"), ] func testURL() { for target in targets { let result = target.url.origin XCTAssertNotNil(result) XCTAssertEqual(result!, target.expect) } } func testURLComponents() { for target in targets { let comps = URLComponents(url: target.url, resolvingAgainstBaseURL: false)! let result = comps.origin XCTAssertNotNil(result) XCTAssertEqual(result!, target.expect) } } }
mit
moongift/NCMBiOSGoogle
NCMBiOSGoogleTests/NCMBiOSGoogleTests.swift
1
916
// // NCMBiOSGoogleTests.swift // NCMBiOSGoogleTests // // Created by naokits on 7/15/15. // Copyright (c) 2015 Naoki Tsutsui. All rights reserved. // import UIKit import XCTest class NCMBiOSGoogleTests: 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
sempliva/Emotly-iOS
Emotly/AppDelegate.swift
1
3163
/* * The MIT License (MIT) * * Copyright (c) 2016 Emotly Contributors * * 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 @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) { EmotlyService.sharedService.updateMoods { err in // TODO: We may want to report the error to the user? if let e = err { print("Error: \(e.debugDescription)") } } } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
JGiola/swift-package-manager
Fixtures/Miscellaneous/PackageEdit/bar/Package.swift
4
236
// swift-tools-version:4.2 import PackageDescription let package = Package( name: "bar", products: [ .library(name: "bar", targets: ["bar"]), ], targets: [ .target(name: "bar", path: "Sources"), ] )
apache-2.0
CoderST/DYZB
DYZB/DYZB/Class/Room/View/ShowAnchorHeadFollowPersonCell.swift
1
1416
// // ShowAnchorHeadFollowPersonCell.swift // DYZB // // Created by xiudou on 16/11/8. // Copyright © 2016年 xiudo. All rights reserved. // import UIKit import SDWebImage // MARK:- 常量 private let iconImageViewWH :CGFloat = 30 class ShowAnchorHeadFollowPersonCell: UICollectionViewCell { // MARK:- 懒加载 fileprivate lazy var iconImageView : UIImageView = { let iconImageView = UIImageView() iconImageView.frame = CGRect(x: 0, y: 0, width: iconImageViewWH, height: iconImageViewWH) return iconImageView }() // MARK:- SET var roomFollowPerson : RoomFollowPerson?{ didSet{ guard let model = roomFollowPerson else { return } iconImageView.sd_setImage(with: URL(string: model.photo), placeholderImage: UIImage(named: "placeholder_head"), options: .allowInvalidSSLCertificates) } } // MARK:- 系统回调 override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(iconImageView) iconImageView.layer.cornerRadius = iconImageViewWH * 0.5 iconImageView.clipsToBounds = true iconImageView.layer.borderWidth = 5 iconImageView.layer.borderColor = UIColor.green.cgColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
IBM-MIL/IBM-Ready-App-for-Retail
iOS/ReadyAppRetail/ReadyAppRetail/ExternalLibraries/RLMSupport.swift
2
2892
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Realm extension RLMObject { // Swift query convenience functions public class func objectsWhere(predicateFormat: String, _ args: CVarArgType...) -> RLMResults { return objectsWithPredicate(NSPredicate(format: predicateFormat, arguments: getVaList(args))) } public class func objectsInRealm(realm: RLMRealm, _ predicateFormat: String, _ args: CVarArgType...) -> RLMResults { return objectsInRealm(realm, withPredicate:NSPredicate(format: predicateFormat, arguments: getVaList(args))) } } extension RLMArray: SequenceType { // Support Sequence-style enumeration public func generate() -> AnyGenerator<RLMObject> { var i: UInt = 0 return anyGenerator { if (i >= self.count) { return .None } else { return self[i++] as? RLMObject } } } // Swift query convenience functions public func indexOfObjectWhere(predicateFormat: String, _ args: CVarArgType...) -> UInt { return indexOfObjectWithPredicate(NSPredicate(format: predicateFormat, arguments: getVaList(args))) } public func objectsWhere(predicateFormat: String, _ args: CVarArgType...) -> RLMResults { return objectsWithPredicate(NSPredicate(format: predicateFormat, arguments: getVaList(args))) } } extension RLMResults: SequenceType { // Support Sequence-style enumeration public func generate() -> AnyGenerator<RLMObject> { var i: UInt = 0 return anyGenerator { if (i >= self.count) { return .None } else { return self[i++] as? RLMObject } } } // Swift query convenience functions public func indexOfObjectWhere(predicateFormat: String, _ args: CVarArgType...) -> UInt { return indexOfObjectWithPredicate(NSPredicate(format: predicateFormat, arguments: getVaList(args))) } public func objectsWhere(predicateFormat: String, _ args: CVarArgType...) -> RLMResults { return objectsWithPredicate(NSPredicate(format: predicateFormat, arguments: getVaList(args))) } }
epl-1.0
Marquis103/RecipeFinder
RecipeFinder/FavoriteRecipeTableViewControllerDataSource.swift
1
4137
// // FavoriteRecipeTableViewControllerDataSource.swift // RecipeFinder // // Created by Marquis Dennis on 5/11/16. // Copyright © 2016 Marquis Dennis. All rights reserved. // import UIKit import CoreData class FavoriteRecipeTableViewControllerDataSource:NSObject, UITableViewDataSource { private weak var tableView:UITableView! //data source initializer init(withTableView tableView:UITableView) { super.init() self.tableView = tableView self.tableView.dataSource = self } //MARK: UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { if let sections = fetchedResultsController.sections { return sections.count } return 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = fetchedResultsController.sections { let sectionInfo = sections[section] return sectionInfo.numberOfObjects } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("recipeCell", forIndexPath: indexPath) as! RecipeTableViewCell let recipe = fetchedResultsController.objectAtIndexPath(indexPath) as! RecipeEntity cell.userInteractionEnabled = true cell.configureCell(recipe.convertToRecipe()) return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let recipe = fetchedResultsController.objectAtIndexPath(indexPath) let coreData = CoreDataStack.defaultStack coreData.managedObjectContext.deleteObject(recipe as! NSManagedObject) do { try coreData.saveContext() } catch let error as NSError { print(error) } } } //MARK: FetchRequest func entryListFetchRequest() -> NSFetchRequest { let fetchRequest = NSFetchRequest(entityName: "RecipeEntity") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)] return fetchRequest } func performFetch() throws { do { try fetchedResultsController.performFetch() } catch let error as NSError { tableView = nil NSLog("Error during fetch\n \(error)") throw error } } //MARK: NSFetchedResultsController lazy var fetchedResultsController:NSFetchedResultsController = { let coreData = CoreDataStack.defaultStack let fetchedResultsController = NSFetchedResultsController(fetchRequest: self.entryListFetchRequest(), managedObjectContext: coreData.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController.delegate = self return fetchedResultsController }() } //MARK: NSFetchedResultsControllerDelegate extension FavoriteRecipeTableViewControllerDataSource: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(controller: NSFetchedResultsController) { tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch(type) { case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic) break case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic) break case .Update: tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic) break default: break } } func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.endUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic) break case .Delete: tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic) break default: break } } }
gpl-3.0
davecom/ClassicComputerScienceProblemsInSwift
Classic Computer Science Problems in Swift.playground/Pages/Chapter 8.xcplaygroundpage/Contents.swift
1
12013
//: [Previous](@previous) // Classic Computer Science Problems in Swift Chapter 8 Source // Copyright 2017 David Kopec // // 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 /// Knapsack struct Item { let name: String let weight: Int let value: Float } // originally based on Algorithms in C by Sedgewick, Second Edition, p 596 func knapsack(items: [Item], maxCapacity: Int) -> [Item] { //build up dynamic programming table var table: [[Float]] = [[Float]](repeating: [Float](repeating: 0.0, count: maxCapacity + 1), count: items.count + 1) //initialize table - overshooting in size for (i, item) in items.enumerated() { for capacity in 1...maxCapacity { let previousItemsValue = table[i][capacity] if capacity >= item.weight { // item fits in knapsack let valueFreeingWeightForItem = table[i][capacity - item.weight] table[i + 1][capacity] = max(valueFreeingWeightForItem + item.value, previousItemsValue) // only take if more valuable than previous combo } else { // no room for this item table[i + 1][capacity] = previousItemsValue //use prior combo } } } // figure out solution from table var solution: [Item] = [Item]() var capacity = maxCapacity for i in stride(from: items.count, to: 0, by: -1) { // work backwards if table[i - 1][capacity] != table[i][capacity] { // did we use this item? solution.append(items[i - 1]) capacity -= items[i - 1].weight // if we used an item, remove its weight } } return solution } let items = [Item(name: "television", weight: 50, value: 500), Item(name: "candlesticks", weight: 2, value: 300), Item(name: "stereo", weight: 35, value: 400), Item(name: "laptop", weight: 3, value: 1000), Item(name: "food", weight: 15, value: 50), Item(name: "clothing", weight: 20, value: 800), Item(name: "jewelry", weight: 1, value: 4000), Item(name: "books", weight: 100, value: 300), Item(name: "printer", weight: 18, value: 30), Item(name: "refrigerator", weight: 200, value: 700), Item(name: "painting", weight: 10, value: 1000)] knapsack(items: items, maxCapacity: 75) /// Travelling Salesman let vtCities = ["Rutland", "Burlington", "White River Junction", "Bennington", "Brattleboro"] let vtDistances = [ "Rutland": ["Burlington": 67, "White River Junction": 46, "Bennington": 55, "Brattleboro": 75], "Burlington": ["Rutland": 67, "White River Junction": 91, "Bennington": 122, "Brattleboro": 153], "White River Junction": ["Rutland": 46, "Burlington": 91, "Bennington": 98, "Brattleboro": 65], "Bennington": ["Rutland": 55, "Burlington": 122, "White River Junction": 98, "Brattleboro": 40], "Brattleboro": ["Rutland": 75, "Burlington": 153, "White River Junction": 65, "Bennington": 40] ] // backtracking permutations algorithm func allPermutationsHelper<T>(contents: [T], permutations: inout [[T]], n: Int) { guard n > 0 else { permutations.append(contents); return } var tempContents = contents for i in 0..<n { tempContents.swapAt(i, n - 1) // move the element at i to the end // move everything else around, holding the end constant allPermutationsHelper(contents: tempContents, permutations: &permutations, n: n - 1) tempContents.swapAt(i, n - 1) // backtrack } } // find all of the permutations of a given array func allPermutations<T>(_ original: [T]) -> [[T]] { var permutations = [[T]]() allPermutationsHelper(contents: original, permutations: &permutations, n: original.count) return permutations } // test allPermutations let abc = ["a","b","c"] let testPerms = allPermutations(abc) print(testPerms) print(testPerms.count) // make complete paths for tsp func tspPaths<T>(_ permutations: [[T]]) -> [[T]] { return permutations.map { if let first = $0.first { return ($0 + [first]) // append first to end } else { return [] // empty is just itself } } } print(tspPaths(testPerms)) func solveTSP<T>(cities: [T], distances: [T: [T: Int]]) -> (solution: [T], distance: Int) { let possiblePaths = tspPaths(allPermutations(cities)) // all potential paths var bestPath: [T] = [] // shortest path by distance var minDistance: Int = Int.max // distance of the shortest path for path in possiblePaths { if path.count < 2 { continue } // must be at least one city pair to calculate var distance = 0 var last = path.first! // we know there is one becuase of above line for next in path[1..<path.count] { // add up all pair distances distance += distances[last]![next]! last = next } if distance < minDistance { // found a new best path minDistance = distance bestPath = path } } return (solution: bestPath, distance: minDistance) } let vtTSP = solveTSP(cities: vtCities, distances: vtDistances) print("The shortest path is \(vtTSP.solution) in \(vtTSP.distance) miles.") /// Phone Number Mnemonics let phoneMapping: [Character: [Character]] = ["1": ["1"], "2": ["a", "b", "c"], "3": ["d", "e", "f"], "4": ["g", "h", "i"], "5": ["j", "k", "l"], "6": ["m", "n", "o"], "7": ["p", "q", "r", "s"], "8": ["t", "u", "v"], "9": ["w", "x", "y", "z"], "0": ["0"]] // return all of the possible characters combos, given a mapping, for a given number func stringToPossibilities(_ s: String, mapping: [Character: [Character]]) -> [[Character]]{ let possibilities = s.compactMap{ mapping[$0] } print(possibilities) return combineAllPossibilities(possibilities) } // takes a set of possible characters for each position and finds all possible permutations func combineAllPossibilities(_ possibilities: [[Character]]) -> [[Character]] { guard let possibility = possibilities.first else { return [[]] } var permutations: [[Character]] = possibility.map { [$0] } // turn each into an array for possibility in possibilities[1..<possibilities.count] where possibility != [] { let toRemove = permutations.count // temp for permutation in permutations { for c in possibility { // try adding every letter var newPermutation: [Character] = permutation // need a mutable copy newPermutation.append(c) // add character on the end permutations.append(newPermutation) // new combo ready } } permutations.removeFirst(toRemove) // remove combos missing new last letter } return permutations } let permutations = stringToPossibilities("1440787", mapping: phoneMapping) /// Tic-tac-toe enum Piece: String { case X = "X" case O = "O" case E = " " var opposite: Piece { switch self { case .X: return .O case .O: return .X case .E: return .E } } } // a move is an integer 0-8 indicating a place to put a piece typealias Move = Int struct Board { let position: [Piece] let turn: Piece let lastMove: Move // by default the board is empty and X goes first // lastMove being -1 is a marker of a start position init(position: [Piece] = [.E, .E, .E, .E, .E, .E, .E, .E, .E], turn: Piece = .X, lastMove: Int = -1) { self.position = position self.turn = turn self.lastMove = lastMove } // location can be 0-8, indicating where to move // return a new board with the move played func move(_ location: Move) -> Board { var tempPosition = position tempPosition[location] = turn return Board(position: tempPosition, turn: turn.opposite, lastMove: location) } // the legal moves in a position are all of the empty squares var legalMoves: [Move] { return position.indices.filter { position[$0] == .E } } var isWin: Bool { return position[0] == position[1] && position[0] == position[2] && position[0] != .E || // row 0 position[3] == position[4] && position[3] == position[5] && position[3] != .E || // row 1 position[6] == position[7] && position[6] == position[8] && position[6] != .E || // row 2 position[0] == position[3] && position[0] == position[6] && position[0] != .E || // col 0 position[1] == position[4] && position[1] == position[7] && position[1] != .E || // col 1 position[2] == position[5] && position[2] == position[8] && position[2] != .E || // col 2 position[0] == position[4] && position[0] == position[8] && position[0] != .E || // diag 0 position[2] == position[4] && position[2] == position[6] && position[2] != .E // diag 1 } var isDraw: Bool { return !isWin && legalMoves.count == 0 } } // Find the best possible outcome for originalPlayer func minimax(_ board: Board, maximizing: Bool, originalPlayer: Piece) -> Int { // Base case — evaluate the position if it is a win or a draw if board.isWin && originalPlayer == board.turn.opposite { return 1 } // win else if board.isWin && originalPlayer != board.turn.opposite { return -1 } // loss else if board.isDraw { return 0 } // draw // Recursive case — maximize your gains or minimize the opponent's gains if maximizing { var bestEval = Int.min for move in board.legalMoves { // find the move with the highest evaluation let result = minimax(board.move(move), maximizing: false, originalPlayer: originalPlayer) bestEval = max(result, bestEval) } return bestEval } else { // minimizing var worstEval = Int.max for move in board.legalMoves { let result = minimax(board.move(move), maximizing: true, originalPlayer: originalPlayer) worstEval = min(result, worstEval) } return worstEval } } // Run minimax on every possible move to find the best one func findBestMove(_ board: Board) -> Move { var bestEval = Int.min var bestMove = -1 for move in board.legalMoves { let result = minimax(board.move(move), maximizing: false, originalPlayer: board.turn) if result > bestEval { bestEval = result bestMove = move } } return bestMove } // win in 1 move let toWinEasyPosition: [Piece] = [.X, .O, .X, .X, .E, .O, .E, .E, .O] let testBoard1: Board = Board(position: toWinEasyPosition, turn: .X, lastMove: 8) let answer1 = findBestMove(testBoard1) print(answer1) // must block O's win let toBlockPosition: [Piece] = [.X, .E, .E, .E, .E, .O, .E, .X, .O] let testBoard2: Board = Board(position: toBlockPosition, turn: .X, lastMove: 8) let answer2 = findBestMove(testBoard2) print(answer2) // find the best move to win in 2 moves let toWinHardPosition: [Piece] = [.X, .E, .E, .E, .E, .O, .O, .X, .E] let testBoard3: Board = Board(position: toWinHardPosition, turn: .X, lastMove: 6) let answer3 = findBestMove(testBoard3) print(answer3) //: [Next](@next)
apache-2.0
sarvex/SwiftRecepies
Maps/Detecting Which Floor the User is on in a Building/Detecting Which Floor the User is on in a BuildingTests/Detecting_Which_Floor_the_User_is_on_in_a_BuildingTests.swift
1
1806
// // Detecting_Which_Floor_the_User_is_on_in_a_BuildingTests.swift // Detecting Which Floor the User is on in a BuildingTests // // Created by Vandad Nahavandipoor on 7/8/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at vandad.np@gmail.com // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 import UIKit import XCTest class Detecting_Which_Floor_the_User_is_on_in_a_BuildingTests: 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
isc
1Fr3dG/TextFormater
Sources/TFBlankLine.swift
1
591
// // TFBlankLine.swift // TextFormater // // Created by 高宇 on 2019/3/21. // import Foundation import MarkdownKit open class TFBlankLine: MarkdownCommonElement { fileprivate static let regex = "<br>|<br />" open var font: MarkdownFont? open var color: MarkdownColor? open var regex: String { return TFBlankLine.regex } public init() { } public func match(_ match: NSTextCheckingResult, attributedString: NSMutableAttributedString) { attributedString.replaceCharacters(in: match.range, with: "\n") } }
mit
taktamur/followKeyboardView
viewWithKeyboard/ViewController.swift
1
5746
// // ViewController.swift // viewWithKeyboard // // Created by 田村孝文 on 2015/08/24. // Copyright (c) 2015年 田村孝文. All rights reserved. // /* 前提: - Storyboard+AutoLayoutで配置 - キーボード追従するViewの下側に制約を配置し、この制約をアニメーションさせる。 ポイント: - キーボードの表示/非表示は、NSNotificationCenterでUIKeyboardWill{Show|Hide}Notification を監視すれば良い。 - Notificationの監視は、「ViewControllerが表示されている時」だけにするのが良い。他の画面でのキーボード表示に反応してしまう場合があるから - Notificationには「キーボード表示アニメーションの時間」と「どの位置にキーボードが表示されるのか」の情報がuserInfoに含まれるので、それを使ってAutoLayoutの制約の値をアニメーションで変化させる - AutoLayoutの制約をアニメーションさせるには、制約の値を書き換えた後、UIView.animationでlayoutIfNeed()を呼び出す - タブバーが表示されているかどうかを考慮する必要がある。ViewControllerのbottomLayoutGuide.lengthでタブバーの高さが取れるので、これを使う - もしも「テーブルビューで」これを行う場合には、UITableViewControllerは使えない。これはキーボード追従するViewを、「画面下に貼り付ける」というStoryboardが作れないから。 */ import UIKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.startObserveKeyboardNotification() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.stopOberveKeyboardNotification() } /** キーボードを閉じるIBAction */ @IBAction func tapView(sender: AnyObject) { self.textView.resignFirstResponder() } } /** キーボード追従に関連する処理をまとめたextenstion */ extension ViewController{ /** キーボードのNotificationを購読開始 */ func startObserveKeyboardNotification(){ let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector:"willShowKeyboard:", name: UIKeyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector:"willHideKeyboard:", name: UIKeyboardWillHideNotification, object: nil) } /** キーボードのNotificationの購読停止 */ func stopOberveKeyboardNotification(){ let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) notificationCenter.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } /** キーボードが開いたときに呼び出されるメソッド */ func willShowKeyboard(notification:NSNotification){ NSLog("willShowKeyboard called.") let duration = notification.duration() let rect = notification.rect() if let duration=duration,rect=rect { // ここで「self.bottomLayoutGuide.length」を使っている理由: // tabBarの表示/非表示に応じて制約の高さを変えないと、 // viewとキーボードの間にtabBar分の隙間が空いてしまうため、 // ここでtabBar分の高さを計算に含めています。 // - tabBarが表示されていない場合、self.bottomLayoutGuideは0となる // - tabBarが表示されている場合、self.bottomLayoutGuideにはtabBarの高さが入る // layoutIfNeeded()→制約を更新→UIView.animationWithDuration()の中でlayoutIfNeeded() の流れは // 以下を参考にしました。 // http://qiita.com/caesar_cat/items/051cda589afe45255d96 self.view.layoutIfNeeded() self.bottomConstraint.constant=rect.size.height - self.bottomLayoutGuide.length; UIView.animateWithDuration(duration, animations: { () -> Void in self.view.layoutIfNeeded() // ここ、updateConstraint()でも良いのかと思ったけど動かなかった。 }) } } /** キーボードが閉じたときに呼び出されるメソッド */ func willHideKeyboard(notification:NSNotification){ NSLog("willHideKeyboard called.") let duration = notification.duration() if let duration=duration { self.view.layoutIfNeeded() self.bottomConstraint.constant=0 UIView.animateWithDuration(duration,animations: { () -> Void in self.view.layoutIfNeeded() }) } } } /** キーボード表示通知の便利拡張 */ extension NSNotification{ /** 通知から「キーボードの開く時間」を取得 */ func duration()->NSTimeInterval?{ let duration:NSTimeInterval? = self.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double return duration; } /** 通知から「表示されるキーボードの表示位置」を取得 */ func rect()->CGRect?{ let rowRect:NSValue? = self.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue let rect:CGRect? = rowRect?.CGRectValue() return rect } }
mit
alessiobrozzi/firefox-ios
SharedTests/NSMutableAttributedStringExtensionsTests.swift
10
2067
/* 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 UIKit import XCTest @testable import Shared class NSMutableAttributedStringExtensionsTests: XCTestCase { fileprivate func checkCharacterAtPosition(_ position: Int, isColored color: UIColor, inString string: NSAttributedString) -> Bool { let attributes = string.attributes(at: position, effectiveRange: nil) if let foregroundColor = attributes[NSForegroundColorAttributeName] as? UIColor { if foregroundColor == color { return true } } return false } func testColorsSubstring() { let substring = "bc" let example = NSMutableAttributedString(string: "abcd") example.colorSubstring(substring, withColor: UIColor.red) XCTAssertFalse(checkCharacterAtPosition(0, isColored: UIColor.red, inString: example)) for position in 1..<3 { XCTAssertTrue(checkCharacterAtPosition(position, isColored: UIColor.red, inString: example)) } XCTAssertFalse(checkCharacterAtPosition(3, isColored: UIColor.red, inString: example)) } func testDoesNothingWithEmptySubstring() { let substring = "" let example = NSMutableAttributedString(string: "abcd") example.colorSubstring(substring, withColor: UIColor.red) for position in 0..<example.string.characters.count { XCTAssertFalse(checkCharacterAtPosition(position, isColored: UIColor.red, inString: example)) } } func testDoesNothingWhenSubstringNotFound() { let substring = "yyz" let example = NSMutableAttributedString(string: "abcd") example.colorSubstring(substring, withColor: UIColor.red) for position in 0..<example.string.characters.count { XCTAssertFalse(checkCharacterAtPosition(position, isColored: UIColor.red, inString: example)) } } }
mpl-2.0
garethknowles/JBDatePicker
JBDatePicker/Classes/JBFont.swift
2
354
// // JBFont.swift // Pods // // Created by Joost van Breukelen on 07-02-17. // // import UIKit public final class JBFont: NSObject { var fontName: String var fontSize: JBFontSize public init(name: String = "", size: JBFontSize = .medium) { self.fontName = name self.fontSize = size } }
mit
64characters/Telephone
UseCases/SystemDefaultingSoundIO.swift
1
1369
// // SystemDefaultingSoundIO.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone 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. // // Telephone 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. // import Domain public struct SystemDefaultingSoundIO { public let input: Item public let output: Item public let ringtoneOutput: Item public init(input: Item, output: Item, ringtoneOutput: Item) { self.input = input self.output = output self.ringtoneOutput = ringtoneOutput } public init(_ soundIO: SoundIO) { input = Item(soundIO.input) output = Item(soundIO.output) ringtoneOutput = Item(soundIO.ringtoneOutput) } public enum Item { case systemDefault case device(name: String) init(_ device: SystemAudioDevice) { self = device.isNil ? .systemDefault : .device(name: device.name) } } }
gpl-3.0
moozzyk/SignalR-Client-Swift
Examples/HubSamplePhone/AppDelegate.swift
1
2185
// // AppDelegate.swift // HubSamplePhone // // Created by Pawel Kadluczka on 2/11/18. // Copyright © 2018 Pawel Kadluczka. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
benlangmuir/swift
stdlib/public/core/OptionSet.swift
25
15462
//===--- OptionSet.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 // //===----------------------------------------------------------------------===// /// A type that presents a mathematical set interface to a bit set. /// /// You use the `OptionSet` protocol to represent bitset types, where /// individual bits represent members of a set. Adopting this protocol in /// your custom types lets you perform set-related operations such as /// membership tests, unions, and intersections on those types. What's more, /// when implemented using specific criteria, adoption of this protocol /// requires no extra work on your part. /// /// When creating an option set, include a `rawValue` property in your type /// declaration. For your type to automatically receive default implementations /// for set-related operations, the `rawValue` property must be of a type that /// conforms to the `FixedWidthInteger` protocol, such as `Int` or `UInt8`. /// Next, create unique options as static properties of your custom type using /// unique powers of two (1, 2, 4, 8, 16, and so forth) for each individual /// property's raw value so that each property can be represented by a single /// bit of the type's raw value. /// /// For example, consider a custom type called `ShippingOptions` that is an /// option set of the possible ways to ship a customer's purchase. /// `ShippingOptions` includes a `rawValue` property of type `Int` that stores /// the bit mask of available shipping options. The static members `nextDay`, /// `secondDay`, `priority`, and `standard` are unique, individual options. /// /// struct ShippingOptions: OptionSet { /// 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] /// } /// /// Declare additional preconfigured option set values as static properties /// initialized with an array literal containing other option values. In the /// example, because the `express` static property is assigned an array /// literal with the `nextDay` and `secondDay` options, it will contain those /// two elements. /// /// Using an Option Set Type /// ======================== /// /// When you need to create an instance of an option set, assign one of the /// type's static members to your variable or constant. Alternatively, to /// create an option set instance with multiple members, assign an array /// literal with multiple static members of the option set. To create an empty /// instance, assign an empty array literal to your variable. /// /// let singleOption: ShippingOptions = .priority /// let multipleOptions: ShippingOptions = [.nextDay, .secondDay, .priority] /// let noOptions: ShippingOptions = [] /// /// Use set-related operations to check for membership and to add or remove /// members from an instance of your custom option set type. The following /// example shows how you can determine free shipping options based on a /// customer's purchase price: /// /// let purchasePrice = 87.55 /// /// var freeOptions: ShippingOptions = [] /// if purchasePrice > 50 { /// freeOptions.insert(.priority) /// } /// /// if freeOptions.contains(.priority) { /// print("You've earned free priority shipping!") /// } else { /// print("Add more to your cart for free priority shipping!") /// } /// // Prints "You've earned free priority shipping!" public protocol OptionSet: SetAlgebra, RawRepresentable { // We can't constrain the associated Element type to be the same as // Self, but we can do almost as well with a default and a // constrained extension /// The element type of the option set. /// /// To inherit all the default implementations from the `OptionSet` protocol, /// the `Element` type must be `Self`, the default. associatedtype Element = Self // FIXME: This initializer should just be the failable init from // RawRepresentable. Unfortunately, current language limitations // that prevent non-failable initializers from forwarding to // failable ones would prevent us from generating the non-failing // default (zero-argument) initializer. Since OptionSet's main // purpose is to create convenient conformances to SetAlgebra, // we opt for a non-failable initializer. /// Creates a new option set from the given raw value. /// /// This initializer always succeeds, even if the value passed as `rawValue` /// exceeds the static properties declared as part of the option set. This /// example creates an instance of `ShippingOptions` with a raw value beyond /// the highest element, with a bit mask that effectively contains all the /// declared static members. /// /// let extraOptions = ShippingOptions(rawValue: 255) /// print(extraOptions.isStrictSuperset(of: .all)) /// // Prints "true" /// /// - Parameter rawValue: The raw value of the option set to create. Each bit /// of `rawValue` potentially represents an element of the option set, /// though raw values may include bits that are not defined as distinct /// values of the `OptionSet` type. init(rawValue: RawValue) } /// `OptionSet` requirements for which default implementations /// are supplied. /// /// - Note: A type conforming to `OptionSet` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSet { /// Returns a new option set of the elements contained in this set, in the /// given set, or in both. /// /// This example uses the `union(_:)` method to add two more shipping options /// to the default set. /// /// let defaultShipping = ShippingOptions.standard /// let memberShipping = defaultShipping.union([.secondDay, .priority]) /// print(memberShipping.contains(.priority)) /// // Prints "true" /// /// - Parameter other: An option set. /// - Returns: A new option set made up of the elements contained in this /// set, in `other`, or in both. @inlinable // generic-performance public func union(_ other: Self) -> Self { var r: Self = Self(rawValue: self.rawValue) r.formUnion(other) return r } /// Returns a new option set with only the elements contained in both this /// set and the given set. /// /// This example uses the `intersection(_:)` method to limit the available /// shipping options to what can be used with a PO Box destination. /// /// // Can only ship standard or priority to PO Boxes /// let poboxShipping: ShippingOptions = [.standard, .priority] /// let memberShipping: ShippingOptions = /// [.standard, .priority, .secondDay] /// /// let availableOptions = memberShipping.intersection(poboxShipping) /// print(availableOptions.contains(.priority)) /// // Prints "true" /// print(availableOptions.contains(.secondDay)) /// // Prints "false" /// /// - Parameter other: An option set. /// - Returns: A new option set with only the elements contained in both this /// set and `other`. @inlinable // generic-performance public func intersection(_ other: Self) -> Self { var r = Self(rawValue: self.rawValue) r.formIntersection(other) return r } /// Returns a new option set with the elements contained in this set or in /// the given set, but not in both. /// /// - Parameter other: An option set. /// - Returns: A new option set with only the elements contained in either /// this set or `other`, but not in both. @inlinable // generic-performance public func symmetricDifference(_ other: Self) -> Self { var r = Self(rawValue: self.rawValue) r.formSymmetricDifference(other) return r } } /// `OptionSet` requirements for which default implementations are /// supplied when `Element == Self`, which is the default. /// /// - Note: A type conforming to `OptionSet` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSet where Element == Self { /// Returns a Boolean value that indicates whether a given element is a /// member of the option set. /// /// This example uses the `contains(_:)` method to check whether next-day /// shipping is in the `availableOptions` instance. /// /// let availableOptions = ShippingOptions.express /// if availableOptions.contains(.nextDay) { /// print("Next day shipping available") /// } /// // Prints "Next day shipping available" /// /// - Parameter member: The element to look for in the option set. /// - Returns: `true` if the option set contains `member`; otherwise, /// `false`. @inlinable // generic-performance public func contains(_ member: Self) -> Bool { return self.isSuperset(of: member) } /// Adds the given element to the option set if it is not already a member. /// /// In the following example, the `.secondDay` shipping option is added to /// the `freeOptions` option set if `purchasePrice` is greater than 50.0. For /// the `ShippingOptions` declaration, see the `OptionSet` protocol /// discussion. /// /// let purchasePrice = 87.55 /// /// var freeOptions: ShippingOptions = [.standard, .priority] /// if purchasePrice > 50 { /// freeOptions.insert(.secondDay) /// } /// print(freeOptions.contains(.secondDay)) /// // Prints "true" /// /// - Parameter newMember: The element to insert. /// - Returns: `(true, newMember)` if `newMember` was not contained in /// `self`. Otherwise, returns `(false, oldMember)`, where `oldMember` is /// the member of the set equal to `newMember`. @inlinable // generic-performance @discardableResult public mutating func insert( _ newMember: Element ) -> (inserted: Bool, memberAfterInsert: Element) { let oldMember = self.intersection(newMember) let shouldInsert = oldMember != newMember let result = ( inserted: shouldInsert, memberAfterInsert: shouldInsert ? newMember : oldMember) if shouldInsert { self.formUnion(newMember) } return result } /// Removes the given element and all elements subsumed by it. /// /// In the following example, the `.priority` shipping option is removed from /// the `options` option set. Attempting to remove the same shipping option /// a second time results in `nil`, because `options` no longer contains /// `.priority` as a member. /// /// var options: ShippingOptions = [.secondDay, .priority] /// let priorityOption = options.remove(.priority) /// print(priorityOption == .priority) /// // Prints "true" /// /// print(options.remove(.priority)) /// // Prints "nil" /// /// In the next example, the `.express` element is passed to `remove(_:)`. /// Although `.express` is not a member of `options`, `.express` subsumes /// the remaining `.secondDay` element of the option set. Therefore, /// `options` is emptied and the intersection between `.express` and /// `options` is returned. /// /// let expressOption = options.remove(.express) /// print(expressOption == .express) /// // Prints "false" /// print(expressOption == .secondDay) /// // Prints "true" /// /// - Parameter member: The element of the set to remove. /// - Returns: The intersection of `[member]` and the set, if the /// intersection was nonempty; otherwise, `nil`. @inlinable // generic-performance @discardableResult public mutating func remove(_ member: Element) -> Element? { let intersectionElements = intersection(member) guard !intersectionElements.isEmpty else { return nil } self.subtract(member) return intersectionElements } /// Inserts the given element into the set. /// /// If `newMember` is not contained in the set but subsumes current members /// of the set, the subsumed members are returned. /// /// var options: ShippingOptions = [.secondDay, .priority] /// let replaced = options.update(with: .express) /// print(replaced == .secondDay) /// // Prints "true" /// /// - Returns: The intersection of `[newMember]` and the set if the /// intersection was nonempty; otherwise, `nil`. @inlinable // generic-performance @discardableResult public mutating func update(with newMember: Element) -> Element? { let r = self.intersection(newMember) self.formUnion(newMember) return r.isEmpty ? nil : r } } /// `OptionSet` requirements for which default implementations are /// supplied when `RawValue` conforms to `FixedWidthInteger`, /// which is the usual case. Each distinct bit of an option set's /// `.rawValue` corresponds to a disjoint value of the `OptionSet`. /// /// - `union` is implemented as a bitwise "or" (`|`) of `rawValue`s /// - `intersection` is implemented as a bitwise "and" (`&`) of /// `rawValue`s /// - `symmetricDifference` is implemented as a bitwise "exclusive or" /// (`^`) of `rawValue`s /// /// - Note: A type conforming to `OptionSet` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSet where RawValue: FixedWidthInteger { /// Creates an empty option set. /// /// This initializer creates an option set with a raw value of zero. @inlinable // generic-performance public init() { self.init(rawValue: 0) } /// Inserts the elements of another set into this option set. /// /// This method is implemented as a `|` (bitwise OR) operation on the /// two sets' raw values. /// /// - Parameter other: An option set. @inlinable // generic-performance public mutating func formUnion(_ other: Self) { self = Self(rawValue: self.rawValue | other.rawValue) } /// Removes all elements of this option set that are not /// also present in the given set. /// /// This method is implemented as a `&` (bitwise AND) operation on the /// two sets' raw values. /// /// - Parameter other: An option set. @inlinable // generic-performance public mutating func formIntersection(_ other: Self) { self = Self(rawValue: self.rawValue & other.rawValue) } /// Replaces this set with a new set containing all elements /// contained in either this set or the given set, but not in both. /// /// This method is implemented as a `^` (bitwise XOR) operation on the two /// sets' raw values. /// /// - Parameter other: An option set. @inlinable // generic-performance public mutating func formSymmetricDifference(_ other: Self) { self = Self(rawValue: self.rawValue ^ other.rawValue) } }
apache-2.0
malaonline/iOS
mala-ios/Model/Course/MemberServiceModel.swift
1
1117
// // MemberServiceModel.swift // mala-ios // // Created by Elors on 1/12/16. // Copyright © 2016 Mala Online. All rights reserved. // import UIKit class MemberServiceModel: BaseObjectModel { // MARK: - Property var detail: String? var enbaled: Bool = false // MARK: - Constructed override init() { super.init() } override init(dict: [String: Any]) { super.init(dict: dict) setValuesForKeys(dict) } convenience init(name: String?, detail: String?) { self.init() self.name = name self.detail = detail } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Override override func setValue(_ value: Any?, forUndefinedKey key: String) { println("SchoolModel - Set for UndefinedKey: \(key)") } // MARK: - Description override var description: String { let keys = ["detail", "enbaled"] return super.description + dictionaryWithValues(forKeys: keys).description } }
mit
marcelganczak/swift-js-transpiler
test/binary-expression/custom-operators.swift
1
1412
prefix operator +++ infix operator +-: AdditionPrecedence struct Vector2D { var x = 0, y = 0 static func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } static prefix func - (vector: Vector2D) -> Vector2D { return Vector2D(x: -vector.x, y: -vector.y) } static func += (left: inout Vector2D, right: Vector2D) { left = left + right } static prefix func +++ (vector: inout Vector2D) -> Vector2D { vector += vector return vector } static func +- (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y - right.y) } } let vector = Vector2D(x: 3, y: 1) let anotherVector = Vector2D(x: 2, y: 4) let combinedVector = vector + anotherVector print(combinedVector.x) print(combinedVector.y) let inverseCombinedVector = -combinedVector print(inverseCombinedVector.x) print(inverseCombinedVector.y) var original = Vector2D(x: 1, y: 2) let vectorToAdd = Vector2D(x: 3, y: 4) original += vectorToAdd print(original.x) print(original.y) var toBeDoubled = Vector2D(x: 1, y: 4) let afterDoubling = +++toBeDoubled print(afterDoubling.x) print(afterDoubling.y) let firstVector = Vector2D(x: 1, y: 2) let secondVector = Vector2D(x: 3, y: 4) let plusMinusVector = firstVector +- secondVector print(plusMinusVector.x) print(plusMinusVector.y)
mit
trifl/TKit
Pod/Classes/TKTimer.swift
1
1395
import Foundation open class TKTimer { open var fps = 60.0 fileprivate var initialDate: Date! fileprivate var timer = Timer() fileprivate var timeFunction: ((Double) -> Bool)? fileprivate var duration = 0.0 fileprivate var usesDuration = false public init(fps: Double) { self.fps = fps } open func fire(_ function:@escaping (_ time: Double) -> Bool) { fire(function, duration: 0) usesDuration = false } open func fire(_ function:@escaping (_ time: Double) -> Bool, duration: TimeInterval) { invalidate() timeFunction = function initialDate = Date() self.duration = duration timer = Timer.scheduledTimer( timeInterval: 1.0 / fps, target: self, selector: Selector(("fireTimeFunction")), userInfo: nil, repeats: true ) } open func invalidate() { timer.invalidate() duration = 0.0 usesDuration = true } fileprivate func fireTimeFunction() { if let timeFunction = timeFunction { var time = Date().timeIntervalSince(initialDate) // This makes sure it always ends at duration where you are intending it to end, unless // explicitly stopped if usesDuration { time = min(time, duration) } let stop = !timeFunction(time) if stop || (usesDuration && time == duration) { invalidate() } } } }
mit
steelwheels/KiwiControls
UnitTest/OSX/UTTerminal/TerminalViewController.swift
1
3341
/* * @file TerminalViewController.swift * @brief Define TerminalViewController class * @par Copyright * Copyright (C) 2020 Steel Wheels Project */ import KiwiControls import CoconutData import CoconutShell import Foundation open class UTShellThread: CNShellThread { public var terminalView: KCTerminalView? = nil open override func execute(command cmd: String) { #if false CNExecuteInMainThread(doSync: true, execute: { () -> Void in if let view = self.terminalView { let offset = view.verticalOffset() self.console.print(string: "vOffset = \(offset)\n") } }) #endif } } public class TerminalViewController: KCSingleViewController { private var mTerminalView: KCTerminalView? = nil private var mShell: UTShellThread? = nil open override func loadContext() -> KCView? { let termview = KCTerminalView() /* Allocate shell */ CNLog(logLevel: .detail, message: "Launch terminal") let procmgr : CNProcessManager = CNProcessManager() let infile : CNFile = termview.inputFile let outfile : CNFile = termview.outputFile let errfile : CNFile = termview.errorFile let terminfo = CNTerminalInfo(width: 80, height: 25) let environment = CNEnvironment() CNLog(logLevel: .detail, message: "Allocate shell") let shell = UTShellThread(processManager: procmgr, input: infile, output: outfile, error: errfile, terminalInfo: terminfo, environment: environment) mShell = shell shell.terminalView = termview mTerminalView = termview #if true let box = KCStackView() box.axis = .vertical box.addArrangedSubView(subView: termview) return box #else return termview #endif } public override func viewDidAppear() { super.viewDidAppear() guard let termview = mTerminalView else { CNLog(logLevel: .error, message: "No terminal view") return } /* Start shell */ if let shell = mShell { CNLog(logLevel: .detail, message: "Start shell") shell.start(argument: .nullValue) } /* Receive key input */ let infile = termview.inputFile let outfile = termview.outputFile let errfile = termview.errorFile /* Print to output */ let red = CNEscapeCode.foregroundColor(CNColor.red).encode() outfile.put(string: red + "Red\n") let blue = CNEscapeCode.foregroundColor(CNColor.blue).encode() outfile.put(string: blue + "Blue\n") let green = CNEscapeCode.foregroundColor(CNColor.green).encode() outfile.put(string: green + "Green\n") let reset = CNEscapeCode.resetCharacterAttribute.encode() let under = CNEscapeCode.underlineCharacter(true).encode() outfile.put(string: reset + under + "Underline\n") let bold = CNEscapeCode.boldCharacter(true).encode() outfile.put(string: bold + "Bold\n" + reset) let terminfo = termview.terminalInfo //let width = terminfo.width //let height = terminfo.height let console = CNFileConsole(input: infile, output: outfile, error: errfile) let curses = CNCurses(console: console, terminalInfo: terminfo) curses.begin() curses.fill(x: 0, y: 0, width: terminfo.width, height: terminfo.height, char: "x") /* for i in 0..<10 { curses.moveTo(x: i, y: i) curses.put(string: "o") } for x in 0..<width { curses.moveTo(x: x, y: 0) console.print(string: "+") curses.moveTo(x: x, y: height-1) console.print(string: "+") }*/ } }
lgpl-2.1
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBAProfileInfoForm.swift
1
14551
// // SBARegistrationForm.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit public enum SBAProfileInfoOption : String { case email = "email" case password = "password" case externalID = "externalID" case name = "name" case birthdate = "birthdate" case gender = "gender" } enum SBAProfileInfoOptionsError: Error { case missingRequiredOptions case missingEmail case missingExternalID case missingName case notConsented case unrecognizedSurveyItemType } struct SBAExternalIDOptions { static let defaultAutocapitalizationType: UITextAutocapitalizationType = .allCharacters static let defaultKeyboardType: UIKeyboardType = .asciiCapable let autocapitalizationType: UITextAutocapitalizationType let keyboardType: UIKeyboardType init() { self.autocapitalizationType = SBAExternalIDOptions.defaultAutocapitalizationType self.keyboardType = SBAExternalIDOptions.defaultKeyboardType } init(autocapitalizationType: UITextAutocapitalizationType, keyboardType: UIKeyboardType) { self.autocapitalizationType = autocapitalizationType self.keyboardType = keyboardType } init(options: [AnyHashable: Any]?) { self.autocapitalizationType = { if let autocap = options?["autocapitalizationType"] as? String { return UITextAutocapitalizationType(key: autocap) } else { return SBAExternalIDOptions.defaultAutocapitalizationType } }() self.keyboardType = { if let keyboard = options?["keyboardType"] as? String { return UIKeyboardType(key: keyboard) } else { return SBAExternalIDOptions.defaultKeyboardType } }() } } public struct SBAProfileInfoOptions { public let includes: [SBAProfileInfoOption] public let customOptions: [Any] let externalIDOptions: SBAExternalIDOptions public init(includes: [SBAProfileInfoOption]) { self.includes = includes self.externalIDOptions = SBAExternalIDOptions() self.customOptions = [] } init(externalIDOptions: SBAExternalIDOptions) { self.includes = [.externalID] self.externalIDOptions = externalIDOptions self.customOptions = [] } public init?(inputItem: SBASurveyItem?) { guard let surveyForm = inputItem as? SBAFormStepSurveyItem, let items = surveyForm.items else { return nil } // Map the includes, and if it is an external ID then also map the keyboard options var externalIDOptions = SBAExternalIDOptions(autocapitalizationType: .none, keyboardType: .default) var customOptions: [Any] = [] self.includes = items.mapAndFilter({ (obj) -> SBAProfileInfoOption? in if let str = obj as? String { return SBAProfileInfoOption(rawValue: str) } else if let dictionary = obj as? [String : AnyObject], let identifier = dictionary["identifier"] as? String, let option = SBAProfileInfoOption(rawValue: identifier) { if option == .externalID { externalIDOptions = SBAExternalIDOptions(options: dictionary) } return option } else { customOptions.append(obj) } return nil }) self.externalIDOptions = externalIDOptions self.customOptions = customOptions } func makeFormItems(surveyItemType: SBASurveyItemType) -> [ORKFormItem] { var formItems: [ORKFormItem] = [] for option in self.includes { switch option { case .email: let formItem = makeEmailFormItem(option) formItems.append(formItem) case .password: let (formItem, answerFormat) = makePasswordFormItem(option) formItems.append(formItem) // confirmation if (surveyItemType == .account(.registration)) { let confirmFormItem = makeConfirmationFormItem(formItem, answerFormat: answerFormat) formItems.append(confirmFormItem) } case .externalID: let formItem = makeExternalIDFormItem(option) formItems.append(formItem) case .name: let formItem = makeNameFormItem(option) formItems.append(formItem) case .birthdate: let formItem = makeBirthdateFormItem(option) formItems.append(formItem) case .gender: let formItem = makeGenderFormItem(option) formItems.append(formItem) } } return formItems } func makeEmailFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let answerFormat = ORKAnswerFormat.emailAnswerFormat() let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("EMAIL_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("EMAIL_FORM_ITEM_PLACEHOLDER") return formItem } func makePasswordFormItem(_ option: SBAProfileInfoOption) -> (ORKFormItem, ORKTextAnswerFormat) { let answerFormat = ORKAnswerFormat.textAnswerFormat() answerFormat.multipleLines = false answerFormat.isSecureTextEntry = true answerFormat.autocapitalizationType = .none answerFormat.autocorrectionType = .no answerFormat.spellCheckingType = .no let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("PASSWORD_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("PASSWORD_FORM_ITEM_PLACEHOLDER") return (formItem, answerFormat) } func makeConfirmationFormItem(_ formItem: ORKFormItem, answerFormat: ORKTextAnswerFormat) -> ORKFormItem { // If this is a registration, go ahead and set the default password verification let minLength = SBARegistrationStep.defaultPasswordMinLength let maxLength = SBARegistrationStep.defaultPasswordMaxLength answerFormat.validationRegex = "[[:ascii:]]{\(minLength),\(maxLength)}" answerFormat.invalidMessage = Localization.localizedStringWithFormatKey("SBA_REGISTRATION_INVALID_PASSWORD_LENGTH_%@_TO_%@", NSNumber(value: minLength), NSNumber(value: maxLength)) // Add a confirmation field let confirmIdentifier = SBARegistrationStep.confirmationIdentifier let confirmText = Localization.localizedString("CONFIRM_PASSWORD_FORM_ITEM_TITLE") let confirmError = Localization.localizedString("CONFIRM_PASSWORD_ERROR_MESSAGE") let confirmFormItem = formItem.confirmationAnswer(withIdentifier: confirmIdentifier, text: confirmText, errorMessage: confirmError) confirmFormItem.placeholder = Localization.localizedString("CONFIRM_PASSWORD_FORM_ITEM_PLACEHOLDER") return confirmFormItem } func makeExternalIDFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let answerFormat = ORKAnswerFormat.textAnswerFormat() answerFormat.multipleLines = false answerFormat.autocapitalizationType = self.externalIDOptions.autocapitalizationType answerFormat.autocorrectionType = .no answerFormat.spellCheckingType = .no answerFormat.keyboardType = self.externalIDOptions.keyboardType let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("SBA_REGISTRATION_EXTERNALID_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("SBA_REGISTRATION_EXTERNALID_PLACEHOLDER") return formItem } func makeNameFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let answerFormat = ORKAnswerFormat.textAnswerFormat() answerFormat.multipleLines = false answerFormat.autocapitalizationType = .words answerFormat.autocorrectionType = .no answerFormat.spellCheckingType = .no answerFormat.keyboardType = .default let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("SBA_REGISTRATION_FULLNAME_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("SBA_REGISTRATION_FULLNAME_PLACEHOLDER") return formItem } func makeBirthdateFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { // Calculate default date (20 years old). let defaultDate = (Calendar.current as NSCalendar).date(byAdding: .year, value: -20, to: Date(), options: NSCalendar.Options(rawValue: 0)) let answerFormat = ORKAnswerFormat.dateAnswerFormat(withDefaultDate: defaultDate, minimumDate: nil, maximumDate: Date(), calendar: Calendar.current) let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("DOB_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("DOB_FORM_ITEM_PLACEHOLDER") return formItem } func makeGenderFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let textChoices: [ORKTextChoice] = [ ORKTextChoice(text: Localization.localizedString("GENDER_FEMALE"), value: HKBiologicalSex.female.rawValue as NSNumber), ORKTextChoice(text: Localization.localizedString("GENDER_MALE"), value: HKBiologicalSex.male.rawValue as NSNumber), ORKTextChoice(text: Localization.localizedString("GENDER_OTHER"), value: HKBiologicalSex.other.rawValue as NSNumber), ] let answerFormat = ORKValuePickerAnswerFormat(textChoices: textChoices) let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("GENDER_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("GENDER_FORM_ITEM_PLACEHOLDER") return formItem } } public protocol SBAFormProtocol : class { var identifier: String { get } var title: String? { get set } var text: String? { get set } var formItems: [ORKFormItem]? { get set } init(identifier: String) } extension SBAFormProtocol { public func formItemForIdentifier(_ identifier: String) -> ORKFormItem? { return self.formItems?.find({ $0.identifier == identifier }) } } extension ORKFormStep: SBAFormProtocol { } public protocol SBAProfileInfoForm : SBAFormProtocol { var surveyItemType: SBASurveyItemType { get } func defaultOptions(_ inputItem: SBASurveyItem?) -> [SBAProfileInfoOption] } extension SBAProfileInfoForm { public var options: [SBAProfileInfoOption]? { return self.formItems?.mapAndFilter({ SBAProfileInfoOption(rawValue: $0.identifier) }) } public func formItemForProfileInfoOption(_ profileInfoOption: SBAProfileInfoOption) -> ORKFormItem? { return self.formItems?.find({ $0.identifier == profileInfoOption.rawValue }) } func commonInit(_ inputItem: SBASurveyItem?) { self.title = inputItem?.stepTitle self.text = inputItem?.stepText if let formStep = self as? ORKFormStep { formStep.footnote = inputItem?.stepFootnote } let options = SBAProfileInfoOptions(inputItem: inputItem) ?? SBAProfileInfoOptions(includes: defaultOptions(inputItem)) self.formItems = options.makeFormItems(surveyItemType: self.surveyItemType) } }
bsd-3-clause
p7s1-ctf/7pass-ios-sample
7pass-ios-sample/Util.swift
2
971
// // Util.swift // SevenPass // // Created by Jan Votava on 26/01/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit func showAlert(title: String, message: String) { if let topController = UIApplication.shared.keyWindow?.rootViewController { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) // Delay alert by 0.5s, so it doesn't collide with a WebView presentation let dispatchTime = DispatchTime.now() + Double(500000000) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: { topController.present(alertController, animated: true, completion: nil) }) } } func errorHandler(_ error: NSError) { showAlert(title: "Error", message: error.localizedDescription) }
mit
i-schuetz/SwiftCharts
Examples/Examples/NotificationsExample.swift
1
6128
// // NotificationsExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class NotificationsExample: UIViewController { fileprivate var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let chartPoints: [ChartPoint] = [(1, 3), (2, 4), (4, 1), (5, 6), (6, 4), (7, 9), (8, 0), (10, 4), (12, 2)].map{ChartPoint(x: ChartAxisValueInt($0.0, labelSettings: labelSettings), y: ChartAxisValueInt($0.1))} let xValues = chartPoints.map{$0.x} let yValues = ChartAxisValuesStaticGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false) let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.red, animDuration: 1, animDelay: 0) let notificationViewWidth: CGFloat = Env.iPad ? 30 : 20 let notificationViewHeight: CGFloat = Env.iPad ? 30 : 20 let notificationGenerator = {[weak self] (chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in let (chartPoint, screenLoc) = (chartPointModel.chartPoint, chartPointModel.screenLoc) if chartPoint.y.scalar <= 1 { let chartPointView = HandlingView(frame: CGRect(x: screenLoc.x + 5, y: screenLoc.y - notificationViewHeight - 5, width: notificationViewWidth, height: notificationViewHeight)) let label = UILabel(frame: chartPointView.bounds) label.layer.cornerRadius = Env.iPad ? 15 : 10 label.clipsToBounds = true label.backgroundColor = UIColor.red label.textColor = UIColor.white label.textAlignment = NSTextAlignment.center label.font = UIFont.boldSystemFont(ofSize: Env.iPad ? 22 : 18) label.text = "!" chartPointView.addSubview(label) label.transform = CGAffineTransform(scaleX: 0, y: 0) chartPointView.movedToSuperViewHandler = { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: UIView.AnimationOptions(), animations: { label.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: nil) } chartPointView.touchHandler = { let title = "Lorem" let message = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua." let ok = "Ok" if #available(iOS 8.0, *) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: ok, style: UIAlertAction.Style.default, handler: nil)) self!.present(alert, animated: true, completion: nil) } else { let alert = UIAlertView() alert.title = title alert.message = message alert.addButton(withTitle: ok) alert.show() } } return chartPointView } return nil } let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let chartFrame = ExamplesDefaults.chartFrame(view.bounds) let chartSettings = ExamplesDefaults.chartSettingsWithPanZoom let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame) let chartPointsNotificationsLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPoints, viewGenerator: notificationGenerator, displayDelay: 1, mode: .custom) // To preserve the offset of the notification views from the chart point they represent, during transforms, we need to pass mode: .custom along with this custom transformer. chartPointsNotificationsLayer.customTransformer = {(model, view, layer) -> Void in let screenLoc = layer.modelLocToScreenLoc(x: model.chartPoint.x.scalar, y: model.chartPoint.y.scalar) view.frame.origin = CGPoint(x: screenLoc.x + 5, y: screenLoc.y - notificationViewHeight - 5) } let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, lineModels: [lineModel]) let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, settings: settings) let chart = Chart( frame: chartFrame, innerFrame: innerFrame, settings: chartSettings, layers: [ xAxisLayer, yAxisLayer, guidelinesLayer, chartPointsLineLayer, chartPointsNotificationsLayer] ) view.addSubview(chart.view) self.chart = chart } }
apache-2.0
saagarjha/Swimat
CLI/OptionParser.swift
2
3520
import Foundation struct Option { let options: [String] let helpArguments: String let helpText: String let number: Int let setter: ([String]) -> Void } class Options { static var shared = Options() var recursive = false var verbose = false init() { Indent.char = "\t" } static let options: [Option] = [ Option(options: ["-h", "--help"], helpArguments: "", helpText: "Display this help message.", number: 0, setter: { _ in printHeader() printOptions() exit(.success) }), Option(options: ["-i", "--indent"], helpArguments: "<value>=-1", helpText: "Set the number of spaces to indent; use -1 for tabs.", number: 1, setter: { indentSize in guard indentSize.count == 1, let indentSize = Int(indentSize[0]) else { printToError("Invalid indent size") exit(.invalidIndent) } if indentSize < 0 { Indent.char = "\t" } else { Indent.char = String(repeating: " ", count: indentSize) } }), Option(options: ["-r", "--recursive"], helpArguments: "", helpText: "Search and format directories recursively.", number: 0, setter: { _ in shared.recursive = true }), Option(options: ["-v", "--verbose"], helpArguments: "", helpText: "Enable verbose output.", number: 0, setter: { _ in shared.verbose = true }) ] static func printHeader() { printToError("The Swimat Swift formatter") printToError() printToError("USAGE: swimat [options] <inputs...>") printToError() printToError("OPTIONS:") } static func printOptions() { for option in options { let optionsString = " \(option.options.joined(separator: ", ")) \(option.helpArguments)" .padding(toLength: 25, withPad: " ", startingAt: 0) printToError("\(optionsString)\(option.helpText)") } } func parseArguments(_ arguments: [String]) -> [String] { if arguments.isEmpty { Options.printHeader() Options.printOptions() exit(.noArguments) } var files = [String]() var i = 0 while i < arguments.count { let argument = arguments[i] i += 1 if argument.hasPrefix("-") { var validOption = false for option in Options.options { if option.options.contains(argument) { let startIndex = min(i, arguments.count) let endIndex = min(i + option.number, arguments.count) option.setter(Array(arguments[startIndex..<endIndex])) i = endIndex validOption = true } } if !validOption { printToError("Invalid option \(argument). Valid options are:") Options.printOptions() exit(.invalidOption) } } else { files.append(argument) } } return files } }
mit
muvetian/acquaintest00
ChatRoom/ChatRoom/LoginController+handlers.swift
1
3925
// // LoginController+handlers.swift // ChatRoom // // Created by Binwei Xu on 3/23/17. // Copyright © 2017 Binwei Xu. All rights reserved. // import UIKit import Firebase extension LoginController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func handleRegister() { guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text else { print("Form is not valid") return } FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in if error != nil { print(error) return } guard let uid = user?.uid else { return } // upload image to firebase storage using the reference let imageName = NSUUID().uuidString //gives a unique string // add more child directory to reconstruct the storage space let storageRef = FIRStorage.storage().reference().child("profile_images").child("\(imageName).png") if let profileImage = self.profileImageView.image, let uploadData = UIImageJPEGRepresentation(profileImage, 0.1) { storageRef.put(uploadData, metadata: nil, completion: { (metadata, error) in //metadata is description of the data uploaded if error != nil { print(error) return } if let profileImageUrl = metadata?.downloadURL()?.absoluteString { let values = ["name": name, "email": email, "profileImageUrl": profileImageUrl] self.registerUserIntoDatabaseWithUID(uid: uid, values: values) } }) } }) } private func registerUserIntoDatabaseWithUID(uid : String, values: [String: Any]) { //successfully authenticated user let ref = FIRDatabase.database().reference(fromURL: "https://chatroom-29e51.firebaseio.com/") let usersReference = ref.child("users").child(uid) usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in if err != nil { print(err) return } //update nav bar title let user = User() //this setter potentially crash if keys don't match the model User's user.setValuesForKeys(values) self.messagesController?.setupNavBarWithUser(user: user) self.dismiss(animated: true, completion: nil) }) } func handleSelectProfileImage() { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = true present(picker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { var selectedImageFromPicker: UIImage? if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage { selectedImageFromPicker = editedImage } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { selectedImageFromPicker = originalImage } if let selectedImage = selectedImageFromPicker { profileImageView.image = selectedImage } dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } }
mit
malt03/Balblair
Balblair/Core/Classes/BalblairHeader.swift
1
185
// // BalblairHeader.swift // Pods // // Created by Koji Murata on 2016/08/25. // // import Foundation public protocol BalblairHeaderBuilder { func build() -> [String: String] }
mit
mamouneyya/TheSkillsProof
SouqTask/Modules/Tutorial/Controllers/TutorialViewController.swift
1
3898
// // TutorialViewController.swift // SouqTask // // Created by Ma'moun Diraneyya on 3/7/16. // Copyright © 2016 Mamouneyya. All rights reserved. // import UIKit class TutorialViewController: BaseViewController { // MARK: - Outlets @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var actionButton: UIButton! // MARK: - Public Vars /// Active step to use for filling current screen's data. var activeStep = TutorialStep.StepOne // MARK: - Private Vars /// Tutorial manager object, to get the configurations from. private let manager = TutorialManager.sharedInstance private typealias actionHandler = () -> () // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() initialize() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Private // MARK: - Initialize private func initialize() { let configurations = self.manager.configurationsSetForStep(self.activeStep) self.titleLabel.text = configurations.title self.imageView.image = configurations.asset?.image self.actionButton.setTitle(configurations.buttonTitle, forState: .Normal) } // MARK: - Helpers /** Handles OAuth2 stuff, and move to the next step if authorization succeeded. - Note: We actually go in both ways currently, as nothing really depends on the token. */ private func handleAuth() { Authenticator.onAuthorize = { parameters in #if DEBUG print("Did authorize with parameters: \(parameters)") #endif self.goToNextStep() } Authenticator.onFailure = { error in #if DEBUG if let error = error { print("Authorization went wrong: \(error)") } else { print("Authorization went wrong.") } #endif //self.goToFail() self.goToNextStep() } Authenticator.authorizeEmbeddedFrom(self) } /** Navigates to the product types selection controller, as user needs to configure them before access the app after a fresh install. */ private func handleInitialConfigurations() { let productTypesController = StoryboardScene.Main.instanciateProductTypes() let productTypesInNavigationController = UINavigationController(rootViewController: productTypesController) AppDelegate.sharedAppDelegate()?.changeRootViewController(productTypesInNavigationController) } // MARK: - Actions @IBAction func actionButtonTapped(sender: UIButton) { switch self.activeStep { case .StepOne: self.handleAuth() case .StepTwo: self.handleInitialConfigurations() } } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } /** Navigates to the fail view controller. */ private func goToFail() { let failController = StoryboardScene.Main.instanciateFail() AppDelegate.sharedAppDelegate()?.changeRootViewController(failController) } /** Goes to the next step of the tutorial. */ private func goToNextStep() { let nextStepController = StoryboardScene.Main.instanciateTutorial() nextStepController.activeStep = self.activeStep.nextStep let nextStepInNavigationController = UINavigationController(rootViewController: nextStepController) AppDelegate.sharedAppDelegate()?.changeRootViewController(nextStepInNavigationController) } }
mit
dmegahan/Destiny.gg-for-iOS
Destiny.gg/iphoneViewController.swift
1
13333
// // ViewController.swift // Destiny.gg // // Created by Daniel Megahan on 1/31/16. // Copyright © 2016 Daniel Megahan. All rights reserved. // import UIKit import WebKit //inherit from UIWebViewDelegate so we can track when the webviews have loaded/not loaded class iphoneViewController: UIViewController, UIWebViewDelegate { @IBOutlet var myChatWebView: WKWebView! @IBOutlet var myStreamWebView: UIWebView! //When a double tap gesture is done, this will be used to determine how we should change the chat and stream frames var isChatFullScreen = true; var defaultPortraitChatFrame = CGRect.null; var defaultPortraitStreamFrame = CGRect.null; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //set up the gesture recognition /* these aren't currently being used, but we might want ot use them later let swipeDown = UISwipeGestureRecognizer(target: self, action: "OnSwipeGesture:"); swipeDown.direction = UISwipeGestureRecognizerDirection.Down; self.view.addGestureRecognizer(swipeDown); let swipeUp = UISwipeGestureRecognizer(target: self, action: "OnSwipeGesture:") swipeUp.direction = UISwipeGestureRecognizerDirection.Up; self.view.addGestureRecognizer(swipeUp); let doubleTap = UITapGestureRecognizer(target: self, action: "OnDoubleTapGesture:"); doubleTap.numberOfTapsRequired = 2; doubleTap.numberOfTouchesRequired = 2; view.addGestureRecognizer(doubleTap); */ //let panSwipe = UIPanGestureRecognizer(target: self, action: "OnPanSwipe:"); //self.view.addGestureRecognizer(panSwipe); let streamer = "destiny"; //let streamOnline = RestAPIManager.sharedInstance.isStreamOnline(streamer); self.defaultPortraitChatFrame = self.myChatWebView.frame; self.defaultPortraitStreamFrame = self.myStreamWebView.frame; /* if(streamOnline){ //if online, send request for stream. embedStream(streamer); }else{ embedStream(streamer); //will eventually display splash image and label that says offline } */ //embed chat whether or not stream is online embedChat(); print("We in iphone view control"); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func embedStream(_ streamer : String){ let url = URL(string: "http://player.twitch.tv/?channel=" + streamer); let requestObj = URLRequest(url: url!); myStreamWebView.loadRequest(requestObj); self.myStreamWebView.allowsInlineMediaPlayback = true; //attempt at figuring out inline media playback, apparently just turning the above to true doesnt work //let embeddedHTML = "<video width=\"640\" height=\"360\" id=\"player1\" preload=\"none\" webkit-playsinline><source type=\"video/youtube\" src=\"" + url + "\" /></video>"; //self.myStreamWebView.loadHTMLString(embeddedHTML, baseURL: NSBundle.mainBundle().bundleURL); } func embedChat(){ //chat embed URL let url = URL(string: "https://www.destiny.gg/embed/chat"); let requestObj = URLRequest(url: url!); let connectionObj = NSURLConnection(request: requestObj, delegate: self)! myChatWebView.load(requestObj); } /* func OnDoubleTapGesture(gesture: UIGestureRecognizer) { print("double tap"); if let doubleTapGesture = gesture as? UITapGestureRecognizer{ if(!isChatFullScreen){ //In both portait mode and landscape mode, an up swipe will full screen the caht //when we get an upward swipe, we want to fullscreen the chat //to do this, we move the origin.y up to 0 and change the height to match the screen height let newChatFrame = CGRectMake(myChatWebView.frame.origin.x, 0, myChatWebView.frame.width, UIScreen.mainScreen().bounds.height); myChatWebView.frame = newChatFrame; //change the height of the stream to 0 so it doesnt appear anymore let newStreamFrame = CGRectMake(myStreamWebView.frame.origin.x, myStreamWebView.frame.origin.y, myStreamWebView.frame.width, 0); myStreamWebView.frame = newStreamFrame; }else if(isChatFullScreen){ //down swipes have a different function depending on the orientation if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)){ //a down swipe in landscape mode will full screen the stream //to do this, we need to adjust the chat origin back to the original, which is //at the bottom of the screen (so we set origin.y to the height of the screen) and make the height of the frame to 0 let newChatFrame = CGRectMake(myChatWebView.frame.origin.x, UIScreen.mainScreen().bounds.height, myChatWebView.frame.width, 0); myChatWebView.frame = newChatFrame; //full screen the stream, set origin to 0 and height to size of screen let newStreamFrame = CGRectMake(myStreamWebView.frame.origin.x, 0, myStreamWebView.frame.width, UIScreen.mainScreen().bounds.height); myStreamWebView.frame = newStreamFrame; }else if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)){ //this may change later, but a double tap in portrait mode, with the chat full screened, //will cause the stream to take up half the window. So we're going to change the origin.y to halfway //down the screen for the chat and halve the hieght as well let newChatFrame = CGRectMake(myChatWebView.frame.origin.x, UIScreen.mainScreen().bounds.height/2, myChatWebView.bounds.width, UIScreen.mainScreen().bounds.height/2); myChatWebView.frame = newChatFrame; //stream origin.y stays at 0 but we change the height to half the screen let newStreamFrame = CGRectMake(myStreamWebView.frame.origin.x, myStreamWebView.frame.origin.y, myStreamWebView.frame.width, UIScreen.mainScreen().bounds.height/2) myStreamWebView.frame = newStreamFrame; } } } } //when a swipe is detected, resize the webviews depending on direction func OnSwipeGesture(gesture: UIGestureRecognizer) { print("swipe detected"); if let swipeGesture = gesture as? UISwipeGestureRecognizer{ switch swipeGesture.direction{ case UISwipeGestureRecognizerDirection.Up: //In both portait mode and landscape mode, an up swipe will full screen the caht //when we get an upward swipe, we want to fullscreen the chat //to do this, we move the origin.x up to 0 and change the height to match the screen height let newChatFrame = CGRectMake(0, myChatWebView.frame.origin.y, myChatWebView.frame.width, UIScreen.mainScreen().bounds.height); myChatWebView.frame = newChatFrame; //change the height of the stream to 0 so it doesnt appear anymore let newStreamFrame = CGRectMake(myStreamWebView.frame.origin.x, myStreamWebView.frame.origin.y, myStreamWebView.frame.width, 0); myStreamWebView.frame = newStreamFrame; case UISwipeGestureRecognizerDirection.Down: //down swipes have a different function depending on the orientation if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)){ //a down swipe in landscape mode will full screen the stream //to do this, we need to adjust the chat origin back to the original, which is //at the bottom of the screen (so we set origin.x to the height of the screen) and make the height of the frame to 0 let newChatFrame = CGRectMake(UIScreen.mainScreen().bounds.height, myChatWebView.frame.origin.y, myChatWebView.frame.width, 0); myChatWebView.frame = newChatFrame; //full screen the stream, set origin to 0 and height to size of screen let newStreamFrame = CGRectMake(0, myStreamWebView.frame.origin.y, myStreamWebView.frame.width, UIScreen.mainScreen().bounds.height); myStreamWebView.frame = newStreamFrame; } myChatWebView.frame = chatDefaultFrame; myStreamWebView.frame = streamDefaultFrame; default: break; } } } func OnPanSwipe(gesture: UIPanGestureRecognizer){ if (gesture.state == UIGestureRecognizerState.Began){ startPanLocation = gesture.translationInView(self.view); }else if (gesture.state == UIGestureRecognizerState.Changed){ let currentPanLocation = gesture.translationInView(self.view) let distanceY = currentPanLocation.y - startPanLocation.y; let newChatFrame = CGRectMake(myChatWebView.frame.origin.x, myChatWebView.frame.origin.y + distanceY, myChatWebView.frame.width, myChatWebView.frame.height - distanceY) //we do a check to determine if the chat will go offscreen (too far up or down). If it will, we don't move it anymore if(myChatWebView.frame.origin.y + distanceY >= 1 && myChatWebView.frame.origin.y + distanceY <= UIScreen.mainScreen().bounds.height){ myChatWebView.frame = newChatFrame; } let newStreamFrame = CGRectMake(myStreamWebView.frame.origin.x, myStreamWebView.frame.origin.y, myStreamWebView.frame.width + distanceY, myStreamWebView.frame.height) //no point in panning the stream if the width + distanceX is smaller than 0 or if the stream > the width of the screen if(myStreamWebView.frame.width + distanceY > -1 && myStreamWebView.frame.width + distanceY <= UIScreen.mainScreen().bounds.width){ myStreamWebView.frame = newStreamFrame; } startPanLocation = currentPanLocation; } } */ override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation){ //were going to do some lazy programming here. We're going to take the web views that we have //and resize them based on the orientation, rather than use a different storyboard if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation)){ //minimize the chat web view and make the stream web view full screen //new chat frame will have a height of 0, and a width to match the screen size (so we can bring it up using //a swipe easily if we want to) //We also construct a new origin.y, so the chat frame is at the bottom of the screen, instead of at the top let newChatFrame = CGRect(x: myChatWebView.frame.origin.x, y: myChatWebView.frame.origin.y + UIScreen.main.bounds.height, width: UIScreen.main.bounds.width, height: 0); myChatWebView.frame = newChatFrame; //max out the height so it becomes full screened let newStreamFrame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) myStreamWebView.frame = newStreamFrame; isChatFullScreen = false; //unhide it if it is hidden myStreamWebView.isHidden = false; } else if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation)){ print("portraitmode"); //try putting delay on when to resize //set height to 0, we want it to be hidden at the start self.myStreamWebView.frame = self.defaultPortraitStreamFrame; //minimize the stream web view and make the chat web view full screen self.myChatWebView.frame = self.defaultPortraitChatFrame; self.isChatFullScreen = true; //self.myStreamWebView.mediaPlaybackRequiresUserAction = false; //self.myChatWebView.reload(); //self.myChatWebView.reload() //self.myStreamWebView.reload() } } func webView(_ webView: UIWebView, didFailLoadWithError error: Error){ print("Webview fail with error \(error)"); } }
apache-2.0
natecook1000/swift-compiler-crashes
crashes-duplicates/07456-swift-sourcemanager-getmessage.swift
11
333
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct B<D> { class B<l { deinit { func p(v: d = A>() { enum e { func g<H : B? { func a<D> Void>) { p(v: B? { let t: P { if true { protocol A : B<l { class case c,
mit
natecook1000/swift-compiler-crashes
crashes-duplicates/20455-no-stacktrace.swift
11
219
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing deinit { var b { println( { func a { class case ,
mit
simonracz/detox
examples/SwiftExample/SwiftExample/ViewController.swift
1
484
// // ViewController.swift // SwiftExample // // Created by Leo Natan (Wix) on 30/07/2017. // Copyright © 2017 Leo Natan (Wix). All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
Julyyq/FolioReaderKit
Source/FolioReaderCenter.swift
1
59876
// // FolioReaderCenter.swift // FolioReaderKit // // Created by Heberti Almeida on 08/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit import ZFDragableModalTransition /// Protocol which is used from `FolioReaderCenter`s. @objc public protocol FolioReaderCenterDelegate: class { /// Notifies that a page appeared. This is triggered when a page is chosen and displayed. /// /// - Parameter page: The appeared page @objc optional func pageDidAppear(_ page: FolioReaderPage) /// Passes and returns the HTML content as `String`. Implement this method if you want to modify the HTML content of a `FolioReaderPage`. /// /// - Parameters: /// - page: The `FolioReaderPage`. /// - htmlContent: The current HTML content as `String`. /// - Returns: The adjusted HTML content as `String`. This is the content which will be loaded into the given `FolioReaderPage`. @objc optional func htmlContentForPage(_ page: FolioReaderPage, htmlContent: String) -> String /// Notifies that a page changed. This is triggered when collection view cell is changed. /// /// - Parameter pageNumber: The appeared page item @objc optional func pageItemChanged(_ pageNumber: Int) } /// The base reader class open class FolioReaderCenter: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { /// This delegate receives the events from the current `FolioReaderPage`s delegate. open weak var delegate: FolioReaderCenterDelegate? /// This delegate receives the events from current page open weak var pageDelegate: FolioReaderPageDelegate? /// The base reader container open weak var readerContainer: FolioReaderContainer? /// The current visible page on reader open fileprivate(set) var currentPage: FolioReaderPage? /// The collection view with pages open var collectionView: UICollectionView! let collectionViewLayout = UICollectionViewFlowLayout() var loadingView: UIActivityIndicatorView! var pages: [String]! var totalPages: Int = 0 var tempFragment: String? var animator: ZFModalTransitionAnimator! var pageIndicatorView: FolioReaderPageIndicator? var pageIndicatorHeight: CGFloat = 20 var recentlyScrolled = false var recentlyScrolledDelay = 2.0 // 2 second delay until we clear recentlyScrolled var recentlyScrolledTimer: Timer! var scrollScrubber: ScrollScrubber? var activityIndicator = UIActivityIndicatorView() var isScrolling = false var pageScrollDirection = ScrollDirection() var nextPageNumber: Int = 0 var previousPageNumber: Int = 0 var currentPageNumber: Int = 0 var pageWidth: CGFloat = 0.0 var pageHeight: CGFloat = 0.0 fileprivate var screenBounds: CGRect! fileprivate var pointNow = CGPoint.zero fileprivate var pageOffsetRate: CGFloat = 0 fileprivate var tempReference: FRTocReference? fileprivate var isFirstLoad = true fileprivate var currentWebViewScrollPositions = [Int: CGPoint]() fileprivate var currentOrientation: UIInterfaceOrientation? fileprivate var readerConfig: FolioReaderConfig { guard let readerContainer = readerContainer else { return FolioReaderConfig() } return readerContainer.readerConfig } fileprivate var book: FRBook { guard let readerContainer = readerContainer else { return FRBook() } return readerContainer.book } fileprivate var folioReader: FolioReader { guard let readerContainer = readerContainer else { return FolioReader() } return readerContainer.folioReader } // MARK: - Init init(withContainer readerContainer: FolioReaderContainer) { self.readerContainer = readerContainer super.init(nibName: nil, bundle: Bundle.frameworkBundle()) self.initialization() } required public init?(coder aDecoder: NSCoder) { fatalError("This class doesn't support NSCoding.") } /** Common Initialization */ fileprivate func initialization() { if (self.readerConfig.hideBars == true) { self.pageIndicatorHeight = 0 } self.totalPages = book.spine.spineReferences.count // Loading indicator let style: UIActivityIndicatorView.Style = folioReader.isNight(.white, .gray) loadingView = UIActivityIndicatorView(style: style) loadingView.hidesWhenStopped = true loadingView.startAnimating() self.view.addSubview(loadingView) } // MARK: - View life cicle override open func viewDidLoad() { super.viewDidLoad() if #available(iOS 11.0, *) { self.additionalSafeAreaInsets = UIEdgeInsets.init(top: -64, left: 0, bottom: 0, right: 0) } screenBounds = self.getScreenBounds() setPageSize(UIApplication.shared.statusBarOrientation) // Layout collectionViewLayout.sectionInset = UIEdgeInsets.zero collectionViewLayout.minimumLineSpacing = 0 collectionViewLayout.minimumInteritemSpacing = 0 collectionViewLayout.scrollDirection = .direction(withConfiguration: self.readerConfig) let background = folioReader.isNight(self.readerConfig.nightModeBackground, UIColor.white) view.backgroundColor = background // CollectionView collectionView = UICollectionView(frame: screenBounds, collectionViewLayout: collectionViewLayout) collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.delegate = self collectionView.dataSource = self collectionView.isPagingEnabled = true collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = background collectionView.decelerationRate = UIScrollView.DecelerationRate.fast enableScrollBetweenChapters(scrollEnabled: true) view.addSubview(collectionView) if #available(iOS 11.0, *) { collectionView.contentInsetAdjustmentBehavior = .never } // Activity Indicator self.activityIndicator.style = .gray self.activityIndicator.hidesWhenStopped = true self.activityIndicator = UIActivityIndicatorView(frame: CGRect(x: screenBounds.size.width/2, y: screenBounds.size.height/2, width: 30, height: 30)) self.activityIndicator.backgroundColor = UIColor.gray self.view.addSubview(self.activityIndicator) self.view.bringSubviewToFront(self.activityIndicator) if #available(iOS 10.0, *) { collectionView.isPrefetchingEnabled = false } // Register cell classes collectionView?.register(FolioReaderPage.self, forCellWithReuseIdentifier: kReuseCellIdentifier) // Configure navigation bar and layout automaticallyAdjustsScrollViewInsets = false extendedLayoutIncludesOpaqueBars = true configureNavBar() // Page indicator view if (self.readerConfig.hidePageIndicator == false) { let frame = self.frameForPageIndicatorView() pageIndicatorView = FolioReaderPageIndicator(frame: frame, readerConfig: readerConfig, folioReader: folioReader) if let pageIndicatorView = pageIndicatorView { view.addSubview(pageIndicatorView) } } guard let readerContainer = readerContainer else { return } self.scrollScrubber = ScrollScrubber(frame: frameForScrollScrubber(), withReaderContainer: readerContainer) self.scrollScrubber?.delegate = self if let scrollScrubber = scrollScrubber { view.addSubview(scrollScrubber.slider) } } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureNavBar() // Update pages pagesForCurrentPage(currentPage) pageIndicatorView?.reloadView(updateShadow: true) } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() screenBounds = self.getScreenBounds() loadingView.center = view.center setPageSize(UIApplication.shared.statusBarOrientation) updateSubviewFrames() } // MARK: Layout /** Enable or disable the scrolling between chapters (`FolioReaderPage`s). If this is enabled it's only possible to read the current chapter. If another chapter should be displayed is has to be triggered programmatically with `changePageWith`. - parameter scrollEnabled: `Bool` which enables or disables the scrolling between `FolioReaderPage`s. */ open func enableScrollBetweenChapters(scrollEnabled: Bool) { self.collectionView.isScrollEnabled = scrollEnabled } fileprivate func updateSubviewFrames() { self.pageIndicatorView?.frame = self.frameForPageIndicatorView() self.scrollScrubber?.frame = self.frameForScrollScrubber() } fileprivate func frameForPageIndicatorView() -> CGRect { var bounds = CGRect(x: 0, y: screenBounds.size.height-pageIndicatorHeight, width: screenBounds.size.width, height: pageIndicatorHeight) if #available(iOS 11.0, *) { bounds.size.height = bounds.size.height + view.safeAreaInsets.bottom } return bounds } fileprivate func frameForScrollScrubber() -> CGRect { let scrubberY: CGFloat = ((self.readerConfig.shouldHideNavigationOnTap == true || self.readerConfig.hideBars == true) ? 50 : 74) return CGRect(x: self.pageWidth + 10, y: scrubberY, width: 40, height: (self.pageHeight - 100)) } func configureNavBar() { let navBackground = folioReader.isNight(self.readerConfig.nightModeNavBackground, self.readerConfig.daysModeNavBackground) let tintColor = readerConfig.tintColor let navText = folioReader.isNight(UIColor.white, UIColor.black) let font = UIFont(name: "Avenir-Light", size: 17)! setTranslucentNavigation(color: navBackground, tintColor: tintColor, titleColor: navText, andFont: font) } func configureNavBarButtons() { // Navbar buttons let shareIcon = UIImage(readerImageNamed: "icon-navbar-share")?.ignoreSystemTint(withConfiguration: self.readerConfig) let audioIcon = UIImage(readerImageNamed: "icon-navbar-tts")?.ignoreSystemTint(withConfiguration: self.readerConfig) //man-speech-icon let closeIcon = UIImage(readerImageNamed: "icon-navbar-close")?.ignoreSystemTint(withConfiguration: self.readerConfig) let tocIcon = UIImage(readerImageNamed: "icon-navbar-toc")?.ignoreSystemTint(withConfiguration: self.readerConfig) let fontIcon = UIImage(readerImageNamed: "icon-navbar-font")?.ignoreSystemTint(withConfiguration: self.readerConfig) let space = 70 as CGFloat let menu = UIBarButtonItem(image: closeIcon, style: .plain, target: self, action:#selector(closeReader(_:))) let toc = UIBarButtonItem(image: tocIcon, style: .plain, target: self, action:#selector(presentChapterList(_:))) navigationItem.leftBarButtonItems = [menu, toc] var rightBarIcons = [UIBarButtonItem]() if (self.readerConfig.allowSharing == true) { rightBarIcons.append(UIBarButtonItem(image: shareIcon, style: .plain, target: self, action:#selector(shareChapter(_:)))) } if self.book.hasAudio || self.readerConfig.enableTTS { rightBarIcons.append(UIBarButtonItem(image: audioIcon, style: .plain, target: self, action:#selector(presentPlayerMenu(_:)))) } let font = UIBarButtonItem(image: fontIcon, style: .plain, target: self, action: #selector(presentFontsMenu)) font.width = space rightBarIcons.append(contentsOf: [font]) navigationItem.rightBarButtonItems = rightBarIcons if(self.readerConfig.displayTitle){ navigationItem.title = book.title } } func reloadData() { self.loadingView.stopAnimating() self.totalPages = book.spine.spineReferences.count self.collectionView.reloadData() self.configureNavBarButtons() self.setCollectionViewProgressiveDirection() if self.readerConfig.loadSavedPositionForCurrentBook { guard let position = folioReader.savedPositionForCurrentBook, let pageNumber = position["pageNumber"] as? Int, pageNumber > 0 else { self.currentPageNumber = 1 return } self.changePageWith(page: pageNumber) self.currentPageNumber = pageNumber } } // MARK: Change page progressive direction private func transformViewForRTL(_ view: UIView?) { if folioReader.needsRTLChange { view?.transform = CGAffineTransform(scaleX: -1, y: 1) } else { view?.transform = CGAffineTransform.identity } } func setCollectionViewProgressiveDirection() { self.transformViewForRTL(self.collectionView) } func setPageProgressiveDirection(_ page: FolioReaderPage) { self.transformViewForRTL(page) } // MARK: Change layout orientation /// Get internal page offset before layout change private func updatePageOffsetRate() { guard let currentPage = self.currentPage, let webView = currentPage.webView else { return } let pageScrollView = webView.scrollView let contentSize = pageScrollView.contentSize.forDirection(withConfiguration: self.readerConfig) let contentOffset = pageScrollView.contentOffset.forDirection(withConfiguration: self.readerConfig) self.pageOffsetRate = (contentSize != 0 ? (contentOffset / contentSize) : 0) } func setScrollDirection(_ direction: FolioReaderScrollDirection) { guard let currentPage = self.currentPage, let webView = currentPage.webView else { return } let pageScrollView = webView.scrollView // Get internal page offset before layout change self.updatePageOffsetRate() // Change layout self.readerConfig.scrollDirection = direction self.collectionViewLayout.scrollDirection = .direction(withConfiguration: self.readerConfig) self.currentPage?.setNeedsLayout() self.collectionView.collectionViewLayout.invalidateLayout() self.collectionView.setContentOffset(frameForPage(self.currentPageNumber).origin, animated: false) // Page progressive direction self.setCollectionViewProgressiveDirection() delay(0.2) { self.setPageProgressiveDirection(currentPage) } /** * This delay is needed because the page will not be ready yet * so the delay wait until layout finished the changes. */ delay(0.1) { var pageOffset = (pageScrollView.contentSize.forDirection(withConfiguration: self.readerConfig) * self.pageOffsetRate) // Fix the offset for paged scroll if (self.readerConfig.scrollDirection == .horizontal && self.pageWidth != 0) { let page = round(pageOffset / self.pageWidth) pageOffset = (page * self.pageWidth) } let pageOffsetPoint = self.readerConfig.isDirection(CGPoint(x: 0, y: pageOffset), CGPoint(x: pageOffset, y: 0), CGPoint(x: 0, y: pageOffset)) pageScrollView.setContentOffset(pageOffsetPoint, animated: true) } } // MARK: Status bar and Navigation bar func hideBars() { guard self.readerConfig.shouldHideNavigationOnTap == true else { return } self.updateBarsStatus(true) } func showBars() { self.configureNavBar() self.updateBarsStatus(false) } func toggleBars() { guard self.readerConfig.shouldHideNavigationOnTap == true else { return } let shouldHide = !self.navigationController!.isNavigationBarHidden if shouldHide == false { self.configureNavBar() } self.updateBarsStatus(shouldHide) } private func updateBarsStatus(_ shouldHide: Bool, shouldShowIndicator: Bool = false) { guard let readerContainer = readerContainer else { return } readerContainer.shouldHideStatusBar = shouldHide UIView.animate(withDuration: 0.25, animations: { readerContainer.setNeedsStatusBarAppearanceUpdate() // Show minutes indicator if (shouldShowIndicator == true) { self.pageIndicatorView?.minutesLabel.alpha = shouldHide ? 0 : 1 } }) self.navigationController?.setNavigationBarHidden(shouldHide, animated: true) } // MARK: UICollectionViewDataSource open func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return totalPages } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let reuseableCell = collectionView.dequeueReusableCell(withReuseIdentifier: kReuseCellIdentifier, for: indexPath) as? FolioReaderPage return self.configure(readerPageCell: reuseableCell, atIndexPath: indexPath) } private func configure(readerPageCell cell: FolioReaderPage?, atIndexPath indexPath: IndexPath) -> UICollectionViewCell { guard let cell = cell, let readerContainer = readerContainer else { return UICollectionViewCell() } cell.setup(withReaderContainer: readerContainer) cell.pageNumber = indexPath.row+1 cell.webView?.scrollView.delegate = self if #available(iOS 11.0, *) { cell.webView?.scrollView.contentInsetAdjustmentBehavior = .never } cell.webView?.setupScrollDirection() cell.webView?.frame = cell.webViewFrame() cell.delegate = self cell.backgroundColor = .clear setPageProgressiveDirection(cell) // Configure the cell let resource = self.book.spine.spineReferences[indexPath.row].resource guard var html = try? String(contentsOfFile: resource.fullHref, encoding: String.Encoding.utf8) else { return cell } let mediaOverlayStyleColors = "\"\(self.readerConfig.mediaOverlayColor.hexString(false))\", \"\(self.readerConfig.mediaOverlayColor.highlightColor().hexString(false))\"" // Inject CSS let jsFilePath = Bundle.frameworkBundle().path(forResource: "Bridge", ofType: "js") let cssFilePath = Bundle.frameworkBundle().path(forResource: "Style", ofType: "css") let cssTag = "<link rel=\"stylesheet\" type=\"text/css\" href=\"\(cssFilePath!)\">" let jsTag = "<script type=\"text/javascript\" src=\"\(jsFilePath!)\"></script>" + "<script type=\"text/javascript\">setMediaOverlayStyleColors(\(mediaOverlayStyleColors))</script>" let toInject = "\n\(cssTag)\n\(jsTag)\n</head>" html = html.replacingOccurrences(of: "</head>", with: toInject) // Font class name var classes = folioReader.currentFont.cssIdentifier classes += " " + folioReader.currentMediaOverlayStyle.className() // Night mode if folioReader.nightMode { classes += " nightMode" } // Font Size classes += " \(folioReader.currentFontSize.cssIdentifier)" html = html.replacingOccurrences(of: "<html ", with: "<html class=\"\(classes)\"") // Let the delegate adjust the html string if let modifiedHtmlContent = self.delegate?.htmlContentForPage?(cell, htmlContent: html) { html = modifiedHtmlContent } cell.loadHTMLString(html, baseURL: URL(fileURLWithPath: resource.fullHref.deletingLastPathComponent)) return cell } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var size = CGSize(width: collectionView.frame.width, height: collectionView.frame.height) if #available(iOS 11.0, *) { let orientation = UIDevice.current.orientation if orientation == .portrait || orientation == .portraitUpsideDown { if readerConfig.scrollDirection == .horizontal { size.height = size.height - view.safeAreaInsets.bottom } } } return size } // MARK: - Device rotation override open func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) { guard folioReader.isReaderReady else { return } setPageSize(toInterfaceOrientation) updateCurrentPage() if self.currentOrientation == nil || (self.currentOrientation?.isPortrait != toInterfaceOrientation.isPortrait) { var pageIndicatorFrame = pageIndicatorView?.frame pageIndicatorFrame?.origin.y = ((screenBounds.size.height < screenBounds.size.width) ? (self.collectionView.frame.height - pageIndicatorHeight) : (self.collectionView.frame.width - pageIndicatorHeight)) pageIndicatorFrame?.origin.x = 0 pageIndicatorFrame?.size.width = ((screenBounds.size.height < screenBounds.size.width) ? (self.collectionView.frame.width) : (self.collectionView.frame.height)) pageIndicatorFrame?.size.height = pageIndicatorHeight var scrollScrubberFrame = scrollScrubber?.slider.frame; scrollScrubberFrame?.origin.x = ((screenBounds.size.height < screenBounds.size.width) ? (screenBounds.size.width - 100) : (screenBounds.size.height + 10)) scrollScrubberFrame?.size.height = ((screenBounds.size.height < screenBounds.size.width) ? (self.collectionView.frame.height - 100) : (self.collectionView.frame.width - 100)) self.collectionView.collectionViewLayout.invalidateLayout() UIView.animate(withDuration: duration, animations: { // Adjust page indicator view if let pageIndicatorFrame = pageIndicatorFrame { self.pageIndicatorView?.frame = pageIndicatorFrame self.pageIndicatorView?.reloadView(updateShadow: true) } // Adjust scroll scrubber slider if let scrollScrubberFrame = scrollScrubberFrame { self.scrollScrubber?.slider.frame = scrollScrubberFrame } // Adjust collectionView self.collectionView.contentSize = self.readerConfig.isDirection( CGSize(width: self.pageWidth, height: self.pageHeight * CGFloat(self.totalPages)), CGSize(width: self.pageWidth * CGFloat(self.totalPages), height: self.pageHeight), CGSize(width: self.pageWidth * CGFloat(self.totalPages), height: self.pageHeight) ) self.collectionView.setContentOffset(self.frameForPage(self.currentPageNumber).origin, animated: false) self.collectionView.collectionViewLayout.invalidateLayout() // Adjust internal page offset self.updatePageOffsetRate() }) } self.currentOrientation = toInterfaceOrientation } override open func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) { guard folioReader.isReaderReady == true, let currentPage = currentPage else { return } // Update pages pagesForCurrentPage(currentPage) currentPage.refreshPageMode() scrollScrubber?.setSliderVal() // After rotation fix internal page offset var pageOffset = (currentPage.webView?.scrollView.contentSize.forDirection(withConfiguration: self.readerConfig) ?? 0) * pageOffsetRate // Fix the offset for paged scroll if (self.readerConfig.scrollDirection == .horizontal && self.pageWidth != 0) { let page = round(pageOffset / self.pageWidth) pageOffset = page * self.pageWidth } let pageOffsetPoint = self.readerConfig.isDirection(CGPoint(x: 0, y: pageOffset), CGPoint(x: pageOffset, y: 0), CGPoint(x: 0, y: pageOffset)) currentPage.webView?.scrollView.setContentOffset(pageOffsetPoint, animated: true) } override open func willAnimateRotation(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) { guard folioReader.isReaderReady else { return } self.collectionView.scrollToItem(at: IndexPath(row: self.currentPageNumber - 1, section: 0), at: UICollectionView.ScrollPosition(), animated: false) if (self.currentPageNumber + 1) >= totalPages { UIView.animate(withDuration: duration, animations: { self.collectionView.setContentOffset(self.frameForPage(self.currentPageNumber).origin, animated: false) }) } } // MARK: - Page func setPageSize(_ orientation: UIInterfaceOrientation) { guard orientation.isPortrait else { if screenBounds.size.width > screenBounds.size.height { self.pageWidth = screenBounds.size.width self.pageHeight = screenBounds.size.height } else { self.pageWidth = screenBounds.size.height self.pageHeight = screenBounds.size.width } return } if screenBounds.size.width < screenBounds.size.height { self.pageWidth = screenBounds.size.width self.pageHeight = screenBounds.size.height } else { self.pageWidth = screenBounds.size.height self.pageHeight = screenBounds.size.width } } func updateCurrentPage(_ page: FolioReaderPage? = nil, completion: (() -> Void)? = nil) { if let page = page { currentPage = page self.previousPageNumber = page.pageNumber-1 self.currentPageNumber = page.pageNumber } else { let currentIndexPath = getCurrentIndexPath() currentPage = collectionView.cellForItem(at: currentIndexPath) as? FolioReaderPage self.previousPageNumber = currentIndexPath.row self.currentPageNumber = currentIndexPath.row+1 } self.nextPageNumber = (((self.currentPageNumber + 1) <= totalPages) ? (self.currentPageNumber + 1) : self.currentPageNumber) // Set pages guard let currentPage = currentPage else { completion?() return } scrollScrubber?.setSliderVal() if let readingTime = currentPage.webView?.js("getReadingTime()") { pageIndicatorView?.totalMinutes = Int(readingTime)! } else { pageIndicatorView?.totalMinutes = 0 } pagesForCurrentPage(currentPage) delegate?.pageDidAppear?(currentPage) delegate?.pageItemChanged?(self.getCurrentPageItemNumber()) completion?() } func pagesForCurrentPage(_ page: FolioReaderPage?) { guard let page = page, let webView = page.webView else { return } let pageSize = self.readerConfig.isDirection(pageHeight, self.pageWidth, pageHeight) let contentSize = page.webView?.scrollView.contentSize.forDirection(withConfiguration: self.readerConfig) ?? 0 self.pageIndicatorView?.totalPages = ((pageSize != 0) ? Int(ceil(contentSize / pageSize)) : 0) let pageOffSet = self.readerConfig.isDirection(webView.scrollView.contentOffset.x, webView.scrollView.contentOffset.x, webView.scrollView.contentOffset.y) let webViewPage = pageForOffset(pageOffSet, pageHeight: pageSize) self.pageIndicatorView?.currentPage = webViewPage } func pageForOffset(_ offset: CGFloat, pageHeight height: CGFloat) -> Int { guard (height != 0) else { return 0 } let page = Int(ceil(offset / height))+1 return page } func getCurrentIndexPath() -> IndexPath { let indexPaths = collectionView.indexPathsForVisibleItems var indexPath = IndexPath() if indexPaths.count > 1 { let first = indexPaths.first! let last = indexPaths.last! switch self.pageScrollDirection { case .up, .left: if first.compare(last) == .orderedAscending { indexPath = last } else { indexPath = first } default: if first.compare(last) == .orderedAscending { indexPath = first } else { indexPath = last } } } else { indexPath = indexPaths.first ?? IndexPath(row: 0, section: 0) } return indexPath } func frameForPage(_ page: Int) -> CGRect { return self.readerConfig.isDirection( CGRect(x: 0, y: self.pageHeight * CGFloat(page-1), width: self.pageWidth, height: self.pageHeight), CGRect(x: self.pageWidth * CGFloat(page-1), y: 0, width: self.pageWidth, height: self.pageHeight), CGRect(x: 0, y: self.pageHeight * CGFloat(page-1), width: self.pageWidth, height: self.pageHeight) ) } open func changePageWith(page: Int, andFragment fragment: String, animated: Bool = false, completion: (() -> Void)? = nil) { if (self.currentPageNumber == page) { if let currentPage = currentPage , fragment != "" { currentPage.handleAnchor(fragment, avoidBeginningAnchors: true, animated: animated) } completion?() } else { tempFragment = fragment changePageWith(page: page, animated: animated, completion: { () -> Void in self.updateCurrentPage { completion?() } }) } } open func changePageWith(href: String, animated: Bool = false, completion: (() -> Void)? = nil) { let item = findPageByHref(href) let indexPath = IndexPath(row: item, section: 0) changePageWith(indexPath: indexPath, animated: animated, completion: { () -> Void in self.updateCurrentPage { completion?() } }) } open func changePageWith(href: String, andAudioMarkID markID: String) { if recentlyScrolled { return } // if user recently scrolled, do not change pages or scroll the webview guard let currentPage = currentPage else { return } let item = findPageByHref(href) let pageUpdateNeeded = item+1 != currentPage.pageNumber let indexPath = IndexPath(row: item, section: 0) changePageWith(indexPath: indexPath, animated: true) { () -> Void in if pageUpdateNeeded { self.updateCurrentPage { currentPage.audioMarkID(markID) } } else { currentPage.audioMarkID(markID) } } } open func changePageWith(indexPath: IndexPath, animated: Bool = false, completion: (() -> Void)? = nil) { guard indexPathIsValid(indexPath) else { print("ERROR: Attempt to scroll to invalid index path") completion?() return } UIView.animate(withDuration: animated ? 0.3 : 0, delay: 0, options: UIView.AnimationOptions(), animations: { () -> Void in self.collectionView.scrollToItem(at: indexPath, at: .direction(withConfiguration: self.readerConfig), animated: false) }) { (finished: Bool) -> Void in completion?() } } open func changePageWith(href: String, pageItem: Int, animated: Bool = false, completion: (() -> Void)? = nil) { changePageWith(href: href, animated: animated) { self.changePageItem(to: pageItem) } } func indexPathIsValid(_ indexPath: IndexPath) -> Bool { let section = indexPath.section let row = indexPath.row let lastSectionIndex = numberOfSections(in: collectionView) - 1 //Make sure the specified section exists if section > lastSectionIndex { return false } let rowCount = self.collectionView(collectionView, numberOfItemsInSection: indexPath.section) - 1 return row <= rowCount } open func isLastPage() -> Bool{ return (currentPageNumber == self.nextPageNumber) } public func changePageToNext(_ completion: (() -> Void)? = nil) { changePageWith(page: self.nextPageNumber, animated: true) { () -> Void in completion?() } } public func changePageToPrevious(_ completion: (() -> Void)? = nil) { changePageWith(page: self.previousPageNumber, animated: true) { () -> Void in completion?() } } public func changePageItemToNext(_ completion: (() -> Void)? = nil) { // TODO: It was implemented for horizontal orientation. // Need check page orientation (v/h) and make correct calc for vertical guard let cell = collectionView.cellForItem(at: getCurrentIndexPath()) as? FolioReaderPage, let contentOffset = cell.webView?.scrollView.contentOffset, let contentOffsetXLimit = cell.webView?.scrollView.contentSize.width else { completion?() return } let cellSize = cell.frame.size let contentOffsetX = contentOffset.x + cellSize.width if contentOffsetX >= contentOffsetXLimit { changePageToNext(completion) } else { cell.scrollPageToOffset(contentOffsetX, animated: true) } completion?() } public func getCurrentPageItemNumber() -> Int { guard let page = currentPage, let webView = page.webView else { return 0 } let pageSize = readerConfig.isDirection(pageHeight, pageWidth, pageHeight) let pageOffSet = readerConfig.isDirection(webView.scrollView.contentOffset.x, webView.scrollView.contentOffset.x, webView.scrollView.contentOffset.y) let webViewPage = pageForOffset(pageOffSet, pageHeight: pageSize) return webViewPage } public func getCurrentPageProgress() -> Float { guard let page = currentPage else { return 0 } let pageSize = self.readerConfig.isDirection(pageHeight, self.pageWidth, pageHeight) let contentSize = page.webView?.scrollView.contentSize.forDirection(withConfiguration: self.readerConfig) ?? 0 let totalPages = ((pageSize != 0) ? Int(ceil(contentSize / pageSize)) : 0) let currentPageItem = getCurrentPageItemNumber() if totalPages > 0 { var progress = Float((currentPageItem * 100) / totalPages) if progress < 0 { progress = 0 } if progress > 100 { progress = 100 } return progress } return 0 } public func changePageItemToPrevious(_ completion: (() -> Void)? = nil) { // TODO: It was implemented for horizontal orientation. // Need check page orientation (v/h) and make correct calc for vertical guard let cell = collectionView.cellForItem(at: getCurrentIndexPath()) as? FolioReaderPage, let contentOffset = cell.webView?.scrollView.contentOffset else { completion?() return } let cellSize = cell.frame.size let contentOffsetX = contentOffset.x - cellSize.width if contentOffsetX < 0 { changePageToPrevious(completion) } else { cell.scrollPageToOffset(contentOffsetX, animated: true) } completion?() } public func changePageItemToLast(animated: Bool = true, _ completion: (() -> Void)? = nil) { // TODO: It was implemented for horizontal orientation. // Need check page orientation (v/h) and make correct calc for vertical guard let cell = collectionView.cellForItem(at: getCurrentIndexPath()) as? FolioReaderPage, let contentSize = cell.webView?.scrollView.contentSize else { completion?() return } let cellSize = cell.frame.size var contentOffsetX: CGFloat = 0.0 if contentSize.width > 0 && cellSize.width > 0 { contentOffsetX = (cellSize.width * (contentSize.width / cellSize.width)) - cellSize.width } if contentOffsetX < 0 { contentOffsetX = 0 } cell.scrollPageToOffset(contentOffsetX, animated: animated) completion?() } public func changePageItem(to: Int, animated: Bool = true, completion: (() -> Void)? = nil) { // TODO: It was implemented for horizontal orientation. // Need check page orientation (v/h) and make correct calc for vertical guard let cell = collectionView.cellForItem(at: getCurrentIndexPath()) as? FolioReaderPage, let contentSize = cell.webView?.scrollView.contentSize else { delegate?.pageItemChanged?(getCurrentPageItemNumber()) completion?() return } let cellSize = cell.frame.size var contentOffsetX: CGFloat = 0.0 if contentSize.width > 0 && cellSize.width > 0 { contentOffsetX = (cellSize.width * CGFloat(to)) - cellSize.width } if contentOffsetX > contentSize.width { contentOffsetX = contentSize.width - cellSize.width } if contentOffsetX < 0 { contentOffsetX = 0 } UIView.animate(withDuration: animated ? 0.3 : 0, delay: 0, options: UIView.AnimationOptions(), animations: { () -> Void in cell.scrollPageToOffset(contentOffsetX, animated: animated) }) { (finished: Bool) -> Void in self.updateCurrentPage { completion?() } } } /** Find a page by FRTocReference. */ public func findPageByResource(_ reference: FRTocReference) -> Int { var count = 0 for item in self.book.spine.spineReferences { if let resource = reference.resource, item.resource == resource { return count } count += 1 } return count } /** Find a page by href. */ public func findPageByHref(_ href: String) -> Int { var count = 0 for item in self.book.spine.spineReferences { if item.resource.href == href { return count } count += 1 } return count } /** Find and return the current chapter resource. */ public func getCurrentChapter() -> FRResource? { var foundResource: FRResource? func search(_ items: [FRTocReference]) { for item in items { guard foundResource == nil else { break } if let reference = book.spine.spineReferences[safe: (currentPageNumber - 1)], let resource = item.resource, resource == reference.resource { foundResource = resource break } else if let children = item.children, children.isEmpty == false { search(children) } } } search(book.flatTableOfContents) return foundResource } /** Return the current chapter progress based on current chapter and total of chapters. */ public func getCurrentChapterProgress() -> CGFloat { let total = totalPages let current = currentPageNumber if total == 0 { return 0 } return CGFloat((100 * current) / total) } /** Find and return the current chapter name. */ public func getCurrentChapterName() -> String? { var foundChapterName: String? func search(_ items: [FRTocReference]) { for item in items { guard foundChapterName == nil else { break } if let reference = self.book.spine.spineReferences[safe: (self.currentPageNumber - 1)], let resource = item.resource, resource == reference.resource, let title = item.title { foundChapterName = title } else if let children = item.children, children.isEmpty == false { search(children) } } } search(self.book.flatTableOfContents) return foundChapterName } // MARK: Public page methods /** Changes the current page of the reader. - parameter page: The target page index. Note: The page index starts at 1 (and not 0). - parameter animated: En-/Disables the animation of the page change. - parameter completion: A Closure which is called if the page change is completed. */ public func changePageWith(page: Int, animated: Bool = false, completion: (() -> Void)? = nil) { if page > 0 && page-1 < totalPages { let indexPath = IndexPath(row: page-1, section: 0) changePageWith(indexPath: indexPath, animated: animated, completion: { () -> Void in self.updateCurrentPage { completion?() } }) } } // MARK: - Audio Playing func audioMark(href: String, fragmentID: String) { changePageWith(href: href, andAudioMarkID: fragmentID) } // MARK: - Sharing /** Sharing chapter method. */ @objc func shareChapter(_ sender: UIBarButtonItem) { guard let currentPage = currentPage else { return } if let chapterText = currentPage.webView?.js("getBodyText()") { let htmlText = chapterText.replacingOccurrences(of: "[\\n\\r]+", with: "<br />", options: .regularExpression) var subject = readerConfig.localizedShareChapterSubject var html = "" var text = "" var bookTitle = "" var chapterName = "" var authorName = "" var shareItems = [AnyObject]() // Get book title if let title = self.book.title { bookTitle = title subject += " “\(title)”" } // Get chapter name if let chapter = getCurrentChapterName() { chapterName = chapter } // Get author name if let author = self.book.metadata.creators.first { authorName = author.name } // Sharing html and text html = "<html><body>" html += "<br /><hr> <p>\(htmlText)</p> <hr><br />" html += "<center><p style=\"color:gray\">"+readerConfig.localizedShareAllExcerptsFrom+"</p>" html += "<b>\(bookTitle)</b><br />" html += readerConfig.localizedShareBy+" <i>\(authorName)</i><br />" if let bookShareLink = readerConfig.localizedShareWebLink { html += "<a href=\"\(bookShareLink.absoluteString)\">\(bookShareLink.absoluteString)</a>" shareItems.append(bookShareLink as AnyObject) } html += "</center></body></html>" text = "\(chapterName)\n\n“\(chapterText)” \n\n\(bookTitle) \n\(readerConfig.localizedShareBy) \(authorName)" let act = FolioReaderSharingProvider(subject: subject, text: text, html: html) shareItems.insert(contentsOf: [act, "" as AnyObject], at: 0) let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil) activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToVimeo] // Pop style on iPad if let actv = activityViewController.popoverPresentationController { actv.barButtonItem = sender } present(activityViewController, animated: true, completion: nil) } } /** Sharing highlight method. */ func shareHighlight(_ string: String, rect: CGRect) { var subject = readerConfig.localizedShareHighlightSubject var html = "" var text = "" var bookTitle = "" var chapterName = "" var authorName = "" var shareItems = [AnyObject]() // Get book title if let title = self.book.title { bookTitle = title subject += " “\(title)”" } // Get chapter name if let chapter = getCurrentChapterName() { chapterName = chapter } // Get author name if let author = self.book.metadata.creators.first { authorName = author.name } // Sharing html and text html = "<html><body>" html += "<br /><hr> <p>\(chapterName)</p>" html += "<p>\(string)</p> <hr><br />" html += "<center><p style=\"color:gray\">"+readerConfig.localizedShareAllExcerptsFrom+"</p>" html += "<b>\(bookTitle)</b><br />" html += readerConfig.localizedShareBy+" <i>\(authorName)</i><br />" if let bookShareLink = readerConfig.localizedShareWebLink { html += "<a href=\"\(bookShareLink.absoluteString)\">\(bookShareLink.absoluteString)</a>" shareItems.append(bookShareLink as AnyObject) } html += "</center></body></html>" text = "\(chapterName)\n\n“\(string)” \n\n\(bookTitle) \n\(readerConfig.localizedShareBy) \(authorName)" let act = FolioReaderSharingProvider(subject: subject, text: text, html: html) shareItems.insert(contentsOf: [act, "" as AnyObject], at: 0) let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil) activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToVimeo] // Pop style on iPad if let actv = activityViewController.popoverPresentationController { actv.sourceView = currentPage actv.sourceRect = rect } present(activityViewController, animated: true, completion: nil) } // MARK: - ScrollView Delegate open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { self.isScrolling = true clearRecentlyScrolled() recentlyScrolled = true pointNow = scrollView.contentOffset if (scrollView is UICollectionView) { scrollView.isUserInteractionEnabled = false } if let currentPage = currentPage { currentPage.webView?.createMenu(options: true) currentPage.webView?.setMenuVisible(false) } scrollScrubber?.scrollViewWillBeginDragging(scrollView) } open func scrollViewDidScroll(_ scrollView: UIScrollView) { if (navigationController?.isNavigationBarHidden == false) { self.toggleBars() } scrollScrubber?.scrollViewDidScroll(scrollView) let isCollectionScrollView = (scrollView is UICollectionView) let scrollType: ScrollType = ((isCollectionScrollView == true) ? .chapter : .page) // Update current reading page if (isCollectionScrollView == false), let page = currentPage, let webView = page.webView { let pageSize = self.readerConfig.isDirection(self.pageHeight, self.pageWidth, self.pageHeight) let contentOffset = webView.scrollView.contentOffset.forDirection(withConfiguration: self.readerConfig) let contentSize = webView.scrollView.contentSize.forDirection(withConfiguration: self.readerConfig) if (contentOffset + pageSize <= contentSize) { let webViewPage = pageForOffset(contentOffset, pageHeight: pageSize) if (readerConfig.scrollDirection == .horizontalWithVerticalContent) { let currentIndexPathRow = (page.pageNumber - 1) // if the cell reload doesn't save the top position offset if let oldOffSet = self.currentWebViewScrollPositions[currentIndexPathRow], (abs(oldOffSet.y - scrollView.contentOffset.y) > 100) { // Do nothing } else { self.currentWebViewScrollPositions[currentIndexPathRow] = scrollView.contentOffset } } if (pageIndicatorView?.currentPage != webViewPage) { pageIndicatorView?.currentPage = webViewPage } self.delegate?.pageItemChanged?(webViewPage) } } self.updatePageScrollDirection(inScrollView: scrollView, forScrollType: scrollType) } private func updatePageScrollDirection(inScrollView scrollView: UIScrollView, forScrollType scrollType: ScrollType) { let scrollViewContentOffsetForDirection = scrollView.contentOffset.forDirection(withConfiguration: self.readerConfig, scrollType: scrollType) let pointNowForDirection = pointNow.forDirection(withConfiguration: self.readerConfig, scrollType: scrollType) // The movement is either positive or negative. This happens if the page change isn't completed. Toggle to the other scroll direction then. let isCurrentlyPositive = (self.pageScrollDirection == .left || self.pageScrollDirection == .up) if (scrollViewContentOffsetForDirection < pointNowForDirection) { self.pageScrollDirection = .negative(withConfiguration: self.readerConfig, scrollType: scrollType) } else if (scrollViewContentOffsetForDirection > pointNowForDirection) { self.pageScrollDirection = .positive(withConfiguration: self.readerConfig, scrollType: scrollType) } else if (isCurrentlyPositive == true) { self.pageScrollDirection = .negative(withConfiguration: self.readerConfig, scrollType: scrollType) } else { self.pageScrollDirection = .positive(withConfiguration: self.readerConfig, scrollType: scrollType) } } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.isScrolling = false if (scrollView is UICollectionView) { scrollView.isUserInteractionEnabled = true } // Perform the page after a short delay as the collection view hasn't completed it's transition if this method is called (the index paths aren't right during fast scrolls). delay(0.2, closure: { [weak self] in if (self?.readerConfig.scrollDirection == .horizontalWithVerticalContent), let cell = ((scrollView.superview as? UIWebView)?.delegate as? FolioReaderPage) { let currentIndexPathRow = cell.pageNumber - 1 self?.currentWebViewScrollPositions[currentIndexPathRow] = scrollView.contentOffset } if (scrollView is UICollectionView) { guard let instance = self else { return } if instance.totalPages > 0 { instance.updateCurrentPage() instance.delegate?.pageItemChanged?(instance.getCurrentPageItemNumber()) } } else { self?.scrollScrubber?.scrollViewDidEndDecelerating(scrollView) } }) } open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { recentlyScrolledTimer = Timer(timeInterval:recentlyScrolledDelay, target: self, selector: #selector(FolioReaderCenter.clearRecentlyScrolled), userInfo: nil, repeats: false) RunLoop.current.add(recentlyScrolledTimer, forMode: RunLoop.Mode.common) } @objc func clearRecentlyScrolled() { if(recentlyScrolledTimer != nil) { recentlyScrolledTimer.invalidate() recentlyScrolledTimer = nil } recentlyScrolled = false } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { scrollScrubber?.scrollViewDidEndScrollingAnimation(scrollView) } // MARK: NavigationBar Actions @objc func closeReader(_ sender: UIBarButtonItem) { dismiss() folioReader.close() } /** Present chapter list */ @objc func presentChapterList(_ sender: UIBarButtonItem) { folioReader.saveReaderState() let chapter = FolioReaderChapterList(folioReader: folioReader, readerConfig: readerConfig, book: book, delegate: self) let highlight = FolioReaderHighlightList(folioReader: folioReader, readerConfig: readerConfig) let pageController = PageViewController(folioReader: folioReader, readerConfig: readerConfig) pageController.viewControllerOne = chapter pageController.viewControllerTwo = highlight pageController.segmentedControlItems = [readerConfig.localizedContentsTitle, readerConfig.localizedHighlightsTitle] let nav = UINavigationController(rootViewController: pageController) present(nav, animated: true, completion: nil) } /** Present fonts and settings menu */ @objc func presentFontsMenu() { folioReader.saveReaderState() hideBars() let menu = FolioReaderFontsMenu(folioReader: folioReader, readerConfig: readerConfig) menu.modalPresentationStyle = .custom animator = ZFModalTransitionAnimator(modalViewController: menu) animator.isDragable = false animator.bounces = false animator.behindViewAlpha = 0.4 animator.behindViewScale = 1 animator.transitionDuration = 0.6 animator.direction = ZFModalTransitonDirection.bottom menu.transitioningDelegate = animator self.present(menu, animated: true, completion: nil) } /** Present audio player menu */ @objc func presentPlayerMenu(_ sender: UIBarButtonItem) { folioReader.saveReaderState() hideBars() let menu = FolioReaderPlayerMenu(folioReader: folioReader, readerConfig: readerConfig) menu.modalPresentationStyle = .custom animator = ZFModalTransitionAnimator(modalViewController: menu) animator.isDragable = true animator.bounces = false animator.behindViewAlpha = 0.4 animator.behindViewScale = 1 animator.transitionDuration = 0.6 animator.direction = ZFModalTransitonDirection.bottom menu.transitioningDelegate = animator present(menu, animated: true, completion: nil) } /** Present Quote Share */ func presentQuoteShare(_ string: String) { let quoteShare = FolioReaderQuoteShare(initWithText: string, readerConfig: readerConfig, folioReader: folioReader, book: book) let nav = UINavigationController(rootViewController: quoteShare) if UIDevice.current.userInterfaceIdiom == .pad { nav.modalPresentationStyle = .formSheet } present(nav, animated: true, completion: nil) } /** Present add highlight note */ func presentAddHighlightNote(_ highlight: Highlight, edit: Bool) { let addHighlightView = FolioReaderAddHighlightNote(withHighlight: highlight, folioReader: folioReader, readerConfig: readerConfig) addHighlightView.isEditHighlight = edit let nav = UINavigationController(rootViewController: addHighlightView) nav.modalPresentationStyle = .formSheet present(nav, animated: true, completion: nil) } } // MARK: FolioPageDelegate extension FolioReaderCenter: FolioReaderPageDelegate { public func pageDidLoad(_ page: FolioReaderPage) { if self.readerConfig.loadSavedPositionForCurrentBook, let position = folioReader.savedPositionForCurrentBook { let pageNumber = position["pageNumber"] as? Int let offset = self.readerConfig.isDirection(position["pageOffsetY"], position["pageOffsetX"], position["pageOffsetY"]) as? CGFloat let pageOffset = offset if isFirstLoad { updateCurrentPage(page) isFirstLoad = false if (self.currentPageNumber == pageNumber && pageOffset > 0) { page.scrollPageToOffset(pageOffset!, animated: false) } } else if (self.isScrolling == false && folioReader.needsRTLChange == true) { page.scrollPageToBottom() } } else if isFirstLoad { updateCurrentPage(page) isFirstLoad = false } // Go to fragment if needed if let fragmentID = tempFragment, let currentPage = currentPage , fragmentID != "" { currentPage.handleAnchor(fragmentID, avoidBeginningAnchors: true, animated: true) tempFragment = nil } if (readerConfig.scrollDirection == .horizontalWithVerticalContent), let offsetPoint = self.currentWebViewScrollPositions[page.pageNumber - 1] { page.webView?.scrollView.setContentOffset(offsetPoint, animated: false) } // Pass the event to the centers `pageDelegate` pageDelegate?.pageDidLoad?(page) } public func pageWillLoad(_ page: FolioReaderPage) { // Pass the event to the centers `pageDelegate` pageDelegate?.pageWillLoad?(page) } public func pageTap(_ recognizer: UITapGestureRecognizer) { // Pass the event to the centers `pageDelegate` pageDelegate?.pageTap?(recognizer) } } // MARK: FolioReaderChapterListDelegate extension FolioReaderCenter: FolioReaderChapterListDelegate { func chapterList(_ chapterList: FolioReaderChapterList, didSelectRowAtIndexPath indexPath: IndexPath, withTocReference reference: FRTocReference) { let item = findPageByResource(reference) if item < totalPages { let indexPath = IndexPath(row: item, section: 0) changePageWith(indexPath: indexPath, animated: false, completion: { () -> Void in self.updateCurrentPage() }) tempReference = reference } else { print("Failed to load book because the requested resource is missing.") } } func chapterList(didDismissedChapterList chapterList: FolioReaderChapterList) { updateCurrentPage() // Move to #fragment if let reference = tempReference { if let fragmentID = reference.fragmentID, let currentPage = currentPage , fragmentID != "" { currentPage.handleAnchor(reference.fragmentID!, avoidBeginningAnchors: true, animated: true) } tempReference = nil } } func getScreenBounds() -> CGRect { var bounds = view.frame if #available(iOS 11.0, *) { bounds.size.height = bounds.size.height - view.safeAreaInsets.bottom } return bounds } }
bsd-3-clause
jwfriese/FrequentFlyer
FrequentFlyerTests/Jobs/PublicJobsDataStreamSpec.swift
1
3614
import XCTest import Quick import Nimble import RxSwift @testable import FrequentFlyer class PublicJobsDataStreamSpec: QuickSpec { class MockJobsService: JobsService { var capturedPipeline: Pipeline? var capturedConcourseURL: String? var jobsSubject = PublishSubject<[Job]>() override func getPublicJobs(forPipeline pipeline: Pipeline, concourseURL: String) -> Observable<[Job]> { capturedPipeline = pipeline capturedConcourseURL = concourseURL return jobsSubject } } override func spec() { describe("PublicJobsDataStream") { var subject: PublicJobsDataStream! var mockJobsService: MockJobsService! beforeEach { subject = PublicJobsDataStream(concourseURL: "concourseURL") mockJobsService = MockJobsService() subject.jobsService = mockJobsService } describe("Opening a data stream") { var jobSection$: Observable<[JobGroupSection]>! var jobSectionStreamResult: StreamResult<JobGroupSection>! beforeEach { let pipeline = Pipeline(name: "turtle pipeline", isPublic: true, teamName: "turtle team") jobSection$ = subject.open(forPipeline: pipeline) jobSectionStreamResult = StreamResult(jobSection$) } it("calls out to the \(JobsService.self)") { let expectedPipeline = Pipeline(name: "turtle pipeline", isPublic: true, teamName: "turtle team") expect(mockJobsService.capturedPipeline).toEventually(equal(expectedPipeline)) expect(mockJobsService.capturedConcourseURL).toEventually(equal("concourseURL")) } describe("When the \(JobsService.self) resolves with jobs") { var turtleJob: Job! var crabJob: Job! var anotherCrabJob: Job! var puppyJob: Job! beforeEach { let finishedTurtleBuild = BuildBuilder().withStatus(.failed).withEndTime(1000).build() turtleJob = Job(name: "turtle job", nextBuild: nil, finishedBuild: finishedTurtleBuild, groups: ["turtle-group"]) let nextCrabBuild = BuildBuilder().withStatus(.pending).withStartTime(500).build() crabJob = Job(name: "crab job", nextBuild: nextCrabBuild, finishedBuild: nil, groups: ["crab-group"]) let anotherCrabBuild = BuildBuilder().withStatus(.aborted).withStartTime(501).build() anotherCrabJob = Job(name: "another crab job", nextBuild: anotherCrabBuild, finishedBuild: nil, groups: ["crab-group"]) puppyJob = Job(name: "puppy job", nextBuild: nil, finishedBuild: nil, groups: []) mockJobsService.jobsSubject.onNext([turtleJob, crabJob, anotherCrabJob, puppyJob]) mockJobsService.jobsSubject.onCompleted() } it("organizes the jobs into sections by group name and emits them") { expect(jobSectionStreamResult.elements[0].items).to(equal([turtleJob])) expect(jobSectionStreamResult.elements[1].items).to(equal([crabJob, anotherCrabJob])) expect(jobSectionStreamResult.elements[2].items).to(equal([puppyJob])) } } } } } }
apache-2.0
eelstork/Start-Developing-IOS-Apps-Today
ToDoList/ToDoList/TodoListTableViewController.swift
1
1820
import UIKit class TodoListTableViewController:UITableViewController{ var todoItems:[ToDoItem]=[] @IBAction func unwindToList(segue:UIStoryboardSegue) { let source = segue.sourceViewController as AddToDoItemViewController var item = source.toDoItem if(item != nil){ todoItems.append(item!) tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() loadInitialData() } func loadInitialData(){ let item1 = ToDoItem(name: "Buy milk" ) let item2 = ToDoItem(name: "Buy eggs" ) let item3 = ToDoItem(name: "Read a book" ) todoItems.append(item1) todoItems.append(item2) todoItems.append(item3) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return todoItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("ListPrototypeCell", forIndexPath: indexPath) as UITableViewCell let toDoItem = todoItems[indexPath.row] cell.textLabel?.text = toDoItem.itemName if(toDoItem.completed){ cell.accessoryType = UITableViewCellAccessoryType.Checkmark }else{ cell.accessoryType = UITableViewCellAccessoryType.None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) var tappedItem = todoItems[indexPath.row] tappedItem.completed = !tappedItem.completed tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None) } }
cc0-1.0
KempinGe/LiveBroadcast
LIveBroadcast/LIveBroadcast/classes/Home/Model/GKBAllGameModel.swift
1
334
// // GKBAllGameModel.swift // LIveBroadcast // // Created by KempinGe on 2016/12/13. // Copyright © 2016年 盖凯宾. All rights reserved. // import UIKit class GKBAllGameModel: GKBBaseGameModel { /* tag_id : 1 short_name : LOL tag_name : 英雄联盟 pic_name : */ //继承父类 }
mit
vgorloff/AUHost
Vendor/mc/mcxUIReusable/Sources/AppKit/Direct Subclasses/Responders/Window.AppKit.swift
1
257
// // Window.AppKit.swift // MCA-OSS-AUH // // Created by Vlad Gorlov on 07.02.18. // Copyright © 2018 Vlad Gorlov. All rights reserved. // #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit open class Window: NSWindow { } #endif
mit
PlutoMa/SwiftProjects
029.Beauty Contest/BeautyContest/BeautyContest/AppDelegate.swift
1
2172
// // AppDelegate.swift // BeautyContest // // Created by Dareway on 2017/11/8. // Copyright © 2017年 Pluto. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
briceZhao/ZXRefresh
ZXRefreshExample/ZXRefreshExample/Default/DefaultScrollViewController.swift
1
1506
// // DefaultScrollViewController.swift // ZXRefreshExample // // Created by briceZhao on 2017/8/22. // Copyright © 2017年 chengyue. All rights reserved. // import UIKit class DefaultScrollViewController: UIViewController { var scrollView: UIScrollView? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.automaticallyAdjustsScrollViewInsets = false setUpScrollView() self.scrollView?.addRefreshHeaderView { [unowned self] in self.refresh() } self.scrollView?.addLoadMoreFooterView { [unowned self] in self.loadMore() } } func refresh() { perform(#selector(endRefresing), with: nil, afterDelay: 3) } func endRefresing() { self.scrollView?.endRefreshing(isSuccess: true) } func loadMore() { perform(#selector(endLoadMore), with: nil, afterDelay: 3) } func endLoadMore() { self.scrollView?.endLoadMore(isNoMoreData: true) } func setUpScrollView(){ self.scrollView = UIScrollView(frame: CGRect(x: 0,y: 0,width: 300,height: 300)) self.scrollView?.backgroundColor = UIColor.lightGray self.scrollView?.center = self.view.center self.scrollView?.contentSize = CGSize(width: 300,height: 600) self.view.addSubview(self.scrollView!) } }
mit
suzuki-0000/HoneycombView
HoneycombViewTests/HoneycombViewTests.swift
1
928
// // HoneycombViewTests.swift // HoneycombViewTests // // Created by suzuki_keishi on 2015/07/22. // Copyright (c) 2015年 suzuki_keishi. All rights reserved. // import UIKit import XCTest class HoneycombViewTests: 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
Incipia/IncSpinner
IncSpinner/Classes/IncSpinner.swift
1
9017
// // IncipiaSpinner.swift // IncipiaSpinner // // Created by Gregory Klein on 10/25/16. // Copyright © 2016 Incipia. All rights reserved. // import UIKit // TODO: Use this class to wrap the replicator layer private class IncSpinner_PlusingCircleView: UIView { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } convenience init(frame: CGRect, circleCount count: Int) { self.init(frame: frame) } } private class IncSpinner_PulsingCircleReplicatorLayer: CAReplicatorLayer { private let _padding: CGFloat = 20 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init() { super.init() } convenience init(circleCount count: Int, circleSize size: CGFloat, circleColor color: UIColor, animationDuration: CFTimeInterval) { self.init() _setupFrame(withCircleCount: CGFloat(count), circleSize: size) let layer = _addShapeLayer(withCircleSize: size, color: color) _addAnimation(toShapeLayer: layer, withDuration: animationDuration) instanceCount = count instanceDelay = animationDuration / CFTimeInterval(count) instanceTransform = CATransform3DMakeTranslation(size + _padding, 0, 0) } private func _setupFrame(withCircleCount count: CGFloat, circleSize size: CGFloat) { frame = CGRect(x: 0, y: 0, width: (size + _padding) * count - _padding, height: size) } private func _addShapeLayer(withCircleSize size: CGFloat, color: UIColor) -> CAShapeLayer { let lineWidth: CGFloat = 4.0 let pathFrame = CGRect(origin: .zero, size: CGSize(width: size, height: size)) let circleLayer = CAShapeLayer() circleLayer.path = UIBezierPath(ovalIn: pathFrame).cgPath circleLayer.frame = pathFrame circleLayer.cornerRadius = size * 0.5 circleLayer.borderWidth = lineWidth circleLayer.borderColor = UIColor(white: 1, alpha: 0.2).cgColor circleLayer.fillColor = color.cgColor circleLayer.opacity = 0 addSublayer(circleLayer) return circleLayer } private func _addAnimation(toShapeLayer layer: CAShapeLayer, withDuration duration: TimeInterval) { let group = CAAnimationGroup() group.animations = [CABasicAnimation.incSpinner_scale, CABasicAnimation.incSpinner_fadeIn] group.duration = duration group.repeatCount = Float.infinity group.autoreverses = true layer.add(group, forKey: nil) } } public class IncSpinner { private static let shared = IncSpinner() public static var pulseDuration: TimeInterval = 0.8 public static var fadeDuration: TimeInterval = 0.8 private weak var container: UIView? private var blurredEffectView: UIVisualEffectView? private var vibrancyEffectView: UIVisualEffectView? private var replicatorLayer: CAReplicatorLayer? private var textLabel: UILabel? private var tapToDismissLabel: UILabel? public class func show(inView view: UIView? = nil, withTitle title: String? = nil, usingFont font: UIFont? = nil, style: UIBlurEffectStyle = .dark, color: UIColor) { let container = view ?? UIApplication.shared.keyWindow guard let unwrappedContainer = container else { return } shared._startUsing(container: unwrappedContainer) let blurredEffectView = shared._addEffectView(toContainer: unwrappedContainer) shared.blurredEffectView = blurredEffectView let layer = shared._addSpinnerLayer(to: blurredEffectView.contentView, withCircleColor: color, pulseDuration: pulseDuration) let yOffset: CGFloat = title != nil ? -20 : 0 layer.position = CGPoint(x: unwrappedContainer.bounds.midX, y: unwrappedContainer.bounds.midY + yOffset) shared.replicatorLayer = layer if let title = title { let label = UILabel(incSpinnerText: title, font: font) let vibrancyEffectView = shared._addEffectView(toContainer: unwrappedContainer) vibrancyEffectView.contentView.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false [label.centerYAnchor.constraint(equalTo: vibrancyEffectView.centerYAnchor, constant: 60), label.centerXAnchor.constraint(equalTo: vibrancyEffectView.centerXAnchor), label.leftAnchor.constraint(equalTo: vibrancyEffectView.leftAnchor, constant: 40), label.rightAnchor.constraint(equalTo: vibrancyEffectView.rightAnchor, constant: -40) ].forEach { $0.isActive = true } label.textAlignment = .center shared.textLabel = label shared.vibrancyEffectView = vibrancyEffectView } if let effectView = shared.vibrancyEffectView { let tapToDismissLabel = UILabel(tapToDismissText: "Tap to dismiss", fontName: font?.fontName) tapToDismissLabel.translatesAutoresizingMaskIntoConstraints = false effectView.contentView.addSubview(tapToDismissLabel) tapToDismissLabel.topAnchor.constraint(equalTo: effectView.topAnchor, constant: 40).isActive = true tapToDismissLabel.centerXAnchor.constraint(equalTo: effectView.centerXAnchor).isActive = true shared.tapToDismissLabel = tapToDismissLabel } shared._animateBlurIn(withDuration: fadeDuration, style: style) } public class func hide(completion: (() -> Void)? = nil) { shared._fadeReplicatorLayerOut(withDuration: fadeDuration * 0.8) DispatchQueue.main.incSpinner_delay(fadeDuration * 0.5) { shared._animateBlurOut(withDuration: fadeDuration) { DispatchQueue.main.async { shared._reset() completion?() } } } } private func _startUsing(container c: UIView) { _reset() container = c } private func _reset() { replicatorLayer?.removeFromSuperlayer() blurredEffectView?.removeFromSuperview() vibrancyEffectView?.removeFromSuperview() replicatorLayer = nil blurredEffectView = nil vibrancyEffectView = nil container = nil } private func _addEffectView(toContainer container: UIView) -> UIVisualEffectView { let effectView = UIVisualEffectView(effect: nil) container.incSpinner_addAndFill(subview: effectView) return effectView } private func _addSpinnerLayer(to view: UIView, withCircleColor color: UIColor, pulseDuration: TimeInterval) -> CAReplicatorLayer { let replicatorLayer = IncSpinner_PulsingCircleReplicatorLayer(circleCount: 3, circleSize: 60, circleColor: color, animationDuration: pulseDuration) view.layer.addSublayer(replicatorLayer) return replicatorLayer } private func _animateBlurIn(withDuration duration: TimeInterval, style: UIBlurEffectStyle) { textLabel?.textColor = .clear tapToDismissLabel?.textColor = .clear let blurEffect = UIBlurEffect(style: style) UIView.animate(withDuration: duration, animations: { self.blurredEffectView?.effect = blurEffect }) { finished in guard let effectView = self.vibrancyEffectView, let label = self.textLabel, let tapToDismissLabel = self.tapToDismissLabel else { return } UIView.animate(withDuration: duration * 0.5, animations: { effectView.effect = UIVibrancyEffect(blurEffect: blurEffect) label.alpha = 1.0 label.textColor = .white tapToDismissLabel.alpha = 1.0 tapToDismissLabel.textColor = .white }) } } private func _animateBlurOut(withDuration duration: TimeInterval, completion: (() -> Void)?) { UIView.animate(withDuration: duration, animations: { self.blurredEffectView?.effect = nil self.vibrancyEffectView?.effect = nil self.textLabel?.alpha = 0.0 self.tapToDismissLabel?.alpha = 0.0 }) { (finished) in completion?() } } private func _fadeReplicatorLayerOut(withDuration duration: TimeInterval) { let anim = CABasicAnimation.incSpinner_fadeOut anim.duration = duration anim.fillMode = kCAFillModeForwards anim.isRemovedOnCompletion = false replicatorLayer?.add(anim, forKey: nil) } private func _addTapToDismissLabel(using font: UIFont) { } }
mit
jisudong/study
Study/Study/Study_RxSwift/AnyObserver.swift
1
1088
// // AnyObserver.swift // Study // // Created by syswin on 2017/7/28. // Copyright © 2017年 syswin. All rights reserved. // public struct AnyObserver<Element> : ObserverType { public typealias E = Element public typealias EventHandler = (Event<Element>) -> Void private let observer: EventHandler public init(eventHandler: @escaping EventHandler) { self.observer = eventHandler } public init<O : ObserverType>(_ observer: O) where O.E == Element { self.observer = observer.on } public func on(_ event: Event<Element>) { return self.observer(event) } public func asObserver() -> AnyObserver<E> { return self } } extension AnyObserver { // TODO: 需要修改 } extension ObserverType { public func asObserver() -> AnyObserver<E> { return AnyObserver(self) } public func mapObserver<R>(_ transform: @escaping (R) throws -> E) -> AnyObserver<R> { return AnyObserver { e in self.on(e.map(transform)) } } }
mit
ahoppen/swift
test/stdlib/SIMD.swift
7
2872
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: freestanding import Foundation import StdlibUnittest let SIMDCodableTests = TestSuite("SIMDCodable") // Round an integer to the closest representable JS integer value func jsInteger<T>(_ value: T) -> T where T : SIMD, T.Scalar : FixedWidthInteger { // Attempt to round-trip though Double; if that fails it's because the // rounded value is too large to fit in T, so use the largest value that // does fit instead. let upperBound = T.Scalar(Double(T.Scalar.max).nextDown) var result = T() for i in result.indices { result[i] = T.Scalar(exactly: Double(value[i])) ?? upperBound } return result } func testRoundTrip<T>(_ for: T.Type) where T : SIMD, T.Scalar : FixedWidthInteger { let input = jsInteger(T.random(in: T.Scalar.min ... T.Scalar.max)) let encoder = JSONEncoder() let decoder = JSONDecoder() do { let data = try encoder.encode(input) let output = try decoder.decode(T.self, from: data) expectEqual(input, output) } catch { expectUnreachableCatch(error) } } func testRoundTrip<T>(_ for: T.Type) where T : SIMD, T.Scalar : BinaryFloatingPoint, T.Scalar.RawSignificand : FixedWidthInteger { let input = T.random(in: -16 ..< 16) let encoder = JSONEncoder() let decoder = JSONDecoder() do { let data = try encoder.encode(input) let output = try decoder.decode(T.self, from: data) expectEqual(input, output) } catch { expectUnreachableCatch(error) } } // Very basic round-trip test. We can be much more sophisticated in the future, // but we want to at least exercise the API. Also need to add some negative // tests for the error paths, and test a more substantial set of types. SIMDCodableTests.test("roundTrip") { testRoundTrip(SIMD2<Int8>.self) testRoundTrip(SIMD3<Int8>.self) testRoundTrip(SIMD4<Int8>.self) testRoundTrip(SIMD2<UInt8>.self) testRoundTrip(SIMD3<UInt8>.self) testRoundTrip(SIMD4<UInt8>.self) testRoundTrip(SIMD2<Int32>.self) testRoundTrip(SIMD3<Int32>.self) testRoundTrip(SIMD4<Int32>.self) testRoundTrip(SIMD2<UInt32>.self) testRoundTrip(SIMD3<UInt32>.self) testRoundTrip(SIMD4<UInt32>.self) testRoundTrip(SIMD2<Int>.self) testRoundTrip(SIMD3<Int>.self) testRoundTrip(SIMD4<Int>.self) testRoundTrip(SIMD2<UInt>.self) testRoundTrip(SIMD3<UInt>.self) testRoundTrip(SIMD4<UInt>.self) /* Apparently these fail to round trip not only for i386 but also on older macOS versions, so we'll disable them entirely for now. #if !arch(i386) // https://bugs.swift.org/browse/SR-9759 testRoundTrip(SIMD2<Float>.self) testRoundTrip(SIMD3<Float>.self) testRoundTrip(SIMD4<Float>.self) testRoundTrip(SIMD2<Double>.self) testRoundTrip(SIMD3<Double>.self) testRoundTrip(SIMD4<Double>.self) #endif */ } runAllTests()
apache-2.0
nifty-swift/Nifty
Sources/exp2.swift
2
1652
/*************************************************************************************************** * exp2.swift * * This file provides functionality for base 2 exponentiation. * * Author: Philip Erickson * Creation Date: 1 May 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. * * Copyright 2016 Philip Erickson **************************************************************************************************/ /// Compute 2 raised to the power x. Mathematically, exp2(x) is the same as /// exp(x*log(2)). #if os(Linux) @_exported import func Glibc.exp2 #else @_exported import func Darwin.exp2 #endif public func exp2(_ v: Vector<Double>) -> Vector<Double> { let newData = v.data.map({exp2($0)}) return Vector(newData, name: v.name, showName: v.showName) } public func exp2(_ m: Matrix<Double>) -> Matrix<Double> { let newData = m.data.map({exp2($0)}) return Matrix(m.size, newData, name: m.name, showName: m.showName) } public func exp2(_ t: Tensor<Double>) -> Tensor<Double> { let newData = t.data.map({exp2($0)}) return Tensor(t.size, newData, name: t.name, showName: t.showName) }
apache-2.0
dreamsxin/swift
validation-test/compiler_crashers_fixed/27802-swift-constraints-constraintsystem-finalize.swift
11
452
// 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 let a{b<:let d{enum S<T where f:a{struct B{}class B{var b=B
apache-2.0
patrick-sheehan/cwic
Source/UITabBarController.swift
1
328
// // UITabBarController.swift // cwic // // Created by Patrick Sheehan on 7/1/17. // Copyright © 2017 Síocháin Solutions. All rights reserved. // import UIKit extension UITabBarController { convenience init(_ viewControllers: [UIViewController]) { self.init() self.viewControllers = viewControllers } }
gpl-3.0
XCEssentials/UniFlow
Sources/3_Storage/Storage+GET+SomeState.swift
1
1639
/* MIT License Copyright (c) 2016 Maxim Khatskevich (maxim@khatskevi.ch) 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 extension Storage { subscript<S: SomeState>(_: S.Type) -> S? { try? fetchState(ofType: S.self) } func hasState<S: SomeState>(ofType _: S.Type) -> Bool { self[S.self] != nil } } //--- public extension SomeState { static func fetch(from storage: Storage) throws -> Self { try storage.fetchState(ofType: self) } //--- static func isPresent(in storage: Storage) -> Bool { storage.hasState(ofType: self) } }
mit
adamkaplan/swifter
SwifterTests/SwiftTestUtilities.swift
1
479
// // SwiftTestUtilities.swift // Swifter // // Created by Daniel Hanggi on 7/7/14. // Copyright (c) 2014 Yahoo!. All rights reserved. // import XCTest func assertArraysEqual<T: Equatable>(one: [T], two: [T]) -> () { let initEq = (one.count - two.count) == 0 XCTAssertTrue(one.reduce((initEq, 0)) { (acc: (Bool, Int), fstElem: T) in let (eq, id) = acc let sndElem = two[id] return (eq && (fstElem == sndElem), id + 1) }.0) }
apache-2.0
idapgroup/IDPDesign
Tests/iOS/iOSTests/Specs/Lens+UITableViewCellSpec.swift
1
12756
// // Lens+UITableViewCellSpec.swift // iOSTests // // Created by Oleksa 'trimm' Korin on 9/2/17. // Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved. // import Quick import Nimble import UIKit @testable import IDPDesign extension UITableViewCell: UITableViewCellProtocol { } class LensUITableViewCellSpec: QuickSpec { override func spec() { describe("Lens+UITableViewCellSpec") { context("imageView") { it("should get and set") { let lens: Lens<UITableViewCell, UIImageView?> = imageView() let object = UITableViewCell() let value: UIImageView = UIImageView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).toNot(equal(value)) expect(resultObject.imageView).to(equal(resultValue)) } } context("textLabel") { it("should get and set") { let lens: Lens<UITableViewCell, UILabel?> = textLabel() let object = UITableViewCell() let value: UILabel = UILabel() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).toNot(equal(value)) expect(resultObject.textLabel).to(equal(resultValue)) } } context("detailTextLabel") { it("should get and set") { let lens: Lens<UITableViewCell, UILabel?> = detailTextLabel() let object = UITableViewCell(style: .value2, reuseIdentifier: nil) let value: UILabel = UILabel() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).toNot(equal(value)) expect(resultObject.detailTextLabel).to(equal(resultValue)) } } context("contentView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView> = contentView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).toNot(equal(value)) expect(resultObject.contentView).to(equal(resultValue)) } } context("backgroundView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView?> = backgroundView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.backgroundView).to(equal(value)) } } context("selectedBackgroundView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView?> = selectedBackgroundView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.selectedBackgroundView).to(equal(value)) } } context("multipleSelectionBackgroundView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView?> = multipleSelectionBackgroundView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.multipleSelectionBackgroundView).to(equal(value)) } } context("selectionStyle") { it("should get and set") { let lens: Lens<UITableViewCell, UITableViewCell.SelectionStyle> = selectionStyle() let object = UITableViewCell() let value: UITableViewCell.SelectionStyle = .none let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.selectionStyle).to(equal(value)) } } context("isSelected") { it("should get and set") { let lens: Lens<UITableViewCell, Bool> = isSelected() let object = UITableViewCell() let value: Bool = !object.isSelected let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.isSelected).to(equal(value)) } } context("isHighlighted") { it("should get and set") { let lens: Lens<UITableViewCell, Bool> = isHighlighted() let object = UITableViewCell() let value: Bool = !object.isHighlighted let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.isHighlighted).to(equal(value)) } } context("showsReorderControl") { it("should get and set") { let lens: Lens<UITableViewCell, Bool> = showsReorderControl() let object = UITableViewCell() let value: Bool = !object.showsReorderControl let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.showsReorderControl).to(equal(value)) } } context("shouldIndentWhileEditing") { it("should get and set") { let lens: Lens<UITableViewCell, Bool> = shouldIndentWhileEditing() let object = UITableViewCell() let value: Bool = !object.shouldIndentWhileEditing let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.shouldIndentWhileEditing).to(equal(value)) } } context("accessoryType") { it("should get and set") { let lens: Lens<UITableViewCell, UITableViewCell.AccessoryType> = accessoryType() let object = UITableViewCell() let value: UITableViewCell.AccessoryType = .checkmark let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.accessoryType).to(equal(value)) } } context("accessoryView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView?> = accessoryView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.accessoryView).to(equal(value)) } } context("editingAccessoryType") { it("should get and set") { let lens: Lens<UITableViewCell, UITableViewCell.AccessoryType> = editingAccessoryType() let object = UITableViewCell() let value: UITableViewCell.AccessoryType = .checkmark let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.editingAccessoryType).to(equal(value)) } } context("editingAccessoryView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView?> = editingAccessoryView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.editingAccessoryView).to(equal(value)) } } context("indentationLevel") { it("should get and set") { let lens: Lens<UITableViewCell, Int> = indentationLevel() let object = UITableViewCell() let value: Int = 2 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.indentationLevel).to(equal(value)) } } context("indentationWidth") { it("should get and set") { let lens: Lens<UITableViewCell, CGFloat> = indentationWidth() let object = UITableViewCell() let value: CGFloat = 0.5 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.indentationWidth).to(equal(value)) } } context("separatorInset") { it("should get and set") { let lens: Lens<UITableViewCell, UIEdgeInsets> = separatorInset() let object = UITableViewCell(style: .subtitle, reuseIdentifier: nil) let value: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) // UITableViewCell automatically adds 8 pixels for left inset on top of the inset let referenceValue = UIEdgeInsets(top: 0, left: 18, bottom: 0, right: 10) expect(resultValue).to(equal(referenceValue)) expect(resultObject.separatorInset).to(equal(referenceValue)) } } context("isEditing") { it("should get and set") { let lens: Lens<UITableViewCell, Bool> = isEditing() let object = UITableViewCell() let value: Bool = !object.isEditing let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.isEditing).to(equal(value)) } } context("focusStyle") { it("should get and set") { let lens: Lens<UITableViewCell, UITableViewCell.FocusStyle> = focusStyle() let object = UITableViewCell() let value: UITableViewCell.FocusStyle = .custom let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.focusStyle).to(equal(value)) } } } } }
bsd-3-clause
steelwheels/Canary
UnitTest/UnitTest/UTStream.swift
1
2158
/** * @file UTStream.swift * @brief Unit test for CNStringStream, CNArrayStream class * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import Canary import Foundation public func UTStream(console cons: CNConsole) -> Bool { console.print(string: "**** testStringStream ****\n") let res0 = testStringStream(console: cons) console.print(string: "**** testArrayStream ****\n") let res1 = testArrayStream(console: cons) return res0 && res1 } private func testStringStream(console cons: CNConsole) -> Bool { let stream0 = CNStringStream(string: "0123456789") let count0 = stream0.count /* peek */ console.print(string: "* peek\n") for i in 0..<count0 { if let c = stream0.peek(offset: i) { console.print(string: "\(i):\(c) ") } else { console.print(string: "\(i):EOF ") } } console.print(string: "\n") /* getc */ console.print(string: "* getc\n") if let c = stream0.getc() { console.print(string: "c=\(c)\n") } else { console.print(string: "c=EOF\n") } /* gets */ console.print(string: "* gets: 5\n") let s = stream0.gets(count: 5) console.print(string: "s=\(s)\n") /* ungetc */ console.print(string: "* ungetc\n") if let c = stream0.ungetc() { console.print(string: "c=\(c)\n") } else { console.print(string: "c=EOF\n") } return true } private func testArrayStream(console cons: CNConsole) -> Bool { let stream0 = CNArrayStream(source: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) let count0 = stream0.count /* peek */ console.print(string: "* peek\n") for i in 0..<count0 { if let d = stream0.peek(offset: i) { console.print(string: "\(i):\(d) ") } else { console.print(string: "\(i):EOF ") } } console.print(string: "\n") /* get */ console.print(string: "* get\n") if let d = stream0.get() { console.print(string: "d=\(d)\n") } else { console.print(string: "d=EOF\n") } /* get */ console.print(string: "* get: 5\n") let d = stream0.get(count: 5) console.print(string: "d=\(d)\n") /* unget */ console.print(string: "* unget\n") if let d = stream0.unget() { console.print(string: "d=\(d)\n") } else { console.print(string: "d=EOF\n") } return true }
gpl-2.0
velvetroom/columbus
Source/View/Settings/VSettingsListCellTravelModeList.swift
1
3152
import UIKit final class VSettingsListCellTravelModeList:VCollection< ArchSettings, VSettingsListCellTravelModeListCell> { weak var model:MSettingsTravelMode? weak var viewSelector:VSettingsListCellTravelModeListSelector! weak var layoutSelectorLeft:NSLayoutConstraint! weak var layoutSelectorTop:NSLayoutConstraint! let selectorSize_2:CGFloat private var cellSize:CGSize? required init(controller:CSettings) { selectorSize_2 = VSettingsListCellTravelModeList.Constants.selectorSize / 2.0 super.init(controller:controller) config() selectCurrent() } required init?(coder:NSCoder) { return nil } override func collectionView( _ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { guard let cellSize:CGSize = self.cellSize else { let width:CGFloat = collectionView.bounds.width let height:CGFloat = collectionView.bounds.height let items:Int = collectionView.numberOfItems(inSection:0) let itemsFloat:CGFloat = CGFloat(items) let widthPerItem:CGFloat = width / itemsFloat let cellSize:CGSize = CGSize( width:widthPerItem, height:height) self.cellSize = cellSize return cellSize } return cellSize } override func collectionView( _ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { guard let count:Int = model?.items.count else { return 0 } return count } override func collectionView( _ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MSettingsTravelModeProtocol = modelAtIndex(index:indexPath) let cell:VSettingsListCellTravelModeListCell = cellAtIndex(indexPath:indexPath) cell.config(model:item) return cell } override func collectionView( _ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool { guard let model:MSettingsTravelMode = self.model else { return false } let item:MSettingsTravelModeProtocol = modelAtIndex( index:indexPath) guard model.settings.travelMode == item.mode else { return true } return false } override func collectionView( _ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) { model?.selected(index:indexPath.item) updateSelector(animationDuration:VSettingsListCellTravelModeList.Constants.animationDuration) } }
mit
iOS-mamu/SS
P/Library/Eureka/Source/Core/InlineRowType.swift
1
5277
// InlineRowType.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public protocol BaseInlineRowType { /** Method that can be called to expand (open) an inline row */ func expandInlineRow() /** Method that can be called to collapse (close) an inline row */ func collapseInlineRow() /** Method that can be called to change the status of an inline row (expanded/collapsed) */ func toggleInlineRow() } /** * Protocol that every inline row type has to conform to. */ public protocol InlineRowType: TypedRowType, BaseInlineRowType { associatedtype InlineRow: BaseRow, RowType, TypedRowType /** This function is responsible for setting up an inline row before it is first shown. */ func setupInlineRow(_ inlineRow: InlineRow) } extension InlineRowType where Self: BaseRow, Self.InlineRow : BaseRow, Self.Cell.Value == Self.Value, Self.InlineRow.Cell.Value == Self.InlineRow.Value, Self.InlineRow.Value == Self.Value { /// The row that will be inserted below after the current one when it is selected. public var inlineRow : Self.InlineRow? { return _inlineRow as? Self.InlineRow } /** Method that can be called to expand (open) an inline row. */ public func expandInlineRow() { if let _ = inlineRow { return } if var section = section, let form = section.form { let inline = InlineRow.init() { _ in } inline.value = value inline.onChange { [weak self] in self?.value = $0.value self?.updateCell() } setupInlineRow(inline) if (form.inlineRowHideOptions ?? Form.defaultInlineRowHideOptions).contains(.AnotherInlineRowIsShown) { for row in form.allRows { if let inlineRow = row as? BaseInlineRowType { inlineRow.collapseInlineRow() } } } if let onExpandInlineRowCallback = onExpandInlineRowCallback { onExpandInlineRowCallback(cell, self, inline) } if let indexPath = indexPath() { section.insert(inline, at: indexPath.row + 1) _inlineRow = inline cell.formViewController()?.makeRowVisible(inline) } } } /** Method that can be called to collapse (close) an inline row. */ public func collapseInlineRow() { if let selectedRowPath = indexPath(), let inlineRow = _inlineRow { if let onCollapseInlineRowCallback = onCollapseInlineRowCallback { onCollapseInlineRowCallback(cell, self, inlineRow as! InlineRow) } section?.remove(at: selectedRowPath.row + 1) _inlineRow = nil } } /** Method that can be called to change the status of an inline row (expanded/collapsed). */ public func toggleInlineRow() { if let _ = inlineRow { collapseInlineRow() } else{ expandInlineRow() } } /** Sets a block to be executed when a row is expanded. */ public func onExpandInlineRow(_ callback: @escaping (Cell, Self, InlineRow)->()) -> Self { callbackOnExpandInlineRow = callback return self } /** Sets a block to be executed when a row is collapsed. */ public func onCollapseInlineRow(_ callback: @escaping (Cell, Self, InlineRow)->()) -> Self { callbackOnCollapseInlineRow = callback return self } /// Returns the block that will be executed when this row expands public var onCollapseInlineRowCallback: ((Cell, Self, InlineRow)->())? { return callbackOnCollapseInlineRow as! ((Cell, Self, InlineRow)->())? } /// Returns the block that will be executed when this row collapses public var onExpandInlineRowCallback: ((Cell, Self, InlineRow)->())? { return callbackOnExpandInlineRow as! ((Cell, Self, InlineRow)->())? } }
mit
davetobin/pxctest
PXCTestKit/Command/RunTests/RunTestsPool.swift
2
4121
// // RunTestsPool.swift // pxctest // // Created by Johannes Plunien on 23/01/17. // Copyright © 2017 Johannes Plunien. All rights reserved. // import FBSimulatorControl import Foundation final class RunTestsPool { private let context: AllocationContext private let pool: FBSimulatorPool private let targets: [FBXCTestRunTarget] private var workers: [RunTestsWorker] = [] init(context: AllocationContext, pool: FBSimulatorPool, targets: [FBXCTestRunTarget]) { self.context = context self.pool = pool self.targets = targets } func allocateWorkers() throws -> [RunTestsWorker] { for target in targets { if context.testsToRun.count > 0 && context.testsToRun[target.name] == nil { continue } for simulatorConfiguration in context.simulatorConfigurations { try allocateWorkers(simulatorConfiguration: simulatorConfiguration, target: target) } } return workers } // MARK: - Private private func allocateWorkers(simulatorConfiguration: FBSimulatorConfiguration, target: FBXCTestRunTarget) throws { if context.partitions == 1 { try context.fileManager.createDirectoryFor(simulatorConfiguration: simulatorConfiguration, target: target.name) let simulator = try pool.allocateSimulator(with: simulatorConfiguration, options: context.simulatorOptions.allocationOptions) let worker = RunTestsWorker( name: target.name, applications: target.applications, simulator: simulator, targetName: target.name, testLaunchConfiguration: target.testLaunchConfiguration ) workers.append(worker) } else { let simulators = try (0..<context.partitions).map { _ in try pool.allocateSimulator(with: simulatorConfiguration, options: context.simulatorOptions.allocationOptions) } let tests = try listTests(simulator: simulators.first!, target: target) let partitionManager = RunTestsPartitionManager(fileURL: context.fileManager.runtimeCacheURL, partitions: context.partitions, targetName: target.name) for (index, subsetOfTests) in partitionManager.split(tests: tests).enumerated() { let partitionName = "\(target.name)/partition-\(index)" try context.fileManager.createDirectoryFor(simulatorConfiguration: simulatorConfiguration, target: partitionName) let worker = RunTestsWorker( name: partitionName, applications: target.applications, simulator: simulators[index], targetName: target.name, testLaunchConfiguration: target.testLaunchConfiguration.withTestsToRun(Set(subsetOfTests.map { $0.testName })) ) workers.append(worker) } } } private func listTests(simulator: FBSimulator, target: FBXCTestRunTarget) throws -> Set<String> { let listTestsShimPath = try ListTestsShim.copy() let testsToRun = context.testsToRun[target.name] ?? Set<String>() let environment = Environment.injectLibrary(atPath: listTestsShimPath, into: target.testLaunchConfiguration.testEnvironment) let testLaunchConfiguration = target.testLaunchConfiguration .withTestEnvironment(environment) .withTestsToRun(testsToRun.union(target.testLaunchConfiguration.testsToRun ?? Set<String>())) let reporter = TestReporter(simulatorIdentifier: simulator.identifier, testTargetName: target.name) let adapter = TestReporterAdapter(reporter: reporter) try simulator.install(applications: target.applications) try simulator.startTest(with: testLaunchConfiguration, reporter: adapter) try simulator.waitUntilAllTestRunnersHaveFinishedTesting(withTimeout: 120.0) return Set(reporter.runtimeRecords.map({ $0.testName })).subtracting(target.testLaunchConfiguration.testsToSkip) } }
mit
Yalantis/StarWars.iOS
Example/StarWarsAnimations/Controller/MainSettingsViewController.swift
1
1829
// // MainSettingsViewController.swift // StarWarsAnimations // // Created by Artem Sidorenko on 10/19/15. // Copyright © 2015 Yalantis. All rights reserved. // import UIKit class MainSettingsViewController: UIViewController { @IBOutlet fileprivate weak var saveButton: UIButton! var theme: SettingsTheme! { didSet { settingsViewController?.theme = theme saveButton?.backgroundColor = theme.primaryColor } } override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() } fileprivate func setupNavigationBar() { navigationController!.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navigationController!.navigationBar.shadowImage = UIImage() navigationController!.navigationBar.isTranslucent = true navigationController!.navigationBar.titleTextAttributes = [ NSAttributedString.Key.font: UIFont(name: "GothamPro", size: 20)!, NSAttributedString.Key.foregroundColor: UIColor.white ] } fileprivate var settingsViewController: SettingsViewController? override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let settings = segue.destination as? SettingsViewController { settingsViewController = settings settings.themeChanged = { [unowned self, unowned settings] darkside, center in let center = self.view.convert(center, from: settings.view) self.view.animateCircular(withDuration: 0.5, center: center, revert: darkside ? false : true, animations: { self.theme = darkside ? .dark : .light }) } } } override var prefersStatusBarHidden : Bool { return true } }
mit
lanit-tercom-school/grouplock
GroupLockiOS/GroupLockTests/ProcessedFileModelsComparison.swift
1
2074
// // ProcessedFileModelsComparison.swift // GroupLock // // Created by Sergej Jaskiewicz on 26.07.16. // Copyright © 2016 Lanit-Tercom School. All rights reserved. // @testable import GroupLock // We are using this methods and not the `==` operator so that in tests we can define equality in a diferent way. extension ProcessedFile.Share.Response: EquatableModel { func isEqualTo(_ response: ProcessedFile.Share.Response) -> Bool { return self.dataToShare.count == response.dataToShare.count && !zip(self.dataToShare.sorted(), response.dataToShare.sorted()).contains { $0 != $1 } && ((self.excludedActivityTypes == nil && response.excludedActivityTypes == nil) || (self.excludedActivityTypes != nil && response.excludedActivityTypes != nil // swiftlint:disable:next force_unwrapping && !zip(self.excludedActivityTypes!.sorted(by: { $0.rawValue < $1.rawValue }), // swiftlint:disable:next force_unwrapping response.excludedActivityTypes!.sorted(by: { $0.rawValue < $1.rawValue })) .contains { $0 != $1 })) } } extension ProcessedFile.Fetch.ViewModel.FileInfo: EquatableModel { func isEqualTo(_ fileInfo: ProcessedFile.Fetch.ViewModel.FileInfo) -> Bool { return self.fileName == fileInfo.fileName && self.encrypted == fileInfo.encrypted && self.fileThumbnail.isEqualToImage(fileInfo.fileThumbnail) } } extension ProcessedFile.Fetch.ViewModel: EquatableModel { func isEqualTo(_ viewModel: ProcessedFile.Fetch.ViewModel) -> Bool { return self.fileInfo.count == viewModel.fileInfo.count && !zip(self.fileInfo, viewModel.fileInfo).contains { !$0.isEqualTo($1) } } } extension ProcessedFile.Fetch.Response: EquatableModel { func isEqualTo(_ response: ProcessedFile.Fetch.Response) -> Bool { return self.files.count == response.files.count && !zip(self.files, response.files).contains { $0 != $1 } } }
apache-2.0
adrfer/swift
test/SourceKit/SourceDocInfo/cursor_info.swift
1
10370
import Foo import FooSwiftModule var glob : Int func foo(x: Int) {} func goo(x: Int) { foo(glob+x+Int(fooIntVar)+fooSwiftFunc()) } /// Aaa. S1. Bbb. struct S1 {} var w : S1 func test2(x: S1) {} class CC { init(x: Int) { self.init(x:0) } } var testString = "testString" let testLetString = "testString" func testLetParam(arg1 : Int) { } func testVarParam(var arg1 : Int) { } func testDefaultParam(arg1: Int = 0) { } fooSubFunc1(0) func myFunc(arg1: String) { } func myFunc(arg1: String, options: Int) { } var derivedObj = FooClassDerived() typealias MyInt = Int var x: MyInt import FooHelper.FooHelperSub class C2 { lazy var lazy_bar : Int = { return x }() } func test1(foo: FooUnavailableMembers) { foo.availabilityIntroduced() foo.swiftUnavailable() foo.unavailable() foo.availabilityIntroducedMsg() foo.availabilityDeprecated() } public class SubscriptCursorTest { public subscript (i: Int) -> Int { return 0 } public static func test() { let s = SubscriptCursorTest() let a = s[1234] + s[4321] } } // RUN: rm -rf %t.tmp // RUN: mkdir %t.tmp // RUN: %swiftc_driver -emit-module -o %t.tmp/FooSwiftModule.swiftmodule %S/Inputs/FooSwiftModule.swift // RUN: %sourcekitd-test -req=cursor -pos=9:8 %s -- -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | FileCheck -check-prefix=CHECK1 %s // CHECK1: source.lang.swift.ref.var.global (4:5-4:9) // CHECK1-NEXT: glob // CHECK1-NEXT: s:v11cursor_info4globSi{{$}} // CHECK1-NEXT: Int // RUN: %sourcekitd-test -req=cursor -pos=9:11 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK2 %s // CHECK2: source.lang.swift.ref.function.operator.infix () // CHECK2-NEXT: + // CHECK2-NEXT: s:ZFsoi1pFTSiSi_Si // CHECK2-NEXT: (Int, Int) -> Int{{$}} // CHECK2-NEXT: Swift{{$}} // CHECK2-NEXT: SYSTEM // CHECK2-NEXT: <Declaration>func +(lhs: <Type usr="s:Si">Int</Type>, rhs: <Type usr="s:Si">Int</Type>) -&gt; <Type usr="s:Si">Int</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=9:12 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK3 %s // CHECK3: source.lang.swift.ref.var.local (8:10-8:11) // CHECK3-NEXT: x{{$}} // CHECK3-NEXT: s:vF11cursor_info3gooFSiT_L_1xSi{{$}} // CHECK3-NEXT: Int{{$}} // RUN: %sourcekitd-test -req=cursor -pos=9:18 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK4 %s // CHECK4: source.lang.swift.ref.var.global ({{.*}}Foo.framework/Headers/Foo.h:62:12-62:21) // CHECK4-NEXT: fooIntVar{{$}} // CHECK4-NEXT: c:@fooIntVar{{$}} // CHECK4-NEXT: Int32{{$}} // CHECK4-NEXT: Foo{{$}} // CHECK4-NEXT: <Declaration>var fooIntVar: <Type usr="s:Vs5Int32">Int32</Type></Declaration> // CHECK4-NEXT: <Variable file="{{[^"]+}}Foo.h" line="{{[0-9]+}}" column="{{[0-9]+}}"><Name>fooIntVar</Name><USR>c:@fooIntVar</USR><Declaration>var fooIntVar: Int32</Declaration><Abstract><Para> Aaa. fooIntVar. Bbb.</Para></Abstract></Variable> // RUN: %sourcekitd-test -req=cursor -pos=8:7 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK5 %s // CHECK5: source.lang.swift.decl.function.free (8:6-8:17) // CHECK5-NEXT: goo(_:){{$}} // CHECK5-NEXT: s:F11cursor_info3gooFSiT_{{$}} // CHECK5-NEXT: (Int) -> (){{$}} // RUN: %sourcekitd-test -req=cursor -pos=9:32 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK6 %s // CHECK6: source.lang.swift.ref.function.free () // CHECK6-NEXT: fooSwiftFunc // CHECK6-NEXT: s:F14FooSwiftModule12fooSwiftFuncFT_Si // CHECK6-NEXT: () -> Int // CHECK6-NEXT: FooSwiftModule // CHECK6-NEXT: <Declaration>func fooSwiftFunc() -&gt; <Type usr="s:Si">Int</Type></Declaration> // CHECK6-NEXT: {{^}}<Function><Name>fooSwiftFunc()</Name><USR>s:F14FooSwiftModule12fooSwiftFuncFT_Si</USR><Declaration>func fooSwiftFunc() -&gt; Int</Declaration><Abstract><Para>This is &apos;fooSwiftFunc&apos; from &apos;FooSwiftModule&apos;.</Para></Abstract></Function>{{$}} // RUN: %sourcekitd-test -req=cursor -pos=14:10 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK7 %s // CHECK7: source.lang.swift.ref.struct (13:8-13:10) // CHECK7-NEXT: S1 // CHECK7-NEXT: s:V11cursor_info2S1 // CHECK7-NEXT: S1.Type // CHECK7-NEXT: <Declaration>struct S1</Declaration> // CHECK7-NEXT: <Class file="{{[^"]+}}cursor_info.swift" line="13" column="8"><Name>S1</Name><USR>s:V11cursor_info2S1</USR><Declaration>struct S1</Declaration><Abstract><Para>Aaa. S1. Bbb.</Para></Abstract></Class> // RUN: %sourcekitd-test -req=cursor -pos=19:12 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK8 %s // CHECK8: source.lang.swift.ref.function.constructor (18:3-18:15) // CHECK8-NEXT: init // CHECK8-NEXT: s:FC11cursor_info2CCcFT1xSi_S0_ // CHECK8-NEXT: CC.Type -> (x: Int) -> CC // RUN: %sourcekitd-test -req=cursor -pos=23:6 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK9 %s // CHECK9: source.lang.swift.decl.var.global (23:5-23:15) // CHECK9: <Declaration>var testString: <Type usr="s:SS">String</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=24:6 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK10 %s // CHECK10: source.lang.swift.decl.var.global (24:5-24:18) // CHECK10: <Declaration>let testLetString: <Type usr="s:SS">String</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=26:20 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK11 %s // CHECK11: source.lang.swift.decl.var.local (26:19-26:23) // CHECK11: <Declaration>let arg1: <Type usr="s:Si">Int</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=28:24 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK12 %s // CHECK12: source.lang.swift.decl.var.local (28:23-28:27) // CHECK12: <Declaration>let arg1: <Type usr="s:Si">Int</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=31:7 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK13 %s // CHECK13: source.lang.swift.decl.function.free (31:6-31:37) // CHECK13: <Declaration>func testDefaultParam(arg1: <Type usr="s:Si">Int</Type> = default)</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=34:4 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK14 %s // CHECK14: source.lang.swift.ref.function.free ({{.*}}Foo.framework/Frameworks/FooSub.framework/Headers/FooSub.h:4:5-4:16) // CHECK14: fooSubFunc1 // CHECK14: c:@F@fooSubFunc1 // CHECK14: Foo.FooSub{{$}} // RUN: %sourcekitd-test -req=cursor -pos=38:8 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK15 %s // CHECK15: source.lang.swift.decl.function.free (38:6-38:40) // CHECK15: myFunc // CHECK15: <Declaration>func myFunc(arg1: <Type usr="s:SS">String</Type>, options: <Type usr="s:Si">Int</Type>)</Declaration> // CHECK15: RELATED BEGIN // CHECK15-NEXT: <RelatedName usr="s:F11cursor_info6myFuncFSST_">myFunc(_:)</RelatedName> // CHECK15-NEXT: RELATED END // RUN: %sourcekitd-test -req=cursor -pos=41:26 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK16 %s // CHECK16: source.lang.swift.ref.class ({{.*}}Foo.framework/Headers/Foo.h:157:12-157:27) // CHECK16-NEXT: FooClassDerived // CHECK16-NEXT: c:objc(cs)FooClassDerived // RUN: %sourcekitd-test -req=cursor -pos=1:10 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK17 %s // CHECK17: source.lang.swift.ref.module () // CHECK17-NEXT: Foo{{$}} // RUN: %sourcekitd-test -req=cursor -pos=44:10 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK18 %s // CHECK18: source.lang.swift.ref.typealias (43:11-43:16) // CHECK18: <Declaration>typealias MyInt = <Type usr="s:Si">Int</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=46:10 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK19 %s // CHECK19: source.lang.swift.ref.module () // CHECK19-NEXT: FooHelper{{$}} // RUN: %sourcekitd-test -req=cursor -pos=46:25 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK20 %s // CHECK20: source.lang.swift.ref.module () // CHECK20-NEXT: FooHelperSub{{$}} // RUN: %sourcekitd-test -req=cursor -pos=50:12 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK21 %s // CHECK21: source.lang.swift.ref.var.global (44:5-44:6) // CHECK21-NEXT: {{^}}x{{$}} // RUN: %sourcekitd-test -req=cursor -pos=55:15 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK22 %s // CHECK22: <Declaration>func availabilityIntroduced()</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=56:15 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK23 %s // CHECK23-NOT: <Declaration>func swiftUnavailable()</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=57:15 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK24 %s // CHECK24-NOT: <Declaration>func unavailable()</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=58:15 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK25 %s // CHECK25: <Declaration>func availabilityIntroducedMsg()</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=59:15 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK26 %s // CHECK26-NOT: <Declaration>func availabilityDeprecated()</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=69:14 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK27 %s // CHECK27: <Declaration>public subscript (i: <Type usr="s:Si">Int</Type>) -&gt; <Type usr="s:Si">Int</Type> { get }</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=69:19 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK28 %s // CHECK28: <Declaration>public subscript (i: <Type usr="s:Si">Int</Type>) -&gt; <Type usr="s:Si">Int</Type> { get }</Declaration>
apache-2.0
adrfer/swift
test/SILGen/break_continue.swift
2
505
// RUN: %target-swift-frontend -module-name Swift -parse-stdlib -emit-silgen %s | FileCheck %s enum Optional<T> { case Some(T), None } protocol BooleanType { var boolValue: Bool { get } } struct Bool : BooleanType { var value: Builtin.Int1 func _getBuiltinLogicValue() -> Builtin.Int1 { return value } var boolValue: Bool { return self } } // CHECK-LABEL: sil hidden @_TFs5test1 func test1(bi: Bool) { var b = bi for var c = b; b; b = c { if b { break } continue } }
apache-2.0
mrdepth/Neocom
Legacy/Neocom/Neocom/FittingLoadoutsPresenter.swift
2
8636
// // FittingLoadoutsPresenter.swift // Neocom // // Created by Artem Shimanski on 11/23/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData import TreeController import Expressible import CoreData class FittingLoadoutsPresenter: TreePresenter { typealias View = FittingLoadoutsViewController typealias Interactor = FittingLoadoutsInteractor typealias Presentation = [AnyTreeItem] weak var view: View? lazy var interactor: Interactor! = Interactor(presenter: self) var content: Interactor.Content? var presentation: Presentation? var loading: Future<Presentation>? var loadouts: Atomic<[Tree.Item.Section<Tree.Content.LoadoutsSection, Tree.Item.LoadoutRow>]?> = Atomic(nil) required init(view: View) { self.view = view } func configure() { view?.tableView.register([Prototype.TreeSectionCell.default, Prototype.TreeDefaultCell.default]) interactor.configure() applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in self?.applicationWillEnterForeground() } switch view?.input { case .ship?: view?.title = NSLocalizedString("Ships", comment: "") case .structure?: view?.title = NSLocalizedString("Structures", comment: "") default: break } } private var applicationWillEnterForegroundObserver: NotificationObserver? func presentation(for content: Interactor.Content) -> Future<Presentation> { guard let input = view?.input else {return .init(.failure(NCError.invalidInput(type: type(of: self))))} let treeController = view?.treeController let storageContext = interactor.storageContext return storageContext.perform { [weak self] () -> [Tree.Item.Section<Tree.Content.LoadoutsSection, Tree.Item.LoadoutRow>] in guard let strongSelf = self else {throw NCError.cancelled(type: type(of: self), function: #function)} let loadouts = try storageContext.managedObjectContext .from(Loadout.self) .fetch() return strongSelf.presentation(for: loadouts, categoryID: input, treeController: treeController) }.then(on: .main) { [weak self] result -> Presentation in self?.loadouts.value = result let menu: [Tree.Item.RoutableRow<Tree.Content.Default>] switch input { case .ship: let category = Services.sde.viewContext.dgmppItemCategory(categoryID: .ship)! let typePickerRoute = Router.Fitting.dgmTypePicker(.init(category: category, completion: { (controller, type) in })) menu = [ Tree.Item.RoutableRow(Tree.Content.Default(title: NSLocalizedString("New Ship Fit", comment: ""), image:Image( #imageLiteral(resourceName: "fitting")), accessoryType: .disclosureIndicator), route: typePickerRoute), Tree.Item.RoutableRow(Tree.Content.Default(title: NSLocalizedString("Import/Export", comment: ""), image:Image( #imageLiteral(resourceName: "browser")), accessoryType: .disclosureIndicator), route: nil) ] case .structure: menu = [ Tree.Item.RoutableRow(Tree.Content.Default(title: NSLocalizedString("New Structure Fit", comment: ""), image:Image( #imageLiteral(resourceName: "station")), accessoryType: .disclosureIndicator), route: nil) ] default: menu = [] } return [Tree.Item.Virtual(children: menu, diffIdentifier: "Menu").asAnyItem, Tree.Item.Virtual(children: result, diffIdentifier: "Loadouts").asAnyItem ] } } private func presentation(for loadouts: [Loadout], categoryID: SDECategoryID, treeController: TreeController?) -> [Tree.Item.Section<Tree.Content.LoadoutsSection, Tree.Item.LoadoutRow>] { let context = Services.sde.newBackgroundContext() return context.performAndWait { () -> [Tree.Item.Section<Tree.Content.LoadoutsSection, Tree.Item.LoadoutRow>] in let items = loadouts.compactMap { i -> (loadout: Loadout, type: SDEInvType)? in context.invType(Int(i.typeID)).map {(loadout: i, type: $0)} }.filter {$0.type.group?.category?.categoryID == categoryID.rawValue} .sorted {$0.type.typeName ?? "" < $1.type.typeName ?? ""} let groups = Dictionary(grouping: items) {$0.type.group}.sorted {$0.key?.groupName ?? "" < $1.key?.groupName ?? ""} return groups.map { i -> Tree.Item.Section<Tree.Content.LoadoutsSection, Tree.Item.LoadoutRow> in let rows = i.value.sorted{$0.0.name ?? "" < $1.0.name ?? ""} .map{ Tree.Item.LoadoutRow(Tree.Content.Loadout(loadoutID: $0.loadout.objectID, loadoutName: $0.loadout.name ?? "", typeID: $0.type.objectID), diffIdentifier: $0.loadout.objectID) } let section = Tree.Content.LoadoutsSection(groupID: Int(i.key!.groupID), groupName: i.key?.groupName?.uppercased() ?? NSLocalizedString("Unknown", comment: "").uppercased()) return Tree.Item.Section(section, diffIdentifier: i.key!.objectID, expandIdentifier: i.key!.objectID, treeController: treeController, children: rows) } } } func didUpdateLoaoduts(updated: [Loadout]?, inserted: [Loadout]?, deleted: [Loadout]?) { guard var loadouts = loadouts.value else {return} guard let input = view?.input else {return} if let updated = updated, !updated.isEmpty { let pairs = loadouts.enumerated().compactMap { i in i.element.children?.enumerated().map { j in (j.element.content.loadoutID, IndexPath(row: j.offset, section: i.offset)) } }.joined() let map = Dictionary(pairs, uniquingKeysWith: { a, _ in a}) for i in updated { guard let indexPath = map[i.objectID], let row = loadouts[indexPath.section].children?[indexPath.row] else {continue} let new = Tree.Item.LoadoutRow(Tree.Content.Loadout(loadoutID: i.objectID, loadoutName: i.name ?? "", typeID: row.content.typeID), diffIdentifier: i.objectID) loadouts[indexPath.section].children?[indexPath.row] = new } } deleted?.forEach { i in for (j, section) in loadouts.enumerated() { if let index = section.children?.firstIndex(where: {$0.content.loadoutID == i.objectID}) { section.children?.remove(at: index) if section.children?.isEmpty == true { loadouts.remove(at: j) } return } } } let treeController = (try? DispatchQueue.main.async {self.view?.treeController}.get()) ?? nil if let inserted = inserted, !inserted.isEmpty { let newSections = presentation(for: inserted, categoryID: input, treeController: treeController) for i in newSections { let r = loadouts.lowerBound(where: {$0.content.groupName <= i.content.groupName }) if let j = r.last, j.content == i.content { let children = [j.children, i.children].compactMap{$0}.joined().sorted(by: {$0.content.loadoutName < $1.content.loadoutName}) j.children? = children } else { loadouts.insert(i, at: r.indices.upperBound) } } } DispatchQueue.main.async { guard var presentation = self.presentation, presentation.count == 2 else {return} presentation[1] = Tree.Item.Virtual(children: loadouts, diffIdentifier: "Loadouts").asAnyItem self.presentation = presentation self.loadouts.value = loadouts self.view?.present(presentation, animated: true) } } } extension Tree.Item { class LoadoutRow: Row<Tree.Content.Loadout> { override var prototype: Prototype? { return Prototype.TreeDefaultCell.default } lazy var type: SDEInvType = try! Services.sde.viewContext.existingObject(with: content.typeID) override func configure(cell: UITableViewCell, treeController: TreeController?) { super.configure(cell: cell, treeController: treeController) guard let cell = cell as? TreeDefaultCell else {return} cell.accessoryType = .disclosureIndicator cell.titleLabel?.text = type.typeName cell.subtitleLabel?.text = content.loadoutName cell.subtitleLabel?.isHidden = false cell.iconView?.image = type.icon?.image?.image ?? Services.sde.viewContext.eveIcon(.defaultType)?.image?.image } } } extension Tree.Content { struct Loadout: Hashable { var loadoutID: NSManagedObjectID var loadoutName: String var typeID: NSManagedObjectID } struct LoadoutsSection: Hashable, CellConfigurable { var prototype: Prototype? = Prototype.TreeSectionCell.default var groupID: Int var groupName: String func configure(cell: UITableViewCell, treeController: TreeController?) { guard let cell = cell as? TreeSectionCell else {return} cell.titleLabel?.text = groupName } init(groupID: Int, groupName: String) { self.groupID = groupID self.groupName = groupName } } }
lgpl-2.1
tmandry/Swindler
Sources/AXPropertyDelegate.swift
1
6308
import Foundation import AXSwift import PromiseKit import Cocoa /// Implements PropertyDelegate using the AXUIElement API. class AXPropertyDelegate<T: Equatable, UIElement: UIElementType>: PropertyDelegate { typealias InitDict = [AXSwift.Attribute: Any] let axElement: UIElement let attribute: AXSwift.Attribute let initPromise: Promise<InitDict> init(_ axElement: UIElement, _ attribute: AXSwift.Attribute, _ initPromise: Promise<InitDict>) { self.axElement = axElement self.attribute = attribute self.initPromise = initPromise } func readFilter(_ value: T?) -> T? { return value } func readValue() throws -> T? { do { let value: T? = try traceRequest(axElement, "attribute", attribute) { try axElement.attribute(attribute) } return readFilter(value) } catch AXError.cannotComplete { // If messaging timeout unspecified, we'll pass -1. var time = UIElement.globalMessagingTimeout if time == 0 { time = -1.0 } throw PropertyError.timeout(time: TimeInterval(time)) } catch AXError.invalidUIElement { log.debug("Got invalidUIElement for element \(axElement) " + "when attempting to read \(attribute)") throw PropertyError.invalidObject(cause: AXError.invalidUIElement) } catch let error { log.warn("Got unexpected error for element \(axElement) " + "when attempting to read \(attribute)") //unexpectedError(error) throw PropertyError.invalidObject(cause: error) } } func writeValue(_ newValue: T) throws { do { return try traceRequest(axElement, "setAttribute", attribute, newValue) { try axElement.setAttribute(attribute, value: newValue) } } catch AXError.illegalArgument { throw PropertyError.illegalValue } catch AXError.cannotComplete { // If messaging timeout unspecified, we'll pass -1. var time = UIElement.globalMessagingTimeout if time == 0 { time = -1.0 } throw PropertyError.timeout(time: TimeInterval(time)) } catch AXError.failure { throw PropertyError.failure(cause: AXError.failure) } catch AXError.invalidUIElement { log.debug("Got invalidUIElement for element \(axElement) " + "when attempting to write \(attribute)") throw PropertyError.invalidObject(cause: AXError.invalidUIElement) } catch let error { unexpectedError(error) throw PropertyError.invalidObject(cause: error) } } func initialize() -> Promise<T?> { return initPromise.map { dict in guard let value = dict[self.attribute] else { return nil } return self.readFilter(Optional(value as! T)) }.recover { error -> Promise<T?> in switch error { case AXError.cannotComplete: // If messaging timeout unspecified, we'll pass -1. var time = UIElement.globalMessagingTimeout if time == 0 { time = -1.0 } throw PropertyError.timeout(time: TimeInterval(time)) default: log.debug("Got error while initializing attribute \(self.attribute) " + "for element \(self.axElement)") throw PropertyError.invalidObject(cause: error) } } } } // Non-generic protocols of generic types make it easy to store (or cast) objects. protocol AXPropertyDelegateType { var attribute: AXSwift.Attribute { get } } extension AXPropertyDelegate: AXPropertyDelegateType {} protocol PropertyType { func issueRefresh() var delegate: Any { get } var initialized: Promise<Void>! { get } } extension Property: PropertyType { func issueRefresh() { refresh() } } /// Asynchronously fetches all the element attributes. func fetchAttributes<UIElement: UIElementType>(_ attributeNames: [Attribute], forElement axElement: UIElement, after: Promise<Void>, seal: Resolver<[Attribute: Any]>) { // Issue a request in the background. after.done(on: .global()) { let attributes = try traceRequest(axElement, "getMultipleAttributes", attributeNames) { try axElement.getMultipleAttributes(attributeNames) } seal.fulfill(attributes) }.catch { error in seal.reject(error) } } /// Returns a promise that resolves when all the provided properties are initialized. /// Adds additional error information for AXPropertyDelegates. func initializeProperties(_ properties: [PropertyType]) -> Promise<Void> { let propertiesInitialized: [Promise<Void>] = Array(properties.map({ $0.initialized })) return when(fulfilled: propertiesInitialized) } /// Tracks how long `requestFunc` takes, and logs it if needed. /// - Parameter object: The object the request is being made on (usually, a UIElement). func traceRequest<T>( _ object: Any, _ request: String, _ arg1: Any, _ arg2: Any? = nil, requestFunc: () throws -> T ) throws -> T { var result: T? var error: Error? let start = Date() do { result = try requestFunc() } catch let err { error = err } let end = Date() let elapsed = end.timeIntervalSince(start) log.trace({ () -> String in // This closure won't be evaluated if tracing is disabled. let formatElapsed = String(format: "%.1f", elapsed * 1000) let formatArgs = (arg2 == nil) ? "\(arg1)" : "\(arg1), \(arg2!)" let formatResult = (error == nil) ? "responded with \(result!)" : "failed with \(error!)" return "\(request)(\(formatArgs)) on \(object) \(formatResult) in \(formatElapsed)ms" }()) // TODO: if more than some threshold, log as info if let error = error { throw error } return result! }
mit