hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
de86f3dd2c276a89179c7675352b575cba44e295
20,264
// RUN: %target-typecheck-verify-swift -swift-version 5 protocol P {} struct S : P { var other: S { S() } } struct G<T> : P { var other: G<T> { fatalError() } } extension P where Self == S { static var property: S { S() } static var iuoProp: S! { S() } static var optProp: S? { S() } static var fnProp: () -> S { { S() } } static func method() -> S { return S() } static subscript(_: Int) -> S { get { S() } } } extension P { static func genericFn<T>(_: T) -> G<T> where Self == G<T> { // expected-note 5 {{'G<T>' = 'G<Int>}} expected-note 2 {{'G<T>' = 'G<String>'}} return G<T>() } static subscript<T>(t t: T) -> G<T> where Self == G<T> { // expected-note 5 {{'G<T>' = 'G<Int>'}} expected-note 2 {{'G<T>' = 'G<String>'}} get { G<T>() } } } // References on protocol metatype are only allowed through a leading dot syntax _ = P.property // expected-error {{static member 'property' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'property' requires the types 'Self' and 'S' be equivalent}} _ = P.property.other // expected-error {{static member 'property' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'property' requires the types 'Self' and 'S' be equivalent}} _ = P.iuoProp // expected-error {{static member 'iuoProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'iuoProp' requires the types 'Self' and 'S' be equivalent}} _ = P.iuoProp.other // expected-error {{static member 'iuoProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'iuoProp' requires the types 'Self' and 'S' be equivalent}} _ = P.optProp // expected-error {{static member 'optProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'optProp' requires the types 'Self' and 'S' be equivalent}} _ = P.optProp?.other // expected-error {{static member 'optProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'optProp' requires the types 'Self' and 'S' be equivalent}} _ = P.fnProp // expected-error {{static member 'fnProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'fnProp' requires the types 'Self' and 'S' be equivalent}} _ = P.fnProp() // expected-error {{static member 'fnProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'fnProp' requires the types 'Self' and 'S' be equivalent}} _ = P.fnProp().other // expected-error {{static member 'fnProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'fnProp' requires the types 'Self' and 'S' be equivalent}} _ = P.method() // expected-error {{static member 'method' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{referencing static method 'method()' on 'P' requires the types 'Self' and 'S' be equivalent}} _ = P.method // expected-error {{static member 'method' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{referencing static method 'method()' on 'P' requires the types 'Self' and 'S' be equivalent}} _ = P.method().other // expected-error {{static member 'method' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{referencing static method 'method()' on 'P' requires the types 'Self' and 'S' be equivalent}} _ = P.genericFn(42) // expected-error {{static member 'genericFn' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static method 'genericFn' requires the types 'Self' and 'G<Int>' be equivalent}} _ = P.genericFn(42).other // expected-error {{static member 'genericFn' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static method 'genericFn' requires the types 'Self' and 'G<Int>' be equivalent}} _ = P[42] // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{referencing static subscript 'subscript(_:)' on 'P' requires the types 'Self' and 'S' be equivalent}} _ = P[42].other // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{referencing static subscript 'subscript(_:)' on 'P' requires the types 'Self' and 'S' be equivalent}} _ = P[t: 42] // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static subscript 'subscript(t:)' requires the types 'Self' and 'G<Int>' be equivalent}} _ = P[t: 42].other // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static subscript 'subscript(t:)' requires the types 'Self' and 'G<Int>' be equivalent}} let _: S = P.property // expected-error {{static member 'property' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'property' requires the types 'Self' and 'S' be equivalent}} let _: S = P.property.other // expected-error {{static member 'property' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'property' requires the types 'Self' and 'S' be equivalent}} let _: () -> S = P.fnProp // expected-error {{static member 'fnProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'fnProp' requires the types 'Self' and 'S' be equivalent}} let _: S = P.fnProp() // expected-error {{static member 'fnProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'fnProp' requires the types 'Self' and 'S' be equivalent}} let _: S = P.fnProp().other // expected-error {{static member 'fnProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static property 'fnProp' requires the types 'Self' and 'S' be equivalent}} let _: () -> S = P.method // expected-error {{static member 'method' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{referencing static method 'method()' on 'P' requires the types 'Self' and 'S' be equivalent}} let _: S = P.method() // expected-error {{static member 'method' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{referencing static method 'method()' on 'P' requires the types 'Self' and 'S' be equivalent}} let _: S = P.method().other // expected-error {{static member 'method' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{referencing static method 'method()' on 'P' requires the types 'Self' and 'S' be equivalent}} let _: G<Int> = P.genericFn(42) // expected-error {{static member 'genericFn' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static method 'genericFn' requires the types 'Self' and 'G<Int>' be equivalent}} let _: G = P.genericFn(42) // expected-error {{static member 'genericFn' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static method 'genericFn' requires the types 'Self' and 'G<Int>' be equivalent}} let _: G<String> = P.genericFn(42) // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} // expected-error@-1 {{static member 'genericFn' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-2 {{static method 'genericFn' requires the types 'Self' and 'G<String>' be equivalent}} let _: G<Int> = P.genericFn(42).other // expected-error {{static member 'genericFn' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static method 'genericFn' requires the types 'Self' and 'G<Int>' be equivalent}} let _: G<String> = P.genericFn(42).other // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} // expected-error@-1 {{static method 'genericFn' requires the types 'Self' and 'G<String>' be equivalent}} // expected-error@-2 {{static member 'genericFn' cannot be used on protocol metatype '(any P).Type'}} let _: S = P[42] // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{referencing static subscript 'subscript(_:)' on 'P' requires the types 'Self' and 'S' be equivalent}} let _: S = P[42].other // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{referencing static subscript 'subscript(_:)' on 'P' requires the types 'Self' and 'S' be equivalent}} let _: G<Int> = P[t: 42] // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static subscript 'subscript(t:)' requires the types 'Self' and 'G<Int>' be equivalent}} let _: G = P[t: 42] // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static subscript 'subscript(t:)' requires the types 'Self' and 'G<Int>' be equivalent}} let _: G<String> = P[t: 42] // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} // expected-error@-1 {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-2 {{static subscript 'subscript(t:)' requires the types 'Self' and 'G<String>' be equivalent}} let _: G<Int> = P[t: 42].other // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-1 {{static subscript 'subscript(t:)' requires the types 'Self' and 'G<Int>' be equivalent}} let _: G<String> = P[t: 42].other // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} // expected-error@-1 {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-2 {{static subscript 'subscript(t:)' requires the types 'Self' and 'G<String>' be equivalent}} func test<T: P>(_: T) {} test(.property) // Ok, base is inferred as Style.Type test(.property.other) // Ok test(.iuoProp) // Ok test(.iuoProp.other) // Ok test(.optProp!) // Ok test(.optProp) // expected-error@-1 {{value of optional type 'S?' must be unwrapped to a value of type 'S'}} // expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-3 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} test(.optProp!.other) // Ok test(.fnProp()) // Ok test(.fnProp().other) // Ok test(.method()) // Ok, static method call on the metatype test(.method().other) // Ok test(.genericFn(42)) // Ok test(.genericFn(42).other) // Ok protocol Q {} func test_combo<T: P & Q>(_: T) {} // expected-note {{where 'T' = 'G<Int>'}} extension Q where Self == S { static var otherProperty: S { S() } static func otherMethod() -> S { return S() } static func otherGeneric<T>(_: T) -> S { return S() } } extension S : Q { } test_combo(.property) // Ok test_combo(.method()) // Ok test_combo(.otherProperty) // Ok test_combo(.otherProperty.other) // Ok test_combo(.otherProperty.property) // expected-error {{static member 'property' cannot be used on instance of type 'S'}} test_combo(.otherMethod()) // Ok test_combo(.otherMethod().method()) // expected-error {{static member 'method' cannot be used on instance of type 'S'}} test_combo(.otherGeneric(42)) // Ok test_combo(.genericFn(42)) // expected-error {{global function 'test_combo' requires that 'G<Int>' conform to 'Q'}} /* Invalid result types */ extension P { // expected-note 13 {{missing same-type requirement on 'Self'}} {{12-12= where Self == <#Type#>}} static func generic<T>(_: T) -> T { fatalError() } static func genericWithReqs<T: Collection, Q>(_: T) -> Q where T.Element == Q { // expected-note {{in call to function 'genericWithReqs'}} expected-note {{required by static method 'genericWithReqs' where 'T' = '()'}} fatalError() } } extension P { // expected-note 6 {{missing same-type requirement on 'Self'}} static var invalidProp: Int { 42 } static var selfProp: Self { fatalError() } static func invalidMethod() -> Int { 42 } static subscript(q q: String) -> Int { get { 42 } } } _ = P.doesntExist // expected-error {{type 'any P' has no member 'doesntExist'}} _ = P.selfProp // expected-error {{static member 'selfProp' cannot be used on protocol metatype '(any P).Type'}} _ = P.invalidProp // expected-error@-1 {{static member 'invalidProp' cannot be used on protocol metatype '(any P).Type'}} _ = P.invalidProp.other // expected-error@-1 {{static member 'invalidProp' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-2 {{value of type 'Int' has no member 'other'}} _ = P.invalidMethod // Partial application with an invalid base type // expected-error@-1 {{static member 'invalidMethod' cannot be used on protocol metatype '(any P).Type'}} _ = P.invalidMethod() // expected-error@-1 {{static member 'invalidMethod' cannot be used on protocol metatype '(any P).Type'}} _ = P.invalidMethod().other // expected-error@-1 {{static member 'invalidMethod' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-2 {{value of type 'Int' has no member 'other'}} _ = P.generic(42) // expected-error@-1 {{static member 'generic' cannot be used on protocol metatype '(any P).Type'}} _ = P.generic(42).other // expected-error@-1 {{static member 'generic' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-2 {{value of type 'Int' has no member 'other'}} _ = P.generic(S()) // expected-error {{static member 'generic' cannot be used on protocol metatype '(any P).Type'}} _ = P.generic(S()).other // expected-error {{static member 'generic' cannot be used on protocol metatype '(any P).Type'}} _ = P.generic(G<Int>()) // expected-error {{static member 'generic' cannot be used on protocol metatype '(any P).Type'}} _ = P.genericWithReqs([S()]) // expected-error {{static member 'genericWithReqs' cannot be used on protocol metatype '(any P).Type'}} _ = P.genericWithReqs([42]) // expected-error@-1 {{static member 'genericWithReqs' cannot be used on protocol metatype '(any P).Type'}} _ = P.genericWithReqs(()) // expected-error@-1 {{type '()' cannot conform to 'Collection'}} expected-note@-1 {{only concrete types such as structs, enums and classes can conform to protocols}} // expected-error@-2 {{static member 'genericWithReqs' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-3 {{generic parameter 'Q' could not be inferred}} _ = P[q: ""] // expected-error@-1 {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} _ = P[q: ""].other // expected-error@-1 {{static member 'subscript' cannot be used on protocol metatype '(any P).Type'}} // expected-error@-2 {{value of type 'Int' has no member 'other'}} test(.doesntExist) // expected-error {{type 'P' has no member 'doesntExist'}} test(.doesnt.exist()) // expected-error {{type 'P' has no member 'doesnt'}} test(.invalidProp) // expected-error@-1 {{contextual member reference to static property 'invalidProp' requires 'Self' constraint in the protocol extension}} test(.invalidProp.other) // expected-error@-1 {{contextual member reference to static property 'invalidProp' requires 'Self' constraint in the protocol extension}} // expected-error@-2 {{value of type 'Int' has no member 'other'}} test(.invalidMethod()) // expected-error@-1 {{contextual member reference to static method 'invalidMethod()' requires 'Self' constraint in the protocol extension}} test(.invalidMethod().other) // expected-error@-1 {{contextual member reference to static method 'invalidMethod()' requires 'Self' constraint in the protocol extension}} // expected-error@-2 {{value of type 'Int' has no member 'other'}} test(.generic(42)) // expected-error@-1 {{contextual member reference to static method 'generic' requires 'Self' constraint in the protocol extension}} test(.generic(42).other) // expected-error@-1 {{contextual member reference to static method 'generic' requires 'Self' constraint in the protocol extension}} // expected-error@-2 {{value of type 'Int' has no member 'other'}} test(.generic(S())) // expected-error {{contextual member reference to static method 'generic' requires 'Self' constraint in the protocol extension}} test(.generic(G<Int>())) // expected-error {{contextual member reference to static method 'generic' requires 'Self' constraint in the protocol extension}} test(.genericWithReqs([S()])) // expected-error {{contextual member reference to static method 'genericWithReqs' requires 'Self' constraint in the protocol extension}} test(.genericWithReqs([42])) // expected-error@-1 {{contextual member reference to static method 'genericWithReqs' requires 'Self' constraint in the protocol extension}} test(.genericWithReqs(())) // expected-error@-1 {{contextual member reference to static method 'genericWithReqs' requires 'Self' constraint in the protocol extension}} test_combo(.doesntExist) // expected-error {{reference to member 'doesntExist' cannot be resolved without a contextual type}} test_combo(.doesnt.exist()) // expected-error {{reference to member 'doesnt' cannot be resolved without a contextual type}} test_combo(.invalidProp) // expected-error@-1 {{contextual member reference to static property 'invalidProp' requires 'Self' constraint in the protocol extension}} test_combo(.invalidMethod()) // expected-error@-1 {{contextual member reference to static method 'invalidMethod()' requires 'Self' constraint in the protocol extension}} test_combo(.generic(42)) // expected-error@-1 {{contextual member reference to static method 'generic' requires 'Self' constraint in the protocol extension}} test_combo(.generic(S())) // expected-error {{contextual member reference to static method 'generic' requires 'Self' constraint in the protocol extension}} test_combo(.generic(G<Int>())) // expected-error {{contextual member reference to static method 'generic' requires 'Self' constraint in the protocol extension}} test_combo(.genericWithReqs([S()])) // expected-error {{contextual member reference to static method 'genericWithReqs' requires 'Self' constraint in the protocol extension}} test_combo(.genericWithReqs([42])) // expected-error@-1 {{contextual member reference to static method 'genericWithReqs' requires 'Self' constraint in the protocol extension}} test_combo(.genericWithReqs(())) // expected-error@-1 {{contextual member reference to static method 'genericWithReqs' requires 'Self' constraint in the protocol extension}} protocol TestWithAssoc { associatedtype U } struct S_With_U : P { typealias U = Int } extension TestWithAssoc where U == Int { // expected-note {{missing same-type requirement on 'Self'}} {{39-39=, Self == <#Type#> }} static var intVar: Int { 42 } } func test_fixit_with_where_clause() { func test_assoc<T: TestWithAssoc>(_: T) {} test_assoc(.intVar) // expected-error {{contextual member reference to static property 'intVar' requires 'Self' constraint in the protocol extension}} } // rdar://77700261 - incorrect warning about assuming non-optional base for unresolved member lookup struct WithShadowedMember : P {} extension WithShadowedMember { static var warnTest: WithShadowedMember { get { WithShadowedMember() } } } extension P where Self == WithShadowedMember { static var warnTest: WithShadowedMember { get { fatalError() } } } func test_no_warning_about_optional_base() { func test(_: WithShadowedMember?) {} test(.warnTest) // Ok and no warning even though the `warnTest` name is shadowed } // rdar://78425221 - invalid defaulting of literal argument when base is inferred from protocol protocol Style {} struct FormatString : ExpressibleByStringInterpolation { init(stringLiteral: String) {} } struct Number : ExpressibleByIntegerLiteral { init(integerLiteral: Int) {} } struct TestStyle: Style { public init(format: FormatString) { } } extension Style where Self == TestStyle { static func formattedString(format: FormatString) -> TestStyle { fatalError() } static func number(_: Number) -> TestStyle { fatalError() } } func acceptStyle<S: Style>(_: S) {} acceptStyle(.formattedString(format: "hi")) // Ok acceptStyle(.number(42)) // Ok
61.780488
219
0.706721
e8a65a7818022672acdee38ddc1a63e91920b262
1,251
// // NOAColorExtension.swift // NorikaeOpenAPIFramework // // Created by MasamiYamate on 2018/07/06. // Copyright © 2018年 MasamiYamate. All rights reserved. // import UIKit class NOAColorExtension { class func hexToUiColor (hex:String) -> UIColor { let tmpHexStr = hex.replacingOccurrences(of: "#", with: "") let cString:String = tmpHexStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() if ((cString as String).count != 6) { return UIColor.gray } let rString = (cString as NSString).substring(with: NSRange(location: 0, length: 2)) let gString = (cString as NSString).substring(with: NSRange(location: 2, length: 2)) let bString = (cString as NSString).substring(with: NSRange(location: 4, length: 2)) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; Scanner(string: rString).scanHexInt32(&r) Scanner(string: gString).scanHexInt32(&g) Scanner(string: bString).scanHexInt32(&b) return UIColor( red: CGFloat(Float(r) / 255.0), green: CGFloat(Float(g) / 255.0), blue: CGFloat(Float(b) / 255.0), alpha: CGFloat(Float(1.0)) ) } }
35.742857
111
0.629097
61b780e3dc84a6a5414b21c15c1893d5b8353cf7
10,404
import Quick import Nimble import ReactiveSwift import OHHTTPStubs import Alamofire @testable import Moya @testable import ReactiveMoya class ReactiveSwiftMoyaProviderSpec: QuickSpec { override func spec() { var provider: ReactiveSwiftMoyaProvider<GitHub>! beforeEach { provider = ReactiveSwiftMoyaProvider<GitHub>(stubClosure: MoyaProvider.immediatelyStub) } describe("failing") { var provider: ReactiveSwiftMoyaProvider<GitHub>! beforeEach { provider = ReactiveSwiftMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubClosure: MoyaProvider.immediatelyStub) } it("returns the correct error message") { var receivedError: MoyaError? waitUntil { done in provider.request(.zen).startWithFailed { error in receivedError = error done() } } switch receivedError { case .some(.underlying(let error)): expect(error.localizedDescription) == "Houston, we have a problem" default: fail("expected an Underlying error that Houston has a problem") } } it("returns an error") { var errored = false let target: GitHub = .zen provider.request(target).startWithFailed { error in errored = true } expect(errored).to(beTruthy()) } } describe("a subsclassed reactive provider that tracks cancellation with delayed stubs") { struct TestCancellable: Cancellable { static var isCancelled = false var isCancelled: Bool { return TestCancellable.isCancelled } func cancel() { TestCancellable.isCancelled = true } } class TestProvider<Target: TargetType>: ReactiveSwiftMoyaProvider<Target> { init(endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping, requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping, stubClosure: @escaping StubClosure = MoyaProvider.neverStub, manager: Manager = MoyaProvider<Target>.defaultAlamofireManager(), plugins: [PluginType] = []) { super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins) } override func request(_ target: Target, completion: @escaping Moya.Completion) -> Cancellable { return TestCancellable() } } var provider: ReactiveSwiftMoyaProvider<GitHub>! beforeEach { TestCancellable.isCancelled = false provider = TestProvider<GitHub>(stubClosure: MoyaProvider.delayedStub(1)) } it("cancels network request when subscription is cancelled") { let target: GitHub = .zen let disposable = provider.request(target).startWithCompleted { // Should never be executed fail() } disposable.dispose() expect(TestCancellable.isCancelled).to( beTrue() ) } } describe("provider with SignalProducer") { it("returns a Response object") { var called = false provider.request(.zen).startWithResult { _ in called = true } expect(called).to(beTruthy()) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .zen provider.request(target).startWithResult { result in if case .success(let response) = result { message = String(data: response.data, encoding: .utf8) } } let sampleString = String(data: target.sampleData, encoding: .utf8) expect(message!).to(equal(sampleString)) } it("returns correct data for user profile request") { var receivedResponse: NSDictionary? let target: GitHub = .userProfile("ashfurrow") provider.request(target).startWithResult { result in if case .success(let response) = result { receivedResponse = try! JSONSerialization.jsonObject(with: response.data, options: []) as? NSDictionary } } let sampleData = target.sampleData let sampleResponse = try! JSONSerialization.jsonObject(with: sampleData, options: []) as! NSDictionary expect(receivedResponse).toNot(beNil()) expect(receivedResponse) == sampleResponse } describe("a subsclassed reactive provider that tracks cancellation with delayed stubs") { struct TestCancellable: Cancellable { static var isCancelled = false var isCancelled: Bool { return TestCancellable.isCancelled } func cancel() { TestCancellable.isCancelled = true } } class TestProvider<Target: TargetType>: ReactiveSwiftMoyaProvider<Target> { init(endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping, requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping, stubClosure: @escaping StubClosure = MoyaProvider.neverStub, manager: Manager = MoyaProvider<Target>.defaultAlamofireManager(), plugins: [PluginType] = []) { super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins) } override func request(_ target: Target, completion: @escaping Moya.Completion) -> Cancellable { return TestCancellable() } } var provider: ReactiveSwiftMoyaProvider<GitHub>! beforeEach { TestCancellable.isCancelled = false provider = TestProvider<GitHub>(stubClosure: MoyaProvider.delayedStub(1)) } it("cancels network request when subscription is cancelled") { let target: GitHub = .zen let disposable = provider.request(target).startWithCompleted { // Should never be executed fail() } disposable.dispose() expect(TestCancellable.isCancelled).to( beTrue() ) } } } describe("provider with a TestScheduler") { var testScheduler: TestScheduler! = nil var response: Moya.Response? = nil beforeEach { testScheduler = TestScheduler() provider = ReactiveSwiftMoyaProvider<GitHub>(stubClosure: MoyaProvider.immediatelyStub, stubScheduler: testScheduler) provider.request(.zen).startWithResult { result in if case .success(let next) = result { response = next } } } afterEach { response = nil } it("sends the stub when the test scheduler is advanced") { testScheduler.run() expect(response).toNot(beNil()) } it("does not send the stub when the test scheduler is not advanced") { expect(response).to(beNil()) } } describe("a reactive provider") { var provider: ReactiveSwiftMoyaProvider<GitHub>! beforeEach { OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}) { _ in return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) } provider = ReactiveSwiftMoyaProvider<GitHub>(trackInflights: true) } it("returns identical signalproducers for inflight requests") { let target: GitHub = .zen let signalProducer1: SignalProducer<Moya.Response, MoyaError> = provider.request(target) let signalProducer2: SignalProducer<Moya.Response, MoyaError> = provider.request(target) expect(provider.inflightRequests.keys.count).to( equal(0) ) var receivedResponse: Moya.Response! signalProducer1.startWithResult { result in if case .success(let response) = result { receivedResponse = response expect(provider.inflightRequests.count).to( equal(1) ) } } signalProducer2.startWithResult { result in if case .success(let response) = result { expect(receivedResponse).toNot( beNil() ) expect(receivedResponse).to( beIdenticalToResponse(response) ) expect(provider.inflightRequests.count).to( equal(1) ) } } // Allow for network request to complete expect(provider.inflightRequests.count).toEventually( equal(0) ) } } } }
41.285714
166
0.521722
d564f71918835b9877c7dc2974fff232950c6087
7,840
// // ImportProfileImageViewController.swift // enHueco // // Created by Diego Montoya Sefair on 1/1/16. // Copyright © 2016 Diego Gómez. All rights reserved. // import UIKit import FBSDKLoginKit import RSKImageCropper import MobileCoreServices protocol ImportProfileImageViewControllerDelegate: class { func importProfileImageViewControllerDidFinishImportingImage(controller: ImportProfileImageViewController) func importProfileImageViewControllerDidCancel(controller: ImportProfileImageViewController) } class ImportProfileImageViewController: UIViewController, UINavigationControllerDelegate { @IBOutlet weak var importFromLocalStorageButton: UIButton! @IBOutlet weak var importFromFacebookButton: UIButton! @IBOutlet weak var cancelButton: UIButton! let imagePicker = UIImagePickerController() var cancelButtonText: String? var hideCancelButton = false var translucent = false weak var delegate: ImportProfileImageViewControllerDelegate? /// Status bar style before presenting this controller private var originalStatusBarStyle: UIStatusBarStyle! override func viewDidLoad() { super.viewDidLoad() originalStatusBarStyle = UIApplication.sharedApplication().statusBarStyle modalPresentationStyle = .OverCurrentContext if hideCancelButton { cancelButton.hidden = true } if let cancelButtonText = cancelButtonText { cancelButton.setTitle(cancelButtonText, forState: .Normal) } let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight)) if translucent { view.backgroundColor = UIColor.clearColor() view.insertSubview(effectView, atIndex: 0) } else { effectView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.3) let backgroundImageView = UIImageView(imageNamed: "blurryBackground") view.insertSubview(backgroundImageView, atIndex: 0) backgroundImageView.autoPinEdgesToSuperviewEdges() backgroundImageView.addSubview(effectView) } effectView.autoPinEdgesToSuperviewEdges() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() importFromFacebookButton.roundCorners() importFromLocalStorageButton.roundCorners() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIApplication.sharedApplication().setStatusBarStyle(.Default, animated: animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) UIApplication.sharedApplication().setStatusBarStyle(originalStatusBarStyle, animated: animated) } @IBAction func importFromLocalStorageButtonPressed(sender: UIButton) { imagePicker.mediaTypes = [kUTTypeImage as String] imagePicker.allowsEditing = false imagePicker.delegate = self let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) if UIImagePickerController.isSourceTypeAvailable(.Camera) { // There is a camera on this device, so show the take photo button. alertController.addAction(UIAlertAction(title: "TakePhoto".localizedUsingGeneralFile(), style: .Default, handler: { (action) -> Void in self.imagePicker.sourceType = .Camera self.presentViewController(self.imagePicker, animated: true, completion: nil) })) } alertController.addAction(UIAlertAction(title: "ChoosePhoto".localizedUsingGeneralFile(), style: .Default, handler: { (action) -> Void in self.imagePicker.sourceType = .PhotoLibrary self.presentViewController(self.imagePicker, animated: true, completion: nil) })) alertController.addAction(UIAlertAction(title: "Cancel".localizedUsingGeneralFile(), style: .Cancel, handler: nil)) presentViewController(alertController, animated: true, completion: nil) } @IBAction func importFromFacebookButtonPressed(sender: UIButton) { let loginManager = FBSDKLoginManager() loginManager.logInWithReadPermissions(["public_profile"], fromViewController: self) { (result, error) -> Void in guard error == nil else { EHNotifications.tryToShowErrorNotificationInViewController(self, withPossibleTitle: error?.localizedUserSuitableDescriptionOrDefaultUnknownErrorMessage()) return } if !result.isCancelled { //We are logged into Facebook FBSDKGraphRequest(graphPath: "me/picture", parameters: ["fields":"url", "width":"500", "redirect":"false"], HTTPMethod: "GET").startWithCompletionHandler() { (_, result, error) -> Void in guard let data = result["data"], let imageURL = data?["url"] as? String, let imageData = NSData(contentsOfURL: NSURL(string: imageURL)!), let image = UIImage(data: imageData) where error == nil else { EHNotifications.tryToShowErrorNotificationInViewController(self, withPossibleTitle: error?.localizedUserSuitableDescriptionOrDefaultUnknownErrorMessage()) return } let imageCropVC = RSKImageCropViewController(image: image) imageCropVC.delegate = self self.presentViewController(imageCropVC, animated: true, completion: nil) } } } } @IBAction func cancelButtonPressed(sender: AnyObject) { delegate?.importProfileImageViewControllerDidCancel(self) } } extension ImportProfileImageViewController: UIImagePickerControllerDelegate { func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String:AnyObject]?) { let imageCropVC = RSKImageCropViewController(image: image) imageCropVC.delegate = self picker.dismissViewControllerAnimated(true) { self.presentViewController(imageCropVC, animated: true, completion: nil) } } } extension ImportProfileImageViewController: RSKImageCropViewControllerDelegate { func imageCropViewController(controller: RSKImageCropViewController, didCropImage croppedImage: UIImage, usingCropRect cropRect: CGRect) { EHProgressHUD.showSpinnerInView(controller.view) let finalImage = RBResizeImage(croppedImage, targetSize: CGSizeMake(275, 275)) AppUserInformationManager.sharedManager.pushProfilePicture(finalImage) { success, error in guard error == nil else { EHNotifications.tryToShowErrorNotificationInViewController(self, withPossibleTitle: error?.localizedUserSuitableDescriptionOrDefaultUnknownErrorMessage()) return } controller.dismissViewControllerAnimated(true) { self.delegate?.importProfileImageViewControllerDidFinishImportingImage(self) } } } func imageCropViewControllerDidCancelCrop(controller: RSKImageCropViewController) { controller.dismissViewControllerAnimated(true, completion: nil) } }
38.243902
203
0.65625
dee7541f82e0a29a4cfadccc956670736616907d
373
// // AppThemeConfigurator.swift // Timmee // // Created by Ilya Kharabet on 05.09.17. // Copyright © 2017 Mesterra. All rights reserved. // import UIKit final class AppThemeConfigurator { static func setupInitialThemeIfNeeded() { if UserProperty.appTheme.value() == nil { UserProperty.appTheme.setInt(AppTheme.white.code) } } }
18.65
61
0.662198
ef27dd098174cece313c2fb0f09fc1e3954eee31
4,369
// // PhotosCollectionViewController.swift // PulleyDemo // // Created by Carmel Neta on 28/10/2019. // Copyright © 2019 52inc. All rights reserved. // import UIKit private let reuseIdentifier = "PhotoCell" protocol PhotosCollectionDelegateProtocol: AnyObject { func imagesDidChange(_ indexes: [Int], images: [ImageRep]) } class PhotosCollectionViewController: UICollectionViewController { weak var delegate: PhotosCollectionDelegateProtocol? weak var dataManager: DataManger? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes self.collectionView.register(UINib(nibName: "PhotoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier) self.collectionView.allowsMultipleSelection = true } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.dataManager?.photos.count ?? 0 } private func photo(for indexPath: IndexPath) -> ImageRep? { return dataManager?.photos[indexPath.item] } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? PhotoCollectionViewCell else { return UICollectionViewCell() } guard let imageRep = self.photo(for: indexPath) else { cell.imageView.image = nil cell.isSelected = false return cell } cell.isSelected = dataManager?.state.selectedPhotos.contains(indexPath.item) ?? false cell.imageView.image = imageRep.image return cell } // MARK: UICollectionViewDelegate private var selectIndex: [Int] { guard let selected = self.collectionView.indexPathsForSelectedItems else { return [] } return selected.compactMap({ $0.item }) } private var selectedImages: [ImageRep] { guard let selected = self.collectionView.indexPathsForSelectedItems else { return [] } return selected.compactMap({ self.photo(for: $0) }) } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.delegate?.imagesDidChange(selectIndex, images: selectedImages) } override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { self.delegate?.imagesDidChange(selectIndex, images: selectedImages) } /* Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } */ override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { } */ } extension PhotosCollectionViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let size = collectionView.frame.width / 3.0 return CGSize(width: size, height: size) } }
37.025424
170
0.715038
6ad24315f48d86ffef0bceb695a4c8cec14649aa
3,363
// // UIViewTestController.swift // SwiftExtension // // Created by jumpingfrog0 on 01/12/2016. // // // Copyright (c) 2016 Jumpingfrog0 LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class UIViewTestController: UIViewController { @IBOutlet weak var view1: UIView! @IBOutlet weak var view2: UIView! @IBOutlet weak var view4: UIView! override func viewDidLoad() { super.viewDidLoad() // Test UIView extension // Mask view1.setBorder(cornerRadius: 25, color: UIColor.white, width: 2) view2.setRoundCorners(byRoundingCorners: .topLeft, radius: 10) // Nib let amazingView = AmazingView.load(fromNibName: "AmazingView", bundle: nil) as? AmazingView amazingView?.titleLabel.text = "指定Nib名称" amazingView?.frame = CGRect(x: 10, y: 570, width: 100, height: 100) view.addSubview(amazingView!) let amazingView2 = AmazingView.loadFromNib() as? AmazingView amazingView2?.titleLabel.text = "不指定Nib名称" amazingView2?.frame = CGRect(x: 120, y: 570, width: 100, height: 100) view.addSubview(amazingView2!) let amazingView_index_1 = AmazingView.loadFromNib(ofIndex: 1) as? AmazingView amazingView_index_1?.titleLabel.text = "根据index生成Nib中对应的view" amazingView_index_1?.frame = CGRect(x: 230, y: 570, width: 100, height: 100) view.addSubview(amazingView_index_1!) jf_print(AmazingView.entityName()) // Frame jf_print("The x of view1 is \(view1.x)") // 200 jf_print("The y of view1 is \(view1.y)") // 100 jf_print("The width of view1 is \(view1.width)") // 50 jf_print("The height of view1 is \(view1.height)") // 50 jf_print("The right of view1 is \(view1.right)") // 250 jf_print("The bottom of view1 is \(view1.bottom)") // 150 jf_print("The midX of view1 is \(view1.midX)") // 225 jf_print("The midY of view1 is \(view1.midY)") // 125 // XibConfiguration // Please see the view3 of UIViewTestController at Main.storyboard. } @IBAction func removeAllSubviews() { view4.removeAllSubviews() } }
40.518072
99
0.655665
91338e41148829c0f1f5a310869dcde55d425568
3,122
import SwiftUI import CoreLocation class VarsomApiClient { public static func currentLang() -> Language { return Locale.current.languageCode == "nb" ? .norwegian : .english } public enum Language: CustomStringConvertible { case norwegian case english var description: String { switch self { case .norwegian: return "1" case .english: return "2" } } } public enum VarsomError: Error { case requestError case invalidUrlError } private let baseUrl = "https://api01.nve.no/hydrology/forecast/avalanche/v6.0.1/api" private let argumentDateFormatter:DateFormatter init() { argumentDateFormatter = DateFormatter() argumentDateFormatter.dateFormat = "yyyy-MM-dd" } public func loadRegions(lang: Language) async throws -> [RegionSummary] { guard let url = URL(string: "\(baseUrl)/RegionSummary/Simple/\(lang)/") else { throw VarsomError.invalidUrlError } return try await getData(url: url); } public func loadRegions(lang: Language, coordinate:CLLocationCoordinate2D) async throws -> RegionSummary { let from = Date() let to = Calendar.current.date(byAdding: .day, value: 2, to: from)! let warnings = try await loadWarnings(lang: lang, coordinate: coordinate, from: from, to: to) let region = RegionSummary( Id: warnings[0].RegionId, Name: warnings[0].RegionName, TypeName: warnings[0].RegionTypeName, AvalancheWarningList: warnings) return region } public func loadWarnings(lang: Language, regionId: Int, from:Date, to:Date) async throws -> [AvalancheWarningSimple] { let fromArg = argumentDateFormatter.string(from: from) let toArg = argumentDateFormatter.string(from: to) guard let url = URL(string: "\(baseUrl)/AvalancheWarningByRegion/Simple/\(regionId)/\(lang)/\(fromArg)/\(toArg)") else { throw VarsomError.invalidUrlError } return try await getData(url: url); } public func loadWarnings(lang: Language, coordinate:CLLocationCoordinate2D, from:Date, to:Date) async throws -> [AvalancheWarningSimple] { let fromArg = argumentDateFormatter.string(from: from) let toArg = argumentDateFormatter.string(from: to) guard let url = URL(string: "\(baseUrl)/AvalancheWarningByCoordinates/Simple/\(coordinate.latitude)/\(coordinate.longitude)/\(lang)/\(fromArg)/\(toArg)") else { throw VarsomError.invalidUrlError } return try await getData(url: url); } private func getData<T>(url: URL) async throws -> T where T : Codable { print(url.absoluteString) let (data, response) = try await URLSession.shared.data(from: url) guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw VarsomError.requestError } let decoder = JSONDecoder() decoder.dateDecodingStrategy = .varsomDate return try decoder.decode(T.self, from: data) } }
40.545455
204
0.648302
5daa93d64db9840b134eea94ed2a4b27952cddbf
642
// // SSCameraDebug.swift // SSCamera // // Created by 2020 on 2021/5/7. // import Foundation func debug(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, method: String = #function) { #if DEBUG print("SSCameraDebug ","\((file as NSString).lastPathComponent)[\(line)], \(method):", terminator: separator) var i = 0 let j = items.count for a in items { i += 1 print(" ",a, terminator:i == j ? terminator: separator) } #endif }
24.692308
117
0.493769
ccbf5fb37e55444ca3e07d1e8515a60a49ee6a24
1,034
// // 123.swift // swift-leetcode // // Created by Q YiZhong on 2019/4/20. // Copyright © 2019 YiZhong Qi. All rights reserved. // import Foundation func maxProfit3(_ prices: [Int]) -> Int { guard prices.count > 0 else { return 0 } // 天 总共可以买卖几次 是否持有股票 var dp: [[[Int]]] = Array.init(repeating: Array.init(repeating: Array.init(repeating: 0, count: 2), count: 3), count: prices.count) dp[0][0][0] = 0 dp[0][0][1] = -prices[0] dp[0][1][0] = -Int.max / 2 dp[0][1][1] = -Int.max / 2 dp[0][2][0] = -Int.max / 2 dp[0][2][1] = -Int.max / 2 for i in 1..<prices.count { dp[i][0][0] = dp[i - 1][0][0] dp[i][0][1] = max(dp[i - 1][0][1], dp[i - 1][0][0] - prices[i]) dp[i][1][0] = max(dp[i - 1][1][0], dp[i - 1][0][1] + prices[i]) dp[i][1][1] = max(dp[i - 1][1][1], dp[i - 1][1][0] - prices[i]) dp[i][2][0] = max(dp[i - 1][2][0], dp[i - 1][1][1] + prices[i]) } return max(dp.last![0][0], dp.last![1][0], dp.last![2][0]) }
30.411765
135
0.482592
29c04e346c28df40bab1cdd347a26810b718bd33
7,840
// // ViewController.swift // Visual Signal // // Created by Vergil Choi on 2018/12/29. // Copyright © 2018 Vergil Choi. All rights reserved. // import UIKit import SceneKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { @IBOutlet var sceneView: ARSCNView! @IBOutlet weak var strengthLabel: UILabel! var cameraTransform = simd_float4x4() var timer: Timer! var currentNode: SCNNode? var currentLabelNode: SCNNode? var link: CADisplayLink? override func viewDidLoad() { super.viewDidLoad() // Set the view's delegate sceneView.delegate = self // Show statistics such as fps and timing information sceneView.showsStatistics = true // Create a new scene let scene = SCNScene(named: "art.scnassets/main.scn")! // Set the scene to the view sceneView.scene = scene } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create a session configuration let configuration = ARWorldTrackingConfiguration() // Run the view's session sceneView.session.run(configuration) timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { _ in self.strengthLabel.text = String(format: " WiFi Strength: %.02f%% ", self.wifiStrength() * 100) }) timer.fire() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Pause the view's session sceneView.session.pause() timer.invalidate() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let strength = wifiStrength() let sphere = SCNSphere(radius: 0.01) sphere.firstMaterial?.diffuse.contents = UIColor( hue: CGFloat((2 * strength - strength * strength) / 2), saturation: 1, brightness: 1, alpha: 1 ) currentLabelNode = TextNode(text: String(format: "%.02f%%", strength * 100), font: "AvenirNext-Regular", colour: UIColor( hue: CGFloat((2 * strength - strength * strength) / 2), saturation: 1, brightness: 1, alpha: 1 )) currentNode = SCNNode(geometry: sphere) updatePositionAndOrientationOf(currentNode!, withPosition: SCNVector3(0, 0, -0.15), relativeTo: sceneView.pointOfView!) updatePositionAndOrientationOf(currentLabelNode!, withPosition: SCNVector3(0, 0.02, -0.15), relativeTo: sceneView.pointOfView!) sceneView.scene.rootNode.addChildNode(currentNode!) sceneView.scene.rootNode.addChildNode(currentLabelNode!) link = CADisplayLink(target: self, selector: #selector(scalingNode)) link?.add(to: RunLoop.main, forMode: .common) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { link?.invalidate() } @objc func scalingNode() { if let node = currentNode { node.scale = SCNVector3(node.scale.x + 0.02, node.scale.y + 0.02, node.scale.z + 0.02) } if let node = currentLabelNode { node.scale = SCNVector3(node.scale.x + 0.02, node.scale.y + 0.02, node.scale.z + 0.02) node.position.y += 0.0002 } } func updatePositionAndOrientationOf(_ node: SCNNode, withPosition position: SCNVector3, relativeTo referenceNode: SCNNode) { let referenceNodeTransform = matrix_float4x4(referenceNode.transform) // Setup a translation matrix with the desired position var translationMatrix = matrix_identity_float4x4 translationMatrix.columns.3.x = position.x translationMatrix.columns.3.y = position.y translationMatrix.columns.3.z = position.z // Combine the configured translation matrix with the referenceNode's transform to get the desired position AND orientation let updatedTransform = matrix_multiply(referenceNodeTransform, translationMatrix) node.transform = SCNMatrix4(updatedTransform) } func wifiStrength() -> Double { let app = UIApplication.shared let subviews = ((app.value(forKey: "statusBar") as! NSObject).value(forKey: "foregroundView") as! UIView).subviews var dataNetworkItemView: UIView? for subview in subviews { if subview.isKind(of: NSClassFromString("UIStatusBarDataNetworkItemView")!) { dataNetworkItemView = subview break } } let dBm = (dataNetworkItemView!.value(forKey: "wifiStrengthRaw") as! NSNumber).intValue var strength = (Double(dBm) + 90.0) / 60.0 if strength > 1 { strength = 1 } return strength } // MARK: - ARSCNViewDelegate /* // Override to create and configure nodes for anchors added to the view's session. func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { let node = SCNNode() return node } */ func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user } func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay } func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required } } // https://stackoverflow.com/questions/50678671/setting-up-the-orientation-of-3d-text-in-arkit-application class TextNode: SCNNode{ var textGeometry: SCNText! /// Creates An SCNText Geometry /// /// - Parameters: /// - text: String (The Text To Be Displayed) /// - depth: Optional CGFloat (Defaults To 1) /// - font: UIFont /// - textSize: Optional CGFloat (Defaults To 3) /// - colour: UIColor init(text: String, depth: CGFloat = 0.01, font: String = "Helvatica", textSize: CGFloat = 1, colour: UIColor) { super.init() //1. Create A Billboard Constraint So Our Text Always Faces The Camera let constraints = SCNBillboardConstraint() //2. Create An SCNNode To Hold Out Text let node = SCNNode() let max, min: SCNVector3 let tx, ty, tz: Float //3. Set Our Free Axes constraints.freeAxes = .Y //4. Create Our Text Geometry textGeometry = SCNText(string: text, extrusionDepth: depth) //5. Set The Flatness To Zero (This Makes The Text Look Smoother) textGeometry.flatness = 0 //6. Set The Alignment Mode Of The Text textGeometry.alignmentMode = CATextLayerAlignmentMode.center.rawValue //7. Set Our Text Colour & Apply The Font textGeometry.firstMaterial?.diffuse.contents = colour textGeometry.firstMaterial?.isDoubleSided = true textGeometry.font = UIFont(name: font, size: textSize) //8. Position & Scale Our Node max = textGeometry.boundingBox.max min = textGeometry.boundingBox.min tx = (max.x - min.x) / 2.0 ty = min.y tz = Float(depth) / 2.0 node.geometry = textGeometry node.scale = SCNVector3(0.01, 0.01, 0.1) node.pivot = SCNMatrix4MakeTranslation(tx, ty, tz) self.addChildNode(node) self.constraints = [constraints] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
34.844444
135
0.620536
5bd05833b9c638f607238695088008f09dd0f8ee
17,587
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import NIOConcurrencyHelpers import Dispatch struct NIORegistration: Registration { enum ChannelType { case serverSocketChannel(ServerSocketChannel) case socketChannel(SocketChannel) case datagramChannel(DatagramChannel) case pipeChannel(PipeChannel, PipeChannel.Direction) } var channel: ChannelType /// The `SelectorEventSet` in which this `NIORegistration` is interested in. var interested: SelectorEventSet /// The registration ID for this `NIORegistration` used by the `Selector`. var registrationID: SelectorRegistrationID } private let nextEventLoopGroupID = NIOAtomic.makeAtomic(value: 0) /// Called per `NIOThread` that is created for an EventLoop to do custom initialization of the `NIOThread` before the actual `EventLoop` is run on it. typealias ThreadInitializer = (NIOThread) -> Void /// An `EventLoopGroup` which will create multiple `EventLoop`s, each tied to its own `NIOThread`. /// /// The effect of initializing a `MultiThreadedEventLoopGroup` is to spawn `numberOfThreads` fresh threads which will /// all run their own `EventLoop`. Those threads will not be shut down until `shutdownGracefully` or /// `syncShutdownGracefully` is called. /// /// - note: It's good style to call `MultiThreadedEventLoopGroup.shutdownGracefully` or /// `MultiThreadedEventLoopGroup.syncShutdownGracefully` when you no longer need this `EventLoopGroup`. In /// many cases that is just before your program exits. /// - warning: Unit tests often spawn one `MultiThreadedEventLoopGroup` per unit test to force isolation between the /// tests. In those cases it's important to shut the `MultiThreadedEventLoopGroup` down at the end of the /// test. A good place to start a `MultiThreadedEventLoopGroup` is the `setUp` method of your `XCTestCase` /// subclass, a good place to shut it down is the `tearDown` method. public final class MultiThreadedEventLoopGroup: EventLoopGroup { private enum RunState { case running case closing([(DispatchQueue, (Error?) -> Void)]) case closed(Error?) } private static let threadSpecificEventLoop = ThreadSpecificVariable<SelectableEventLoop>() private let myGroupID: Int private let index = NIOAtomic<Int>.makeAtomic(value: 0) private var eventLoops: [SelectableEventLoop] private let shutdownLock: Lock = Lock() private var runState: RunState = .running private static func runTheLoop(thread: NIOThread, parentGroup: MultiThreadedEventLoopGroup? /* nil iff thread take-over */, canEventLoopBeShutdownIndividually: Bool, selectorFactory: @escaping () throws -> NIOPosix.Selector<NIORegistration>, initializer: @escaping ThreadInitializer, _ callback: @escaping (SelectableEventLoop) -> Void) { assert(NIOThread.current == thread) initializer(thread) do { let loop = SelectableEventLoop(thread: thread, parentGroup: parentGroup, selector: try selectorFactory(), canBeShutdownIndividually: canEventLoopBeShutdownIndividually) threadSpecificEventLoop.currentValue = loop defer { threadSpecificEventLoop.currentValue = nil } callback(loop) try loop.run() } catch { // We fatalError here because the only reasons this can be hit is if the underlying kqueue/epoll give us // errors that we cannot handle which is an unrecoverable error for us. fatalError("Unexpected error while running SelectableEventLoop: \(error).") } } private static func setupThreadAndEventLoop(name: String, parentGroup: MultiThreadedEventLoopGroup, selectorFactory: @escaping () throws -> NIOPosix.Selector<NIORegistration>, initializer: @escaping ThreadInitializer) -> SelectableEventLoop { let lock = Lock() /* the `loopUpAndRunningGroup` is done by the calling thread when the EventLoop has been created and was written to `_loop` */ let loopUpAndRunningGroup = DispatchGroup() /* synchronised by `lock` */ var _loop: SelectableEventLoop! = nil loopUpAndRunningGroup.enter() NIOThread.spawnAndRun(name: name, detachThread: false) { t in MultiThreadedEventLoopGroup.runTheLoop(thread: t, parentGroup: parentGroup, canEventLoopBeShutdownIndividually: false, // part of MTELG selectorFactory: selectorFactory, initializer: initializer) { l in lock.withLock { _loop = l } loopUpAndRunningGroup.leave() } } loopUpAndRunningGroup.wait() return lock.withLock { _loop } } /// Creates a `MultiThreadedEventLoopGroup` instance which uses `numberOfThreads`. /// /// - note: Don't forget to call `shutdownGracefully` or `syncShutdownGracefully` when you no longer need this /// `EventLoopGroup`. If you forget to shut the `EventLoopGroup` down you will leak `numberOfThreads` /// (kernel) threads which are costly resources. This is especially important in unit tests where one /// `MultiThreadedEventLoopGroup` is started per test case. /// /// - arguments: /// - numberOfThreads: The number of `Threads` to use. public convenience init(numberOfThreads: Int) { self.init(numberOfThreads: numberOfThreads, selectorFactory: NIOPosix.Selector<NIORegistration>.init) } internal convenience init(numberOfThreads: Int, selectorFactory: @escaping () throws -> NIOPosix.Selector<NIORegistration>) { precondition(numberOfThreads > 0, "numberOfThreads must be positive") let initializers: [ThreadInitializer] = Array(repeating: { _ in }, count: numberOfThreads) self.init(threadInitializers: initializers, selectorFactory: selectorFactory) } /// Creates a `MultiThreadedEventLoopGroup` instance which uses the given `ThreadInitializer`s. One `NIOThread` per `ThreadInitializer` is created and used. /// /// - arguments: /// - threadInitializers: The `ThreadInitializer`s to use. internal init(threadInitializers: [ThreadInitializer], selectorFactory: @escaping () throws -> NIOPosix.Selector<NIORegistration> = NIOPosix.Selector<NIORegistration>.init) { let myGroupID = nextEventLoopGroupID.add(1) self.myGroupID = myGroupID var idx = 0 self.eventLoops = [] // Just so we're fully initialised and can vend `self` to the `SelectableEventLoop`. self.eventLoops = threadInitializers.map { initializer in // Maximum name length on linux is 16 by default. let ev = MultiThreadedEventLoopGroup.setupThreadAndEventLoop(name: "NIO-ELT-\(myGroupID)-#\(idx)", parentGroup: self, selectorFactory: selectorFactory, initializer: initializer) idx += 1 return ev } } /// Returns the `EventLoop` for the calling thread. /// /// - returns: The current `EventLoop` for the calling thread or `nil` if none is assigned to the thread. public static var currentEventLoop: EventLoop? { return self.currentSelectableEventLoop } internal static var currentSelectableEventLoop: SelectableEventLoop? { return threadSpecificEventLoop.currentValue } /// Returns an `EventLoopIterator` over the `EventLoop`s in this `MultiThreadedEventLoopGroup`. /// /// - returns: `EventLoopIterator` public func makeIterator() -> EventLoopIterator { return EventLoopIterator(self.eventLoops) } /// Returns the next `EventLoop` from this `MultiThreadedEventLoopGroup`. /// /// `MultiThreadedEventLoopGroup` uses _round robin_ across all its `EventLoop`s to select the next one. /// /// - returns: The next `EventLoop` to use. public func next() -> EventLoop { return eventLoops[abs(index.add(1) % eventLoops.count)] } /// Returns the current `EventLoop` if we are on an `EventLoop` of this `MultiThreadedEventLoopGroup` instance. /// /// - returns: The `EventLoop`. public func any() -> EventLoop { if let loop = Self.currentSelectableEventLoop, // We are on `loop`'s thread, so we may ask for the its parent group. loop.parentGroupCallableFromThisEventLoopOnly() === self { // Nice, we can return this. loop.assertInEventLoop() return loop } else { // Oh well, let's just vend the next one then. return self.next() } } /// Shut this `MultiThreadedEventLoopGroup` down which causes the `EventLoop`s and their associated threads to be /// shut down and release their resources. /// /// Even though calling `shutdownGracefully` more than once should be avoided, it is safe to do so and execution /// of the `handler` is guaranteed. /// /// - parameters: /// - queue: The `DispatchQueue` to run `handler` on when the shutdown operation completes. /// - handler: The handler which is called after the shutdown operation completes. The parameter will be `nil` /// on success and contain the `Error` otherwise. public func shutdownGracefully(queue: DispatchQueue, _ handler: @escaping (Error?) -> Void) { // This method cannot perform its final cleanup using EventLoopFutures, because it requires that all // our event loops still be alive, and they may not be. Instead, we use Dispatch to manage // our shutdown signaling, and then do our cleanup once the DispatchQueue is empty. let g = DispatchGroup() let q = DispatchQueue(label: "nio.shutdownGracefullyQueue", target: queue) let wasRunning: Bool = self.shutdownLock.withLock { // We need to check the current `runState` and react accordingly. switch self.runState { case .running: // If we are still running, we set the `runState` to `closing`, // so that potential future invocations know, that the shutdown // has already been initiaited. self.runState = .closing([]) return true case .closing(var callbacks): // If we are currently closing, we need to register the `handler` // for invocation after the shutdown is completed. callbacks.append((q, handler)) self.runState = .closing(callbacks) return false case .closed(let error): // If we are already closed, we can directly dispatch the `handler` q.async { handler(error) } return false } } // If the `runState` was not `running` when `shutdownGracefully` was called, // the shutdown has already been initiated and we have to return here. guard wasRunning else { return } var result: Result<Void, Error> = .success(()) for loop in self.eventLoops { g.enter() loop.initiateClose(queue: q) { closeResult in switch closeResult { case .success: () case .failure(let error): result = .failure(error) } g.leave() } } g.notify(queue: q) { for loop in self.eventLoops { loop.syncFinaliseClose(joinThread: true) } var overallError: Error? var queueCallbackPairs: [(DispatchQueue, (Error?) -> Void)]? = nil self.shutdownLock.withLock { switch self.runState { case .closed, .running: preconditionFailure("MultiThreadedEventLoopGroup in illegal state when closing: \(self.runState)") case .closing(let callbacks): queueCallbackPairs = callbacks switch result { case .success: overallError = nil case .failure(let error): overallError = error } self.runState = .closed(overallError) } } queue.async { handler(overallError) } for queueCallbackPair in queueCallbackPairs! { queueCallbackPair.0.async { queueCallbackPair.1(overallError) } } } } /// Convert the calling thread into an `EventLoop`. /// /// This function will not return until the `EventLoop` has stopped. You can initiate stopping the `EventLoop` by /// calling `eventLoop.shutdownGracefully` which will eventually make this function return. /// /// - parameters: /// - callback: Called _on_ the `EventLoop` that the calling thread was converted to, providing you the /// `EventLoop` reference. Just like usually on the `EventLoop`, do not block in `callback`. public static func withCurrentThreadAsEventLoop(_ callback: @escaping (EventLoop) -> Void) { let callingThread = NIOThread.current MultiThreadedEventLoopGroup.runTheLoop(thread: callingThread, parentGroup: nil, canEventLoopBeShutdownIndividually: true, selectorFactory: NIOPosix.Selector<NIORegistration>.init, initializer: { _ in }) { loop in loop.assertInEventLoop() callback(loop) } } public func _preconditionSafeToSyncShutdown(file: StaticString, line: UInt) { if let eventLoop = MultiThreadedEventLoopGroup.currentEventLoop { preconditionFailure(""" BUG DETECTED: syncShutdownGracefully() must not be called when on an EventLoop. Calling syncShutdownGracefully() on any EventLoop can lead to deadlocks. Current eventLoop: \(eventLoop) """, file: file, line: line) } } } extension MultiThreadedEventLoopGroup: CustomStringConvertible { public var description: String { return "MultiThreadedEventLoopGroup { threadPattern = NIO-ELT-\(self.myGroupID)-#* }" } } @usableFromInline internal struct ScheduledTask { /// The id of the scheduled task. /// /// - Important: This id has two purposes. First, it is used to give this struct an identity so that we can implement ``Equatable`` /// Second, it is used to give the tasks an order which we use to execute them. /// This means, the ids need to be unique for a given ``SelectableEventLoop`` and they need to be in ascending order. @usableFromInline let id: UInt64 let task: () -> Void private let failFn: (Error) ->() @usableFromInline internal let _readyTime: NIODeadline @usableFromInline init(id: UInt64, _ task: @escaping () -> Void, _ failFn: @escaping (Error) -> Void, _ time: NIODeadline) { self.id = id self.task = task self.failFn = failFn self._readyTime = time } func readyIn(_ t: NIODeadline) -> TimeAmount { if _readyTime < t { return .nanoseconds(0) } return _readyTime - t } func fail(_ error: Error) { failFn(error) } } extension ScheduledTask: CustomStringConvertible { @usableFromInline var description: String { return "ScheduledTask(readyTime: \(self._readyTime))" } } extension ScheduledTask: Comparable { @usableFromInline static func < (lhs: ScheduledTask, rhs: ScheduledTask) -> Bool { if lhs._readyTime == rhs._readyTime { return lhs.id < rhs.id } else { return lhs._readyTime < rhs._readyTime } } @usableFromInline static func == (lhs: ScheduledTask, rhs: ScheduledTask) -> Bool { return lhs.id == rhs.id } }
44.411616
160
0.60033
c1322cc849b340b78670900fcc2027f676a03cf4
950
//// TemplatesTestProjectTests.swift // TemplatesTestProjectTests // // Created by Jovan Radivojsa on 4/14/19. // Copyright © 2019 Jovan. All rights reserved. // import XCTest @testable import TemplatesTestProject class TemplatesTestProjectTests: XCTestCase { override func 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. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
27.941176
111
0.672632
20065e8109413cc2b77c26080ac43dc0b0c31812
1,104
// // RoundDropMenuDataSource.swift // Round-Drop-Menu // // Created by Arthur Myronenko on 1/21/16. // Copyright © 2016 Arthur Myronenko. All rights reserved. // import Foundation /** * The `RoundDropMenuDataSource` is adopted by an object that mediates the application's * data model for a `RoundDropMenu` object. */ public protocol RoundDropMenuDataSource { /** Asks the data source to return the number of dropViews in the menu. - parameter menu: An object representing the `RoundDropMenu` requesting the information. - returns: The number of dropViews in the menu. */ func numberOfDropsInRoundDropMenu(menu: RoundDropMenu) -> Int /** Asks the data source for a `DropView` to insert into particular index in `RoundDropMenu` - parameter menu: An object representing the `RoundDropMenu` requesting the information. - parameter index: An index locating `DropView` in `menu`. - returns: `DropView` object that `menu` can use for the specified `index`. */ func roundDropMenu(menu: RoundDropMenu, dropViewForIndex index: Int) -> DropView }
30.666667
92
0.72192
bb918fab8f6c00ff946795a315b2983d15f5646a
1,286
// // Box.swift // Flair // // MIT License // // Copyright (c) 2017 Mobelux // // 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 class Box<T> { let object: T init(object: T) { self.object = object } }
34.756757
81
0.724728
11995c936909304cc529eccc4e14660a559b6996
1,703
import iOSSignIn import FacebookCore import ServerShared import iOSShared /// Enables you to sign in as a Facebook user to (a) create a new sharing user (must have an invitation from another SyncServer user), or (b) sign in as an existing sharing user. public class FacebookCredentials : GenericCredentials { private var savedCreds:FacebookSavedCreds! public var emailAddress: String! { return savedCreds?.emailAddress } var accessToken:AccessToken! { return savedCreds?.accessToken } var userProfile:Profile! { return savedCreds?.userProfile } public var userId:String { guard let userId = savedCreds?.userId else { logger.error("FacebookCredentials: No savedCreds; could not get userId") return "" } return userId } public var username:String? { return savedCreds?.username } public var uiDisplayName:String? { return savedCreds?.username } // Helper public init(savedCreds:FacebookSavedCreds) { self.savedCreds = savedCreds } public var httpRequestHeaders:[String:String] { var result = [String:String]() result[ServerConstants.XTokenTypeKey] = AuthTokenType.FacebookToken.rawValue result[ServerConstants.HTTPOAuth2AccessTokenKey] = accessToken?.tokenString return result } public func refreshCredentials(completion: @escaping (Error?) ->()) { FacebookSyncServerSignIn.refreshAccessToken { error in if let error = error { logger.error("\(error)") } completion(error) } } }
28.383333
178
0.641809
5b33b48854ffbd93d0f72cd0e1650d8daad67b6e
2,541
/// Copyright (c) 2019 Razeware LLC /// /// 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// 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 SwiftUI import UIKit struct PageControl: UIViewRepresentable { var pageCount: Int class PageCoordinator: NSObject { var control: PageControl init(_ control: PageControl) { self.control = control } @objc func updateCurrentPage(sender: UIPageControl) { control.currentPage = sender.currentPage } } @Binding var currentPage: Int func makeUIView(context: Context) -> UIPageControl { let pageControl = UIPageControl() pageControl.numberOfPages = pageCount pageControl.addTarget(context.coordinator, action: #selector(PageCoordinator.updateCurrentPage(sender:)), for: .valueChanged) return pageControl } func updateUIView(_ uiView: UIPageControl, context: Context) { uiView.currentPage = currentPage } func makeCoordinator() -> PageCoordinator { PageCoordinator(self) } }
38.5
129
0.740653
61d078dac284a4884be9e88e2ad9ce1f441c3746
326
// // WelcomeTableViewCell.swift // yemekye // // Created by Arsalan Wahid Asghar on 12/9/17. // Copyright © 2017 Arsalan Wahid Asghar. All rights reserved. // import UIKit class WelcomeTableViewCell: UITableViewCell { @IBOutlet weak var welcomeLabel: UILabel! @IBOutlet weak var userNameLabel: UILabel! }
19.176471
63
0.717791
2068b4231cbe6926d8b433b98e32d03991af03ad
964
// // HLDefaultCitiesFactory+Config.swift // AviasalesSDKTemplate // // Created by Dim on 05.09.17. // Copyright © 2017 Go Travel Un Limited. All rights reserved. // extension HLDefaultCitiesFactory { static func configCity() -> HDKCity? { guard let id = ConfigManager.shared.hotelsCityID, let name = ConfigManager.shared.hotelsCityName, !id.isEmpty, !name.isEmpty else { return nil } return HDKCity(cityId: id, name: name, latinName: nil, fullName: nil, countryName: nil, countryLatinName: nil, countryCode: nil, state: nil, latitude: 0, longitude: 0, hotelsCount: 0, cityCode: nil, points: [], seasons: []) } }
29.212121
139
0.470954
8acc359430427bce54399ad2fb5b954f0d6f79ab
455
// // Repository.swift // SampleGithubMVVMBrowser // // Created by Mariusz Sut on 02/02/2019. // Copyright © 2019 Mariusz Sut. All rights reserved. // import Foundation struct Repository: Codable { let name: String let owner: Owner let url: String let description: String? enum CodingKeys: String, CodingKey { case name = "full_name" case owner case url = "html_url" case description } }
18.958333
54
0.635165
8f48f5418bafd7a1eba06ae73ffbc9bc3720d47a
518
// // NewsLocation.swift // EcoNews // // Created by Никита Ткаченко on 31.12.2020. // import Foundation import MapKit /// Потом создать еще один класс который будет хранить массив мусорок и инициализировать их из БД class NewsLocation:NSObject, MKAnnotation{ var coordinate: CLLocationCoordinate2D var name: String var title: String? init(coordinate: CLLocationCoordinate2D, name: String) { self.coordinate = coordinate self.name = name self.title = name } }
22.521739
97
0.69112
918d065eb8a771c2beef2c6694b68556b43e3a0c
36,446
// // DropDown.swift // DropDown // // Created by Kevin Hirsch on 28/07/15. // Copyright (c) 2015 Kevin Hirsch. All rights reserved. // #if os(iOS) import UIKit public typealias Index = Int public typealias Closure = () -> Void public typealias SelectionClosure = (Index, String) -> Void public typealias MultiSelectionClosure = ([Index], [String]) -> Void public typealias ConfigurationClosure = (Index, String) -> String public typealias CellConfigurationClosure = (Index, String, DropDownCell) -> Void private typealias ComputeLayoutTuple = (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat) /// Can be `UIView` or `UIBarButtonItem`. @objc public protocol AnchorView: class { var plainView: UIView { get } } extension UIView: AnchorView { public var plainView: UIView { return self } } extension UIBarButtonItem: AnchorView { public var plainView: UIView { return value(forKey: "view") as! UIView } } /// A Material Design drop down in replacement for `UIPickerView`. public final class TedoooDropDown: UIView { //TODO: handle iOS 7 landscape mode /// The dismiss mode for a drop down. public enum DismissMode { /// A tap outside the drop down is required to dismiss. case onTap /// No tap is required to dismiss, it will dimiss when interacting with anything else. case automatic /// Not dismissable by the user. case manual } /// The direction where the drop down will show from the `anchorView`. public enum Direction { /// The drop down will show below the anchor view when possible, otherwise above if there is more place than below. case any /// The drop down will show above the anchor view or will not be showed if not enough space. case top /// The drop down will show below or will not be showed if not enough space. case bottom } //MARK: - Properties /// The current visible drop down. There can be only one visible drop down at a time. public static weak var VisibleDropDown: TedoooDropDown? //MARK: UI fileprivate let dismissableView = UIView() fileprivate let tableViewContainer = UIView() fileprivate let tableView = UITableView() fileprivate var templateCell: DropDownCell! fileprivate lazy var arrowIndication: UIImageView = { UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 10), false, 0) let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 10)) path.addLine(to: CGPoint(x: 20, y: 10)) path.addLine(to: CGPoint(x: 10, y: 0)) path.addLine(to: CGPoint(x: 0, y: 10)) UIColor.black.setFill() path.fill() let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let tintImg = img?.withRenderingMode(.alwaysTemplate) let imgv = UIImageView(image: tintImg) imgv.frame = CGRect(x: 0, y: -10, width: 15, height: 10) return imgv }() /// The view to which the drop down will displayed onto. public weak var anchorView: AnchorView? { didSet { setNeedsUpdateConstraints() } } /** The possible directions where the drop down will be showed. See `Direction` enum for more info. */ public var direction = Direction.any /** The offset point relative to `anchorView` when the drop down is shown above the anchor view. By default, the drop down is showed onto the `anchorView` with the top left corner for its origin, so an offset equal to (0, 0). You can change here the default drop down origin. */ public var topOffset: CGPoint = .zero { didSet { setNeedsUpdateConstraints() } } /** The offset point relative to `anchorView` when the drop down is shown below the anchor view. By default, the drop down is showed onto the `anchorView` with the top left corner for its origin, so an offset equal to (0, 0). You can change here the default drop down origin. */ public var bottomOffset: CGPoint = .zero { didSet { setNeedsUpdateConstraints() } } /** The offset from the bottom of the window when the drop down is shown below the anchor view. DropDown applies this offset only if keyboard is hidden. */ public var offsetFromWindowBottom = CGFloat(0) { didSet { setNeedsUpdateConstraints() } } /** The width of the drop down. Defaults to `anchorView.bounds.width - offset.x`. */ public var width: CGFloat? { didSet { setNeedsUpdateConstraints() } } /** arrowIndication.x arrowIndication will be add to tableViewContainer when configured */ public var arrowIndicationX: CGFloat? { didSet { if let arrowIndicationX = arrowIndicationX { tableViewContainer.addSubview(arrowIndication) arrowIndication.tintColor = tableViewBackgroundColor arrowIndication.frame.origin.x = arrowIndicationX } else { arrowIndication.removeFromSuperview() } } } //MARK: Constraints fileprivate var heightConstraint: NSLayoutConstraint! fileprivate var widthConstraint: NSLayoutConstraint! fileprivate var xConstraint: NSLayoutConstraint! fileprivate var yConstraint: NSLayoutConstraint! //MARK: Appearance @objc public dynamic var cellHeight = DPDConstant.UI.RowHeight { willSet { tableView.rowHeight = newValue } didSet { reloadAllComponents() } } @objc fileprivate dynamic var tableViewBackgroundColor = DPDConstant.UI.BackgroundColor { willSet { tableView.backgroundColor = newValue if arrowIndicationX != nil { arrowIndication.tintColor = newValue } } } public override var backgroundColor: UIColor? { get { return tableViewBackgroundColor } set { tableViewBackgroundColor = newValue! } } /** The color of the dimmed background (behind the drop down, covering the entire screen). */ public var dimmedBackgroundColor = UIColor.clear { willSet { super.backgroundColor = newValue } } /** The background color of the selected cell in the drop down. Changing the background color automatically reloads the drop down. */ @objc public dynamic var selectionBackgroundColor = DPDConstant.UI.SelectionBackgroundColor /** The separator color between cells. Changing the separator color automatically reloads the drop down. */ @objc public dynamic var separatorColor = DPDConstant.UI.SeparatorColor { willSet { tableView.separatorColor = newValue } didSet { reloadAllComponents() } } /** The corner radius of DropDown. Changing the corner radius automatically reloads the drop down. */ @objc public dynamic var cornerRadius = DPDConstant.UI.CornerRadius { willSet { tableViewContainer.layer.cornerRadius = newValue tableView.layer.cornerRadius = newValue } didSet { reloadAllComponents() } } /** Alias method for `cornerRadius` variable to avoid ambiguity. */ @objc public dynamic func setupCornerRadius(_ radius: CGFloat) { tableViewContainer.layer.cornerRadius = radius tableView.layer.cornerRadius = radius reloadAllComponents() } /** The masked corners of DropDown. Changing the masked corners automatically reloads the drop down. */ @available(iOS 11.0, *) @objc public dynamic func setupMaskedCorners(_ cornerMask: CACornerMask) { tableViewContainer.layer.maskedCorners = cornerMask tableView.layer.maskedCorners = cornerMask reloadAllComponents() } /** The color of the shadow. Changing the shadow color automatically reloads the drop down. */ @objc public dynamic var shadowColor = DPDConstant.UI.Shadow.Color { willSet { tableViewContainer.layer.shadowColor = newValue.cgColor } didSet { reloadAllComponents() } } /** The offset of the shadow. Changing the shadow color automatically reloads the drop down. */ @objc public dynamic var shadowOffset = DPDConstant.UI.Shadow.Offset { willSet { tableViewContainer.layer.shadowOffset = newValue } didSet { reloadAllComponents() } } /** The opacity of the shadow. Changing the shadow opacity automatically reloads the drop down. */ @objc public dynamic var shadowOpacity = DPDConstant.UI.Shadow.Opacity { willSet { tableViewContainer.layer.shadowOpacity = newValue } didSet { reloadAllComponents() } } /** The radius of the shadow. Changing the shadow radius automatically reloads the drop down. */ @objc public dynamic var shadowRadius = DPDConstant.UI.Shadow.Radius { willSet { tableViewContainer.layer.shadowRadius = newValue } didSet { reloadAllComponents() } } /** The duration of the show/hide animation. */ @objc public dynamic var animationduration = DPDConstant.Animation.Duration /** The option of the show animation. Global change. */ public static var animationEntranceOptions = DPDConstant.Animation.EntranceOptions /** The option of the hide animation. Global change. */ public static var animationExitOptions = DPDConstant.Animation.ExitOptions /** The option of the show animation. Only change the caller. To change all drop down's use the static var. */ public var animationEntranceOptions: UIView.AnimationOptions = TedoooDropDown.animationEntranceOptions /** The option of the hide animation. Only change the caller. To change all drop down's use the static var. */ public var animationExitOptions: UIView.AnimationOptions = TedoooDropDown.animationExitOptions /** The downScale transformation of the tableview when the DropDown is appearing */ public var downScaleTransform = DPDConstant.Animation.DownScaleTransform { willSet { tableViewContainer.transform = newValue } } /** The color of the text for each cells of the drop down. Changing the text color automatically reloads the drop down. */ @objc public dynamic var textColor = DPDConstant.UI.TextColor { didSet { reloadAllComponents() } } /** The color of the text for selected cells of the drop down. Changing the text color automatically reloads the drop down. */ @objc public dynamic var selectedTextColor = DPDConstant.UI.SelectedTextColor { didSet { reloadAllComponents() } } /** The font of the text for each cells of the drop down. Changing the text font automatically reloads the drop down. */ @objc public dynamic var textFont = DPDConstant.UI.TextFont { didSet { reloadAllComponents() } } /** The NIB to use for DropDownCells Changing the cell nib automatically reloads the drop down. */ public var cellNib = UINib(nibName: "DropDownCell", bundle: bundle) { didSet { tableView.register(cellNib, forCellReuseIdentifier: DPDConstant.ReusableIdentifier.DropDownCell) templateCell = nil reloadAllComponents() } } /// Correctly specify Bundle for Swift Packages fileprivate static var bundle: Bundle { #if SWIFT_PACKAGE return Bundle.module #else return Bundle(for: DropDownCell.self) #endif } //MARK: Content /** The data source for the drop down. Changing the data source automatically reloads the drop down. */ public var dataSource = [String]() { didSet { deselectRows(at: selectedRowIndices) reloadAllComponents() } } /** The localization keys for the data source for the drop down. Changing this value automatically reloads the drop down. This has uses for setting accibility identifiers on the drop down cells (same ones as the localization keys). */ public var localizationKeysDataSource = [String]() { didSet { dataSource = localizationKeysDataSource.map { NSLocalizedString($0, comment: "") } } } /// The indicies that have been selected fileprivate var selectedRowIndices = Set<Index>() /** The format for the cells' text. By default, the cell's text takes the plain `dataSource` value. Changing `cellConfiguration` automatically reloads the drop down. */ public var cellConfiguration: ConfigurationClosure? { didSet { reloadAllComponents() } } /** A advanced formatter for the cells. Allows customization when custom cells are used Changing `customCellConfiguration` automatically reloads the drop down. */ public var customCellConfiguration: CellConfigurationClosure? { didSet { reloadAllComponents() } } /// The action to execute when the user selects a cell. public var selectionAction: SelectionClosure? /** The action to execute when the user selects multiple cells. Providing an action will turn on multiselection mode. The single selection action will still be called if provided. */ public var multiSelectionAction: MultiSelectionClosure? /// The action to execute when the drop down will show. public var willShowAction: Closure? /// The action to execute when the user cancels/hides the drop down. public var cancelAction: Closure? /// The dismiss mode of the drop down. Default is `OnTap`. public var dismissMode = DismissMode.onTap { willSet { if newValue == .onTap { let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissableViewTapped)) dismissableView.addGestureRecognizer(gestureRecognizer) } else if let gestureRecognizer = dismissableView.gestureRecognizers?.first { dismissableView.removeGestureRecognizer(gestureRecognizer) } } } fileprivate var minHeight: CGFloat { return tableView.rowHeight } fileprivate var didSetupConstraints = false //MARK: - Init's deinit { stopListeningToNotifications() } /** Creates a new instance of a drop down. Don't forget to setup the `dataSource`, the `anchorView` and the `selectionAction` at least before calling `show()`. */ public convenience init() { self.init(frame: .zero) } /** Creates a new instance of a drop down. - parameter anchorView: The view to which the drop down will displayed onto. - parameter selectionAction: The action to execute when the user selects a cell. - parameter dataSource: The data source for the drop down. - parameter topOffset: The offset point relative to `anchorView` used when drop down is displayed on above the anchor view. - parameter bottomOffset: The offset point relative to `anchorView` used when drop down is displayed on below the anchor view. - parameter cellConfiguration: The format for the cells' text. - parameter cancelAction: The action to execute when the user cancels/hides the drop down. - returns: A new instance of a drop down customized with the above parameters. */ public convenience init(anchorView: AnchorView, selectionAction: SelectionClosure? = nil, dataSource: [String] = [], topOffset: CGPoint? = nil, bottomOffset: CGPoint? = nil, cellConfiguration: ConfigurationClosure? = nil, cancelAction: Closure? = nil) { self.init(frame: .zero) self.anchorView = anchorView self.selectionAction = selectionAction self.dataSource = dataSource self.topOffset = topOffset ?? .zero self.bottomOffset = bottomOffset ?? .zero self.cellConfiguration = cellConfiguration self.cancelAction = cancelAction } override public init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private var lastRow: IndexPath? private let feedbackGenerator = UIImpactFeedbackGenerator(style: .medium) } //MARK: - Setup private extension TedoooDropDown { func setup() { tableView.register(cellNib, forCellReuseIdentifier: DPDConstant.ReusableIdentifier.DropDownCell) DispatchQueue.main.async { //HACK: If not done in dispatch_async on main queue `setupUI` will have no effect self.updateConstraintsIfNeeded() self.setupUI() } tableView.rowHeight = cellHeight setHiddentState() isHidden = true dismissMode = .onTap let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableTapped)) let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) tableView.addGestureRecognizer(tapGesture) tableView.addGestureRecognizer(gesture) tableView.delegate = self tableView.dataSource = self startListeningToKeyboard() accessibilityIdentifier = "drop_down" } @objc private func tableTapped(_ gesture: UITapGestureRecognizer) { guard let index = tableView.indexPathForRow(at: gesture.location(in: tableView)) else { return } selectedRow(indexPath: index) } private func selectedRow(indexPath: IndexPath) { let selectedRowIndex = indexPath.row // are we in multi-selection mode? if let multiSelectionCallback = multiSelectionAction { // if already selected then deselect if selectedRowIndices.first(where: { $0 == selectedRowIndex}) != nil { deselectRow(at: selectedRowIndex) let selectedRowIndicesArray = Array(selectedRowIndices) let selectedRows = selectedRowIndicesArray.map { dataSource[$0] } multiSelectionCallback(selectedRowIndicesArray, selectedRows) return } else { selectedRowIndices.insert(selectedRowIndex) let selectedRowIndicesArray = Array(selectedRowIndices) let selectedRows = selectedRowIndicesArray.map { dataSource[$0] } selectionAction?(selectedRowIndex, dataSource[selectedRowIndex]) multiSelectionCallback(selectedRowIndicesArray, selectedRows) tableView.reloadData() return } } // Perform single selection logic selectedRowIndices.removeAll() selectedRowIndices.insert(selectedRowIndex) selectionAction?(selectedRowIndex, dataSource[selectedRowIndex]) if let _ = anchorView as? UIBarButtonItem { // DropDown's from UIBarButtonItem are menus so we deselect the selected menu right after selection deselectRow(at: selectedRowIndex) } hide() } @objc private func handlePan(_ pan: UIPanGestureRecognizer) { guard let index = tableView.indexPathForRow(at: pan.location(in: tableView)) else { return } switch pan.state { case .began: lastRow = index tableView.cellForRow(at: index)?.setHighlighted(true, animated: true) feedbackGenerator.impactOccurred() case .changed: if index != lastRow { if let lastRow = lastRow { tableView.cellForRow(at: lastRow)?.setHighlighted(false, animated: true) tableView.cellForRow(at: index)?.setHighlighted(true, animated: true) } lastRow = index feedbackGenerator.impactOccurred() } case .ended: selectedRow(indexPath: index) default:break } } func setupUI() { super.backgroundColor = dimmedBackgroundColor tableViewContainer.layer.masksToBounds = false tableViewContainer.layer.cornerRadius = cornerRadius tableViewContainer.layer.shadowColor = shadowColor.cgColor tableViewContainer.layer.shadowOffset = shadowOffset tableViewContainer.layer.shadowOpacity = shadowOpacity tableViewContainer.layer.shadowRadius = shadowRadius tableView.backgroundColor = tableViewBackgroundColor tableView.separatorColor = separatorColor tableView.layer.cornerRadius = cornerRadius tableView.layer.masksToBounds = true } } //MARK: - UI extension TedoooDropDown { public override func updateConstraints() { if !didSetupConstraints { setupConstraints() } didSetupConstraints = true let layout = computeLayout() if !layout.canBeDisplayed { super.updateConstraints() hide() return } xConstraint.constant = layout.x yConstraint.constant = layout.y widthConstraint.constant = layout.width heightConstraint.constant = layout.visibleHeight // tableView.isScrollEnabled = layout.offscreenHeight > 0 tableView.isScrollEnabled = false DispatchQueue.main.async { [weak self] in self?.tableView.flashScrollIndicators() } super.updateConstraints() } fileprivate func setupConstraints() { translatesAutoresizingMaskIntoConstraints = false // Dismissable view addSubview(dismissableView) dismissableView.translatesAutoresizingMaskIntoConstraints = false addUniversalConstraints(format: "|[dismissableView]|", views: ["dismissableView": dismissableView]) // Table view container addSubview(tableViewContainer) tableViewContainer.translatesAutoresizingMaskIntoConstraints = false xConstraint = NSLayoutConstraint( item: tableViewContainer, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) addConstraint(xConstraint) yConstraint = NSLayoutConstraint( item: tableViewContainer, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) addConstraint(yConstraint) widthConstraint = NSLayoutConstraint( item: tableViewContainer, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0) tableViewContainer.addConstraint(widthConstraint) heightConstraint = NSLayoutConstraint( item: tableViewContainer, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0) tableViewContainer.addConstraint(heightConstraint) // Table view tableViewContainer.addSubview(tableView) tableView.translatesAutoresizingMaskIntoConstraints = false tableViewContainer.addUniversalConstraints(format: "|[tableView]|", views: ["tableView": tableView]) } public override func layoutSubviews() { super.layoutSubviews() // When orientation changes, layoutSubviews is called // We update the constraint to update the position setNeedsUpdateConstraints() let shadowPath = UIBezierPath(roundedRect: tableViewContainer.bounds, cornerRadius: cornerRadius) tableViewContainer.layer.shadowPath = shadowPath.cgPath } fileprivate func computeLayout() -> (x: CGFloat, y: CGFloat, width: CGFloat, offscreenHeight: CGFloat, visibleHeight: CGFloat, canBeDisplayed: Bool, Direction: Direction) { var layout: ComputeLayoutTuple = (0, 0, 0, 0) var direction = self.direction guard let window = UIWindow.visibleWindow() else { return (0, 0, 0, 0, 0, false, direction) } barButtonItemCondition: if let anchorView = anchorView as? UIBarButtonItem { let isRightBarButtonItem = anchorView.plainView.frame.minX > window.frame.midX guard isRightBarButtonItem else { break barButtonItemCondition } let width = self.width ?? fittingWidth() let anchorViewWidth = anchorView.plainView.frame.width let x = -(width - anchorViewWidth) bottomOffset = CGPoint(x: x, y: 0) } if anchorView == nil { layout = computeLayoutBottomDisplay(window: window) direction = .any } else { switch direction { case .any: layout = computeLayoutBottomDisplay(window: window) direction = .bottom if layout.offscreenHeight > 0 { let topLayout = computeLayoutForTopDisplay(window: window) if topLayout.offscreenHeight < layout.offscreenHeight { layout = topLayout direction = .top } } case .bottom: layout = computeLayoutBottomDisplay(window: window) direction = .bottom case .top: layout = computeLayoutForTopDisplay(window: window) direction = .top } } constraintWidthToFittingSizeIfNecessary(layout: &layout) constraintWidthToBoundsIfNecessary(layout: &layout, in: window) let visibleHeight = tableHeight - layout.offscreenHeight let canBeDisplayed = visibleHeight >= minHeight return (layout.x, layout.y, layout.width, layout.offscreenHeight, visibleHeight, canBeDisplayed, direction) } fileprivate func computeLayoutBottomDisplay(window: UIWindow) -> ComputeLayoutTuple { var offscreenHeight: CGFloat = 0 let width = self.width ?? (anchorView?.plainView.bounds.width ?? fittingWidth()) - bottomOffset.x let anchorViewX = anchorView?.plainView.windowFrame?.minX ?? window.frame.midX - (width / 2) let anchorViewY = anchorView?.plainView.windowFrame?.minY ?? window.frame.midY - (tableHeight / 2) let x = anchorViewX + bottomOffset.x let y = anchorViewY + bottomOffset.y let maxY = y + tableHeight let windowMaxY = window.bounds.maxY - DPDConstant.UI.HeightPadding - offsetFromWindowBottom let keyboardListener = KeyboardListener.sharedInstance let keyboardMinY = keyboardListener.keyboardFrame.minY - DPDConstant.UI.HeightPadding if keyboardListener.isVisible && maxY > keyboardMinY { offscreenHeight = abs(maxY - keyboardMinY) } else if maxY > windowMaxY { offscreenHeight = abs(maxY - windowMaxY) } return (x, y, width, offscreenHeight) } fileprivate func computeLayoutForTopDisplay(window: UIWindow) -> ComputeLayoutTuple { var offscreenHeight: CGFloat = 0 let anchorViewX = anchorView?.plainView.windowFrame?.minX ?? 0 let anchorViewMaxY = anchorView?.plainView.windowFrame?.maxY ?? 0 let x = anchorViewX + topOffset.x var y = (anchorViewMaxY + topOffset.y) - tableHeight let windowY = window.bounds.minY + DPDConstant.UI.HeightPadding if y < windowY { offscreenHeight = abs(y - windowY) y = windowY } let width = self.width ?? (anchorView?.plainView.bounds.width ?? fittingWidth()) - topOffset.x return (x, y, width, offscreenHeight) } fileprivate func fittingWidth() -> CGFloat { if templateCell == nil { templateCell = (cellNib.instantiate(withOwner: nil, options: nil)[0] as! DropDownCell) } var maxWidth: CGFloat = 0 for index in 0..<dataSource.count { configureCell(templateCell, at: index) templateCell.bounds.size.height = cellHeight let width = templateCell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).width if width > maxWidth { maxWidth = width } } return maxWidth } fileprivate func constraintWidthToBoundsIfNecessary(layout: inout ComputeLayoutTuple, in window: UIWindow) { let windowMaxX = window.bounds.maxX let maxX = layout.x + layout.width if maxX > windowMaxX { let delta = maxX - windowMaxX let newOrigin = layout.x - delta if newOrigin > 0 { layout.x = newOrigin } else { layout.x = 0 layout.width += newOrigin // newOrigin is negative, so this operation is a substraction } } } fileprivate func constraintWidthToFittingSizeIfNecessary(layout: inout ComputeLayoutTuple) { guard width == nil else { return } if layout.width < fittingWidth() { layout.width = fittingWidth() } } } //MARK: - Actions extension TedoooDropDown { /** An Objective-C alias for the show() method which converts the returned tuple into an NSDictionary. - returns: An NSDictionary with a value for the "canBeDisplayed" Bool, and possibly for the "offScreenHeight" Optional(CGFloat). */ @objc(show) public func objc_show() -> NSDictionary { let (canBeDisplayed, offScreenHeight) = show() var info = [AnyHashable: Any]() info["canBeDisplayed"] = canBeDisplayed if let offScreenHeight = offScreenHeight { info["offScreenHeight"] = offScreenHeight } return NSDictionary(dictionary: info) } /** Shows the drop down if enough height. - returns: Wether it succeed and how much height is needed to display all cells at once. */ @discardableResult public func show(onTopOf window: UIWindow? = nil, beforeTransform transform: CGAffineTransform? = nil, anchorPoint: CGPoint? = nil) -> (canBeDisplayed: Bool, offscreenHeight: CGFloat?) { if self == TedoooDropDown.VisibleDropDown && TedoooDropDown.VisibleDropDown?.isHidden == false { // added condition - DropDown.VisibleDropDown?.isHidden == false -> to resolve forever hiding dropdown issue when continuous taping on button - Kartik Patel - 2016-12-29 return (true, 0) } if let visibleDropDown = TedoooDropDown.VisibleDropDown { visibleDropDown.cancel() } willShowAction?() TedoooDropDown.VisibleDropDown = self setNeedsUpdateConstraints() let visibleWindow = window != nil ? window : UIWindow.visibleWindow() visibleWindow?.addSubview(self) visibleWindow?.bringSubviewToFront(self) self.translatesAutoresizingMaskIntoConstraints = false visibleWindow?.addUniversalConstraints(format: "|[dropDown]|", views: ["dropDown": self]) let layout = computeLayout() if !layout.canBeDisplayed { hide() return (layout.canBeDisplayed, layout.offscreenHeight) } isHidden = false if anchorPoint != nil { tableViewContainer.layer.anchorPoint = anchorPoint! } if transform != nil { tableViewContainer.transform = transform! } else { tableViewContainer.transform = downScaleTransform } layoutIfNeeded() UIView.animate( withDuration: animationduration, delay: 0, options: animationEntranceOptions, animations: { [weak self] in self?.setShowedState() }, completion: nil) accessibilityViewIsModal = true UIAccessibility.post(notification: .screenChanged, argument: self) //deselectRows(at: selectedRowIndices) selectRows(at: selectedRowIndices) return (layout.canBeDisplayed, layout.offscreenHeight) } public override func accessibilityPerformEscape() -> Bool { switch dismissMode { case .automatic, .onTap: cancel() return true case .manual: return false } } /// Hides the drop down. public func hide() { if self == TedoooDropDown.VisibleDropDown { /* If one drop down is showed and another one is not but we call `hide()` on the hidden one: we don't want it to set the `VisibleDropDown` to nil. */ TedoooDropDown.VisibleDropDown = nil } if isHidden { return } UIView.animate( withDuration: animationduration, delay: 0, options: animationExitOptions, animations: { [weak self] in self?.setHiddentState() }, completion: { [weak self] finished in guard let `self` = self else { return } self.isHidden = true self.removeFromSuperview() UIAccessibility.post(notification: .screenChanged, argument: nil) }) } fileprivate func cancel() { hide() cancelAction?() } fileprivate func setHiddentState() { alpha = 0 } fileprivate func setShowedState() { alpha = 1 tableViewContainer.transform = CGAffineTransform.identity } } //MARK: - UITableView extension TedoooDropDown { /** Reloads all the cells. It should not be necessary in most cases because each change to `dataSource`, `textColor`, `textFont`, `selectionBackgroundColor` and `cellConfiguration` implicitly calls `reloadAllComponents()`. */ public func reloadAllComponents() { DispatchQueue.executeOnMainThread { self.tableView.reloadData() self.setNeedsUpdateConstraints() } } /// (Pre)selects a row at a certain index. public func selectRow(at index: Index?, scrollPosition: UITableView.ScrollPosition = .none) { if let index = index { tableView.selectRow( at: IndexPath(row: index, section: 0), animated: true, scrollPosition: scrollPosition ) selectedRowIndices.insert(index) } else { deselectRows(at: selectedRowIndices) selectedRowIndices.removeAll() } } public func selectRows(at indices: Set<Index>?) { indices?.forEach { selectRow(at: $0) } // if we are in multi selection mode then reload data so that all selections are shown if multiSelectionAction != nil { tableView.reloadData() } } public func deselectRow(at index: Index?) { guard let index = index , index >= 0 else { return } // remove from indices if let selectedRowIndex = selectedRowIndices.firstIndex(where: { $0 == index }) { selectedRowIndices.remove(at: selectedRowIndex) } tableView.deselectRow(at: IndexPath(row: index, section: 0), animated: true) } // de-selects the rows at the indices provided public func deselectRows(at indices: Set<Index>?) { indices?.forEach { deselectRow(at: $0) } } /// Returns the index of the selected row. public var indexForSelectedRow: Index? { return (tableView.indexPathForSelectedRow as NSIndexPath?)?.row } /// Returns the selected item. public var selectedItem: String? { guard let row = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row else { return nil } return dataSource[row] } /// Returns the height needed to display all cells. fileprivate var tableHeight: CGFloat { return tableView.rowHeight * CGFloat(dataSource.count) } //MARK: Objective-C methods for converting the Swift type Index @objc public func selectRow(_ index: Int, scrollPosition: UITableView.ScrollPosition = .none) { self.selectRow(at:Index(index), scrollPosition: scrollPosition) } @objc public func clearSelection() { self.selectRow(at:nil) } @objc public func deselectRow(_ index: Int) { tableView.deselectRow(at: IndexPath(row: Index(index), section: 0), animated: true) } @objc public var indexPathForSelectedRow: NSIndexPath? { return tableView.indexPathForSelectedRow as NSIndexPath? } } //MARK: - UITableViewDataSource - UITableViewDelegate extension TedoooDropDown: UITableViewDataSource, UITableViewDelegate { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: DPDConstant.ReusableIdentifier.DropDownCell, for: indexPath) as! DropDownCell let index = (indexPath as NSIndexPath).row configureCell(cell, at: index) return cell } fileprivate func configureCell(_ cell: DropDownCell, at index: Int) { if index >= 0 && index < localizationKeysDataSource.count { cell.accessibilityIdentifier = localizationKeysDataSource[index] } cell.optionLabel.textColor = textColor cell.optionLabel.font = textFont cell.selectedBackgroundColor = selectionBackgroundColor cell.highlightTextColor = selectedTextColor cell.normalTextColor = textColor if let cellConfiguration = cellConfiguration { cell.optionLabel.text = cellConfiguration(index, dataSource[index]) } else { cell.optionLabel.text = dataSource[index] } customCellConfiguration?(index, dataSource[index], cell) } public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.isSelected = selectedRowIndices.first{ $0 == (indexPath as NSIndexPath).row } != nil } } //MARK: - Auto dismiss extension TedoooDropDown { public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let view = super.hitTest(point, with: event) if dismissMode == .automatic && view === dismissableView { cancel() return nil } else { return view } } @objc fileprivate func dismissableViewTapped() { cancel() } } //MARK: - Keyboard events extension TedoooDropDown { /** Starts listening to keyboard events. Allows the drop down to display correctly when keyboard is showed. */ @objc public static func startListeningToKeyboard() { KeyboardListener.sharedInstance.startListeningToKeyboard() } fileprivate func startListeningToKeyboard() { KeyboardListener.sharedInstance.startListeningToKeyboard() NotificationCenter.default.addObserver( self, selector: #selector(keyboardUpdate), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver( self, selector: #selector(keyboardUpdate), name: UIResponder.keyboardWillHideNotification, object: nil) } fileprivate func stopListeningToNotifications() { NotificationCenter.default.removeObserver(self) } @objc fileprivate func keyboardUpdate() { self.setNeedsUpdateConstraints() } } private extension DispatchQueue { static func executeOnMainThread(_ closure: @escaping Closure) { if Thread.isMainThread { closure() } else { main.async(execute: closure) } } } #endif
29.180144
268
0.713466
5685a3c9ad79fc677557ab13c9cab75c3e61bf1a
1,042
// // WWProfileVC.swift // WWDC // // Created by Maxim Eremenko on 3/26/17. // Copyright © 2017 Maxim Eremenko. All rights reserved. // import UIKit class WWProfileVC: WWChildVC { let contentView = WWProfileView() let controller = WWProfileController() override func loadView() { self.view = contentView } override func viewDidLoad() { super.viewDidLoad() self.configureModule() } } private extension WWProfileVC { func configureModule() { let models = WWProfileBuilder.createModels() self.controller.attach(collectionView: self.contentView.collectionView()) self.controller.updateWith(models: models) self.controller.updateWith { (page: Int) in self.contentView.update(currentPage: page) } self.contentView.update(numberOfPages: models.count) self.contentView.updateWith(againBlock: { WWSceneRouter.current.presentScreenWith(sceneType: .Intro) }) } }
24.232558
81
0.639155
d76e9a7e6867e51d075fa157a972ae2a123d40d6
2,039
/** * (C) Copyright IBM Corp. 2017, 2018. * * 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 /** Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. */ public struct SemanticRolesOptions: Codable, Equatable { /** Maximum number of semantic_roles results to return. */ public var limit: Int? /** Set this to `true` to return keyword information for subjects and objects. */ public var keywords: Bool? /** Set this to `true` to return entity information for subjects and objects. */ public var entities: Bool? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case limit = "limit" case keywords = "keywords" case entities = "entities" } /** Initialize a `SemanticRolesOptions` with member variables. - parameter limit: Maximum number of semantic_roles results to return. - parameter keywords: Set this to `true` to return keyword information for subjects and objects. - parameter entities: Set this to `true` to return entity information for subjects and objects. - returns: An initialized `SemanticRolesOptions`. */ public init( limit: Int? = nil, keywords: Bool? = nil, entities: Bool? = nil ) { self.limit = limit self.keywords = keywords self.entities = entities } }
29.985294
101
0.677293
d789759242e2f70e2449e84234df7b3173ba272d
221
// // ImageCollectionTableViewCell.swift // EAO // // Created by Amir Shayegh on 2018-01-12. // Copyright © 2018 FreshWorks. All rights reserved. // import UIKit class ImageCollectionTableViewCell: BaseFormCell { }
17
53
0.733032
72cb16c2f59c8644d68613d93bb4ff20cc5eb10b
14,345
// // HomeViewController.swift // FinanceAPP // // Created by Victor Prado on 21/02/18. // Copyright © 2018 Victor Prado. All rights reserved. // import UIKit import FSCalendar import MaterialComponents.MaterialSnackbar import RealmSwift import UserNotifications class HomeViewController: UIViewControllerExtension { @IBOutlet weak var calendar: FSCalendar! @IBOutlet weak var calendarHeightConstraint: NSLayoutConstraint! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var noResultContainer: UIView! @IBOutlet weak var btSync: UIBarButtonItem! var invoices: [Invoice] = [] var oldCalendarHeight = CGFloat(300) private var api: InvoiceAPI = InvoiceAPI.shared private var defaults = UserDefaults.standard var apiRequested: Bool = false var uiBusy: UIActivityIndicatorView = { let uibusy = UIActivityIndicatorView(activityIndicatorStyle: .white) uibusy.hidesWhenStopped = true uibusy.startAnimating() return uibusy }() var nm = NotificationsManager.shared override func viewDidLoad() { super.viewDidLoad() calendar.appearance.headerMinimumDissolvedAlpha = 0.0 calendar.setScope(.week, animated: true) calendarHeightConstraint.constant = 120 getInvoices() NotificationCenter.default.addObserver(self, selector: #selector(onReceive(notification:)), name: NSNotification.Name(rawValue: "pay"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(onReceiveViewNotitication(notification:)), name: NSNotification.Name(rawValue: "view"), object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) invoices = [] tableView.reloadData() let realm = try! Realm() let results = realm.objects(Invoice.self) invoices = Array(results) if invoices.count > 0 { noResultContainer.isHidden = true } else { noResultContainer.isHidden = false } tableView.reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if let id = sender as? Int { if let invoice = invoices.first(where: {$0.id == id}) { let vc = segue.destination as! InvoiceViewController vc.invoice = invoice } } else if let vc = segue.destination as? InvoiceViewController { let invoice = invoices[tableView.indexPathForSelectedRow!.row] vc.invoice = invoice } else if let vc = segue.destination as? FilterViewController { vc.delegate = self } } @IBAction func toggleScope(_ sender: UIBarButtonItem) { switch calendar.scope { case .month: changeImages("icons8-expand-filled", for: sender, constant: 120) calendar.setScope(.week, animated: true) case .week: changeImages("icons8-collapse-filled", for: sender, constant: oldCalendarHeight) calendar.setScope(.month, animated: true) } } @IBAction func filter(_ sender: UIBarButtonItem) { performSegue(withIdentifier: "filterSegue", sender: nil) } @IBAction func sync(_ sender: UIBarButtonItem) { sender.customView?.isHidden = true navigationItem.leftBarButtonItem = UIBarButtonItem(customView: uiBusy) getInvoices() } func changeImages(_ image: String, for sender: UIBarButtonItem, constant: CGFloat) { UIView.animate(withDuration: 0.1, animations: { sender.image = UIImage(named: image) self.calendarHeightConstraint.constant = constant self.view.layoutIfNeeded() }) } @objc func onReceive(notification: Notification) { if let userInfo = notification.userInfo, let id = userInfo["id"] as? Int { if let invoice = invoices.first(where: {$0.id == id}) { self.api.makePayment(value: invoice.value, invoice: invoice, completionHandler: { (success, error) in if error == nil { self.doSnackbar("invoice \(invoice.title) was paid") if invoice.totalPaid >= invoice.value { let realm = try! Realm() try! realm.write { invoice.paid = true } } DispatchQueue.main.async { self.tableView.reloadData() } self.navigationItem.leftBarButtonItem = self.btSync } else { self.doSnackbar(error!) } }) } } } @objc func onReceiveViewNotitication(notification: Notification) { if let userInfo = notification.userInfo, let id = userInfo["id"] as? Int { performSegue(withIdentifier: "editInvoice", sender: id) } } func getInvoices() { api.getInvoices(params: [:]) { (invoices, error) in if error == nil { if let inv = invoices { self.invoices = inv if self.invoices.count == 0 { let realm = try! Realm() let result = realm.objects(Invoice.self) try! realm.write { realm.delete(result) } } self.createNotifications(invoices: inv) DispatchQueue.main.async { self.tableView.reloadData() self.apiRequested = true self.navigationItem.leftBarButtonItem = self.btSync if inv.count <= 0 { self.noResultContainer.isHidden = false } else { self.noResultContainer.isHidden = true } } } } else { self.doSnackbar(error!) self.navigationItem.leftBarButtonItem = self.btSync self.apiRequested = false } } } func createNotifications(invoices: [Invoice]) { var invoicesToNotCreateNotification: [Int] = [] UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (notifications) in for notification in notifications { for invoice in invoices { if notification.identifier == "\(invoice.id)" { invoicesToNotCreateNotification.append(invoice.id) break } } } }) for id in invoicesToNotCreateNotification { for invoice in invoices { if invoice.id != id && invoice.paid == false { nm.scheduleNotification(identifier: "\(invoice.id)", invoice.title, subtitle: invoice.category!.title, message: "The invoice \(invoice.title) is expiring", when: invoice.expireDate) } } } } func getInvoicesWithFilter(_ filter: (category: Category?, value: Double?)? = nil) { if let filter = filter { let realm = try! Realm() if filter.category != nil && filter.value == nil { let results = realm.objects(Invoice.self).filter("categoryId == %@", filter.category!.id) invoices = Array(results) tableView.reloadData() } else if filter.value != nil && filter.category == nil { let results = realm.objects(Invoice.self).filter("value == %@", filter.value!) invoices = Array(results) tableView.reloadData() } else if filter.value != nil && filter.category != nil { let results = realm.objects(Invoice.self).filter("value == %@ AND categoryId == %@", filter.value!, filter.category!.id) invoices = Array(results) tableView.reloadData() } } } func doSnackbar(_ msg: String) { let message = MDCSnackbarMessage() message.text = msg MDCSnackbarManager.show(message) } } extension HomeViewController: FSCalendarDelegate, FSCalendarDataSource { func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) { let expireDate = DateUtils.dateToString(date) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: self.uiBusy) api.getInvoices(params: ["expireDate": expireDate]) { (invoices, error) in if error == nil { if let inv = invoices { self.invoices = inv DispatchQueue.main.async { self.tableView.reloadData() self.navigationItem.leftBarButtonItem = self.btSync } } } else { self.doSnackbar(error!) self.navigationItem.leftBarButtonItem = self.btSync } } } } extension HomeViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if invoices.count == 0 { self.noResultContainer.isHidden = false } else { self.noResultContainer.isHidden = true } return invoices.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "financeCell", for: indexPath) as! FinanceTableViewCell let backgroundView = UIView() backgroundView.backgroundColor = .black cell.selectedBackgroundView = backgroundView let invoice = invoices[indexPath.row] cell.prepare(invoice: invoice) return cell; } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "editInvoice", sender: nil) tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Upcoming bills to be delayed" } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let action = UIContextualAction(style: .normal, title: "Pay") { (contextAction: UIContextualAction, sourceView: UIView, completionHandler: (Bool) -> Void) in let invoice = self.invoices[indexPath.row] self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: self.uiBusy) self.api.makePayment(value: invoice.value, invoice: invoice, completionHandler: { (success, error) in if error == nil { self.doSnackbar("invoice \(invoice.title) was paid") let cell = tableView.cellForRow(at: indexPath) as! FinanceTableViewCell if invoice.totalPaid >= invoice.value { cell.paidInvoice(true) let realm = try! Realm() try! realm.write { invoice.paid = true } } self.navigationItem.leftBarButtonItem = self.btSync } else { self.doSnackbar(error!) } }) completionHandler(true) } action.image = UIImage(named: "paid") action.backgroundColor = UIColor(named: "main_green") let deleteAction = UIContextualAction(style: .normal, title: "Delete") { (contextAction: UIContextualAction, sourceView: UIView, completionHandler: (Bool) -> Void) in let invoice = self.invoices[indexPath.row] let identified = String(invoice.id) let title = String(invoice.title) self.api.deleteInvoice(invoice: invoice, completionHandler: { (success, error) in if error == nil { self.doSnackbar("Invoice \(title) was removed") self.invoices.remove(at: indexPath.row) self.tableView.deleteRows(at: [indexPath], with: .fade) UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (notifications) in for notification in notifications { if notification.identifier == identified { UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notification.identifier]) } } }) DispatchQueue.main.async { self.tableView.reloadData() if self.invoices.count <= 0 { self.noResultContainer.isHidden = false } } } else { self.doSnackbar(error!) } }) completionHandler(true) } deleteAction.image = UIImage(named: "trash") deleteAction.backgroundColor = UIColor(named: "main_red") let swipeConfig = UISwipeActionsConfiguration(actions: [deleteAction, action]) return swipeConfig } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { print("Time to delete this...") } } }
40.868946
201
0.569397
7a85f85bfb2247d73d426f54b064cacc5d84bcfb
273
// // DinasView+Extension.swift // Dinas-Swift // // Created by ziooooo on 2018/6/7. // Copyright © 2018年 robam. All rights reserved. // import UIKit public extension DinasView { public var din: DinasViewDSL { return DinasViewDSL(view: self) } }
16.058824
49
0.652015
9c66d84b10f0a664b49e807b488583f98118559f
249
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true { case { protocol A { deinit { let c { func c { struct D { class case ,
16.6
87
0.726908
f903e45eaffcd31b1844af4853db99fdaf11433e
516
// // AppDelegate.swift // LTBouncyPlaceholderDemo // // Created by Lex on 6/9/14. // Copyright (c) 2014 LexTang.com. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { self.window!.backgroundColor = UIColor.whiteColor() return true } }
21.5
128
0.668605
e265b47d874e72b57a0cf1ee12d8d8b42695bb70
552
// // PieChartSliceModel.swift // PieChartSwiftUI // // Created by Kirill Pustovalov on 28.06.2020. // Copyright © 2020 Kirill Pustovalov. All rights reserved. // import SwiftUI struct PieChartSliceModel { var value: Double var color: Color var startDegree: Double var endDegree: Double public init(value: Double, color: Color, startDegree: Double, endDegree: Double) { self.value = value self.color = color self.startDegree = startDegree self.endDegree = endDegree } }
20.444444
86
0.652174
75089e5bde8407aa5390277c59cc3ef48c5bf159
271
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum S<T where h=i{class B<w{func f:B<T>struct B
38.714286
87
0.741697
89393006322235001fa3f949464237e86feee0e5
260
//: Playground - noun: a place where people can play import Cocoa import simd var v = float2(5,2) var m = float2(1,2) var vm = float2x2(columns: (v, float2(0))) var mm = float2x2(rows: [m, float2(0)]) let f = vm*mm print(f) f[0] f[1] f.inverse f.transpose
14.444444
52
0.661538
3a258f63c321354fab7e4603b68a8b1964ad2364
2,909
// // Mocking.swift // Plugin // // Created by NOWJOBS on 4/6/20. // Copyright © 2020 Max Lynch. All rights reserved. // import Microblink struct MockRecognizerResult: RecognizerResult { var additionalAddressInformation: String? var additionalNameInformation: String? var address: String? var conditions: String? let dateOfBirth: MBDateResult? = .init(day: 24, month: 1,year: 1984) let dateOfExpiry: MBDateResult? = .init(day: 12, month: 1, year: 2022) let dateOfExpiryPermanent = false let dateOfIssue: MBDateResult? = .init(day: 12, month: 1, year: 2016) var documentAdditionalNumber: String? let documentNumber: String? = "592280642506" var employer: String? let firstName: String? = "John" var fullName: String? let issuingAuthority: String? = "Ieper" let lastName: String? = "Doe" var localizedName: String? var maritalStatus: String? let mrzResult = MockMRZResult() let nationality: String? = "BELG" var personalIdNumber: String? let placeOfBirth: String? = "Kortrijk" var profession: String? var race: String? var religion: String? var residentialStatus: String? var sex: String? let fullDocumentFrontImage = MBImage(named: "demoDocumentFrontImage.jpg") let fullDocumentBackImage = MBImage(named: "demoDocumentBackImage.jpg") let faceImage = MBImage(named: "demoFaceImage.jpeg") } struct MockMRZResult: MRZResult { let documentType: MBMrtdDocumentType = .typeIdentityCard let primaryID = "DOE" let secondaryID = "JOHN" let issuer = "BEL" let issuerName = "BELGIUM" let dateOfBirth = MBDateResult(day: 24, month: 1, year: 1984) let documentNumber = "592280642506" let nationality = "BEL" let gender = "M" let documentCode = "ID" let dateOfExpiry = MBDateResult(day: 1, month: 12, year: 2022) let opt1 = "<<<<<<<<<<" let opt2 = "99012432572" let alienNumber = "" let applicationReceiptNumber = "" let immigrantCaseNumber = "" let mrzText = "IDBEL592280656<5058<<<<<<<<<<<\n9901247M2201122BEL990124325715\nDOE<<JOHN<<<<<<<\n" let isParsed = true let isVerified = true let sanitizedOpt1 = "" let sanitizedOpt2 = "99012432571" let sanitizedNationality = "BEL" let sanitizedIssuer = "BEL" let sanitizedDocumentCode = "ID" let sanitizedDocumentNumber = "592280642507" let nationalityName = "BELGIAN" } private extension MBDateResult { convenience init(day: Int, month: Int, year: Int) { self.init(day: day, month: month, year: year, originalDateString: nil) } } private extension MBImage { convenience init?(named name: String) { let bundle = Bundle(for: BlinkIDPlugin.self) guard #available(iOS 13.0, *), let image = UIImage(named: name, in: bundle, with: nil) else { return nil } self.init(uiImage: image) } }
33.436782
102
0.673771
d63407748140578bd908702cc6c7bfb7205463ef
2,168
// // AppDelegate.swift // Tip_Calculator // // Created by Joshua on 12/28/17. // Copyright © 2017 Joshua. 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:. } }
46.12766
285
0.755535
5b194d6390bc9f5d8a356be1b9b86d9eda1fdb73
1,014
// // InvoiceTest.swift // VoltageTests // // Created by Ben Harold on 2/2/18. // Copyright © 2018 Harold Consulting. All rights reserved. // import XCTest @testable import Voltage class InvoiceTest: XCTestCase { let decoder: JSONDecoder = JSONDecoder.init() func testListInvoicesIsDecodable() throws { // self.measure { let result: InvoiceResult guard let socket = LightningRPCSocket.create() else { throw SocketError.unwrap } let query = LightningRPCQuery( id: Int(getpid()), method: "listinvoices", params: [] ) let response: Data = socket.send(query) do { result = try decoder.decode(InvoiceResult.self, from: response) // I need to figure out how to assert that the result object // is the expected type Swift.print(result) } catch { Swift.print("Error: \(error)") } // } } }
26.684211
75
0.566075
cc146f5ee619250be3138758a22e66e574b765d1
722
// // UITableViewExtension.swift // News // // Created by CoderDream on 2019/4/17. // Copyright © 2019 CoderDream. All rights reserved. // import UIKit extension UITableView { /// 注册 cell 的方法 func ymRegisterCell<T: UITableViewCell>(cell: T.Type) where T: RigisterCellOrNib { if let nib = T.nib { register(nib, forCellReuseIdentifier: T.identifier) } else { register(cell, forCellReuseIdentifier: T.identifier) } } /// 从缓存池出队已经存在的 cell func ymDequeueReusableCell<T: UITableViewCell>(indexPath: IndexPath) -> T where T: RigisterCellOrNib { return dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as! T } }
25.785714
106
0.652355
ebcbc6af9c67785180d5adc754e40a95a805bbde
6,191
// // XDCAccount.swift // XDC // // Created by Developer on 15/06/21. // import Foundation import HDWalletKit protocol XDCAccountProtocol { var address: XDCAddress { get } // For Keystore handling init?(keyStorage: XDCKeyStorageProtocol, keystorePassword: String) throws static func create(keyStorage: XDCKeyStorageProtocol, keystorePassword password: String) throws -> XDCAccount static func createAccountWithMemonic() throws -> String static func importAccountWithMnemonic(mnemonic: String) throws -> Account // For non-Keystore formats. This is not recommended, however some apps may wish to implement their own storage. init(keyStorage: XDCKeyStorageProtocol) throws func sign(data: Data) throws -> Data func sign(hash: String) throws -> Data func sign(hex: String) throws -> Data func sign(message: Data) throws -> Data func sign(message: String) throws -> Data func sign(_ transaction: XDCTransaction) throws -> SignedTransaction } public enum XDCAccountError: Error { case createAccountError case loadAccountError case signError } public class XDCAccount: XDCAccountProtocol { private let privateKeyData: Data private let publicKeyData: Data public lazy var publicKey: String = { return self.publicKeyData.xdc3.hexString }() public lazy var privateKey: String = { return self.privateKeyData.xdc3.hexString }() public lazy var address: XDCAddress = { return KeyUtil.generateAddress(from: self.publicKeyData) }() required public init(keyStorage: XDCKeyStorageProtocol, keystorePassword password: String) throws { do { let data = try keyStorage.loadPrivateKey() if let decodedKey = try? KeystoreUtil.decode(data: data, password: password) { self.privateKeyData = decodedKey self.publicKeyData = try KeyUtil.generatePublicKey(from: decodedKey) } else { print("Error decrypting key data") throw XDCAccountError.loadAccountError } } catch { throw XDCAccountError.loadAccountError } } required public init(keyStorage: XDCKeyStorageProtocol) throws { do { let data = try keyStorage.loadPrivateKey() self.privateKeyData = data self.publicKeyData = try KeyUtil.generatePublicKey(from: data) } catch { throw XDCAccountError.loadAccountError } } // Create a account with private and public key. public static func create(keyStorage: XDCKeyStorageProtocol, keystorePassword password: String) throws -> XDCAccount { guard let privateKey = KeyUtil.generatePrivateKeyData() else { throw XDCAccountError.createAccountError } do { let encodedData = try KeystoreUtil.encode(privateKey: privateKey, password: password) try keyStorage.storePrivateKey(key: encodedData) return try self.init(keyStorage: keyStorage, keystorePassword: password) } catch { throw XDCAccountError.createAccountError } } public func sign(data: Data) throws -> Data { return try KeyUtil.sign(message: data, with: self.privateKeyData, hashing: true) } public func sign(hex: String) throws -> Data { if let data = Data.init(hex: hex) { return try KeyUtil.sign(message: data, with: self.privateKeyData, hashing: true) } else { throw XDCAccountError.signError } } public func sign(hash: String) throws -> Data { if let data = hash.xdc3.hexData { return try KeyUtil.sign(message: data, with: self.privateKeyData, hashing: false) } else { throw XDCAccountError.signError } } public func sign(message: Data) throws -> Data { return try KeyUtil.sign(message: message, with: self.privateKeyData, hashing: false) } public func sign(message: String) throws -> Data { if let data = message.data(using: .utf8) { return try KeyUtil.sign(message: data, with: self.privateKeyData, hashing: true) } else { throw XDCAccountError.signError } } public func signMessage(message: Data) throws -> String { let prefix = "\u{19}XDC Signed Message:\n\(String(message.count))" guard var data = prefix.data(using: .ascii) else { throw XDCAccountError.signError } data.append(message) let hash = data.xdc3.keccak256 guard var signed = try? self.sign(message: hash) else { throw XDCAccountError.signError } // Check last char (v) guard var last = signed.popLast() else { throw XDCAccountError.signError } if last < 27 { last += 27 } signed.append(last) return signed.xdc3.hexString } public func signMessage(message: TypedData) throws -> String { let hash = try message.signableHash() guard var signed = try? self.sign(message: hash) else { throw XDCAccountError.signError } // Check last char (v) guard var last = signed.popLast() else { throw XDCAccountError.signError } if last < 27 { last += 27 } signed.append(last) return signed.xdc3.hexString } public static func createAccountWithMemonic() throws -> String{ let mnemonic = Mnemonic.create() return mnemonic } public static func importAccountWithMnemonic(mnemonic: String) throws -> Account{ let seed = Mnemonic.createSeed(mnemonic: mnemonic) let wallet = Wallet(seed: seed, coin: .ethereum) let account = wallet.generateAccount() // print(account.rawPrivateKey.addHexPrefix()) // print(account.address) return account } }
33.106952
122
0.617509
33a7ddbd9aff1f2f7c092f1c80770391159b40d2
1,383
// // DictionaryExtension.swift // YTTCache // // Created by AndyCui on 2018/11/19. // import Foundation public extension Dictionary { public var ytt: YTTCacheDictionary<Key> { return YTTCacheDictionary<Key>(self) } static func dictionaryWithCache(_ key: String, timeoutIntervalForCache interval: TimeInterval = .greatestFiniteMagnitude, result: ((Dictionary<Key, Any>?) -> Void)?) { YTTCache.dataForKey(key, timeoutIntervalForCache: interval) { (data) in if let da = data, let dic = try? JSONSerialization.jsonObject(with: da, options: .allowFragments) as? Dictionary<Key, Any> { result?(dic) }else { result?(nil) } } } } public class YTTCacheDictionary<T> where T: Hashable { private var dictionary: Dictionary<T, Any> init(_ dictionary: Dictionary<T, Any>) { self.dictionary = dictionary } /// 缓存数据 /// /// - key: 键值 /// - result: 是否缓存成功 public func storeWithKey(_ key: String, result: ((Bool) -> Void)?) { do { let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: []) YTTCache.storeData(jsonData, key: key, result: result) } catch { YTTLog(error) result?(false) } } }
26.09434
172
0.579899
6abf32c2b72a1dd9c1d6c2412800a2e12bb59d9e
2,917
// // TableViewController.swift // test // // Created by ios135 on 2017/7/4. // Copyright © 2017年 Root HSZ HSU. All rights reserved. // import UIKit class TableViewController: UITableViewController { @IBAction func inBtn(_ sender: UIButton) { } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
27.518868
136
0.644155
f546d442c1df5718dd642318c7dc881e9d23528e
482
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck let a{class B<a{enum b{class A{let a{class B{class a{class b<T where T=a{protocol A
48.2
83
0.751037
def691ab6607b654f82b6f94ba7ac361c3533e60
3,144
// // VerseTableDS.swift // TranslationEditor // // Created by Mikko Hilpinen on 14.2.2017. // Copyright © 2017 SIL. All rights reserved. // import Foundation // This class handles verse table content class VerseTableDS: NSObject, UITableViewDataSource { // ATTRIBUTES --------------------- // Language / section name -> Paragraph private let data: [(title: String, paragraph: Paragraph)] private var filteredData: [(title: String, paragraph: Paragraph)] // The specific verse index the context is limited to private var _targetVerseIndex: VerseIndex? var targetVerseIndex: VerseIndex? { get { return _targetVerseIndex } set { _targetVerseIndex = newValue filterData() } } // INIT ----------------------------- // Resource data is combination of a language name and a matching paragraph version init(originalParagraph: Paragraph, resourceData: [(String, Paragraph)]) { var data = [(String, Paragraph)]() let originalTitle = NSLocalizedString("Original:", comment: "A title for the original version of a paragraph / paragraph portion in comment context") let currentTitle = NSLocalizedString("Current:", comment: "A title for the curent version of a paragraph / paragraph portion in comment context") // Adds the current (and original) version of the targeted paragraph first if originalParagraph.isMostRecent { data.append((originalTitle, originalParagraph)) } else { data.append((originalTitle, originalParagraph)) do { if let latestId = try ParagraphHistoryView.instance.mostRecentId(forParagraphWithId: originalParagraph.idString), let latestVersion = try Paragraph.get(latestId) { data.append((currentTitle, latestVersion)) } else { print("ERROR: No latest version available for paragraph \(originalParagraph.idString)") } } catch { print("ERROR: Failed to find the latest paragraph version. \(error)") } } // Also includes other data self.data = data + resourceData self.filteredData = self.data } // IMPLEMENTED METHODS ------------- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Finds a reusable cell first let cell = tableView.dequeueReusableCell(withIdentifier: VerseCell.identifier, for: indexPath) as! VerseCell let data = filteredData[indexPath.row] cell.configure(title: data.title, paragraph: data.paragraph) return cell } // OTHER METHODS -------------- func filterData() { if let targetVerseIndex = targetVerseIndex { filteredData = data.compactMap { let paragraph = $0.paragraph.copy() for para in paragraph.content { para.verses = para.verses.filter { $0.range.contains(index: targetVerseIndex) } } paragraph.content = paragraph.content.filter { !$0.verses.isEmpty } if paragraph.content.isEmpty { return nil } else { return ($0.title, paragraph) } } } else { filteredData = data } } }
25.152
165
0.685751
20c297249b637fe0ebe1168bb08e996baf2e6e10
2,725
// SPDX-License-Identifier: MIT // Copyright © 2018-2020 WireGuard LLC. All Rights Reserved. import UIKit class EditableTextCell: UITableViewCell { var message: String { get { return valueTextField.text ?? "" } set(value) { valueTextField.text = value } } var placeholder: String? { get { return valueTextField.placeholder } set(value) { valueTextField.placeholder = value } } let valueTextField: UITextField = { let valueTextField = UITextField() valueTextField.textAlignment = .left valueTextField.isEnabled = true valueTextField.font = UIFont.preferredFont(forTextStyle: .body) valueTextField.adjustsFontForContentSizeCategory = true valueTextField.autocapitalizationType = .none valueTextField.autocorrectionType = .no valueTextField.spellCheckingType = .no return valueTextField }() var onValueBeingEdited: ((String) -> Void)? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) valueTextField.delegate = self contentView.addSubview(valueTextField) valueTextField.translatesAutoresizingMaskIntoConstraints = false // Reduce the bottom margin by 0.5pt to maintain the default cell height (44pt) let bottomAnchorConstraint = contentView.layoutMarginsGuide.bottomAnchor.constraint(equalTo: valueTextField.bottomAnchor, constant: -0.5) bottomAnchorConstraint.priority = .defaultLow NSLayoutConstraint.activate([ valueTextField.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor), contentView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: valueTextField.trailingAnchor), contentView.layoutMarginsGuide.topAnchor.constraint(equalTo: valueTextField.topAnchor), bottomAnchorConstraint ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func beginEditing() { valueTextField.becomeFirstResponder() } override func prepareForReuse() { super.prepareForReuse() message = "" placeholder = nil } } extension EditableTextCell: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let onValueBeingEdited = onValueBeingEdited { let modifiedText = ((textField.text ?? "") as NSString).replacingCharacters(in: range, with: string) onValueBeingEdited(modifiedText) } return true } }
37.847222
145
0.698349
b9622f25f34eccdb302fa06f7488ac3160165be4
753
// // Doc.swift // Objectify // // Created by ehsan sat on 4/22/20. // Copyright © 2020 ehsan sat. All rights reserved. // import Foundation class Doc { var docSentimentPolarity: String = "" var docSentimentResultString: String = "" var docSentimentValue: Double = 0.0 var subjectivity: String = "" var magnitude: Double = 0.0 init(docSentimentPolarity: String, docSentimentResultString: String, docSentimentValue: Double, subjectivity: String, magnitude: Double) { self.docSentimentPolarity = docSentimentPolarity self.docSentimentResultString = docSentimentResultString self.docSentimentValue = docSentimentValue self.subjectivity = subjectivity self.magnitude = magnitude } }
30.12
142
0.709163
08b7c0f60a936dbb10380bdc7777414cbc842460
298
// // HTTPClient.swift // FeedFramework // // Created by SanjayPathak on 12/06/21. // import Foundation public enum RFResult{ case success(Data, HTTPURLResponse) case failure(Error) } public protocol HTTPClient{ func get(from url: URL, completion: @escaping (RFResult) -> Void) }
16.555556
69
0.697987
14f2cb58d4e7ed7cc7d63576ea0f5009fc35885d
734
/** A set of options used to clone a repository. These are made up of options used to checkout a repository, combined with a set of callbacks updated with cloning progress. */ public struct CloneOptions { internal let checkoutOptions: CheckoutOptions internal let remoteCallbacks: RemoteCallbacks internal let localCloneBehavior: LocalCloneBehavior public init( checkoutOptions: CheckoutOptions = CheckoutOptions(strategy: CheckoutStrategy.SafeCreate), remoteCallbacks: RemoteCallbacks = RemoteCallbacks(), localCloneBehavior: LocalCloneBehavior = .Automatic ) { self.checkoutOptions = checkoutOptions self.remoteCallbacks = remoteCallbacks self.localCloneBehavior = localCloneBehavior } }
33.363636
94
0.784741
9c7c28e47d0f8dfbbb99607e70cc94febe245368
9,869
// // Snap.swift // Pods // // Created by Shaps Mohsenin on 13/07/2016. // // import UIKit /* Snap can be used to provide 'paging' behaviour to a scrollView with arbitrarily sized content. This class also provides advanced snapping behaviour such as edge alignment. Snap is designed to completely plug-n-play. */ public final class Snap: NSObject, UIScrollViewDelegate { // MARK: Variables /// The scrollView this class should apply Snap to private weak var scrollView: UIScrollView! /// The original delegate to forward all delegate methods to so that existing behaviour is still handled private weak var originalDelegate: UIScrollViewDelegate? /// The supported direction private var snapDirection: SnapDirection /// The edge to snap to public private(set) var snapEdge: SnapEdge /// The current snap locations private var locations = [CGFloat]() // MARK: Lifecycle /** Initializes Snap with a scrollView - parameter scrollView: The scrollView to apply snapping to - parameter edge: The scrollView edge to snap to - parameter direction: The scrollView direction to apply snapping - parameter delegate: The original scrollView delegate. If nil, scrollView.delegate will be used - returns: A new instance of Snap */ public init(scrollView: UIScrollView, edge: SnapEdge = .min, direction: SnapDirection = .automatic, delegate: UIScrollViewDelegate? = nil) { self.scrollView = scrollView self.originalDelegate = delegate ?? scrollView.delegate self.snapDirection = direction self.snapEdge = edge super.init() scrollView.delegate = self } // MARK: Public functions /** Scrolls to the nearest snap point, relative to the specified offset - parameter offset: The content offset */ public func scrollToNearestSnapLocationForTargetContentOffset(offset: CGPoint) { let contentOffset = contentOffsetForTargetContentOffset(offset: offset) scrollView?.setContentOffset(contentOffset, animated: true) } /** Called when dragging stops inside the scrollView - parameter scrollView: The scrollView that was being dragged - parameter velocity: The velocity as dragging stopped - parameter targetContentOffset: The expected offset when the scrolling action decelerates to a stop */ public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { guard locations.count > 0 else { return } let direction = supportedDirection() let offset = contentOffsetForTargetContentOffset(offset: targetContentOffset.pointee) let dragVelocity = (direction == .horizontal ? abs(velocity.x) : abs(velocity.y)) guard dragVelocity > 0 else { scrollView.setContentOffset(offset, animated: true) return } targetContentOffset.pointee = offset scrollView.setContentOffset(offset, animated: true) // fixes a flicker bug originalDelegate?.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset) } /** Returns the content offset for a target offset, taking into account the snap locations - parameter offset: The target offset (generally provided by the scrollView) - returns: The snap offset */ public func contentOffsetForTargetContentOffset(offset: CGPoint) -> CGPoint { let direction = supportedDirection() var next: CGFloat = 0 var prev: CGFloat = 0 var offsetValue = direction == .horizontal ? offset.x : offset.y let bounds = direction == .horizontal ? scrollView.bounds.width : scrollView.bounds.height guard offsetValue > 0 else { return CGPoint.zero } switch snapEdge { case .min: break case .mid: offsetValue += bounds / 2 case .max: offsetValue += bounds } if let location = locations.last, offsetValue > location { return direction == .horizontal ? CGPoint(x: location, y: 0) : CGPoint(x: 0, y: location) } for i in 0..<locations.count { next = locations[i] if next > offsetValue { let index = max(0, min(locations.count - 1, i - 1)) prev = locations[index] break } } next = min(next, maximumValue()) let spanValue = fabs(next - prev) let midValue = next - (spanValue / 2) if midValue <= 0 { return CGPoint.zero } var location: CGFloat = next if offsetValue < midValue { location = prev } switch snapEdge { case .min: break case .mid: location -= bounds / 2 case .max: location -= bounds } location = max(location, 0) // clamp our values return direction == .horizontal ? CGPoint(x: location, y: 0) : CGPoint(x: 0, y: location) } /** Returns the supported direction. When direction == .Automatic, and the scrollView is a collectionView using a flow layout, the direction property will be used to determine direction. If the scrollView is a tableView, then this will always return Vertical. In all other cases the direction will be determined by comparing the scrollView's contentSize and looking for the larger value. When no direction can be determined, this defaults to Vertical. - returns: The supported snap direction */ public func supportedDirection() -> SnapDirection { if scrollView is UITableView { return .vertical } guard snapDirection == .automatic else { return snapDirection } if let collectionView = scrollView as? UICollectionView, let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { return layout.scrollDirection == .vertical ? .vertical : .horizontal } return scrollView.contentSize.width > scrollView.contentSize.height ? .horizontal : .vertical } // MARK: Public Setters /** Updates the snap locations - parameter locations: The new locations to apply - parameter realignImmediately: If true, the scrollView will automatically re-align to the nearest location based on its current offset. */ public func setSnapLocations(locations: [CGFloat], realignImmediately: Bool) { let offset = scrollView.contentOffset // Remove duplicates and sort the resulting values var locs = [CGFloat]() locs.append(0) locs.append(contentsOf: locations) self.locations = Set(locs).sorted() guard realignImmediately else { return } scrollToNearestSnapLocationForTargetContentOffset(offset: offset) } /** Updates the snap edge to use when snapping to a location - parameter edge: The edge to snap to - parameter realignImmediately: If true, the scrollView will automatically re-align to the nearest location based on its current offset. */ public func setSnapEdge(edge: SnapEdge, realignImmediately: Bool) { self.snapEdge = edge guard realignImmediately else { return } scrollToNearestSnapLocationForTargetContentOffset(offset: scrollView.contentOffset) } /** Updates the snap direction to apply snapping to - parameter direction: The direction to apply snapping behaviour - parameter realignImmediately: If true, the scrollView will automatically re-align to the nearest location based on its current offset. */ public func setSnapDirection(direction: SnapDirection, realignImmediately: Bool) { self.snapDirection = direction guard realignImmediately else { return } scrollToNearestSnapLocationForTargetContentOffset(offset: scrollView.contentOffset) } // MARK: Delegate forwarding public override func responds(to aSelector: Selector!) -> Bool { if super.responds(to: aSelector) { return true } if originalDelegate?.responds(to: aSelector) ?? false { return true } return false } public override func forwardingTarget(for aSelector: Selector!) -> Any? { if super.responds(to: aSelector) { return self } return originalDelegate } // MARK: Helpers private func maximumValue() -> CGFloat { switch snapEdge { case .min: return supportedDirection() == .horizontal ? scrollView.contentSize.width - scrollView.bounds.width : scrollView.contentSize.height - scrollView.bounds.height case .mid: return supportedDirection() == .horizontal ? scrollView.contentSize.width - scrollView.bounds.width / 2 : scrollView.contentSize.height - scrollView.bounds.height / 2 case .max: return supportedDirection() == .horizontal ? scrollView.contentSize.width : scrollView.contentSize.height } } // MARK: Debugging public override var description: String { return "\(super.description), Locations:\n\(locations)" } }
36.018248
452
0.629952
0915e3c51848de0d20750c31d8efd9222fd86c07
1,440
// // Copyright (c) 2018 Touch Instinct // // 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.UITableView extension UITableView: PaginationWrappable { public var scrollView: UIScrollView { return self } public var footerView: UIView? { get { return tableFooterView } set { tableFooterView = newValue } } }
35.121951
81
0.715278
c1ea50ce84e98bc46b933b48b0a198eef11585ee
234
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let i{[0 struct Q{ struct c<T where g:A{ struct Q<T where H.j.j:A
29.25
87
0.747863
9bebc7fbe22f8c52bf15ec78893f14634cc69c7f
851
import Foundation extension Sequence { /** Filter out duplicate elements according to a key returned by the `selector` closure. The order is preserved and, in case of a duplicate, the first element of that key is matched. The others are omitted from the returned array. - Parameter selector: A closure that returns a key, called for every element in this sequence. - Throws: Rethrows exceptions from `selector`. - Returns: A sequence whose elements have unique values of the field referenced by `key`. */ @usableFromInline internal func unique<T: Hashable>(by selector: (Iterator.Element) throws -> T) rethrows -> [Iterator.Element] { var seen = Set<T>() return try filter { let (inserted, _) = seen.insert(try selector($0)) return inserted } } }
34.04
115
0.666275
f42c7a314dc4edfe44511d0515c1692a2b83f7e9
5,553
// RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | FileCheck %s // CHECK-LABEL: sil hidden @_TF5decls11void_returnFT_T_ // CHECK: = tuple // CHECK: return func void_return() { } // CHECK-LABEL: sil hidden @_TF5decls14typealias_declFT_T_ func typealias_decl() { typealias a = Int } // CHECK-LABEL: sil hidden @_TF5decls15simple_patternsFT_T_ func simple_patterns() { _ = 4 var _ : Int } // CHECK-LABEL: sil hidden @_TF5decls13named_patternFT_Si func named_pattern() -> Int { var local_var : Int = 4 var defaulted_var : Int // Defaults to zero initialization return local_var + defaulted_var } func MRV() -> (Int, Float, (), Double) {} // CHECK-LABEL: sil hidden @_TF5decls14tuple_patternsFT_T_ func tuple_patterns() { var (a, b) : (Int, Float) // CHECK: [[AADDR1:%[0-9]+]] = alloc_box $Int // CHECK: [[AADDR:%[0-9]+]] = mark_uninitialized [var] [[AADDR1]]#1 // CHECK: [[BADDR1:%[0-9]+]] = alloc_box $Float // CHECK: [[BADDR:%[0-9]+]] = mark_uninitialized [var] [[BADDR1]]#1 var (c, d) = (a, b) // CHECK: [[CADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[DADDR:%[0-9]+]] = alloc_box $Float // CHECK: copy_addr [[AADDR]] to [initialization] [[CADDR]]#1 // CHECK: copy_addr [[BADDR]] to [initialization] [[DADDR]]#1 // CHECK: [[EADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[FADDR:%[0-9]+]] = alloc_box $Float // CHECK: [[GADDR:%[0-9]+]] = alloc_box $() // CHECK: [[HADDR:%[0-9]+]] = alloc_box $Double // CHECK: [[EFGH:%[0-9]+]] = apply // CHECK: [[E:%[0-9]+]] = tuple_extract {{.*}}, 0 // CHECK: [[F:%[0-9]+]] = tuple_extract {{.*}}, 1 // CHECK: [[G:%[0-9]+]] = tuple_extract {{.*}}, 2 // CHECK: [[H:%[0-9]+]] = tuple_extract {{.*}}, 3 // CHECK: store [[E]] to [[EADDR]] // CHECK: store [[F]] to [[FADDR]] // CHECK: store [[H]] to [[HADDR]] var (e,f,g,h) : (Int, Float, (), Double) = MRV() // CHECK: [[IADDR:%[0-9]+]] = alloc_box $Int // CHECK-NOT: alloc_box $Float // CHECK: copy_addr [[AADDR]] to [initialization] [[IADDR]]#1 // CHECK: [[B:%[0-9]+]] = load [[BADDR]] // CHECK-NOT: store [[B]] var (i,_) = (a, b) // CHECK: [[JADDR:%[0-9]+]] = alloc_box $Int // CHECK-NOT: alloc_box $Float // CHECK: [[KADDR:%[0-9]+]] = alloc_box $() // CHECK-NOT: alloc_box $Double // CHECK: [[J_K_:%[0-9]+]] = apply // CHECK: [[J:%[0-9]+]] = tuple_extract {{.*}}, 0 // CHECK: [[K:%[0-9]+]] = tuple_extract {{.*}}, 2 // CHECK: store [[J]] to [[JADDR]] var (j,_,k,_) : (Int, Float, (), Double) = MRV() } // CHECK-LABEL: sil hidden @_TF5decls16simple_arguments // CHECK: bb0(%0 : $Int, %1 : $Int): // CHECK: [[X:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %0 to [[X]] // CHECK-NEXT: [[Y:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %1 to [[Y]]#1 func simple_arguments(var x: Int, var y: Int) -> Int { return x+y } // CHECK-LABEL: sil hidden @_TF5decls17curried_arguments // CHECK: bb0(%0 : $Int, %1 : $Int): // CHECK: [[X:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %1 to [[X]] // CHECK: [[Y:%[0-9]+]] = alloc_box $Int // CHECK-NEXT: store %0 to [[Y]] func curried_arguments(x: Int)(y: Int) -> Int { var x = x var y = y return x+y } // CHECK-LABEL: sil hidden @_TF5decls14tuple_argument // CHECK: bb0(%0 : $Int, %1 : $Float): // CHECK: [[UNIT:%[0-9]+]] = tuple () // CHECK: [[TUPLE:%[0-9]+]] = tuple (%0 : $Int, %1 : $Float, [[UNIT]] : $()) // CHECK: [[XADDR:%[0-9]+]] = alloc_box $(Int, Float, ()) // CHECK: store [[TUPLE]] to [[XADDR]]#1 func tuple_argument(var x: (Int, Float, ())) { } // CHECK-LABEL: sil hidden @_TF5decls14inout_argument // CHECK: bb0(%0 : $*Int, %1 : $Int): // CHECK: [[X_LOCAL:%[0-9]+]] = alloc_box $Int // CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int // CHECK: copy_addr [[YADDR]]#1 to [[X_LOCAL]]#1 func inout_argument(inout x: Int, var y: Int) { x = y } var global = 42 // CHECK-LABEL: sil hidden @_TF5decls16load_from_global func load_from_global() -> Int { return global // CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @_TF5declsau6globalSi // CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]() // CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]] // CHECK: [[VALUE:%[0-9]+]] = load [[ADDR]] // CHECK: return [[VALUE]] } // CHECK-LABEL: sil hidden @_TF5decls15store_to_global func store_to_global(var x: Int) { global = x // CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @_TF5declsau6globalSi // CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]() // CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]] // CHECK: copy_addr [[XADDR]]#1 to [[ADDR]] // CHECK: return } struct S { var x:Int // CHECK-LABEL: sil hidden @_TFV5decls1SCf init() { x = 219 } init(a:Int, b:Int) { x = a + b } } // CHECK-LABEL: StructWithStaticVar.init // rdar://15821990 - Don't emit default value for static var in instance init() struct StructWithStaticVar { static var a : String = "" var b : String = "" init() { } } // <rdar://problem/17405715> lazy property crashes silgen of implicit memberwise initializer // CHECK-LABEL: // decls.StructWithLazyField.init // CHECK-NEXT: sil hidden @_TFV5decls19StructWithLazyFieldC{{.*}} : $@convention(thin) (Optional<Int>, @thin StructWithLazyField.Type) -> @owned StructWithLazyField { struct StructWithLazyField { lazy var once : Int = 42 let someProp = "Some value" } // <rdar://problem/21057425> Crash while compiling attached test-app. // CHECK-LABEL: // decls.test21057425 func test21057425() { var x = 0, y: Int = 0 } func useImplicitDecls() { _ = StructWithLazyField(once: 55) }
30.679558
166
0.595714
f7171c06965533c9acf39dcce8ddc7dbdb841a31
810
// // LogSeverity.swift // SLog // // Created by Sam Krishna on 10/17/17. // Copyright © 2017 Sam Krishna. All rights reserved. // import Foundation public func <(lhs: LogSeverity, rhs: LogSeverity) -> Bool { return lhs.rawValue < rhs.rawValue } public func ==(lhs: LogSeverity, rhs: LogSeverity) -> Bool { return lhs.rawValue == rhs.rawValue } public enum LogSeverity: UInt { case verbose = 0 case debug = 1 case info = 2 case warning = 3 case error = 4 public var description: String { switch self { case .verbose: return "Verbose" case .debug: return "Debug" case .info: return "Info" case .warning: return "Warning" case .error: return "Error" } } }
21.891892
60
0.571605
035a360465185d8ecc80128f1aba0c4f54064217
24,329
// // Anchorage.swift // Anchorage // // Created by Rob Visentin on 2/6/16. // // Copyright 2016 Raizlabs and other contributors // http://raizlabs.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 UIKit public protocol LayoutAnchorType {} extension NSLayoutDimension : LayoutAnchorType {} extension NSLayoutXAxisAnchor : LayoutAnchorType {} extension NSLayoutYAxisAnchor : LayoutAnchorType {} public protocol LayoutAxisType {} extension NSLayoutXAxisAnchor : LayoutAxisType {} extension NSLayoutYAxisAnchor : LayoutAxisType {} #if swift(>=3.0) // MARK: - Equality Constraints @discardableResult public func == (lhs: NSLayoutDimension, rhs: CGFloat) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalToConstant: rhs)) } @discardableResult public func == (lhs: NSLayoutXAxisAnchor, rhs: NSLayoutXAxisAnchor) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs)) } @discardableResult public func == (lhs: NSLayoutYAxisAnchor, rhs: NSLayoutYAxisAnchor) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs)) } @discardableResult public func == (lhs: NSLayoutDimension, rhs: NSLayoutDimension) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs)) } @discardableResult public func == <T: NSLayoutDimension>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func == <T: NSLayoutXAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func == <T: NSLayoutYAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(equalTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func == (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension>) -> NSLayoutConstraint { if let anchor = rhs.anchor { return activate(constraint: lhs.constraint(equalTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } else { return activate(constraint: lhs.constraint(equalToConstant: rhs.constant), withPriority: rhs.priority) } } @discardableResult public func == (lhs: EdgeAnchors, rhs: EdgeAnchors) -> EdgeGroup { return lhs.activate(constraintsEqualToEdges: rhs) } @discardableResult public func == (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors>) -> EdgeGroup { return lhs.activate(constraintsEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func == <T: LayoutAxisType, U: LayoutAxisType>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> AxisGroup { return lhs.activate(constraintsEqualToEdges: rhs) } @discardableResult public func == <T: LayoutAxisType, U: LayoutAxisType>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>>) -> AxisGroup { return lhs.activate(constraintsEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } // MARK: - Inequality Constraints @discardableResult public func <= (lhs: NSLayoutDimension, rhs: CGFloat) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualToConstant: rhs)) } @discardableResult public func <= <T: NSLayoutDimension>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs)) } @discardableResult public func <= <T: NSLayoutXAxisAnchor>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs)) } @discardableResult public func <= <T: NSLayoutYAxisAnchor>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs)) } @discardableResult public func <= <T: NSLayoutDimension>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func <= <T: NSLayoutXAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func <= <T: NSLayoutYAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(lessThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func <= (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension>) -> NSLayoutConstraint { if let anchor = rhs.anchor { return activate(constraint: lhs.constraint(lessThanOrEqualTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } else { return activate(constraint: lhs.constraint(lessThanOrEqualToConstant: rhs.constant), withPriority: rhs.priority) } } @discardableResult public func <= (lhs: EdgeAnchors, rhs: EdgeAnchors) -> EdgeGroup { return lhs.activate(constraintsLessThanOrEqualToEdges: rhs) } @discardableResult public func <= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors>) -> EdgeGroup { return lhs.activate(constraintsLessThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func <= <T: LayoutAxisType, U: LayoutAxisType>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> AxisGroup { return lhs.activate(constraintsLessThanOrEqualToEdges: rhs) } @discardableResult public func <= <T: LayoutAxisType, U: LayoutAxisType>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>>) -> AxisGroup { return lhs.activate(constraintsLessThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func >= (lhs: NSLayoutDimension, rhs: CGFloat) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualToConstant: rhs)) } @discardableResult public func >=<T: NSLayoutDimension>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs)) } @discardableResult public func >=<T: NSLayoutXAxisAnchor>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs)) } @discardableResult public func >=<T: NSLayoutYAxisAnchor>(lhs: T, rhs: T) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs)) } @discardableResult public func >= <T: NSLayoutDimension>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func >= <T: NSLayoutXAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func >= <T: NSLayoutYAxisAnchor>(lhs: T, rhs: LayoutExpression<T>) -> NSLayoutConstraint { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority) } @discardableResult public func >= (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension>) -> NSLayoutConstraint { if let anchor = rhs.anchor { return activate(constraint: lhs.constraint(greaterThanOrEqualTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority) } else { return activate(constraint: lhs.constraint(greaterThanOrEqualToConstant: rhs.constant), withPriority: rhs.priority) } } @discardableResult public func >= (lhs: EdgeAnchors, rhs: EdgeAnchors) -> EdgeGroup { return lhs.activate(constraintsGreaterThanOrEqualToEdges: rhs) } @discardableResult public func >= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors>) -> EdgeGroup { return lhs.activate(constraintsGreaterThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } @discardableResult public func >= <T: LayoutAxisType, U: LayoutAxisType>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> AxisGroup { return lhs.activate(constraintsGreaterThanOrEqualToEdges: rhs) } @discardableResult public func >= <T: LayoutAxisType, U: LayoutAxisType>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>>) -> AxisGroup { return lhs.activate(constraintsGreaterThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority) } // MARK: - Priority precedencegroup PriorityPrecedence { associativity: none higherThan: ComparisonPrecedence } infix operator ~: PriorityPrecedence @discardableResult public func ~ (lhs: CGFloat, rhs: UILayoutPriority) -> LayoutExpression<NSLayoutDimension> { return LayoutExpression(constant: lhs, priority: rhs) } @discardableResult public func ~ <T: LayoutAnchorType>(lhs: T, rhs: UILayoutPriority) -> LayoutExpression<T> { return LayoutExpression(anchor: lhs, priority: rhs) } @discardableResult public func ~ <T: LayoutAnchorType>(lhs: LayoutExpression<T>, rhs: UILayoutPriority) -> LayoutExpression<T> { var expr = lhs expr.priority = rhs return expr } // MARK: Layout Expressions @discardableResult public func * (lhs: NSLayoutDimension, rhs: CGFloat) -> LayoutExpression<NSLayoutDimension> { return LayoutExpression(anchor: lhs, multiplier: rhs) } @discardableResult public func * (lhs: CGFloat, rhs: NSLayoutDimension) -> LayoutExpression<NSLayoutDimension> { return LayoutExpression(anchor: rhs, multiplier: lhs) } @discardableResult public func * (lhs: LayoutExpression<NSLayoutDimension>, rhs: CGFloat) -> LayoutExpression<NSLayoutDimension> { var expr = lhs expr.multiplier *= rhs return expr } @discardableResult public func * (lhs: CGFloat, rhs: LayoutExpression<NSLayoutDimension>) -> LayoutExpression<NSLayoutDimension> { var expr = rhs expr.multiplier *= lhs return expr } @discardableResult public func / (lhs: NSLayoutDimension, rhs: CGFloat) -> LayoutExpression<NSLayoutDimension> { return LayoutExpression(anchor: lhs, multiplier: 1.0 / rhs) } @discardableResult public func / (lhs: LayoutExpression<NSLayoutDimension>, rhs: CGFloat) -> LayoutExpression<NSLayoutDimension> { var expr = lhs expr.multiplier /= rhs return expr } @discardableResult public func + <T: LayoutAnchorType>(lhs: T, rhs: CGFloat) -> LayoutExpression<T> { return LayoutExpression(anchor: lhs, constant: rhs) } @discardableResult public func + <T: LayoutAnchorType>(lhs: CGFloat, rhs: T) -> LayoutExpression<T> { return LayoutExpression(anchor: rhs, constant: lhs) } @discardableResult public func + <T: LayoutAnchorType>(lhs: LayoutExpression<T>, rhs: CGFloat) -> LayoutExpression<T> { var expr = lhs expr.constant += rhs return expr } @discardableResult public func + <T: LayoutAnchorType>(lhs: CGFloat, rhs: LayoutExpression<T>) -> LayoutExpression<T> { var expr = rhs expr.constant += lhs return expr } @discardableResult public func - <T: LayoutAnchorType>(lhs: T, rhs: CGFloat) -> LayoutExpression<T> { return LayoutExpression(anchor: lhs, constant: -rhs) } @discardableResult public func - <T: LayoutAnchorType>(lhs: CGFloat, rhs: T) -> LayoutExpression<T> { return LayoutExpression(anchor: rhs, constant: -lhs) } @discardableResult public func - <T: LayoutAnchorType>(lhs: LayoutExpression<T>, rhs: CGFloat) -> LayoutExpression<T> { var expr = lhs expr.constant -= rhs return expr } @discardableResult public func - <T: LayoutAnchorType>(lhs: CGFloat, rhs: LayoutExpression<T>) -> LayoutExpression<T> { var expr = rhs expr.constant -= lhs return expr } #endif public struct LayoutExpression<T : LayoutAnchorType> { var anchor: T? var constant: CGFloat var multiplier: CGFloat var priority: UILayoutPriority init(anchor: T? = nil, constant: CGFloat = 0.0, multiplier: CGFloat = 1.0, priority: UILayoutPriority = UILayoutPriorityRequired) { self.anchor = anchor self.constant = constant self.multiplier = multiplier self.priority = priority } } // MARK: - EdgeAnchorsProvider public protocol AnchorGroupProvider { var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { get } var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { get } var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { get } } extension AnchorGroupProvider { public var edgeAnchors: EdgeAnchors { return EdgeAnchors(horizontal: horizontalAnchors, vertical: verticalAnchors) } } extension UIView: AnchorGroupProvider { public var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { return AnchorPair(first: leadingAnchor, second: trailingAnchor) } public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: topAnchor, second: bottomAnchor) } public var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: centerXAnchor, second: centerYAnchor) } } extension UIViewController: AnchorGroupProvider { public var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { return AnchorPair(first: view.leadingAnchor, second: view.trailingAnchor) } public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: topLayoutGuide.bottomAnchor, second: bottomLayoutGuide.topAnchor) } public var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: view.centerXAnchor, second: view.centerYAnchor) } } extension UILayoutGuide: AnchorGroupProvider { public var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> { return AnchorPair(first: leadingAnchor, second: trailingAnchor) } public var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: topAnchor, second: bottomAnchor) } public var centerAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutYAxisAnchor> { return AnchorPair(first: centerXAnchor, second: centerYAnchor) } } // MARK: - AnchorGroup public struct AnchorPair<T: LayoutAxisType, U: LayoutAxisType>: LayoutAnchorType { private var first: T private var second: U init(first: T, second: U) { self.first = first self.second = second } public func activate(constraintsEqualToEdges anchor: AnchorPair<T, U>?, constant c: CGFloat = 0.0, priority: UILayoutPriority = UILayoutPriorityRequired) -> AxisGroup { let builder = ConstraintBuilder(horizontal: ==, vertical: ==) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } public func activate(constraintsLessThanOrEqualToEdges anchor: AnchorPair<T, U>?, constant c: CGFloat = 0.0, priority: UILayoutPriority = UILayoutPriorityRequired) -> AxisGroup { let builder = ConstraintBuilder(leading: <=, top: <=, trailing: >=, bottom: >=, centerX: <=, centerY: <=) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } public func activate(constraintsGreaterThanOrEqualToEdges anchor: AnchorPair<T, U>?, constant c: CGFloat = 0.0, priority: UILayoutPriority = UILayoutPriorityRequired) -> AxisGroup { let builder = ConstraintBuilder(leading: >=, top: >=, trailing: <=, bottom: <=, centerX: >=, centerY: >=) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } func constraints(forAnchors anchors: AnchorPair<T, U>?, constant c: CGFloat, priority: UILayoutPriority, builder: ConstraintBuilder) -> AxisGroup { guard let anchors = anchors else { preconditionFailure("Encountered nil edge anchors, indicating internal inconsistency of this API.") } switch (first, anchors.first, second, anchors.second) { // Leading, trailing case let (firstX as NSLayoutXAxisAnchor, otherFirstX as NSLayoutXAxisAnchor, secondX as NSLayoutXAxisAnchor, otherSecondX as NSLayoutXAxisAnchor): return AxisGroup(first: builder.leadingBuilder(firstX, (otherFirstX + c) ~ priority), second: builder.trailingBuilder(secondX, (otherSecondX - c) ~ priority)) //Top, bottom case let (firstY as NSLayoutYAxisAnchor, otherFirstY as NSLayoutYAxisAnchor, secondY as NSLayoutYAxisAnchor, otherSecondY as NSLayoutYAxisAnchor): return AxisGroup(first: builder.topBuilder(firstY, (otherFirstY + c) ~ priority), second: builder.bottomBuilder(secondY, (otherSecondY - c) ~ priority)) //CenterX, centerY case let (firstX as NSLayoutXAxisAnchor, otherFirstX as NSLayoutXAxisAnchor, firstY as NSLayoutYAxisAnchor, otherFirstY as NSLayoutYAxisAnchor): return AxisGroup(first: builder.leadingBuilder(firstX, (otherFirstX + c) ~ priority), second: builder.topBuilder(firstY, (otherFirstY - c) ~ priority)) default: preconditionFailure("Layout axes of constrained anchors must match.") } } } public struct EdgeAnchors: LayoutAnchorType { var horizontalAnchors: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor> var verticalAnchors: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor> init(horizontal: AnchorPair<NSLayoutXAxisAnchor, NSLayoutXAxisAnchor>, vertical: AnchorPair<NSLayoutYAxisAnchor, NSLayoutYAxisAnchor>) { self.horizontalAnchors = horizontal self.verticalAnchors = vertical } public func activate(constraintsEqualToEdges anchor: EdgeAnchors?, constant c: CGFloat = 0.0, priority: UILayoutPriority = UILayoutPriorityRequired) -> EdgeGroup { let builder = ConstraintBuilder(horizontal: ==, vertical: ==) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } public func activate(constraintsLessThanOrEqualToEdges anchor: EdgeAnchors?, constant c: CGFloat = 0.0, priority: UILayoutPriority = UILayoutPriorityRequired) -> EdgeGroup { let builder = ConstraintBuilder(leading: <=, top: <=, trailing: >=, bottom: >=, centerX: <=, centerY: <=) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } public func activate(constraintsGreaterThanOrEqualToEdges anchor: EdgeAnchors?, constant c: CGFloat = 0.0, priority: UILayoutPriority = UILayoutPriorityRequired) -> EdgeGroup { let builder = ConstraintBuilder(leading: >=, top: >=, trailing: <=, bottom: <=, centerX: >=, centerY: >=) return constraints(forAnchors: anchor, constant: c, priority: priority, builder: builder) } func constraints(forAnchors anchors: EdgeAnchors?, constant c: CGFloat, priority: UILayoutPriority, builder: ConstraintBuilder) -> EdgeGroup { guard let anchors = anchors else { preconditionFailure("Encountered nil edge anchors, indicating internal inconsistency of this API.") } let horizontalConstraints = horizontalAnchors.constraints(forAnchors: anchors.horizontalAnchors, constant: c, priority: priority, builder: builder) let verticalConstraints = verticalAnchors.constraints(forAnchors: anchors.verticalAnchors, constant: c, priority: priority, builder: builder) return EdgeGroup(top: verticalConstraints.first, leading: horizontalConstraints.first, bottom: verticalConstraints.second, trailing: verticalConstraints.second) } } // MARK: - ConstraintGroup public struct EdgeGroup { public var top: NSLayoutConstraint public var leading: NSLayoutConstraint public var bottom: NSLayoutConstraint public var trailing: NSLayoutConstraint public var horizontal: [NSLayoutConstraint] { return [leading, trailing].flatMap { $0 } } public var vertical: [NSLayoutConstraint] { return [top, bottom].flatMap { $0 } } public var all: [NSLayoutConstraint] { return [top, leading, bottom, trailing].flatMap { $0 } } } public struct AxisGroup { public var first: NSLayoutConstraint public var second: NSLayoutConstraint } // MARK: - Constraint Builders struct ConstraintBuilder { typealias Horizontal = (NSLayoutXAxisAnchor, LayoutExpression<NSLayoutXAxisAnchor>) -> NSLayoutConstraint typealias Vertical = (NSLayoutYAxisAnchor, LayoutExpression<NSLayoutYAxisAnchor>) -> NSLayoutConstraint var topBuilder: Vertical var leadingBuilder: Horizontal var bottomBuilder: Vertical var trailingBuilder: Horizontal var centerYBuilder: Vertical var centerXBuilder: Horizontal #if swift(>=3.0) init(horizontal: @escaping Horizontal, vertical: @escaping Vertical) { topBuilder = vertical leadingBuilder = horizontal bottomBuilder = vertical trailingBuilder = horizontal centerYBuilder = vertical centerXBuilder = horizontal } init(leading: @escaping Horizontal, top: @escaping Vertical, trailing: @escaping Horizontal, bottom: @escaping Vertical, centerX: @escaping Horizontal, centerY: @escaping Vertical) { leadingBuilder = leading topBuilder = top trailingBuilder = trailing bottomBuilder = bottom centerYBuilder = centerY centerXBuilder = centerX } #else init(horizontal: Horizontal, vertical: Vertical) { topBuilder = vertical leadingBuilder = horizontal bottomBuilder = vertical trailingBuilder = horizontal centerYBuilder = vertical centerXBuilder = horizontal } init(leading: Horizontal, top: Vertical, trailing: Horizontal, bottom: Vertical, centerX: Horizontal, centerY: Vertical) { leadingBuilder = leading topBuilder = top trailingBuilder = trailing bottomBuilder = bottom centerYBuilder = centerY centerXBuilder = centerX } #endif } // MARK: - Constraint Activation func activate(constraint theConstraint: NSLayoutConstraint, withPriority priority: UILayoutPriority = UILayoutPriorityRequired) -> NSLayoutConstraint { // Only disable autoresizing constraints on the LHS item, which is the one definitely intended to be governed by Auto Layout if let first = theConstraint.firstItem as? UIView { first.translatesAutoresizingMaskIntoConstraints = false } theConstraint.priority = priority theConstraint.isActive = true return theConstraint }
42.908289
185
0.732459
e26f088475c1fd1dbffea4900742968ab0e28017
190
// // APIs.swift // Example // // Created by 聂高涛 on 2022/3/2. // import UIKit struct APIs { static let list = "https://itunes.apple.com/search?entity=software&limit=50&term=chat" }
14.615385
90
0.652632
f99675c2e9dc846f247f8c1d2423b18a73c9be93
4,956
/** * Copyright 2018 IBM Corp. 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 XCTest @testable import CardKit class CardDescriptorTests: 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 testDescriptorIdentity() { let noActionA = CKTestCards.Action.NoAction let noActionB = CKTestCards.Action.NoAction XCTAssertTrue(noActionA == noActionB) XCTAssertFalse(noActionA != noActionB) } func testDescriptorEquality() { let a1 = ActionCardDescriptor(name: "A", subpath: nil, inputs: nil, tokens: nil, yields: nil, yieldDescription: nil, ends: true, endsDescription: nil, assetCatalog: CardAssetCatalog()) let a2 = ActionCardDescriptor(name: "A", subpath: nil, inputs: nil, tokens: nil, yields: nil, yieldDescription: nil, ends: true, endsDescription: nil, assetCatalog: CardAssetCatalog()) let d1 = DeckCardDescriptor(name: "A", subpath: nil, assetCatalog: CardAssetCatalog()) let d2 = DeckCardDescriptor(name: "A", subpath: nil, assetCatalog: CardAssetCatalog()) let h1 = InputCardDescriptor(name: "A", subpath: nil, inputType: Double.self, inputDescription: "", assetCatalog: CardAssetCatalog()) let h2 = InputCardDescriptor(name: "A", subpath: nil, inputType: Double.self, inputDescription: "", assetCatalog: CardAssetCatalog()) let i1 = HandCardDescriptor(name: "A", subpath: nil, handCardType: .branch, assetCatalog: CardAssetCatalog()) let i2 = HandCardDescriptor(name: "A", subpath: nil, handCardType: .branch, assetCatalog: CardAssetCatalog()) let t1 = TokenCardDescriptor(name: "A", subpath: nil, isConsumed: false, assetCatalog: CardAssetCatalog()) let t2 = TokenCardDescriptor(name: "A", subpath: nil, isConsumed: false, assetCatalog: CardAssetCatalog()) XCTAssertTrue(a1 == a2) XCTAssertTrue(d1 == d2) XCTAssertTrue(h1 == h2) XCTAssertTrue(i1 == i2) XCTAssertTrue(t1 == t2) } func testDescriptorPathInequality() { let a1 = ActionCardDescriptor(name: "A", subpath: nil, inputs: nil, tokens: nil, yields: nil, yieldDescription: nil, ends: true, endsDescription: nil, assetCatalog: CardAssetCatalog()) let a2 = ActionCardDescriptor(name: "A", subpath: "A", inputs: nil, tokens: nil, yields: nil, yieldDescription: nil, ends: true, endsDescription: nil, assetCatalog: CardAssetCatalog()) let d1 = DeckCardDescriptor(name: "A", subpath: nil, assetCatalog: CardAssetCatalog()) let d2 = DeckCardDescriptor(name: "A", subpath: "A", assetCatalog: CardAssetCatalog()) let h1 = InputCardDescriptor(name: "A", subpath: nil, inputType: Double.self, inputDescription: "", assetCatalog: CardAssetCatalog()) let h2 = InputCardDescriptor(name: "A", subpath: "A", inputType: Double.self, inputDescription: "", assetCatalog: CardAssetCatalog()) let i1 = HandCardDescriptor(name: "A", subpath: nil, handCardType: .branch, assetCatalog: CardAssetCatalog()) let i2 = HandCardDescriptor(name: "A", subpath: "A", handCardType: .branch, assetCatalog: CardAssetCatalog()) let t1 = TokenCardDescriptor(name: "A", subpath: nil, isConsumed: false, assetCatalog: CardAssetCatalog()) let t2 = TokenCardDescriptor(name: "A", subpath: "A", isConsumed: false, assetCatalog: CardAssetCatalog()) XCTAssertTrue(a1 != a2) XCTAssertTrue(d1 != d2) XCTAssertTrue(h1 != h2) XCTAssertTrue(i1 != i2) XCTAssertTrue(t1 != t2) } func testDescriptorSerialization() { let noAction = CKTestCards.Action.NoAction let encoder = JSONEncoder() let decoder = JSONDecoder() do { let data = try encoder.encode(noAction) let decodedNoAction: ActionCardDescriptor = try decoder.decode(ActionCardDescriptor.self, from: data) XCTAssertTrue(noAction == decodedNoAction) } catch let error { XCTFail("error: \(error)") } } }
49.069307
192
0.668079
e9503e8b4b5e8699bda86ea00b7248edd262b112
3,244
import Foundation typealias PXOfflineMethodsCellData = (title: PXText?, subtitle: PXText?, imageUrl: String?, isSelected: Bool) final class PXOfflineMethodsCell: UITableViewCell { static let identifier = "PXOfflineMethodsCell" // Selection Indicator let INDICATOR_IMAGE_SIZE: CGFloat = 16.0 // Icon let ICON_SIZE: CGFloat = 48.0 func render(data: PXOfflineMethodsCellData) { contentView.removeAllSubviews() selectionStyle = .none backgroundColor = .white let indicatorImage = ResourceManager.shared.getImage(data.isSelected ? "indicator_selected" : "indicator_unselected") let indicatorImageView = UIImageView(image: indicatorImage) indicatorImageView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(indicatorImageView) NSLayoutConstraint.activate([ indicatorImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: PXLayout.S_MARGIN), indicatorImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor), indicatorImageView.heightAnchor.constraint(equalToConstant: INDICATOR_IMAGE_SIZE), indicatorImageView.widthAnchor.constraint(equalToConstant: INDICATOR_IMAGE_SIZE) ]) // Image var image: UIImage? if let imageURL = data.imageUrl, imageURL.isNotEmpty { image = PXUIImage(url: imageURL) } else { image = ResourceManager.shared.getImage("PaymentGeneric") } let iconImageView = PXUIImageView(image: image, size: ICON_SIZE, shouldAddInsets: true) contentView.addSubview(iconImageView) NSLayoutConstraint.activate([ iconImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 44), iconImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor) ]) let labelsContainerView = UIStackView() labelsContainerView.translatesAutoresizingMaskIntoConstraints = false labelsContainerView.axis = .vertical if let title = data.title { let titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.attributedText = title.getAttributedString(fontSize: PXLayout.XS_FONT) labelsContainerView.addArrangedSubview(titleLabel) } if let subtitle = data.subtitle { let subtitleLabel = UILabel() subtitleLabel.translatesAutoresizingMaskIntoConstraints = false subtitleLabel.attributedText = subtitle.getAttributedString(fontSize: PXLayout.XXS_FONT) subtitleLabel.numberOfLines = 2 labelsContainerView.addArrangedSubview(subtitleLabel) } contentView.addSubview(labelsContainerView) NSLayoutConstraint.activate([ labelsContainerView.leadingAnchor.constraint(equalTo: iconImageView.trailingAnchor, constant: PXLayout.XS_MARGIN), labelsContainerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -PXLayout.XXS_MARGIN), labelsContainerView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor) ]) } }
44.438356
127
0.715783
0af2f1a8fb74f2acfade500425b4c0ab47ca5208
1,470
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct TestFailoverCleanupInputPropertiesData : TestFailoverCleanupInputPropertiesProtocol { public var comments: String? enum CodingKeys: String, CodingKey {case comments = "comments" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.comments) { self.comments = try container.decode(String?.self, forKey: .comments) } if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if self.comments != nil {try container.encode(self.comments, forKey: .comments)} } } extension DataFactory { public static func createTestFailoverCleanupInputPropertiesProtocol() -> TestFailoverCleanupInputPropertiesProtocol { return TestFailoverCleanupInputPropertiesData() } }
36.75
120
0.721769
db8ff3b9bdbaa9d3601dda1296ac867d5df584f4
1,767
// // Movie.swift // MoviesDB // // Created by Dmitry Kocherovets on 25.11.2019. // Copyright © 2019 Dmitry Kocherovets. All rights reserved. // import Foundation struct ServerModels { } extension ServerModels { struct Movie: Codable, Equatable { let posterPath: String? let adult: Bool let overview: String let releaseDate: String let genreIds: [Int] let id: Int let originalTitle: String let originalLanguage: String let title: String let backdropPath: String? let popularity: Double let voteCount: Int let video: Bool let voteAverage: Double } struct NowPlaying: Codable, Equatable { let page: Int let totalPages: Int let results: [Movie] } struct Upcoming: Codable, Equatable { let page: Int let totalPages: Int let results: [Movie] } struct Trending: Codable, Equatable { let page: Int let totalPages: Int let results: [Movie] } struct Popular: Codable, Equatable { let page: Int let totalPages: Int let results: [Movie] } } extension ServerModels.Movie { var votePercentage: Int { Int(voteAverage * 10) } } struct ImageService { enum Size: String { case small = "https://image.tmdb.org/t/p/w154" case medium = "https://image.tmdb.org/t/p/w500" case cast = "https://image.tmdb.org/t/p/w185" case original = "https://image.tmdb.org/t/p/original" func url(poster: String?) -> URL? { guard let poster = poster else { return nil } return URL(string: rawValue + poster) } } }
20.788235
61
0.576684
391c040f0c128397b960e0812b4d5a01d78ab016
275
// // SSRResponse.swift // SSRSwift // // Created by Don.shen on 2019/6/9. // Copyright © 2019 Don.shen. All rights reserved. // import Foundation public struct SSRResponse { public var code: Int = 0 public var message : String = "" public var data: Any? }
17.1875
51
0.650909
2f1dcddde30594ec4dd440a6af608d0c1f4962e1
505
// // DeviceCollection.swift // // // Created by Oscar Byström Ericsson on 2021-04-14. // enum Collection: String, CaseIterable, Argument { static let `default`: Self = .all case all case extra case xcode var description: String { switch self { case .all: return "Selects all devices available." case .xcode: return "Selects all devices listed by Xcode." case .extra: return "Selects all devices not listed by Xcode." } } }
21.956522
70
0.613861
b9c22369b6bb2dd6f1973a48c1d431367b456a8d
1,392
// // WalletsRealmFactory.swift // DataLayer // // Created by rprokofev on 12.08.2019. // Copyright © 2019 Waves Platform. All rights reserved. // import Foundation import RealmSwift import WavesSDK import WavesSDKExtensions import DomainLayer fileprivate enum SchemaVersions: UInt64 { case version_2_5 = 7 static let currentVersion: SchemaVersions = .version_2_5 } enum WalletsRealmFactory { static func walletsConfig(scheme: String) -> Realm.Configuration? { var config = Realm.Configuration() config.objectTypes = [WalletEncryption.self, WalletItem.self] config.schemaVersion = UInt64(SchemaVersions.currentVersion.rawValue) guard let fileURL = config.fileURL else { SweetLogger.error("File Realm is nil") return nil } config.fileURL = fileURL .deletingLastPathComponent() .appendingPathComponent("wallets_\(scheme).realm") config.migrationBlock = { migration, oldSchemaVersion in migration.enumerateObjects(ofType: WalletItem.className()) { _ , newObject in newObject?[WalletItem.isNeedShowWalletCleanBannerKey] = true } SweetLogger.debug("Migration!!! \(oldSchemaVersion)") } return config } }
27.294118
89
0.630029
466067e734dc14c117b7442e5e7c23cf329afb43
763
// // UIImage+Utility.swift // ArtistFinder // // Created by Abdiel Soto. // Copyright © 2018 iOSDevsMx. All rights reserved. // // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Import import UIKit // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Implementation extension UIImage { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Utility static func image(fromLayer layer: CALayer) -> UIImage { UIGraphicsBeginImageContext(layer.frame.size) layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } }
24.612903
75
0.477064
215a692e394c2796ee94465a680eee184c298306
5,997
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. @_exported import AWSSDKSwiftCore /* Client object for interacting with AWS AutoScalingPlans service. AWS Auto Scaling Use AWS Auto Scaling to quickly discover all the scalable AWS resources for your application and configure dynamic scaling and predictive scaling for your resources using scaling plans. Use this service in conjunction with the Amazon EC2 Auto Scaling, Application Auto Scaling, Amazon CloudWatch, and AWS CloudFormation services. Currently, predictive scaling is only available for Amazon EC2 Auto Scaling groups. For more information about AWS Auto Scaling, including information about granting IAM users required permissions for AWS Auto Scaling actions, see the AWS Auto Scaling User Guide. */ public struct AutoScalingPlans { // MARK: Member variables public let client: AWSClient public let serviceConfig: AWSServiceConfig // MARK: Initialization /// Initialize the AutoScalingPlans client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: AWSSDKSwiftCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil ) { self.client = client self.serviceConfig = AWSServiceConfig( region: region, partition: region?.partition ?? partition, amzTarget: "AnyScaleScalingPlannerFrontendService", service: "autoscaling-plans", serviceProtocol: .json(version: "1.1"), apiVersion: "2018-01-06", endpoint: endpoint, possibleErrorTypes: [AutoScalingPlansErrorType.self], timeout: timeout ) } // MARK: API Calls /// Creates a scaling plan. public func createScalingPlan(_ input: CreateScalingPlanRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<CreateScalingPlanResponse> { return self.client.execute(operation: "CreateScalingPlan", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Deletes the specified scaling plan. Deleting a scaling plan deletes the underlying ScalingInstruction for all of the scalable resources that are covered by the plan. If the plan has launched resources or has scaling activities in progress, you must delete those resources separately. public func deleteScalingPlan(_ input: DeleteScalingPlanRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DeleteScalingPlanResponse> { return self.client.execute(operation: "DeleteScalingPlan", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Describes the scalable resources in the specified scaling plan. public func describeScalingPlanResources(_ input: DescribeScalingPlanResourcesRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeScalingPlanResourcesResponse> { return self.client.execute(operation: "DescribeScalingPlanResources", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Describes one or more of your scaling plans. public func describeScalingPlans(_ input: DescribeScalingPlansRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<DescribeScalingPlansResponse> { return self.client.execute(operation: "DescribeScalingPlans", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Retrieves the forecast data for a scalable resource. Capacity forecasts are represented as predicted values, or data points, that are calculated using historical data points from a specified CloudWatch load metric. Data points are available for up to 56 days. public func getScalingPlanResourceForecastData(_ input: GetScalingPlanResourceForecastDataRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<GetScalingPlanResourceForecastDataResponse> { return self.client.execute(operation: "GetScalingPlanResourceForecastData", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } /// Updates the specified scaling plan. You cannot update a scaling plan if it is in the process of being created, updated, or deleted. public func updateScalingPlan(_ input: UpdateScalingPlanRequest, on eventLoop: EventLoop? = nil, logger: Logger = AWSClient.loggingDisabled) -> EventLoopFuture<UpdateScalingPlanResponse> { return self.client.execute(operation: "UpdateScalingPlan", path: "/", httpMethod: .POST, serviceConfig: serviceConfig, input: input, on: eventLoop, logger: logger) } }
64.483871
611
0.721361
f4bbf4da5c54f0de8bb72dac4d73450992524946
2,683
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Dispatch public protocol MessageType: Codable {} /// `RequestType` with no associated type or same-type requirements. Most users should prefer /// `RequestType`. public protocol _RequestType: MessageType { /// The name of the request. static var method: String { get } /// *Implementation detail*. Dispatch `self` to the given handler and reply on `connection`. /// Only needs to be declared as a protocol requirement of `_RequestType` so we can call the implementation on `RequestType` from the underscored type. func _handle( _ handler: MessageHandler, id: RequestID, connection: Connection, reply: @escaping (LSPResult<ResponseType>, RequestID) -> Void ) } /// A request, which must have a unique `method` name as well as an associated response type. public protocol RequestType: _RequestType { /// The type of of the response to this request. associatedtype Response: ResponseType } /// A notification, which must have a unique `method` name. public protocol NotificationType: MessageType { /// The name of the request. static var method: String { get } } /// A response. public protocol ResponseType: MessageType {} extension RequestType { public func _handle( _ handler: MessageHandler, id: RequestID, connection: Connection, reply: @escaping (LSPResult<ResponseType>, RequestID) -> Void ) { handler.handle(self, id: id, from: ObjectIdentifier(connection)) { response in reply(response.map({ $0 as ResponseType }), id) } } } extension NotificationType { public func _handle(_ handler: MessageHandler, connection: Connection) { handler.handle(self, from: ObjectIdentifier(connection)) } } /// A `textDocument/*` notification, which takes a text document identifier /// indicating which document it operates in or on. public protocol TextDocumentNotification: NotificationType { var textDocument: TextDocumentIdentifier { get } } /// A `textDocument/*` request, which takes a text document identifier /// indicating which document it operates in or on. public protocol TextDocumentRequest: RequestType { var textDocument: TextDocumentIdentifier { get } }
33.123457
153
0.69139
d5adac7024172747cfb11f17a0749d8c4d676338
7,167
import Foundation import SwiftSemantics import struct SwiftSemantics.Protocol public final class Interface { public let imports: [Import] public let symbols: [Symbol] public required init(imports: [Import], symbols: [Symbol]) { self.imports = imports self.symbols = symbols.filter { $0.isPublic } self.symbolsGroupedByIdentifier = Dictionary(grouping: symbols, by: { $0.id }) self.symbolsGroupedByQualifiedName = Dictionary(grouping: symbols, by: { $0.id.description }) self.topLevelSymbols = symbols.filter { $0.api is Type || $0.id.pathComponents.isEmpty } self.relationships = { let symbols = symbols.filter { $0.isPublic } let extensionsByExtendedType: [String: [Extension]] = Dictionary(grouping: symbols.flatMap { $0.context.compactMap { $0 as? Extension } }, by: { $0.extendedType }) var relationships: Set<Relationship> = [] for symbol in symbols { let lastDeclarationScope = symbol.context.last(where: { $0 is Extension || $0 is Symbol }) if let container = lastDeclarationScope as? Symbol { let predicate: Relationship.Predicate switch container.api { case is Protocol: if symbol.api.modifiers.contains(where: { $0.name == "optional" }) { predicate = .optionalRequirementOf } else { predicate = .requirementOf } default: predicate = .memberOf } relationships.insert(Relationship(subject: symbol, predicate: predicate, object: container)) } if let `extension` = lastDeclarationScope as? Extension { if let extended = symbols.first(where: { $0.api is Type && $0.id.matches(`extension`.extendedType) }) { let predicate: Relationship.Predicate switch extended.api { case is Protocol: predicate = .defaultImplementationOf default: predicate = .memberOf } relationships.insert(Relationship(subject: symbol, predicate: predicate, object: extended)) } } if let type = symbol.api as? Type { var inheritedTypeNames: Set<String> = [] inheritedTypeNames.formUnion(type.inheritance.flatMap { $0.split(separator: "&").map { $0.trimmingCharacters(in: .whitespaces) } }) for `extension` in extensionsByExtendedType[symbol.id.description] ?? [] { inheritedTypeNames.formUnion(`extension`.inheritance) } inheritedTypeNames = Set(inheritedTypeNames.flatMap { $0.split(separator: "&").map { $0.trimmingCharacters(in: .whitespaces) } }) for name in inheritedTypeNames { let inheritedTypes = symbols.filter({ ($0.api is Class || $0.api is Protocol) && $0.id.description == name }) if inheritedTypes.isEmpty { let inherited = Symbol(api: Unknown(name: name), context: [], declaration: [], documentation: nil, sourceLocation: nil) relationships.insert(Relationship(subject: symbol, predicate: .conformsTo, object: inherited)) } else { for inherited in inheritedTypes { let predicate: Relationship.Predicate if symbol.api is Class, inherited.api is Class { predicate = .inheritsFrom } else { predicate = .conformsTo } relationships.insert(Relationship(subject: symbol, predicate: predicate, object: inherited)) } } } } } return Array(relationships) }() self.relationshipsBySubject = Dictionary(grouping: relationships, by: { $0.subject.id }) self.relationshipsByObject = Dictionary(grouping: relationships, by: { $0.object.id }) } // MARK: - public let symbolsGroupedByIdentifier: [Symbol.ID: [Symbol]] public let symbolsGroupedByQualifiedName: [String: [Symbol]] public let topLevelSymbols: [Symbol] public var baseClasses: [Symbol] { symbols.filter { $0.api is Class && typesInherited(by: $0).isEmpty } } public var classHierarchies: [Symbol: Set<Symbol>] { var classClusters: [Symbol: Set<Symbol>] = [:] for baseClass in baseClasses { var superclasses = Set(CollectionOfOne(baseClass)) while !superclasses.isEmpty { let subclasses = Set(superclasses.flatMap { typesInheriting(from: $0) }.filter { $0.isPublic }) defer { superclasses = subclasses } classClusters[baseClass, default: []].formUnion(subclasses) } } return classClusters } public let relationships: [Relationship] public let relationshipsBySubject: [Symbol.ID: [Relationship]] public let relationshipsByObject: [Symbol.ID: [Relationship]] // MARK: - public func members(of symbol: Symbol) -> [Symbol] { return relationshipsByObject[symbol.id]?.filter { $0.predicate == .memberOf }.map { $0.subject }.sorted() ?? [] } public func requirements(of symbol: Symbol) -> [Symbol] { return relationshipsByObject[symbol.id]?.filter { $0.predicate == .requirementOf }.map { $0.subject }.sorted() ?? [] } public func optionalRequirements(of symbol: Symbol) -> [Symbol] { return relationshipsByObject[symbol.id]?.filter { $0.predicate == .optionalRequirementOf }.map { $0.subject }.sorted() ?? [] } public func typesInherited(by symbol: Symbol) -> [Symbol] { return relationshipsBySubject[symbol.id]?.filter { $0.predicate == .inheritsFrom }.map { $0.object }.sorted() ?? [] } public func typesInheriting(from symbol: Symbol) -> [Symbol] { return relationshipsByObject[symbol.id]?.filter { $0.predicate == .inheritsFrom }.map { $0.subject }.sorted() ?? [] } public func typesConformed(by symbol: Symbol) -> [Symbol] { return relationshipsBySubject[symbol.id]?.filter { $0.predicate == .conformsTo }.map { $0.object }.sorted() ?? [] } public func typesConforming(to symbol: Symbol) -> [Symbol] { return relationshipsByObject[symbol.id]?.filter { $0.predicate == .conformsTo }.map { $0.subject }.sorted() ?? [] } public func conditionalCounterparts(of symbol: Symbol) -> [Symbol] { return symbolsGroupedByIdentifier[symbol.id]?.filter { $0 != symbol }.sorted() ?? [] } }
44.79375
175
0.560625
615693dcc395b847b6161812181ad1289805d212
3,282
// // SBTerminal.swift // ErlangInstaller // // Created by Juan Facorro on 1/19/16. // Copyright © 2016 Erlang Solutions. All rights reserved. // import ScriptingBridge // MARK: SBTerminalApplication @objc public protocol SBTerminalApplication: SBApplicationProtocol { @objc optional func windows() -> SBElementArray @objc optional var name: String { get } @objc optional var version: String { get } @objc optional var frontmost: Bool { get } @objc optional func doScript(_ script: String, in: AnyObject?) -> SBTerminalTab } extension SBApplication: SBTerminalApplication {} // MARK: SBTerminalApplication @objc public protocol SBTerminalWindow: NSObjectProtocol { @objc optional func tabs() -> SBElementArray @objc optional var name: String { get } @objc optional func id() -> Int @objc optional var index: String { get set } @objc optional var bounds: NSRect { get set } @objc optional var selectedTab: SBTerminalTab { get set } } extension SBObject: SBTerminalWindow { } // MARK: SBTerminalApplication @objc public protocol SBTerminalTab: NSObjectProtocol { } extension SBObject: SBTerminalTab {} /************************************************** * iTerm **************************************************/ @objc public protocol SBiTermGenericMethods: NSObjectProtocol { @objc optional func execCommand(_ command: NSString) // Executes a command in a session (attach a trailing space for commands without carriage return) @objc optional func launchSession(_ session: NSString?) -> SBiTermSession // Launches a default or saved session @objc optional func writeContentsOfFile(_ contentsOfFile: String?, text: String) } extension SBObject: SBiTermGenericMethods {} @objc public protocol SBiTermItem: SBiTermGenericMethods { init() } extension SBObject: SBiTermItem {} // MARK: SBiTermITermApplication @objc public protocol SBiTermITermApplication: SBApplicationProtocol { @objc optional func windows() -> SBElementArray @objc optional func documents() -> SBElementArray @objc optional var name: String { get } @objc optional var version: String { get } @objc optional var frontmost: Bool { get } @objc optional func terminals() -> SBElementArray @objc optional var currentTerminal: SBiTermTerminal { get } // currently active terminal @objc optional var uriToken: String { get } // URI token @objc optional func `class`(forScriptingClass className: String) -> Swift.AnyClass? } extension SBApplication: SBiTermITermApplication {} @objc public protocol SBiTermTerminal: SBiTermItem { @objc optional func sessions() -> SBElementArray @objc optional var antiAlias: Bool { get } // Anti alias for window @objc optional var currentSession: SBiTermSession { get } // current session in the terminal @objc optional var numberOfColumns: Int { get } // Number of columns @objc optional var numberOfRows: Int { get } // Number of rows } extension SBObject: SBiTermTerminal {} @objc public protocol SBiTermSession: SBiTermItem { @objc optional var contents: String { get } } extension SBObject: SBiTermSession {} @objc public protocol SBiTermWindow: SBiTermItem { } extension SBObject: SBiTermWindow {}
34.547368
155
0.708105
1ed1a4b2afe22c2504c60d9d8d01ac83fa6a1cba
10,070
// // YPAssetZoomableView.swift // YPImgePicker // // Created by Sacha Durand Saint Omer on 2015/11/16. // Edited by Nik Kov || nik-kov.com on 2018/04 // Copyright © 2015 Yummypets. All rights reserved. // import UIKit import Photos protocol YPAssetZoomableViewDelegate: class { func ypAssetZoomableViewDidLayoutSubviews(_ zoomableView: YPAssetZoomableView) func ypAssetZoomableViewScrollViewDidZoom() func ypAssetZoomableViewScrollViewDidEndZooming() } final class YPAssetZoomableView: UIScrollView { public weak var myDelegate: YPAssetZoomableViewDelegate? public var cropAreaDidChange = {} public var isVideoMode = false public var photoImageView = UIImageView() public var videoView = YPVideoView() public var squaredZoomScale: CGFloat = 1 public var minWidth: CGFloat? = YPConfig.library.minWidthForItem fileprivate var currentAsset: PHAsset? // Image view of the asset for convenience. Can be video preview image view or photo image view. public var assetImageView: UIImageView { return isVideoMode ? videoView.previewImageView : photoImageView } /// Set zoom scale to fit the image to square or show the full image // /// - Parameters: /// - fit: If true - zoom to show squared. If false - show full. public func fitImage(_ fit: Bool, animated isAnimated: Bool = false) { squaredZoomScale = calculateSquaredZoomScale() if fit { setZoomScale(squaredZoomScale, animated: isAnimated) } else { setZoomScale(1, animated: isAnimated) } } /// Re-apply correct scrollview settings if image has already been adjusted in /// multiple selection mode so that user can see where they left off. public func applyStoredCropPosition(_ scp: YPLibrarySelection) { // ZoomScale needs to be set first. if let zoomScale = scp.scrollViewZoomScale { setZoomScale(zoomScale, animated: false) } if let contentOffset = scp.scrollViewContentOffset { setContentOffset(contentOffset, animated: false) } } public func setVideo(_ video: PHAsset, mediaManager: LibraryMediaManager, storedCropPosition: YPLibrarySelection?, completion: @escaping () -> Void, updateCropInfo: @escaping () -> Void) { mediaManager.imageManager?.fetchPreviewFor(video: video) { [weak self] preview in guard let strongSelf = self else { return } guard strongSelf.currentAsset != video else { completion() ; return } if strongSelf.videoView.isDescendant(of: strongSelf) == false { strongSelf.isVideoMode = true strongSelf.photoImageView.removeFromSuperview() strongSelf.addSubview(strongSelf.videoView) } strongSelf.videoView.setPreviewImage(preview) strongSelf.setAssetFrame(for: strongSelf.videoView, with: preview) completion() // Stored crop position in multiple selection if let scp173 = storedCropPosition { strongSelf.applyStoredCropPosition(scp173) // MARK: add update CropInfo after multiple updateCropInfo() } } mediaManager.imageManager?.fetchPlayerItem(for: video) { [weak self] playerItem in guard let strongSelf = self else { return } guard strongSelf.currentAsset != video else { completion() ; return } strongSelf.currentAsset = video strongSelf.videoView.loadVideo(playerItem) strongSelf.videoView.play() strongSelf.myDelegate?.ypAssetZoomableViewDidLayoutSubviews(strongSelf) } } public func setImage(_ photo: PHAsset, mediaManager: LibraryMediaManager, storedCropPosition: YPLibrarySelection?, completion: @escaping (Bool) -> Void, updateCropInfo: @escaping () -> Void) { guard currentAsset != photo else { DispatchQueue.main.async { completion(false) } return } currentAsset = photo mediaManager.imageManager?.fetch(photo: photo) { [weak self] image, isLowResIntermediaryImage in guard let strongSelf = self else { return } if strongSelf.photoImageView.isDescendant(of: strongSelf) == false { strongSelf.isVideoMode = false strongSelf.videoView.removeFromSuperview() strongSelf.videoView.showPlayImage(show: false) strongSelf.videoView.deallocate() strongSelf.addSubview(strongSelf.photoImageView) strongSelf.photoImageView.contentMode = .scaleAspectFill strongSelf.photoImageView.clipsToBounds = true } strongSelf.photoImageView.image = image strongSelf.setAssetFrame(for: strongSelf.photoImageView, with: image) // Stored crop position in multiple selection if let scp173 = storedCropPosition { strongSelf.applyStoredCropPosition(scp173) // add update CropInfo after multiple updateCropInfo() } completion(isLowResIntermediaryImage) } } fileprivate func setAssetFrame(`for` view: UIView, with image: UIImage) { // Reseting the previous scale self.minimumZoomScale = 1 self.zoomScale = 1 // Calculating and setting the image view frame depending on screenWidth let screenWidth = YPImagePickerConfiguration.screenWidth let w = image.size.width let h = image.size.height var aspectRatio: CGFloat = 1 var zoomScale: CGFloat = 1 if w > h { // Landscape aspectRatio = h / w view.frame.size.width = screenWidth view.frame.size.height = screenWidth * aspectRatio } else if h > w { // Portrait aspectRatio = w / h view.frame.size.width = screenWidth * aspectRatio view.frame.size.height = screenWidth if let minWidth = minWidth { let k = minWidth / screenWidth zoomScale = (h / w) * k } } else { // Square view.frame.size.width = screenWidth view.frame.size.height = screenWidth } // Centering image view view.center = center centerAssetView() // Setting new scale minimumZoomScale = zoomScale self.zoomScale = zoomScale } /// Calculate zoom scale which will fit the image to square func calculateSquaredZoomScale() -> CGFloat { guard let image = assetImageView.image else { print("YPAssetZoomableView >>> No image"); return 1.0 } var squareZoomScale: CGFloat = 1.0 let w = image.size.width let h = image.size.height if w > h { // Landscape squareZoomScale = (w / h) } else if h > w { // Portrait squareZoomScale = (h / w) } return squareZoomScale } // Centring the image frame fileprivate func centerAssetView() { let assetView = isVideoMode ? videoView : photoImageView let scrollViewBoundsSize = self.bounds.size var assetFrame = assetView.frame let assetSize = assetView.frame.size assetFrame.origin.x = (assetSize.width < scrollViewBoundsSize.width) ? (scrollViewBoundsSize.width - assetSize.width) / 2.0 : 0 assetFrame.origin.y = (assetSize.height < scrollViewBoundsSize.height) ? (scrollViewBoundsSize.height - assetSize.height) / 2.0 : 0.0 assetView.frame = assetFrame } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! backgroundColor = YPConfig.colors.assetViewBackgroundColor frame.size = CGSize.zero clipsToBounds = true photoImageView.frame = CGRect(origin: CGPoint.zero, size: CGSize.zero) videoView.frame = CGRect(origin: CGPoint.zero, size: CGSize.zero) maximumZoomScale = 6.0 minimumZoomScale = 1 showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false delegate = self alwaysBounceHorizontal = true alwaysBounceVertical = true isScrollEnabled = true } override func layoutSubviews() { super.layoutSubviews() myDelegate?.ypAssetZoomableViewDidLayoutSubviews(self) } } // MARK: UIScrollViewDelegate Protocol extension YPAssetZoomableView: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return isVideoMode ? videoView : photoImageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { myDelegate?.ypAssetZoomableViewScrollViewDidZoom() centerAssetView() } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { guard let view = view, view == photoImageView || view == videoView else { return } // prevent to zoom out if YPConfig.library.onlySquare && scale < squaredZoomScale { self.fitImage(true, animated: true) } myDelegate?.ypAssetZoomableViewScrollViewDidEndZooming() cropAreaDidChange() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { cropAreaDidChange() } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { cropAreaDidChange() } }
37.434944
106
0.6143
b994e591ddb6427774a7c7c0ff07d24e81e9d61b
3,712
// // The MIT License (MIT) // // // 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. // // Forked from mauriciosantos/Buckets-Swift/ import Foundation // Max Heap struct BinaryHeap<T> : Sequence { var isEmpty: Bool { return items.isEmpty } var count: Int { return items.count } var max: T? { return items.first } // returns true if the first argument has the highest priority fileprivate let isOrderedBefore: (T,T) -> Bool fileprivate var items = [T]() init(compareFunction: @escaping (T,T) -> Bool) { isOrderedBefore = compareFunction } mutating func insert(_ element: T) { items.append(element) siftUp() } mutating func removeMax() -> T? { if !isEmpty { let value = items[0] items[0] = items[count - 1] items.removeLast() if !isEmpty { siftDown() } return value } return nil } mutating func removeAll(keepingCapacity keep: Bool = false) { items.removeAll(keepingCapacity: keep) } func makeIterator() -> AnyIterator<T> { return AnyIterator(items.makeIterator()) } fileprivate mutating func siftUp() { func parent(_ index: Int) -> Int { return (index - 1) / 2 } var i = count - 1 var parentIndex = parent(i) while i > 0 && !isOrderedBefore(items[parentIndex], items[i]) { swap(&items[i], &items[parentIndex]) i = parentIndex parentIndex = parent(i) } } fileprivate mutating func siftDown() { // Returns the index of the maximum element if it exists, otherwise -1 func maxIndex(_ i: Int, _ j: Int) -> Int { if j >= count && i >= count { return -1 } else if j >= count && i < count { return i } else if isOrderedBefore(items[i], items[j]) { return i } else { return j } } func leftChild(_ index: Int) -> Int { return (2 * index) + 1 } func rightChild(_ index: Int) -> Int { return (2 * index) + 2 } var i = 0 var max = maxIndex(leftChild(i), rightChild(i)) while max >= 0 && !isOrderedBefore(items[i], items[max]) { swap(&items[max], &items[i]) i = max max = maxIndex(leftChild(i), rightChild(i)) } } } // MARK: Heap Operators /// Returns `true` if and only if the heaps contain the same elements /// in the same order. /// The underlying elements must conform to the `Equatable` protocol. func ==<U: Equatable>(lhs: BinaryHeap<U>, rhs: BinaryHeap<U>) -> Bool { return lhs.items.sorted(by: lhs.isOrderedBefore) == rhs.items.sorted(by: rhs.isOrderedBefore) } func !=<U: Equatable>(lhs: BinaryHeap<U>, rhs: BinaryHeap<U>) -> Bool { return !(lhs==rhs) }
27.909774
95
0.649515
1ab3eca5b811988a47cd3d938359e2ac84de5c42
4,938
// // BaseAnchorViewController.swift // Demo1 // // Created by 钟宏彬 on 2020/3/27. // Copyright © 2020 钟宏彬. All rights reserved. // import UIKit // // BaseAnchorViewController.swift // Demo1 // // Created by 钟宏彬 on 2020/3/27. // Copyright © 2020 钟宏彬. All rights reserved. // //娱乐fun及推荐recommend页面的父类控制器 let kItemMargin :CGFloat = 10 let kItemW : CGFloat = (kScreenW - 3*kItemMargin)/2 let kNormalItemH : CGFloat = kItemW * 3 / 4 let kPrettyItemH : CGFloat = kItemW * 4 / 3 private let kHeaderH : CGFloat = 50 private let kNormalID = "kNormalID" let kPrettyID = "kPrettyID" private let kHeaderID = "kHeaderID" class BaseAnchorViewController : BaseViewController { var baseVM : BaseViewModel? lazy var collectionView : UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) //设置layout中header大小 layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderH) let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor.white //根据父布局适配宽高防止流水布局底部显示不全 collectionView.autoresizingMask = [.flexibleWidth,.flexibleHeight] //注册cell item collectionView.register(UINib(nibName: "CollectionViewNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalID) collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyID) //注册header collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: kHeaderID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() setupUI() getHttp() } } extension BaseAnchorViewController{ override func setupUI(){ //给父布局view赋值 contentView = collectionView view.addSubview(collectionView) //后执行super不然父布局无contentview super.setupUI() } @objc func getHttp(){ } } extension BaseAnchorViewController : UICollectionViewDataSource{ func numberOfSections(in collectionView: UICollectionView) -> Int { //获取data下detail组数量 // if baseVM == nil { // return 1 // } return baseVM?.model.data?.count ?? 0 } //每组下item数量 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // if baseVM == nil { // return 20 // } let group = baseVM?.model.data?[section] return group?.room_list!.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalID, for: indexPath) as! CollectionViewNormalCell // if baseVM == nil { // return cell // } let group = baseVM?.model.data?[indexPath.section] let item = group?.room_list?[indexPath.item] cell.item = item return cell } //设置header func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderID, for: indexPath) as!CollectionHeaderView // if baseVM == nil { // return headerView // } headerView.group = baseVM?.model.data?[indexPath.section] return headerView } } extension BaseAnchorViewController : UICollectionViewDelegate{ func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let room = baseVM?.model.data?[indexPath.section].room_list?[indexPath.item] room?.isVertical == 0 ? pushRoom() : showRoom() } private func showRoom(){ let showVc = RoomShowViewController() present(showVc, animated: true, completion: nil) } private func pushRoom(){ //使用storyboard方式加载controller let iHomeStory:UIStoryboard = UIStoryboard(name: "RoomViewController", bundle: nil) //storyboard中记得设置storyboard ID let iFirstVC = iHomeStory.instantiateViewController(withIdentifier: "Room") as! RoomViewController //直接使用controller let pushVc = RoomViewController() navigationController?.pushViewController(iFirstVC, animated: true) } }
36.577778
187
0.683273
1ab34860cf2ba2bbb8af5a463b10af61d526e5b6
2,311
import EthereumKit class WalletConnectSignMessageRequestService { private let request: WalletConnectSignMessageRequest private let signService: IWalletConnectSignService private let signer: Signer init(request: WalletConnectSignMessageRequest, signService: IWalletConnectSignService, signer: Signer) { self.request = request self.signService = signService self.signer = signer } private func sign(message: Data) throws -> Data { try signer.signed(message: message) } private func signTypedData(message: Data) throws -> Data { try signer.signTypedData(message: message) } } extension WalletConnectSignMessageRequestService { var message: String { switch request.payload { case let .sign(data, _): return String(decoding: data, as: UTF8.self) case let .personalSign(data, _): return String(decoding: data, as: UTF8.self) case let .signTypeData(_, data, _): guard let object = try? JSONSerialization.jsonObject(with: data, options: []), let prettyData = try? JSONSerialization.data(withJSONObject: object, options: .prettyPrinted) else { return "" } return String(decoding: prettyData, as: UTF8.self) } } var domain: String? { if case let .signTypeData(_, data, _) = request.payload { let typeData = try? signer.parseTypedData(rawJson: data) if case let .object(json) = typeData?.domain, let domainJson = json["name"], case let .string(domainString) = domainJson { return domainString } } return nil } var dAppName: String? { request.dAppName } func sign() throws { let signedMessage: Data switch request.payload { case let .sign(data, _): signedMessage = try sign(message: data) case let .personalSign(data, _): signedMessage = try sign(message: data) case let .signTypeData(_, data, _): signedMessage = try signTypedData(message: data) } signService.approveRequest(id: request.id, result: signedMessage) } func reject() { signService.rejectRequest(id: request.id) } }
30.012987
134
0.624838
91337637183f95ef69eeb919e157cc4e85548db9
1,594
// // MovementPreview.swift // // // Created by Bastián Véliz Vega on 17-09-20. // import Combine import DataManagement class MovementPreview: DataSourceModify { private var movements: [Movement] = [] func save(movement: Movement) -> AnyPublisher<Void, Error> { let future = Future<Void, Error>() { [weak self] promise in guard let strongSelf = self else { return promise(.failure(MovementPreviewError.other)) } strongSelf.movements.append(movement) promise(.success(())) } return future.eraseToAnyPublisher() } func delete(movement: Movement) -> AnyPublisher<Void, Error> { let future = Future<Void, Error>() { [weak self] promise in guard let strongSelf = self else { return promise(.failure(MovementPreviewError.other)) } strongSelf.movements.removeAll(where: { $0.id == movement.id }) promise(.success(())) } return future.eraseToAnyPublisher() } func update(movement: Movement) -> AnyPublisher<Void, Error> { let future = Future<Void, Error>() { [weak self] promise in guard let strongSelf = self else { return promise(.failure(MovementPreviewError.other)) } strongSelf.movements.removeAll(where: { $0.id == movement.id }) strongSelf.movements.append(movement) promise(.success(())) } return future.eraseToAnyPublisher() } } enum MovementPreviewError: Error { case other }
30.653846
75
0.599122
b91168aa48dfc5e4fbfb37966f903a18b4833f2a
308
// // StringExtenssion.swift // Localizabler // // Created by Baluta Cristian on 06/10/15. // Copyright © 2015 Cristian Baluta. All rights reserved. // import Foundation extension String { @inline(__always) func trim() -> String { return self.trimmingCharacters(in: CharacterSet.whitespaces) } }
18.117647
62
0.714286
f8cfdd8ef06cfe73cf9a57c9e09e1e1cb6b0b13e
3,353
// // Geofence.swift // My LBS // // Created by Keusen Alain, INI-ONE-CIS-CLI on 29.06.19. // Copyright © 2019 Keusen DEV. All rights reserved. // import UIKit import MapKit import CoreLocation class Geofence: NSObject, Codable, MKAnnotation { enum CodingKeys: String, CodingKey { case latitude, longitude, radius, identifier, note, dateTime, eventType } var coordinate: CLLocationCoordinate2D var radius: CLLocationDistance var identifier: String var note: String var dateTime: Date var eventType: EventType var title: String? { if note.isEmpty { return "No Note" } return note } var subtitle: String? { let eventTypeString = eventType.rawValue return "Radius: \(radius)m - \(eventTypeString)" } init(coordinate: CLLocationCoordinate2D, radius: CLLocationDistance, identifier: String, note: String, dateTime: Date = Date(), eventType: EventType) { self.coordinate = coordinate self.radius = radius self.identifier = identifier self.note = note self.dateTime = dateTime self.eventType = eventType } // MARK: Codable required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let latitude = try values.decode(Double.self, forKey: .latitude) let longitude = try values.decode(Double.self, forKey: .longitude) coordinate = CLLocationCoordinate2DMake(latitude, longitude) radius = try values.decode(Double.self, forKey: .radius) identifier = try values.decode(String.self, forKey: .identifier) note = try values.decode(String.self, forKey: .note) dateTime = try values.decode(Date.self, forKey: .dateTime) dateTime = try dateStringDecode(forKey: .dateTime, from: values, with: .iso8601) let event = try values.decode(String.self, forKey: .eventType) eventType = EventType(rawValue: event) ?? .onEntry } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(coordinate.latitude, forKey: .latitude) try container.encode(coordinate.longitude, forKey: .longitude) try container.encode(radius, forKey: .radius) try container.encode(identifier, forKey: .identifier) try container.encode(note, forKey: .note) try container.encode(DateFormatter.iso8601.string(from: dateTime), forKey: .dateTime) try container.encode(eventType.rawValue, forKey: .eventType) } } extension Geofence { public class func readFromJson() -> [Geofence] { let documentDirectoryURL = URL(fileURLWithPath: "data", relativeTo: FileManager.documentDirectoryURL) let fileURL: URL = documentDirectoryURL.appendingPathComponent("geofences").appendingPathExtension("json") do { let savedData = try Data(contentsOf: fileURL) let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 if let savedGeofences = try? decoder.decode(Array.self, from: savedData) as [Geofence] { return savedGeofences } } catch { return [] } return [] } }
36.053763
155
0.651655
91e70fef4c7cfaf74e47e44099474c1d09b6c97b
1,675
// // Copyright 2018-2019 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // /// CategoryPlugins implement the behavior defined by the category. The `Plugin` protocol defines behavior common to /// all plugins, but each category will also define client API behavior and optionally, plugin API behavior to describe /// the contract to which the plugin must conform. public protocol Plugin: CategoryTypeable, PluginResettable { /// The key under which the plugin is registered in the Amplify configuration. Keys must be unique within the /// category configuration section. var key: PluginKey { get } /// Configures the category plugin using `configuration` /// /// - Parameter configuration: The category plugin configuration for configuring the plugin. The plugin /// implementation is responsible for validating the incoming object, including required configurations, and /// handling potential conflicts with globally-specified options. /// - Throws: /// - PluginError.pluginConfigurationError: If the plugin encounters an error during configuration func configure(using configuration: Any) throws } /// Convenience typealias to clarify when Strings are being used as plugin keys public typealias PluginKey = String /// The conforming type can be initialized with a `Plugin`. Allows for construction of concrete, type-erasing wrappers /// to store heterogenous collections of Plugins in a category. /// - Throws: PluginError.mismatchedPlugin if the instance is associated with the wrong category public protocol PluginInitializable { init<P: Plugin>(instance: P) }
47.857143
119
0.761194
4a003e5341f7102da605f3b87607dd4ecccec703
1,551
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** The timestamp of a word in a Speech to Text transcription. */ public struct WordTimestamp: JSONDecodable { /// A particular word from the transcription. public let word: String /// The start time, in seconds, of the given word in the audio input. public let startTime: Double /// The end time, in seconds, of the given word in the audio input. public let endTime: Double /// Used internally to initialize a `WordTimestamp` model from JSON. public init(json: JSON) throws { let array = try json.getArray() word = try array[Index.word.rawValue].getString() startTime = try array[Index.startTime.rawValue].getDouble() endTime = try array[Index.endTime.rawValue].getDouble() } /// The index of each element in the JSON array. private enum Index: Int { case word = 0 case startTime = 1 case endTime = 2 } }
33
75
0.692456
5d54ac74fae156f0d9507d8d33f9f3668826281f
2,456
// // Store.swift // personal-planner // // Created by Calvin De Aquino on 2020-02-21. // Copyright © 2020 Calvin Aquino. All rights reserved. // import SwiftUI import CloudKit import Combine class Storage { static let shared = Storage() var storage: [String: Record] = [:] func save(_ record: Record) { storage[record.id] = record } func fetch(_ recordId: String) -> Record? { return storage[recordId] } } class Store { init() { Cloud.fetchShoppingCategories { } Cloud.fetchTransactionCategories { } Cloud.fetchGoalCategories { } Cloud.fetchShoppingItems { } Cloud.fetchTransactionItems(for: Date()) { } Cloud.fetchGoalItems { } } static let shared = Store() @discardableResult func deleteRecord(_ recordID: CKRecord.ID) -> Bool { let id = recordID.recordName if self.shoppingItems.delete(id) { return true } if self.shoppingCategories.delete(id) { return true } if self.transactionItems.delete(id) { return true } if self.transactionCategories.delete(id) { return true } if self.goalItems.delete(id) { return true } if self.goalCategories.delete(id) { return true } return false } var shoppingItems = Cache<ShoppingItem>() var shoppingCategories = Cache<ShoppingCategory>() var transactionItems = Cache<TransactionItem>() var transactionCategories = Cache<TransactionCategory>() var goalItems = Cache<GoalItem>() var goalCategories = Cache<GoalCategory>() } class Cache<T: Record> { init() { self.subject = CurrentValueSubject<[T], Never>([]) self.publisher = self.subject.eraseToAnyPublisher() } let subject: CurrentValueSubject<[T], Never> let publisher: AnyPublisher<[T], Never> private var itemCache: [String: T] = [:] var items: [T] { get { self.itemCache.map { (key: String, value: T) -> T in return value } } set { self.itemCache.removeAll() newValue.forEach { record in self.itemCache[record.id] = record } self.subject.send(self.items) } } func save(_ record: T) { self.itemCache[record.id] = record self.subject.send(self.items) } @discardableResult func delete(_ id: String) -> Bool { if self.itemCache[id] != nil { self.itemCache[id] = nil self.subject.send(self.items) return true } return false } func fetch(_ id: String) -> T? { self.itemCache[id] } }
23.84466
60
0.650651
28d470b96c2b730bd16668c4224e559ce314ca23
510
import ConsoleKit import Foundation let console: Console = Terminal() var input = CommandInput(arguments: CommandLine.arguments) var context = CommandContext(console: console, input: input) var commands = Commands(enableAutocomplete: false) commands.use(ReleaseCommand(), as: "release", isDefault: false) do { let group = commands.group(help: "A tool for releasing the Restler framework to CocoaPods repo.") try console.run(group, input: input) } catch { console.error("\(error)") exit(1) }
28.333333
101
0.739216
295c0ad770eb6c3553c3bd41cbe7ec5e167815c1
1,600
// // Environment.swift // Wei // // Created by yuzushioh on 2018/03/15. // Copyright © 2018 popshoot. All rights reserved. // import Foundation enum Environment { case production case development case staging static var current: Environment { #if DEBUG return .development #elseif INHOUSE return .staging #else return .production #endif } var weiBaseURL: URL { switch self { case .development: return URL(string: "https://stg.wei.tokyo")! case .staging: return URL(string: "https://stg.wei.tokyo")! case .production: return URL(string: "https://wei.tokyo")! } } var appGroupID: String { switch self { case .development: return "group.com.popshoot.wei.debug" case .staging: return "group.com.popshoot.wei.inhouse" case .production: return "group.com.popshoot.wei" } } var nodeEndpoint: String { switch self { case .production: return "https://mainnet.infura.io/z1sEfnzz0LLMsdYMX4PV" case .development, .staging: return "https://ropsten.infura.io/z1sEfnzz0LLMsdYMX4PV" } } var etherscanAPIKey: String { return "XE7QVJNVMKJT75ATEPY1HPWTPYCVCKMMJ7" } var debugPrints: Bool { switch self { case .production, .staging: return false case .development: return true } } }
22.857143
67
0.54875
4ac7719852d391eb8de6588ede1208a7cd3fa88d
1,347
// // AppDelegate.swift // Demo // // Created by 吴炜 on 2020/4/7. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.405405
179
0.746102
1844b716033bef25acd07fb92edea55d6557c951
1,396
// // DemoJamStackUITests.swift // // Created on 6/19/20. // import XCTest class DemoJamStackUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication() app.launch() // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testLaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) { XCUIApplication().launch() } } } }
33.238095
182
0.656877
8984ddc97e2f944cd35e47dcfd1ac4bb05a4cc9d
596
// // DetailCellEntity.swift // nemo // // Created by Andyy Hope on 21/7/18. // Copyright © 2018 Andyy Hope. All rights reserved. // import Foundation struct DetailCellEntity { let detail: String let heading: String let backgroundColor: String? init?(json: JSON) { guard let heading = json["heading-text"] as? String, let detail = json["detail-text"] as? String else { return nil } self.heading = heading self.detail = detail self.backgroundColor = json["backgroundColor"] as? String } }
22.074074
65
0.597315
0a3285ac3caf28c65b27cde2ad28f9b95639e29b
3,796
// RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/malformed-but-valid-yaml-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/malformed-after-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./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.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // CHECK-SECOND: Handled other.swift // CHECK-SECOND: Handled main.swift // RUN: touch -t 201401240007 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s // CHECK-THIRD: Handled main.swift // CHECK-THIRD: Handled other.swift // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/malformed-but-valid-yaml-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/malformed-after-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: touch -t 201401240006 %t/main.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s // RUN: touch -t 201401240007 %t/main.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -disable-direct-intramodule-dependencies -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FOURTH %s // CHECK-FOURTH-NOT: Handled other.swift // CHECK-FOURTH: Handled main.swift // CHECK-FOURTH-NOT: Handled other.swift
77.469388
357
0.739199
0e2e2a405db2cde606108fc11e15b90979d00771
2,553
// // Copyright © 2021 Essential Developer. All rights reserved. // import XCTest import EssentialFeed class ImageCommentsMapperTests: XCTestCase { func test_map_throwsErrorOnNon2xxHTTPResponse() throws { let samples = [199, 300, 400, 500] try samples.forEach { code in XCTAssertThrowsError( try ImageCommentsMapper.map(anyData(), from: HTTPURLResponse(statusCode: code)) ) } } func test_map_deliversInvalidDataErrorOn2xxHTTPResponseWithEmptyData() throws { let emptyData = Data() try successfulResponses.forEach { code in XCTAssertThrowsError( try ImageCommentsMapper.map(emptyData, from: code) ) } } func test_map_throwsErrorOn2xxHTTPResponseWithInvalidJSON() throws { let invalidJSON = Data("invalid json".utf8) try successfulResponses.forEach { code in XCTAssertThrowsError( try ImageCommentsMapper.map(invalidJSON, from: code) ) } } func test_map_deliversNoItemsOn2xxHTTPResponseWithEmptyJSONList() throws { let emptyListJSON = makeItemsJSON([]) try successfulResponses.forEach { code in let result = try ImageCommentsMapper.map(emptyListJSON, from: code) XCTAssertEqual(result, []) } } func test_map_deliversItemsOn2xxHTTPResponseWithJSONItems() throws { let item1 = makeItem(id: UUID(), message: "a comment", creationTime: (Date(timeIntervalSince1970: 1598627222), "2020-08-28T15:07:02+00:00"), authorName: "an author") let item2 = makeItem(id: UUID(), message: "another comment", creationTime: (Date(timeIntervalSince1970: 1577881882), "2020-01-01T12:31:22+00:00"), authorName: "another author") let json = makeItemsJSON([item1.json, item2.json]) try successfulResponses.forEach { code in let result = try ImageCommentsMapper.map(json, from: code) XCTAssertEqual(result, [item1.model, item2.model]) } } // MARK: - Helpers private func makeItem(id: UUID, message: String, creationTime: (date: Date, iso8601String: String), authorName: String) -> (model: ImageComment, json: [String: Any]) { let item = ImageComment(id: id, message: message, creationTime: creationTime.date, authorName: authorName) let json: [String: Any] = [ "id": id.uuidString, "message": message, "created_at": creationTime.iso8601String, "author": [ "username": authorName ] ] return (item, json) } private var successfulResponses: [HTTPURLResponse] { [200, 201, 299].map(HTTPURLResponse.init) } }
28.685393
168
0.693302
fc3aa11f639e26010bcebf1ea61b702be3e27936
2,728
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for LexRuntimeV2 public struct LexRuntimeV2ErrorType: AWSErrorType { enum Code: String { case accessDeniedException = "AccessDeniedException" case badGatewayException = "BadGatewayException" case conflictException = "ConflictException" case dependencyFailedException = "DependencyFailedException" case internalServerException = "InternalServerException" case resourceNotFoundException = "ResourceNotFoundException" case throttlingException = "ThrottlingException" case validationException = "ValidationException" } private let error: Code public let context: AWSErrorContext? /// initialize LexRuntimeV2 public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } public static var accessDeniedException: Self { .init(.accessDeniedException) } public static var badGatewayException: Self { .init(.badGatewayException) } public static var conflictException: Self { .init(.conflictException) } public static var dependencyFailedException: Self { .init(.dependencyFailedException) } public static var internalServerException: Self { .init(.internalServerException) } public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } public static var throttlingException: Self { .init(.throttlingException) } public static var validationException: Self { .init(.validationException) } } extension LexRuntimeV2ErrorType: Equatable { public static func == (lhs: LexRuntimeV2ErrorType, rhs: LexRuntimeV2ErrorType) -> Bool { lhs.error == rhs.error } } extension LexRuntimeV2ErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
38.422535
117
0.679985
286738017c066a41717bb6b87268138e589a5070
14,259
// // UnitTests.swift // SmartAILibraryTests // // Created by Michael Rommel on 16.08.21. // Copyright © 2021 Michael Rommel. All rights reserved. // import Foundation import XCTest @testable import SmartAILibrary class UnitTests: XCTestCase { // Embarked Units cant move in water #67 func testUnitMovesEmbarked() { // GIVEN let barbarianPlayer = Player(leader: .barbar, isHuman: false) barbarianPlayer.initialize() let aiPlayer = Player(leader: .victoria, isHuman: false) aiPlayer.initialize() let humanPlayer = Player(leader: .alexander, isHuman: true) humanPlayer.initialize() do { try humanPlayer.techs?.discover(tech: .sailing) } catch {} let mapModel = MapUtils.mapFilled(with: .ocean, sized: .small) // start island mapModel.set(terrain: .plains, at: HexPoint(x: 1, y: 2)) mapModel.set(terrain: .plains, at: HexPoint(x: 2, y: 2)) // target island mapModel.set(terrain: .plains, at: HexPoint(x: 6, y: 2)) mapModel.set(terrain: .plains, at: HexPoint(x: 7, y: 2)) let gameModel = GameModel(victoryTypes: [.domination], handicap: .king, turnsElapsed: 0, players: [barbarianPlayer, aiPlayer, humanPlayer], on: mapModel) // add UI let userInterface = TestUI() gameModel.userInterface = userInterface let humanPlayerWarrior = Unit(at: HexPoint(x: 2, y: 2), type: .warrior, owner: humanPlayer) gameModel.add(unit: humanPlayerWarrior) let warriorMission = UnitMission(type: .moveTo, at: HexPoint(x: 6, y: 2)) humanPlayerWarrior.push(mission: warriorMission, in: gameModel) // WHEN var turnCounter = 0 var hasVisited = false repeat { repeat { gameModel.update() if humanPlayer.isTurnActive() { humanPlayer.finishTurn() humanPlayer.setAutoMoves(to: true) } } while !(humanPlayer.hasProcessedAutoMoves() && humanPlayer.finishTurnButtonPressed()) hasVisited = humanPlayerWarrior.location == HexPoint(x: 6, y: 2) turnCounter += 1 } while turnCounter < 10 && !hasVisited // THEN XCTAssertEqual(humanPlayerWarrior.location, HexPoint(x: 6, y: 2)) } func testUnitScoutAutomation() { // GIVEN let barbarianPlayer = Player(leader: .barbar, isHuman: false) barbarianPlayer.initialize() let aiPlayer = Player(leader: .victoria, isHuman: false) aiPlayer.initialize() let humanPlayer = Player(leader: .alexander, isHuman: true) humanPlayer.initialize() let mapModel = MapUtils.mapFilled(with: .grass, sized: .small) let gameModel = GameModel(victoryTypes: [.domination], handicap: .king, turnsElapsed: 0, players: [barbarianPlayer, aiPlayer, humanPlayer], on: mapModel) // add UI let userInterface = TestUI() gameModel.userInterface = userInterface let humanPlayerScout = Unit(at: HexPoint(x: 2, y: 2), type: .scout, owner: humanPlayer) gameModel.add(unit: humanPlayerScout) // WHEN humanPlayerScout.automate(with: .explore) var turnCounter = 0 var hasStayed = true repeat { repeat { gameModel.update() if humanPlayer.isTurnActive() { humanPlayer.finishTurn() humanPlayer.setAutoMoves(to: true) } } while !(humanPlayer.hasProcessedAutoMoves() && humanPlayer.finishTurnButtonPressed()) hasStayed = humanPlayerScout.location == HexPoint(x: 2, y: 2) turnCounter += 1 } while turnCounter < 4 && hasStayed // THEN XCTAssertNotEqual(humanPlayerScout.location, HexPoint(x: 2, y: 2)) } func testUnitCanTransferToAnotherCity() { // GIVEN let humanPlayer = Player(leader: .alexander, isHuman: true) humanPlayer.initialize() // civilians ------------------------------ let unitSettler = Unit(at: HexPoint(x: 2, y: 2), type: .settler, owner: humanPlayer) let unitBuilder = Unit(at: HexPoint(x: 2, y: 2), type: .builder, owner: humanPlayer) let unitTrader = Unit(at: HexPoint(x: 2, y: 2), type: .trader, owner: humanPlayer) // recon ------------------------------ let unitScout = Unit(at: HexPoint(x: 2, y: 2), type: .scout, owner: humanPlayer) // melee ------------------------------ let unitWarrior = Unit(at: HexPoint(x: 2, y: 2), type: .warrior, owner: humanPlayer) let unitSwordman = Unit(at: HexPoint(x: 2, y: 2), type: .swordman, owner: humanPlayer) // ranged ------------------------------ let unitSlinger = Unit(at: HexPoint(x: 2, y: 2), type: .slinger, owner: humanPlayer) let unitArcher = Unit(at: HexPoint(x: 2, y: 2), type: .archer, owner: humanPlayer) // anti-cavalry ------------------------------ let unitSpearman = Unit(at: HexPoint(x: 2, y: 2), type: .spearman, owner: humanPlayer) // light cavalry ------------------------------ let unitHorseman = Unit(at: HexPoint(x: 2, y: 2), type: .horseman, owner: humanPlayer) // heavy cavalry ------------------------------ let unitHeavyChariot = Unit(at: HexPoint(x: 2, y: 2), type: .heavyChariot, owner: humanPlayer) // siege ------------------------------ let unitCatapult = Unit(at: HexPoint(x: 2, y: 2), type: .catapult, owner: humanPlayer) // naval melee ------------------------------ let unitGalley = Unit(at: HexPoint(x: 2, y: 2), type: .galley, owner: humanPlayer) // naval ranged ------------------------------ let unitQuadrireme = Unit(at: HexPoint(x: 2, y: 2), type: .quadrireme, owner: humanPlayer) // support ------------------------------ let unitMedic = Unit(at: HexPoint(x: 2, y: 2), type: .medic, owner: humanPlayer) // great people ------------------------------ let unitArtist = Unit(at: HexPoint(x: 2, y: 2), type: .artist, owner: humanPlayer) let unitAdmiral = Unit(at: HexPoint(x: 2, y: 2), type: .admiral, owner: humanPlayer) let unitEngineer = Unit(at: HexPoint(x: 2, y: 2), type: .engineer, owner: humanPlayer) let unitGeneral = Unit(at: HexPoint(x: 2, y: 2), type: .general, owner: humanPlayer) let unitMerchant = Unit(at: HexPoint(x: 2, y: 2), type: .merchant, owner: humanPlayer) let unitMusician = Unit(at: HexPoint(x: 2, y: 2), type: .musician, owner: humanPlayer) let unitProphet = Unit(at: HexPoint(x: 2, y: 2), type: .prophet, owner: humanPlayer) let unitScientist = Unit(at: HexPoint(x: 2, y: 2), type: .scientist, owner: humanPlayer) let unitWriter = Unit(at: HexPoint(x: 2, y: 2), type: .writer, owner: humanPlayer) // WHEN // civilians ------------------------------ let canSettlerTransfer = unitSettler.canTransferToAnotherCity() let canBuilderTransfer = unitBuilder.canTransferToAnotherCity() let canTraderTransfer = unitTrader.canTransferToAnotherCity() // recon ------------------------------ let canScoutTransfer = unitScout.canTransferToAnotherCity() // melee ------------------------------ let canWarriorTransfer = unitWarrior.canTransferToAnotherCity() let canSwordmanTransfer = unitSwordman.canTransferToAnotherCity() // ranged ------------------------------ let canSlingerTransfer = unitSlinger.canTransferToAnotherCity() let canArcherTransfer = unitArcher.canTransferToAnotherCity() // anti-cavalry ------------------------------ let canSpearmanTransfer = unitSpearman.canTransferToAnotherCity() // light cavalry ------------------------------ let canHorsemanTransfer = unitHorseman.canTransferToAnotherCity() // heavy cavalry ------------------------------ let canHeavyChariotTransfer = unitHeavyChariot.canTransferToAnotherCity() // siege ------------------------------ let canCatapultTransfer = unitCatapult.canTransferToAnotherCity() // naval melee ------------------------------ let canGalleyTransfer = unitGalley.canTransferToAnotherCity() // naval ranged ------------------------------ let canQuadriremeTransfer = unitQuadrireme.canTransferToAnotherCity() // support ------------------------------ let canMedicTransfer = unitMedic.canTransferToAnotherCity() // great people ------------------------------ let canArtistTransfer = unitArtist.canTransferToAnotherCity() let canAdmiralTransfer = unitAdmiral.canTransferToAnotherCity() let canEngineerTransfer = unitEngineer.canTransferToAnotherCity() let canGeneralTransfer = unitGeneral.canTransferToAnotherCity() let canMerchantTransfer = unitMerchant.canTransferToAnotherCity() let canMusicianTransfer = unitMusician.canTransferToAnotherCity() let canProphetTransfer = unitProphet.canTransferToAnotherCity() let canScientistTransfer = unitScientist.canTransferToAnotherCity() let canWriterTransfer = unitWriter.canTransferToAnotherCity() // THEN // civilians ------------------------------ XCTAssertFalse(canSettlerTransfer) XCTAssertFalse(canBuilderTransfer) XCTAssertTrue(canTraderTransfer) // recon ------------------------------ XCTAssertFalse(canScoutTransfer) // melee ------------------------------ XCTAssertFalse(canWarriorTransfer) XCTAssertFalse(canSwordmanTransfer) // ranged ------------------------------ XCTAssertFalse(canSlingerTransfer) XCTAssertFalse(canArcherTransfer) // anti-cavalry ------------------------------ XCTAssertFalse(canSpearmanTransfer) // light cavalry ------------------------------ XCTAssertFalse(canHorsemanTransfer) // heavy cavalry ------------------------------ XCTAssertFalse(canHeavyChariotTransfer) // siege ------------------------------ XCTAssertFalse(canCatapultTransfer) // naval melee ------------------------------ XCTAssertFalse(canGalleyTransfer) // naval ranged ------------------------------ XCTAssertFalse(canQuadriremeTransfer) // support ------------------------------ XCTAssertFalse(canMedicTransfer) // great people ------------------------------ XCTAssertTrue(canArtistTransfer) XCTAssertTrue(canAdmiralTransfer) XCTAssertTrue(canEngineerTransfer) XCTAssertTrue(canGeneralTransfer) XCTAssertTrue(canMerchantTransfer) XCTAssertTrue(canMusicianTransfer) XCTAssertTrue(canProphetTransfer) XCTAssertTrue(canScientistTransfer) XCTAssertTrue(canWriterTransfer) } func testUnitRenaming() { // GIVEN let barbarianPlayer = Player(leader: .barbar, isHuman: false) barbarianPlayer.initialize() let aiPlayer = Player(leader: .victoria, isHuman: false) aiPlayer.initialize() let humanPlayer = Player(leader: .alexander, isHuman: true) humanPlayer.initialize() let mapModel = MapUtils.mapFilled(with: .grass, sized: .small) let gameModel = GameModel(victoryTypes: [.domination], handicap: .king, turnsElapsed: 0, players: [barbarianPlayer, aiPlayer, humanPlayer], on: mapModel) // add UI let userInterface = TestUI() gameModel.userInterface = userInterface let humanPlayerScout = Unit(at: HexPoint(x: 2, y: 2), type: .scout, owner: humanPlayer) gameModel.add(unit: humanPlayerScout) // WHEN let beforeRenaming = humanPlayerScout.name() humanPlayerScout.rename(to: "Flamingo") let afterRenaming = humanPlayerScout.name() // THEN XCTAssertNotEqual(beforeRenaming, afterRenaming) XCTAssertEqual(beforeRenaming, "Scout") XCTAssertEqual(afterRenaming, "Flamingo") } func testUnitUpgrade() { // GIVEN let barbarianPlayer = Player(leader: .barbar, isHuman: false) barbarianPlayer.initialize() let aiPlayer = Player(leader: .victoria, isHuman: false) aiPlayer.initialize() let humanPlayer = Player(leader: .alexander, isHuman: true) humanPlayer.initialize() do { try humanPlayer.techs?.discover(tech: .ironWorking) } catch {} humanPlayer.treasury?.changeGold(by: 1000.0) let mapModel = MapUtils.mapFilled(with: .grass, sized: .small) let gameModel = GameModel(victoryTypes: [.domination], handicap: .king, turnsElapsed: 0, players: [barbarianPlayer, aiPlayer, humanPlayer], on: mapModel) // add UI let userInterface = TestUI() gameModel.userInterface = userInterface let humanPlayerScout = Unit(at: HexPoint(x: 2, y: 2), type: .warrior, owner: humanPlayer) gameModel.add(unit: humanPlayerScout) let humanCapital = City(name: "Human Capital", at: HexPoint(x: 2, y: 1), capital: true, owner: humanPlayer) humanCapital.initialize(in: gameModel) gameModel.add(city: humanCapital) // WHEN let canUpgradeBefore = humanPlayerScout.canUpgrade(to: .swordman, in: gameModel) humanPlayerScout.doUpgrade(to: .swordman, in: gameModel) // <= will crash on failure // THEN XCTAssertEqual(canUpgradeBefore, true) } }
38.852861
115
0.567712
761b8c4db4b1436177c8a344479c606adf3ea488
1,909
// // STPhotoMapView+BusinessLogic.swift // STPhotoMap-iOS // // Created by Dimitri Strauneanu on 24/06/2019. // Copyright © 2019 Streetography. All rights reserved. // import Foundation extension STPhotoMapView { func shouldDownloadImageForPhotoAnnotation(_ photoAnnotation: PhotoAnnotation) { self.interactor?.shouldDownloadImageForPhotoAnnotation(request: STPhotoMapModels.PhotoAnnotationImageDownload.Request(photoAnnotation: photoAnnotation)) } func shouldSelectPhotoAnnotation(_ photoAnnotation: PhotoAnnotation, previousPhotoAnnotation: PhotoAnnotation?) { self.interactor?.shouldSelectPhotoAnnotation(request: STPhotoMapModels.PhotoAnnotationSelection.Request(photoAnnotation: photoAnnotation, previousPhotoAnnotation: previousPhotoAnnotation)) } func shouldInflatePhotoClusterAnnotation(_ clusterAnnotation: MultiplePhotoClusterAnnotation, previousClusterAnnotation: MultiplePhotoClusterAnnotation?, zoomLevel: Int) { self.interactor?.shouldInflatePhotoClusterAnnotation(request: STPhotoMapModels.PhotoClusterAnnotationInflation.Request(clusterAnnotation: clusterAnnotation, previousClusterAnnotation: previousClusterAnnotation, zoomLevel: zoomLevel)) } func shouldSelectPhotoClusterAnnotation(_ clusterAnnotation: MultiplePhotoClusterAnnotation, photoAnnotation: PhotoAnnotation, previousPhotoAnnotation: PhotoAnnotation?) { self.interactor?.shouldSelectPhotoClusterAnnotation(request: STPhotoMapModels.PhotoClusterAnnotationSelection.Request(clusterAnnotation: clusterAnnotation, photoAnnotation: photoAnnotation, previousPhotoAnnotation: previousPhotoAnnotation)) } func shouldUpdateSelectedPhotoAnnotation(_ photoAnnotation: PhotoAnnotation?) { self.interactor?.shouldUpdateSelectedPhotoAnnotation(request: STPhotoMapModels.SelectedPhotoAnnotation.Request(annotation: photoAnnotation)) } }
59.65625
248
0.828182
762b70fc9e358b52f7cf8d48a86c86ac0f8bf555
990
// // Extensions+UITableView.swift // Pods-Swift-Utils_Example // // Created by Amritpal Singh on 3/5/19. // import Foundation extension UITableView { public func indexPath(for view: UIView) -> IndexPath? { let location = view.convert(CGPoint.zero, to: self) return self.indexPathForRow(at: location) } public func handleEmptyTable(text: String?) { if text == nil { self.backgroundView = nil } else { let backGroundView = UIView() let noDataLbl = UILabel() noDataLbl.frame = CGRect(x: 10, y: 20, width: self.bounds.width - 20, height: self.bounds.height) noDataLbl.textAlignment = .center noDataLbl.textColor = UIColor.black noDataLbl.text = text noDataLbl.numberOfLines = 0 backGroundView.addSubview(noDataLbl) self.backgroundView = backGroundView } } }
26.756757
109
0.577778
d7a53890647646681dd9a0d2b7a23887a5e6bd6a
1,630
// // ActionCell.swift // Sample App Customers // // Created by Shopify. // Copyright (c) 2016 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class ActionCell: UITableViewCell { @IBOutlet private weak var actionLabel: UILabel! @IBOutlet private weak var loader: UIActivityIndicatorView! var loading: Bool { get { return self.actionLabel.isHidden } set { self.actionLabel.isHidden = newValue self.loader.isHidden = !newValue } } }
36.222222
81
0.707975
fef0738389bc6017df20bd23c5d01c920cfce34f
1,737
// // EntityTwitterUser.swift // iLike // // Created by HongQuan on 2018/06/02. // Copyright © 2018年 Roan.Hong. All rights reserved. // import Foundation //import RealmSwift final class EntityTwitterUser { @objc dynamic var id = "" @objc dynamic var name = "" @objc dynamic var screenName = "" @objc dynamic var imageURL = "" // override static func primaryKey() -> String? { // return "id" // } } extension EntityTwitterUser { convenience init(_ user: TwitterUser) { self.init() self.id = user.id self.name = user.name self.screenName = user.screenName self.imageURL = user.profileImageURLString } //static func findAll() -> Results<EntityTwitterUser> { static func findAll() { //return Realms.realm.objects(EntityTwitterUser.self).sorted(byKeyPath: "createdAt") } static func find(byId userId: String) -> EntityTwitterUser? { //return Realms.realm.object(ofType: EntityTwitterUser.self, forPrimaryKey: userId) return nil } //static func find(byIds userIds: [String]) -> Results<EntityTwitterUser> { static func find(byIds userIds: [String]) { //return Realms.realm.objects(EntityTwitterUser.self).filter("id IN %@", userIds) } static func delete(userId: String) { // Realms.commit { (realm) in // guard let user = realm.object(ofType: EntityTwitterUser.self, forPrimaryKey: userId) else { // return // } // realm.delete(user) // } } static func deleteAll() { // Realms.commit { (realm) in // realm.delete(realm.objects(EntityTwitterUser.self)) // } } }
28.016129
105
0.60852
7572f6ce5abac76d75d21fdbec331572bac9b4d8
481
import Foundation /// Swaps elements of the array (in-place). /// /// - Parameter input: An array to swap the elements. /// - Parameter a: An index of an element to swap. /// - Parameter b: An index of an element to swap. public func swap(_ input: inout [Int], _ a: Int, _ b: Int) { // No-op when indexes are the equal if a == b { return } // Copy values from elements let x = input[a], y = input[b] // Swap values of elements input[a] = y; input[b] = x }
30.0625
60
0.621622
efa8470375c2d2f4b0002dad65c5bc65fa587baa
1,178
// // DownloadService.swift // UITableViewSwift // // Created by Павел Нехорошкин on 28/01/2020. // Copyright © 2020 Павел Нехорошкин. All rights reserved. // import Foundation /// Ошибки загрузки /// /// - downloadError: ошибка загрузки, содержит Error c описанием. /// - unknown: данные не были получены, но описание ошибки отсутствует enum DownloadError : Error { case downloadError(Error) case unknown(String) } /// Класс для загрузи данных final class DownloadService { private let url = "https://pokeapi.co/api/v2/pokemon?limit=1500" /// Выполнить запрос по url /// /// - Parameter completionHandler: замыкание, вызываемое в background после завершения загрузки func downloadList(completionHandler: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) { let configuration = URLSessionConfiguration.default let session = URLSession(configuration: configuration) guard let url = URL(string: url) else { return } let task = session.dataTask(with: url, completionHandler: completionHandler) task.resume() } }
28.047619
120
0.667233
d77924e05daf3e87fd6b677570b64898b7902faf
6,292
// // CategoryProvider.swift // GetTodo // // Created by Batuhan Göbekli on 21.11.2020. // Copyright © 2020 Batuhan Göbekli. All rights reserved. // import Foundation import RealmSwift /// Category Provider ( Table Data Gateway and Row Data Gateway) manages Category Domain objects class CategoryProvider { private static let adapter = RealmAdapter<CategoryModel>() static let shared = CategoryProvider() /// Returns all categories /// /// - Returns: Array of categories recorded to realm static func categories() -> [CategoryItem] { return adapter.objects()?.map({$0.toItem}) ?? [] } /// Returns category by its primary key /// /// - Parameter identifier: primary key of category /// - Returns: Optional CategoryItem instance static func category(for identifier: String) -> CategoryItem? { return categoryModel(for: identifier)?.toItem } /// Returns task count of selected category /// /// - Parameter categoryId: primary key of category /// - Returns: count of tasks by selected category static func getCategoryTaskCount(categoryId:String) -> Int { return TaskProvider.tasks(categoryId: categoryId).count } /// Creates category in realm by given categoryItem /// /// - Parameter categoryItem: category item object to create static func create(with categoryItem: CategoryItem) { if categoryModel(for: categoryItem.identifier) != nil{ return } guard (try? adapter.create(["identifier": categoryItem.identifier,"name":categoryItem.name,"imageString":categoryItem.imageString,"hexColorString":categoryItem.hexColorString])) != nil else { fatalError("RealmObjectAdapter failed to create Object. Please check Realm configuration.") } } /// Updates category model in database with category item /// /// - Parameter category: category item object to update static func update(category: CategoryItem) { guard let model = categoryModel(for: category.identifier) else { return } try? RealmService.write { model.name = category.name model.imageString = category.imageString model.hexColorString = category.hexColorString } } /// Deletes category model in database with category item /// /// - Parameter user: category item object to delete static func remove(category: CategoryItem) { guard let model = categoryModel(for: category.identifier) else { return } try? RealmService.remove(model) } } extension CategoryProvider { /// Creates notification token for changes in user list /// /// - Parameter onDidChange: completion closure called on change /// - Returns: returns notification token which has to be stored as strong reference static func token(_ onDidChange: @escaping ()->() ) -> NotificationToken? { return adapter.objects()?.observe({ (change) in switch change { case .update: onDidChange() default: break } }) } /// Creates notification token for changes in specified category /// /// - Parameter category: completion closure called on change /// - Parameter onDidChange: completion closure called on change /// - Returns: returns notification token which has to be stored as strong reference static func token(for category: CategoryItem, _ onDidChange: @escaping ()->() ) -> NotificationToken? { if let model = categoryModel(for: category.identifier) { return model.observe { (change) in switch change { case .change: onDidChange() case .deleted: break default: break } } } return nil } } extension CategoryProvider { /// Check and instantiate category model for given identifier(pk) /// /// - Parameter identifier: category pk to search /// - Returns: Optional category model if exist static func categoryModel(for identifier: String) -> CategoryModel? { return adapter.object(primaryKey: identifier) } } extension CategoryProvider { /// Creates category models in realm if not exist func createUserDummyCategories() { var travelCategory = CategoryItem() travelCategory.identifier = "1" travelCategory.imageString = "airplane" travelCategory.name = "Travel" travelCategory.hexColorString = "#f6e58d" CategoryProvider.create(with: travelCategory) var workCategory = CategoryItem() workCategory.identifier = "2" workCategory.imageString = "briefcase.fill" workCategory.name = "Work" workCategory.hexColorString = "#3f4996" CategoryProvider.create(with: workCategory) var musicCategory = CategoryItem() musicCategory.identifier = "3" musicCategory.imageString = "music.note.list" musicCategory.name = "Music" musicCategory.hexColorString = "#ff7979" CategoryProvider.create(with: musicCategory) var homeCategory = CategoryItem() homeCategory.identifier = "4" homeCategory.imageString = "house.fill" homeCategory.name = "Home" homeCategory.hexColorString = "#badc58" CategoryProvider.create(with: homeCategory) var studyCategory = CategoryItem() studyCategory.identifier = "5" studyCategory.imageString = "pencil" studyCategory.name = "Study" studyCategory.hexColorString = "#dff9fb" CategoryProvider.create(with: studyCategory) var shopCategory = CategoryItem() shopCategory.identifier = "6" shopCategory.imageString = "cart.fill.badge.plus" shopCategory.name = "Shoppping" shopCategory.hexColorString = "#7ed6df" CategoryProvider.create(with: shopCategory) var artCategory = CategoryItem() artCategory.identifier = "7" artCategory.imageString = "paintbrush.fill" artCategory.name = "Art" artCategory.hexColorString = "#e056fd" CategoryProvider.create(with: artCategory) } }
35.348315
199
0.648601
f91ae3a657f302e6e3ec4057b93fc620e01a559e
342
// // File.swift // // // Created by Yaroslav Zhurakovskiy on 02.12.2019. // import UIKit class UITextFieldSpy: UITextField { var numberOfBecomeFirstResponderCalls = 0 override func becomeFirstResponder() -> Bool { numberOfBecomeFirstResponderCalls += 1 return super.becomeFirstResponder() } }
18
51
0.663743
de4feb1fa516b8d6f0f99a68bb0aa466d048844f
238
// 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<T where I.B == b() let t: NSObject { d<D> Void>(t: B<f = .d
29.75
87
0.710084
d992b868be0f9438eecfad8815bb930de3c209ce
5,446
// // EasyPay.swift // BraspagApplePaySdk // // Created by Jeferson Nazario on 29/09/19. // Copyright © 2019 jnazario.com. All rights reserved. // import Foundation import PassKit @objc public class BraspagApplePay: NSObject, BraspagApplePayProtocol { var currencyCode, countryCode, merchantId: String! weak var delegate: BraspagApplePayViewControllerDelegate! @objc init(currencyCode: String = "BRL", countryCode: String = "BR", merchantId: String, delegate: BraspagApplePayViewControllerDelegate) { self.currencyCode = currencyCode self.countryCode = countryCode self.merchantId = merchantId self.delegate = delegate } public static func createInstance(merchantId: String, currencyCode: String = "BRL", countryCode: String = "BR", viewDelegate: BraspagApplePayViewControllerDelegate) -> BraspagApplePayProtocol { return BraspagApplePay(currencyCode: currencyCode, countryCode: countryCode, merchantId: merchantId, delegate: viewDelegate) } @objc public func makePayment(itemDescription: String, amount: Double, contactInfo: ContactInfo? = nil) { let paymentItem = PKPaymentSummaryItem(label: itemDescription, amount: NSDecimalNumber(value: amount)) let paymentNetworks = getAllowedPaymentNetwork() let requiredFields = Set<PKContactField>(arrayLiteral: PKContactField.name, PKContactField.emailAddress, PKContactField.postalAddress, PKContactField.phoneNumber) guard PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks) else { delegate.displayAlert(title: "Error", message: "Unable to make Apple Pay transaction.") return } let request = PKPaymentRequest() request.currencyCode = currencyCode request.countryCode = countryCode request.merchantIdentifier = merchantId request.merchantCapabilities = PKMerchantCapability.capability3DS request.supportedNetworks = paymentNetworks request.paymentSummaryItems = [paymentItem] if let contact = contactInfo { request.requiredBillingContactFields = requiredFields request.requiredShippingContactFields = requiredFields request.billingContact = createContactAddress(contactInfo: contact) request.shippingContact = createContactAddress(contactInfo: contact, isShippingAddress: true) } guard let paymentVC = PKPaymentAuthorizationViewController(paymentRequest: request) else { delegate.displayAlert(title: "Error", message: "Unable to present Apple Pay authorization.") return } paymentVC.delegate = self delegate.presentAuthorizationViewController(viewController: paymentVC) } fileprivate func createContact(contactInfo: ContactInfo) -> PKContact { var fullName = PersonNameComponents() fullName.givenName = contactInfo.firstname fullName.familyName = contactInfo.lastname let contact = PKContact() contact.name = fullName contact.emailAddress = contactInfo.email if let phone = contactInfo.phoneNumber { contact.phoneNumber = CNPhoneNumber(stringValue: phone) } return contact } fileprivate func createMutableAddress(addressInfo: AddressInfo) -> CNMutablePostalAddress { let address = CNMutablePostalAddress() address.street = addressInfo.street address.state = addressInfo.state address.city = addressInfo.city address.postalCode = addressInfo.postalCode return address } fileprivate func createContactAddress(contactInfo: ContactInfo, isShippingAddress: Bool = false) -> PKContact { let contact = createContact(contactInfo: contactInfo) guard let addressInfo = contactInfo.billingAddress else { return contact } contact.postalAddress = createMutableAddress(addressInfo: addressInfo) if isShippingAddress { guard let addressInfo = contactInfo.shippingAddress else { return contact } contact.postalAddress = createMutableAddress(addressInfo: addressInfo) } return contact } } extension BraspagApplePay: PKPaymentAuthorizationViewControllerDelegate { @objc public func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) { debugPrint(#function) delegate.dismissPaymentAuthorizationViewController() } @objc public func paymentAuthorizationViewController( _ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) { debugPrint(#function) delegate.dismissPaymentAuthorizationViewController() delegate.displayAlert(title: "Success!", message: "The Apple Pay transaction was complete.") } }
41.892308
119
0.659567
03eff7e1dfcb83b54c60ceae55f1f6a200aaf03d
3,670
// // VolumeViewController.swift // MusicPimp // // Created by Michael Skogberg on 10/01/16. // Copyright © 2016 Skogberg Labs. All rights reserved. // import Foundation import RxSwift fileprivate extension Selector { static let volumeChanged = #selector(VolumeViewController.userDidChangeVolume(_:)) static let cancelClicked = #selector(VolumeViewController.backClicked(_:)) } class VolumeViewController: PimpViewController { let lowVolumeButton = UIButton() let highVolumeButton = UIButton() let volumeSlider = UISlider() var appearedBag = DisposeBag() var player: PlayerType { get { PlayerManager.sharedInstance.active } } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "SET VOLUME" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: .cancelClicked) initUI() updateVolume() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateVolume() listenWhenAppeared(player) } func initUI() { addSubviews(views: [lowVolumeButton, volumeSlider, highVolumeButton]) installFaImage("fa-volume-down", button: lowVolumeButton) lowVolumeButton.snp.makeConstraints { (make) in make.leadingMargin.equalToSuperview() make.centerY.equalToSuperview() } volumeSlider.addTarget(self, action: .volumeChanged, for: .valueChanged) volumeSlider.snp.makeConstraints { (make) in make.leading.equalTo(lowVolumeButton.snp.trailing).offset(8) make.trailing.equalTo(highVolumeButton.snp.leading).offset(-8) make.centerY.equalToSuperview() } installFaImage("fa-volume-up", button: highVolumeButton) highVolumeButton.snp.makeConstraints { (make) in make.trailingMargin.equalToSuperview() make.centerY.equalToSuperview() } } func updateVolume() { volumeSlider.value = sliderValue(player.current().volume) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) unlistenWhenDisappeared() } func installFaImage(_ name: String, button: UIButton) { button.setTitle("", for: UIControl.State()) button.setImage(faImage(name), for: UIControl.State()) } func faImage(_ name: String) -> UIImage { UIImage(icon: name, backgroundColor: UIColor.clear, iconColor: PimpColors.shared.tintColor, fontSize: 28) } @objc func userDidChangeVolume(_ sender: UISlider) { let percent = sender.value / (sender.maximumValue - sender.minimumValue) let volume = VolumeValue(volume: Int(100.0 * percent)) _ = player.volume(volume) } @objc func backClicked(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } fileprivate func onVolumeChanged(_ volume: VolumeValue) { let value = sliderValue(volume) Util.onUiThread { self.volumeSlider.value = value } } func sliderValue(_ volume: VolumeValue) -> Float { volume.toFloat() * (volumeSlider.maximumValue - volumeSlider.minimumValue) } fileprivate func listenWhenAppeared(_ targetPlayer: PlayerType) { unlistenWhenDisappeared() targetPlayer.volumeEvent.subscribe(onNext: { (vol) in self.onVolumeChanged(vol) }).disposed(by: appearedBag) } fileprivate func unlistenWhenDisappeared() { appearedBag = DisposeBag() } }
33.063063
125
0.659401
674022e0165b753c364e0f396665a53f4839d6b3
93
#!/usr/bin/swift /* Even though the shebang is set, this file is actually not executable. */
31
75
0.72043
618936ce7beb7cd19b8361b5852a1e8a12b73aa4
3,632
// // DefaultPatternChoices.swift // Arrow // // Created by David Williams on 12/2/20. // Copyright © 2020 David Williams. All rights reserved. // // // 0 1 2 // 3 4 5 6 7 8 // 9 10 11 12 13 14 15 // 16 17 18 19 20 21 // 22 23 24 // struct DefaultPatterns { static let choices = [ ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- - -- ---> 0b0000000000000000011000000000, 0b0000000000000011111000000000, 0b0001001000001011111100000100, 0b0000000000000000000000000000, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- - -- <--- 0b0000000000001100000000000000, 0b0000000000001111100000000000, 0b0000010000011111101000001001, 0b0000000000000000000000000000, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- -> --> ---> 0b0000010000100000111000010001, 0b0000100010000010111001000010, 0b0001001000001011111100000100, 0b0000000000000000000000000000, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- <- <-- <--- 0b0001000100001110000010000100, 0b0000100001001110100000100010, 0b0000010000011111101000001001, 0b0000000000000000000000000000, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- > >> >>> 0b0000010000100000100000010001, 0b0000110010100010100001010011, 0b0001111010101010100101010111, 0b0000000000000000000000000000, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- < << <<< 0b0001000100000010000010000100, 0b0001100101000010100010100110, 0b0001110101010010101010101111, 0b0000000000000000000000000000, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- <> <> 0b0000010000110000101000011001, 0b0001001100001010000110000100, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- --> flash 0b0001001000001011111100000100, 0b0000000000000000000000000000, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- <-- flash 0b0000010000011111101000001001, 0b0000000000000000000000000000, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- <-> flash 0b0001011000011011101100001101, 0b0000000000000000000000000000, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- : : flash 0b0001010000000000000000000101, 0b0000000000000000000000000000, ]), ArrowPattern(frames: [ // 24 20 16 12 8 4 0 //----....----....----....---- ---- flash 0b0000000000001111111000000000, 0b0000000000000000000000000000, ]), ] }
34.590476
57
0.449615
f7e00751d80af34e655bf6812d5152b0e7fa5aa9
1,248
// // FirstViewController.swift // FontChangeApp // // Created by Civel Xu on 2020/4/26. // Copyright © 2020 Civel Xu. All rights reserved. // import UIKit class FirstViewController: UIViewController { @IBOutlet weak var label: UILabel! @IBOutlet weak var button: UIButton! @IBOutlet weak var textFiled: UITextField! @IBOutlet weak var textView: UITextView! deinit { label.dispose() button.dispose() textFiled.dispose() textView.dispose() print("\(String(describing: type(of: self))) - deinit") } override func viewDidLoad() { super.viewDidLoad() label.bindFont(style: .title1) button.bindFont(style: .title3) textFiled.bindFont(style: .headline) textView.bindFont(style: .caption2) NotificationCenter.default.addObserver(self, selector: #selector(fontChanged(notify:)), name: .fontScaleDidChange, object: nil) } @objc func fontChanged(notify: Notification) { guard let object = notify.object as? [String : FontTypeSizes] else { return } guard let style = object[FontTextManage.FontSizeStyleKey] else { return } debugPrint("FirstViewController fontChanged style - \(style)") } }
28.363636
135
0.66266
1d8ff3cfad2b9d82506f3e8ccd3f9216b597f697
2,618
// // AppDelegate.swift // Lookingforme // // Created by Elen on 22/02/2019. // Copyright © 2019 Winston. All rights reserved. // import UIKit import SVProgressHUD import MMModuleManager @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. SVProgressHUD.setDefaultMaskType(.clear) if let launchOptions = launchOptions, let url = launchOptions[.url] as? URL { ShareUtil.shared.openRoute(file: url) } return true } private func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { ShareUtil.shared.openRoute(file: url) 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:. } }
46.75
285
0.739496
561ea6c441d572bff672dc42b46edace8aa3c2fe
7,944
// // CipherChaCha20Tests.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 27/12/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // import XCTest @testable import CryptoSwift final class ChaCha20Tests: XCTestCase { func testChaCha20() { let keys: [Array<UInt8>] = [ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F], ] let ivs: [Array<UInt8>] = [ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07], ] let expectedHexes = [ "76B8E0ADA0F13D90405D6AE55386BD28BDD219B8A08DED1AA836EFCC8B770DC7DA41597C5157488D7724E03FB8D84A376A43B8F41518A11CC387B669B2EE6586", "4540F05A9F1FB296D7736E7B208E3C96EB4FE1834688D2604F450952ED432D41BBE2A0B6EA7566D2A5D1E7E20D42AF2C53D792B1C43FEA817E9AD275AE546963", "DE9CBA7BF3D69EF5E786DC63973F653A0B49E015ADBFF7134FCB7DF137821031E85A050278A7084527214F73EFC7FA5B5277062EB7A0433E445F41E3", "EF3FDFD6C61578FBF5CF35BD3DD33B8009631634D21E42AC33960BD138E50D32111E4CAF237EE53CA8AD6426194A88545DDC497A0B466E7D6BBDB0041B2F586B", "F798A189F195E66982105FFB640BB7757F579DA31602FC93EC01AC56F85AC3C134A4547B733B46413042C9440049176905D3BE59EA1C53F15916155C2BE8241A38008B9A26BC35941E2444177C8ADE6689DE95264986D95889FB60E84629C9BD9A5ACB1CC118BE563EB9B3A4A472F82E09A7E778492B562EF7130E88DFE031C79DB9D4F7C7A899151B9A475032B63FC385245FE054E3DD5A97A5F576FE064025D3CE042C566AB2C507B138DB853E3D6959660996546CC9C4A6EAFDC777C040D70EAF46F76DAD3979E5C5360C3317166A1C894C94A371876A94DF7628FE4EAAF2CCB27D5AAAE0AD7AD0F9D4B6AD3B54098746D4524D38407A6DEB3AB78FAB78C9", ] for idx in 0 ..< keys.count { let expectedHex = expectedHexes[idx] let message = Array<UInt8>(repeating: 0, count: (expectedHex.characters.count / 2)) do { let encrypted = try message.encrypt(cipher: ChaCha20(key: keys[idx], iv: ivs[idx])) let decrypted = try encrypted.decrypt(cipher: ChaCha20(key: keys[idx], iv: ivs[idx])) XCTAssertEqual(message, decrypted, "ChaCha20 decryption failed") XCTAssertEqual(encrypted, Array<UInt8>(hex: expectedHex)) } catch CipherError.encrypt { XCTAssert(false, "Encryption failed") } catch CipherError.decrypt { XCTAssert(false, "Decryption failed") } catch { XCTAssert(false, "Failed") } } } func testCore() { let key: Array<UInt8> = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] var counter: Array<UInt8> = [1,0,0,0,0,0,0,9,0,0,0,74,0,0,0,0] let input = Array<UInt8>.init(repeating: 0, count: 129) let chacha = try! ChaCha20(key: key, iv: Array(key[4..<16])) let result = chacha.process(bytes: input, counter: &counter, key: key) XCTAssertEqual(result.toHexString(), "10f1e7e4d13b5915500fdd1fa32071c4c7d1f4c733c068030422aa9ac3d46c4ed2826446079faa0914c2d705d98b02a2b5129cd1de164eb9cbd083e8a2503c4e0a88837739d7bf4ef8ccacb0ea2bb9d69d56c394aa351dfda5bf459f0a2e9fe8e721f89255f9c486bf21679c683d4f9c5cf2fa27865526005b06ca374c86af3bdc") } func testVector1Py() { let key: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] let iv: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] let expected: Array<UInt8> = [0x76, 0xB8, 0xE0, 0xAD, 0xA0, 0xF1, 0x3D, 0x90, 0x40, 0x5D, 0x6A, 0xE5, 0x53, 0x86, 0xBD, 0x28, 0xBD, 0xD2, 0x19, 0xB8, 0xA0, 0x8D, 0xED, 0x1A, 0xA8, 0x36, 0xEF, 0xCC, 0x8B, 0x77, 0x0D, 0xC7, 0xDA, 0x41, 0x59, 0x7C, 0x51, 0x57, 0x48, 0x8D, 0x77, 0x24, 0xE0, 0x3F, 0xB8, 0xD8, 0x4A, 0x37, 0x6A, 0x43, 0xB8, 0xF4, 0x15, 0x18, 0xA1, 0x1C, 0xC3, 0x87, 0xB6, 0x69, 0xB2, 0xEE, 0x65, 0x86] let message = Array<UInt8>(repeating: 0, count: expected.count) do { let encrypted = try ChaCha20(key: key, iv: iv).encrypt(message) XCTAssertEqual(encrypted, expected, "Ciphertext failed") } catch { XCTFail() } } func testChaCha20EncryptPartial() { let key: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F] let iv: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07] let expectedHex = "F798A189F195E66982105FFB640BB7757F579DA31602FC93EC01AC56F85AC3C134A4547B733B46413042C9440049176905D3BE59EA1C53F15916155C2BE8241A38008B9A26BC35941E2444177C8ADE6689DE95264986D95889FB60E84629C9BD9A5ACB1CC118BE563EB9B3A4A472F82E09A7E778492B562EF7130E88DFE031C79DB9D4F7C7A899151B9A475032B63FC385245FE054E3DD5A97A5F576FE064025D3CE042C566AB2C507B138DB853E3D6959660996546CC9C4A6EAFDC777C040D70EAF46F76DAD3979E5C5360C3317166A1C894C94A371876A94DF7628FE4EAAF2CCB27D5AAAE0AD7AD0F9D4B6AD3B54098746D4524D38407A6DEB3AB78FAB78C9" let plaintext: Array<UInt8> = Array<UInt8>(repeating: 0, count: (expectedHex.characters.count / 2)) do { let cipher = try ChaCha20(key: key, iv: iv) var ciphertext = Array<UInt8>() var encryptor = cipher.makeEncryptor() ciphertext += try encryptor.update(withBytes: Array(plaintext[0 ..< 8])) ciphertext += try encryptor.update(withBytes: Array(plaintext[8 ..< 16])) ciphertext += try encryptor.update(withBytes: Array(plaintext[16 ..< 80])) ciphertext += try encryptor.update(withBytes: Array(plaintext[80 ..< 256])) ciphertext += try encryptor.finish() XCTAssertEqual(Array<UInt8>(hex: expectedHex), ciphertext) } catch { XCTFail() } } func testChaCha20Performance() { let key: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F] let iv: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07] let message = Array<UInt8>(repeating: 7, count: 1024) measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in do { let _ = try ChaCha20(key: key, iv: iv).encrypt(message) } catch { XCTFail() } self.stopMeasuring() }) } }
68.482759
540
0.674975