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
de87501b1578784a7be78affbcd692d7d480bdc5
1,160
// // SettingViewHeaderViewModel.swift // AlphaWallet // // Created by Vladyslav Shepitko on 02.06.2020. // import UIKit struct SettingViewHeaderViewModel { let titleText: String var detailsText: String? var titleTextFont: UIFont var showTopSeparator: Bool = true var titleTextColor: UIColor { return R.color.dove()! } var detailsTextColor: UIColor { return R.color.dove()! } var detailsTextFont: UIFont { return Fonts.regular(size: 13)! } var backgroundColor: UIColor { return R.color.alabaster()! } var separatorColor: UIColor { return R.color.mercury()! } } extension SettingViewHeaderViewModel { init(section: SettingsSection) { titleText = section.title switch section { case .tokenStandard(let value), .version(let value): detailsText = value titleTextFont = Fonts.regular(size: 15)! if case .tokenStandard = section { showTopSeparator = false } case .wallet, .system, .help: titleTextFont = Fonts.semibold(size: 15)! } } }
22.745098
60
0.610345
16218a701f315e2cb92766f27660116ef36d4b5f
1,973
// // DelaySubscription.swift // RxSwift // // Created by Krunoslav Zaher on 6/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) - parameter dueTime: Relative time shift of the subscription. - parameter scheduler: Scheduler to run the subscription delay timer on. - returns: Time-shifted sequence. */ public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType) -> Observable<E> { return DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) } } final private class DelaySubscriptionSink<O: ObserverType> : Sink<O>, ObserverType { typealias E = O.E func on(_ event: Event<E>) { self.forwardOn(event) if event.isStopEvent { self.dispose() } } } final private class DelaySubscription<Element>: Producer<Element> { private let _source: Observable<Element> private let _dueTime: RxTimeInterval private let _scheduler: SchedulerType init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) { self._source = source self._dueTime = dueTime self._scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = DelaySubscriptionSink(observer: observer, cancel: cancel) let subscription = self._scheduler.scheduleRelative((), dueTime: self._dueTime) { _ in return self._source.subscribe(sink) } return (sink: sink, subscription: subscription) } }
33.440678
157
0.685251
3901cb43b589ab70fd7b10597ef75e55fda1d807
34,276
// RUN: %target-swift-frontend -swift-version 5 -emit-sil -primary-file %s -Xllvm -sil-print-after=OSLogOptimization -o /dev/null 2>&1 | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // RUN: %target-swift-frontend -enable-ownership-stripping-after-serialization -swift-version 5 -emit-sil -primary-file %s -Xllvm -sil-print-after=OSLogOptimization -o /dev/null 2>&1 | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos // Tests for the OSLogOptimization pass that performs compile-time analysis // and optimization of the new os log prototype APIs. The tests here check // whether specific compile-time constants such as the format string, // the size of the byte buffer etc. are literals after the mandatory pipeline. import OSLogPrototype import Foundation if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { // CHECK-LABEL: @${{.*}}testSimpleInterpolationL_ func testSimpleInterpolation(h: Logger) { h.log(level: .debug, "Minimum integer value: \(Int.min)") // Check if there is a call to _os_log_impl with a literal format string. // CHECK-DAG is used here as it is easier to perform the checks backwards // from uses to the definitions. // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // We need to wade through some borrows and copy values here. // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-64-DAG: [[LIT]] = string_literal utf8 "Minimum integer value: %{public}lld" // CHECK-32-DAG: [[LIT]] = string_literal utf8 "Minimum integer value: %{public}d" // Check if the size of the argument buffer is a constant. // CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ // CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]] // CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 12 // CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 8 // Check whether the header bytes: premable and argument count are constants. // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0 // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 1 // Check whether argument array is folded. We need not check the contents of // the array which is checked by a different test suite. // CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF // CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>>({{%.*}}, [[ARGSARRAYADDR:%[0-9]+]]) // CHECK-DAG: store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR]] // We need to wade through some borrows and copy values here. // CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[ARGSARRAY:%[0-9]+]] // CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]] // CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>([[ARRAYSIZE:%[0-9]+]]) // CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 3 } // CHECK-LABEL: @${{.*}}testInterpolationWithFormatOptionsL_ func testInterpolationWithFormatOptions(h: Logger) { h.log(level: .info, "Maximum integer value: \(Int.max, format: .hex)") // Check if there is a call to _os_log_impl with a literal format string. // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-64-DAG: [[LIT]] = string_literal utf8 "Maximum integer value: %{public}llx" // CHECK-32-DAG: [[LIT]] = string_literal utf8 "Maximum integer value: %{public}x" // Check if the size of the argument buffer is a constant. // CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ // CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]] // CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 12 // CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 8 // Check whether the header bytes: premable and argument count are constants. // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0 // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 1 // Check whether argument array is folded. We need not check the contents of // the array which is checked by a different test suite. // CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF // CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>>({{%.*}}, [[ARGSARRAYADDR:%[0-9]+]]) // CHECK-DAG: store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR]] // CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[ARGSARRAY:%[0-9]+]] // CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]] // CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>([[ARRAYSIZE:%[0-9]+]]) // CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 3 } // CHECK-LABEL: @${{.*}}testInterpolationWithFormatOptionsAndPrivacyL_ func testInterpolationWithFormatOptionsAndPrivacy(h: Logger) { let privateID = 0x79abcdef h.log( level: .error, "Private Identifier: \(privateID, format: .hex, privacy: .private)") // Check if there is a call to _os_log_impl with a literal format string. // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-64-DAG: [[LIT]] = string_literal utf8 "Private Identifier: %{private}llx" // CHECK-32-DAG: [[LIT]] = string_literal utf8 "Private Identifier: %{private}x" // Check if the size of the argument buffer is a constant. // CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ // CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]] // CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 12 // CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 8 // Check whether the header bytes: premable and argument count are constants. // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 1 // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 1 // Check whether argument array is folded. We need not check the contents of // the array which is checked by a different test suite. // CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF // CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>>({{%.*}}, [[ARGSARRAYADDR:%[0-9]+]]) // CHECK-DAG: store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR]] // CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[ARGSARRAY:%[0-9]+]] // CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]] // CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>([[ARRAYSIZE:%[0-9]+]]) // CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 3 } // CHECK-LABEL: @${{.*}}testInterpolationWithMultipleArgumentsL_ func testInterpolationWithMultipleArguments(h: Logger) { let privateID = 0x79abcdef let filePermissions = 0o777 let pid = 122225 h.log( level: .error, """ Access prevented: process \(pid) initiated by \ user: \(privateID, privacy: .private) attempted resetting \ permissions to \(filePermissions, format: .octal) """) // Check if there is a call to _os_log_impl with a literal format string. // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-64-DAG: [[LIT]] = string_literal utf8 "Access prevented: process %{public}lld initiated by user: %{private}lld attempted resetting permissions to %{public}llo" // CHECK-32-DAG: [[LIT]] = string_literal utf8 "Access prevented: process %{public}d initiated by user: %{private}d attempted resetting permissions to %{public}o" // Check if the size of the argument buffer is a constant. // CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ // CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]] // CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 32 // CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 20 // Check whether the header bytes: premable and argument count are constants. // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 1 // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 3 // Check whether argument array is folded. We need not check the contents of // the array which is checked by a different test suite. // CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF // CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>>({{%.*}}, [[ARGSARRAYADDR:%[0-9]+]]) // CHECK-DAG: store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR]] // CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[ARGSARRAY:%[0-9]+]] // CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]] // CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>([[ARRAYSIZE:%[0-9]+]]) // CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 9 } // CHECK-LABEL: @${{.*}}testLogMessageWithoutDataL_ func testLogMessageWithoutData(h: Logger) { // FIXME: here `ExpressibleByStringLiteral` conformance of OSLogMessage // is used. In this case, the constant evaluation begins from the apply of // the "string.makeUTF8: initializer. The constant evaluator ends up using // the backward mode to identify the string_literal inst passed to the // initializer. Eliminate reliance on this backward mode by starting from // the string_literal inst, instead of initialization instruction. h.log("A message with no data") // Check if there is a call to _os_log_impl with a literal format string. // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-DAG: [[LIT]] = string_literal utf8 "A message with no data" // Check if the size of the argument buffer is a constant. // CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ // CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]] // CHECK-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int{{[0-9]+}}, 2 // Check whether the header bytes: premable and argument count are constants. // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0 // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 0 // Check whether argument array is folded. // CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF // CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>>({{%.*}}, [[ARGSARRAYADDR:%[0-9]+]]) // CHECK-DAG: store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR]] // CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[ARGSARRAY:%[0-9]+]] // CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]] // CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>([[ARRAYSIZE:%[0-9]+]]) // CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 0 } // CHECK-LABEL: @${{.*}}testEscapingOfPercentsL_ func testEscapingOfPercents(h: Logger) { h.log("Process failed after 99% completion") // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-DAG: [[LIT]] = string_literal utf8 "Process failed after 99%% completion" } // CHECK-LABEL: @${{.*}}testDoublePercentsL_ func testDoublePercents(h: Logger) { h.log("Double percents: %%") // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-DAG: [[LIT]] = string_literal utf8 "Double percents: %%%%" } // CHECK-LABEL: @${{.*}}testSmallFormatStringsL_ func testSmallFormatStrings(h: Logger) { h.log("a") // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-DAG: [[LIT]] = string_literal utf8 "a" } /// A stress test that checks whether the optimizer handle messages with more /// than 48 interpolated expressions. Interpolated expressions beyond this /// limit must be ignored. // CHECK-LABEL: @${{.*}}testMessageWithTooManyArgumentsL_ func testMessageWithTooManyArguments(h: Logger) { h.log( level: .error, """ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(48) \(49) """) // Check if there is a call to _os_log_impl with a literal format string. // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-64-DAG: [[LIT]] = string_literal utf8 "%{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld %{public}lld " // CHECK-32-DAG: [[LIT]] = string_literal utf8 "%{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d %{public}d " // Check if the size of the argument buffer is a constant. // CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ // CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]] // CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 482 // CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 290 // Check whether the header bytes: premable and argument count are constants. // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0 // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 48 // Check whether argument array is folded. // CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF // CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>>({{%.*}}, [[ARGSARRAYADDR:%[0-9]+]]) // CHECK-DAG: store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR]] // CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[ARGSARRAY:%[0-9]+]] // CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]] // CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>([[ARRAYSIZE:%[0-9]+]]) // CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 144 } // CHECK-LABEL: @${{.*}}testInt32InterpolationL_ func testInt32Interpolation(h: Logger) { h.log("32-bit integer value: \(Int32.min)") // Check if there is a call to _os_log_impl with a literal format string. // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-DAG: [[LIT]] = string_literal utf8 "32-bit integer value: %{public}d" // Check if the size of the argument buffer is a constant. // CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ // CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]] // CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 8 // CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 8 // Check whether the header bytes: premable and argument count are constants. // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 0 // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 1 } // CHECK-LABEL: @${{.*}}testDynamicStringArgumentsL_ func testDynamicStringArguments(h: Logger) { let concatString = "hello" + " - " + "world" let interpolatedString = "\(31) trillion digits of pi are known so far" h.log(""" concat: \(concatString, privacy: .public) \ interpolated: \(interpolatedString, privacy: .private) """) // Check if there is a call to _os_log_impl with a literal format string. // CHECK-DAG is used here as it is easier to perform the checks backwards // from uses to the definitions. // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-DAG: [[LIT]] = string_literal utf8 "concat: %{public}s interpolated: %{private}s" // Check if the size of the argument buffer is a constant. // CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ // CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]] // CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 22 // CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 14 // Check whether the header bytes: premable and argument count are constants. // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 3 // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 2 // Check whether argument array is folded. We need not check the contents of // the array which is checked by a different test suite. // CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF // CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>>({{%.*}}, [[ARGSARRAYADDR:%[0-9]+]]) // CHECK-DAG: store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR]] // CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[ARGSARRAY:%[0-9]+]] // CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]] // CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>([[ARRAYSIZE:%[0-9]+]]) // CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 6 } // CHECK-LABEL: @${{.*}}testNSObjectInterpolationL_ func testNSObjectInterpolation(h: Logger) { let nsArray: NSArray = [0, 1, 2] let nsDictionary: NSDictionary = [1 : ""] h.log(""" NSArray: \(nsArray, privacy: .public) \ NSDictionary: \(nsDictionary, privacy: .private) """) // Check if there is a call to _os_log_impl with a literal format string. // CHECK-DAG is used here as it is easier to perform the checks backwards // from uses to the definitions. // CHECK-DAG: builtin "globalStringTablePointer"([[STRING:%[0-9]+]] : $String) // CHECK-DAG: [[STRING]] = begin_borrow [[STRING2:%[0-9]+]] // CHECK-DAG: [[STRING2]] = copy_value [[STRING3:%[0-9]+]] // CHECK-DAG: [[STRING3]] = begin_borrow [[STRING4:%[0-9]+]] // CHECK-DAG: [[STRING4]] = apply [[STRING_INIT:%[0-9]+]]([[LIT:%[0-9]+]], // CHECK-DAG: [[STRING_INIT]] = function_ref @$sSS21_builtinStringLiteral17utf8CodeUnitCount7isASCIISSBp_BwBi1_tcfC // CHECK-DAG: [[LIT]] = string_literal utf8 "NSArray: %{public}@ NSDictionary: %{private}@" // Check if the size of the argument buffer is a constant. // CHECK-DAG: [[ALLOCATE:%[0-9]+]] = function_ref @$sSp8allocate8capacitySpyxGSi_tFZ // CHECK-DAG: apply [[ALLOCATE]]<UInt8>([[BUFFERSIZE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[BUFFERSIZE]] = struct $Int ([[BUFFERSIZELIT:%[0-9]+]] // CHECK-64-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int64, 22 // CHECK-32-DAG: [[BUFFERSIZELIT]] = integer_literal $Builtin.Int32, 14 // Check whether the header bytes: premable and argument count are constants. // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[PREAMBLE:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[PREAMBLE]] = struct $UInt8 ([[PREAMBLELIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[PREAMBLELIT]] = integer_literal $Builtin.Int8, 3 // CHECK-DAG: [[SERIALIZE:%[0-9]+]] = function_ref @$s14OSLogPrototype9serialize_2atys5UInt8V_SpyAEGztF // CHECK-DAG: apply [[SERIALIZE]]([[ARGCOUNT:%[0-9]+]], {{%.*}}) // CHECK-DAG: [[ARGCOUNT]] = struct $UInt8 ([[ARGCOUNTLIT:%[0-9]+]] : $Builtin.Int8) // CHECK-DAG: [[ARGCOUNTLIT]] = integer_literal $Builtin.Int8, 2 // Check whether argument array is folded. We need not check the contents of // the array which is checked by a different test suite. // CHECK-DAG: [[FOREACH:%[0-9]+]] = function_ref @$sSTsE7forEachyyy7ElementQzKXEKF // CHECK-DAG: try_apply [[FOREACH]]<Array<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>>({{%.*}}, [[ARGSARRAYADDR:%[0-9]+]]) // CHECK-DAG: store_borrow [[ARGSARRAY2:%[0-9]+]] to [[ARGSARRAYADDR]] // CHECK-DAG: [[ARGSARRAY2]] = begin_borrow [[ARGSARRAY3:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY3]] = copy_value [[ARGSARRAY4:%[0-9]+]] // CHECK-DAG: [[ARGSARRAY4]] = begin_borrow [[ARGSARRAY:%[0-9]+]] // CHECK-DAG: ([[ARGSARRAY]], {{%.*}}) = destructure_tuple [[ARRAYINITRES:%[0-9]+]] // CHECK-DAG: [[ARRAYINITRES]] = apply [[ARRAYINIT:%[0-9]+]]<(inout UnsafeMutablePointer<UInt8>, inout Array<AnyObject>) -> ()>([[ARRAYSIZE:%[0-9]+]]) // CHECK-DAG: [[ARRAYINIT]] = function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF // CHECK-DAG: [[ARRAYSIZE]] = integer_literal $Builtin.Word, 6 } // CHECK-LABEL: @${{.*}}testDeadCodeEliminationL_ func testDeadCodeElimination( h: Logger, number: Int, num32bit: Int32, string: String ) { h.log("A message with no data") h.log("smallstring") h.log( level: .error, """ A message with many interpolations \(number), \(num32bit), \(string), \ and a suffix """) h.log( level: .info, """ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(48) \(49) """) let concatString = string + ":" + String(number) h.log("\(concatString)") // CHECK-NOT: OSLogMessage // CHECK-NOT: OSLogInterpolation // CHECK-LABEL: end sil function '${{.*}}testDeadCodeEliminationL_ } }
61.536804
677
0.635547
e566d009033a24fa29a388d86b5f4bafc3d26a75
434
import Foundation import Path /// Constants used across the codebase public enum Constant { /// The default name for the stackgen file public static let stackGenFileName = "stackgen.yml" /// The version of the current StackGen binary public static let version = "0.0.4" /// The temporary directory to use, if needed public static let tmpDir: Path = Path(NSTemporaryDirectory())!.join("stackgen-\(version)") }
33.384615
94
0.71659
875d78a5e004b5a816d26328bf667ef8d0348db1
3,557
// // CollectionSyncUpTarget.swift // MobileSync // // Created by Wolfgang Mathurin on 5/26/22. // Copyright (c) 2022-present, salesforce.com, inc. All rights reserved. // // Redistribution and use of this software in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this list of conditions // and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to // endorse or promote products derived from this software without specific prior written // permission of salesforce.com, inc. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY // WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation import SalesforceSDKCore import Combine // // Subclass of SyncUpTarget that batches create/update/delete operations by using sobject collection apis // @objc(SFCollectionSyncUpTarget) public class CollectionSyncUpTarget: BatchSyncUpTarget { static let maxRecordsCollectionAPI:UInt = 200 override public class func build(dict: Dictionary<AnyHashable, Any>?) -> Self { return self.init(dict: dict ?? Dictionary()) } override public convenience init() { self.init(createFieldlist:nil, updateFieldlist:nil, maxBatchSize:nil) } override public convenience init(createFieldlist: Array<String>?, updateFieldlist: Array<String>?) { self.init(createFieldlist:createFieldlist, updateFieldlist:updateFieldlist, maxBatchSize:nil) } // Construct CollectionSyncUpTarget with a different maxBatchSize and id/modifiedDate/externalId fields override public init(createFieldlist: Array<String>?, updateFieldlist: Array<String>?, maxBatchSize:NSNumber?) { super.init(createFieldlist:createFieldlist, updateFieldlist:updateFieldlist, maxBatchSize: maxBatchSize) } // Construct SyncUpTarget from json override required public init(dict: Dictionary<AnyHashable, Any>) { super.init(dict: dict); } override func maxAPIBatchSize() -> UInt { return CollectionSyncUpTarget.maxRecordsCollectionAPI } override func sendRecordRequests(_ syncManager:SyncManager, recordRequests:Array<CompositeRequestHelper.RecordRequest>, onComplete: @escaping OnSendCompleteCallback, onFail: @escaping OnFailCallback) { CompositeRequestHelper.sendAsCollectionRequests(syncManager, allOrNone: false, recordRequests: recordRequests, onComplete: onComplete, onFail: onFail) } }
48.726027
158
0.754006
4b86e42094f8cc52a3f9b28a80c2b5815e64b7b5
2,892
// // Copyright 2021 New Vector Ltd // // 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 class LocationPlainCell: SizableBaseRoomCell, RoomCellReactionsDisplayable, RoomCellReadMarkerDisplayable { private var locationView: RoomTimelineLocationView! override func render(_ cellData: MXKCellData!) { super.render(cellData) guard #available(iOS 14.0, *), let bubbleData = cellData as? RoomBubbleCellData, let event = bubbleData.events.last, event.eventType == __MXEventType.roomMessage, let locationContent = event.location else { return } locationView.update(theme: ThemeService.shared().theme) locationView.locationDescription = locationContent.locationDescription let location = CLLocationCoordinate2D(latitude: locationContent.latitude, longitude: locationContent.longitude) let mapStyleURL = bubbleData.mxSession.vc_homeserverConfiguration().tileServer.mapStyleURL if locationContent.assetType == .user { let avatarViewData = AvatarViewData(matrixItemId: bubbleData.senderId, displayName: bubbleData.senderDisplayName, avatarUrl: bubbleData.senderAvatarUrl, mediaManager: bubbleData.mxSession.mediaManager, fallbackImage: .matrixItem(bubbleData.senderId, bubbleData.senderDisplayName)) locationView.displayLocation(location, userAvatarData: avatarViewData, mapStyleURL: mapStyleURL) } else { locationView.displayLocation(location, mapStyleURL: mapStyleURL) } } override func setupViews() { super.setupViews() roomCellContentView?.backgroundColor = .clear roomCellContentView?.showSenderInfo = true roomCellContentView?.showPaginationTitle = false guard #available(iOS 14.0, *), let contentView = roomCellContentView?.innerContentView else { return } locationView = RoomTimelineLocationView.loadFromNib() contentView.vc_addSubViewMatchingParent(locationView) } }
40.166667
126
0.645228
ccb37e45c26d52a66db17e128e2e492f3062e232
612
// // Video.swift // Movies&Tvs // // Created by Jesus on 9/24/18. // Copyright © 2018 Jesus Paraada. All rights reserved. // import Foundation import ObjectMapper let youtubeLink = "https://www.youtube.com/watch?v=" struct VideoList: Mappable { var list:[Video]? init?(map: Map) { } mutating func mapping(map: Map) { list <- map["results"] } } struct Video: Mappable { var videoPath:String? var type:String? init?(map: Map) { } mutating func mapping(map: Map) { videoPath <- map["key"] type <- map["type"] } }
16.105263
56
0.570261
019ebbca13c3a9e60efe9377ce9076c1f0aee8e0
2,443
// // CLDExplicitRequest.swift // // Copyright (c) 2016 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** The `CLDExplodeRequest` object is returned when creating an explode request. It allows the options to add a response closure to be called once the request has finished, as well as performing actions on the request, such as cancelling, suspending or resuming it. */ @objc open class CLDExplicitRequest: CLDRequest { /** Set a response closure to be called once the request has finished. - parameter completionHandler: The closure to be called once the request has finished, holding either the response object or the error. - returns: The same instance of CLDExplicitRequest. */ @discardableResult open func response(_ completionHandler: ((_ result: CLDExplicitResult?, _ error: NSError?) -> ())?) -> CLDExplicitRequest { responseRaw { (response, error) in if let res = response as? [String : AnyObject] { completionHandler?(CLDExplicitResult(json: res), nil) } else if let err = error { completionHandler?(nil, err) } else { completionHandler?(nil, CLDError.generalError()) } } return self } }
42.12069
145
0.683586
e8b2eed88a4bdfd6ae038b1f6d6d32300ace2567
1,053
// // MKActivityIndicatorView.swift // MKProgress // // Created by Muhammad Kamran on 3/29/17. // Copyright © 2017 Muhammad Kamran. All rights reserved. // import UIKit class MKActivityIndicatorView: MKProgressBaseView { let activityIndicatorView: UIActivityIndicatorView = { let config = MKProgress.config let activity = UIActivityIndicatorView(style: config.activityIndicatorStyle) activity.color = config.activityIndicatorColor activity.translatesAutoresizingMaskIntoConstraints = false return activity }() override func configureView() { super.configureView() activityIndicatorView.startAnimating() addSubview(activityIndicatorView) let x = activityIndicatorView.centerXAnchor.constraint(equalTo: self.centerXAnchor) let y = activityIndicatorView.centerYAnchor.constraint(equalTo: self.centerYAnchor) NSLayoutConstraint.activate([x, y]) } override func stopAnimation() { self.activityIndicatorView.stopAnimating() } }
29.25
91
0.722697
ac6d2cd87938666be729f5def0d473f02d88282e
1,726
// // VerificationViewController.swift // iMorph3d // // Created by Likhit Garimella on 03/12/20. // import UIKit import OTPFieldView class VerificationViewController: UIViewController, OTPFieldViewDelegate { // Outlets @IBOutlet var otpTextFieldView: OTPFieldView! func setupOtpView() { self.otpTextFieldView.fieldsCount = 4 self.otpTextFieldView.fieldBorderWidth = 1 self.otpTextFieldView.defaultBorderColor = UIColor.white self.otpTextFieldView.filledBorderColor = UIColor.darkGray self.otpTextFieldView.cursorColor = UIColor.red self.otpTextFieldView.displayType = .roundedCorner self.otpTextFieldView.fieldSize = 40 self.otpTextFieldView.separatorSpace = 8 self.otpTextFieldView.shouldAllowIntermediateEditing = false self.otpTextFieldView.delegate = self self.otpTextFieldView.initializeUI() } func shouldBecomeFirstResponderForOTP(otpTextFieldIndex index: Int) -> Bool { return true } func enteredOTP(otp otpString: String) { print("OTPString: \(otpString)") } func hasEnteredAllOTP(hasEnteredAll hasEntered: Bool) -> Bool { print("Has entered all OTP? \(hasEntered)") return false } override func viewDidLoad() { super.viewDidLoad() // remove title for left bar button item navigationController?.navigationBar.topItem?.title = "" hideKeyboardWhenTappedAround() setupOtpView() } @IBAction func goBack(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } } // #64
26.96875
81
0.64832
9b395bc732b3644eb3d630c689e3e43842066e73
1,464
import UIKit import WoWonderTimelineSDK class AddCommentCell: UITableViewCell,UITextViewDelegate { @IBOutlet weak var textView: UITextView! @IBOutlet weak var sendBtn: UIButton! override func awakeFromNib() { super.awakeFromNib() self.textView.delegate = self } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func textViewDidBeginEditing(_ textView: UITextView) { if self.textView.text == "Add a comment here"{ self.textView.text = nil } } func textViewDidEndEditing(_ textView: UITextView) { if self.textView.text == "" || self.textView.text.isEmpty == true{ self.textView.text = "Add a comment here" self.sendBtn.isEnabled = false self.sendBtn.setImage(#imageLiteral(resourceName: "right-arrow"), for: .normal) } } func textViewDidChangeSelection(_ textView: UITextView) { // print(self.commentText.text) if self.textView.text.count > 0{ self.sendBtn.isEnabled = true self.sendBtn.setImage(#imageLiteral(resourceName: "send"), for: .normal) } else { self.sendBtn.isEnabled = false self.sendBtn.setImage(#imageLiteral(resourceName: "right-arrow"), for: .normal) } } }
30.5
91
0.622951
d5c131b39dd8886bf3e62509359e7f5adb97d1fe
1,726
// // Copyright 2022 New Vector Ltd // // 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 /// Simple view model that computes the placeholder avatar properties. struct PlaceholderAvatarViewModel { /// The displayname used to create the `firstCharacterCapitalized`. let displayName: String? /// The matrix id used as input to create the `stableColorIndex` from. let matrixItemId: String /// The number of total colors available for the `stableColorIndex`. let colorCount: Int /// Get the first character of the display name capitalized or else a space character. var firstCharacterCapitalized: Character { return displayName?.capitalized.first ?? " " } /// Provides the same color each time for a specified matrixId /// /// Same algorithm as in AvatarGenerator. /// - Parameters: /// - matrixItemId: the matrix id used as input to create the stable index. /// - Returns: The stable index. var stableColorIndex: Int { // Sum all characters let sum = matrixItemId.utf8 .map({ UInt($0) }) .reduce(0, +) // modulo the color count return Int(sum) % colorCount } }
35.958333
90
0.686559
39e603019bb600fe7c19079d14495b761d98b1cf
1,088
// // SeizuresViewModelTests.swift // // Created on 8/3/20. // Copyright © 2020 WildAid. All rights reserved. // import XCTest @testable import O_FISH class SeizuresViewModelTests: XCTestCase { var sut: SeizuresViewModel? override func setUpWithError() throws { sut = SeizuresViewModel() } override func tearDownWithError() throws { sut = nil } func testSaveSeizuresNotNil() { //given let description = "Test description" let attachments = AttachmentsViewModel() sut?.description = description sut?.attachments = attachments //when let seizures = sut?.save() //then XCTAssertEqual(seizures?.text, description) XCTAssertNotNil(seizures?.attachments) } func testSaveSeizuresNil() { //given let seizures: Seizures? = nil sut = SeizuresViewModel(seizures) //when let seizuresIn = sut?.save() //then XCTAssertNotNil(seizuresIn) } }
21.333333
51
0.582721
56d8eab2a2126f6dc47b7eae38f9f917e67c2690
6,922
// // ViewController.swift // Word Talk Test // // Created by Jack Vaughn on 4/7/20. // Copyright © 2020 vaughn0523. All rights reserved. // import UIKit import Speech class ViewController: UIViewController, SFSpeechRecognizerDelegate { private let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))! private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? private var recognitionTask: SFSpeechRecognitionTask? private let audioEngine = AVAudioEngine() private var whatYouSay = String() @IBOutlet weak var wordLabel: UILabel! var defaults = UserDefaults.standard lazy var words = defaults.object(forKey: "words") as? [String] ?? [String]() var wordCount = 0 var isQueueRunning = false override func viewDidLoad() { super.viewDidLoad() if words.count == 0 { wordLabel.text = "a" } else { wordLabel.text = words[0] } } override public func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if words.count == 0 { words = ["a", "the", "car"] defaults.set(words, forKey: "words") } else { words = defaults.object(forKey: "words") as! [String] } wordLabel.text = words[wordCount] requestPermission() do { try startRecording() print("Listening....") } catch { print("Oh no") } } func requestPermission() { speechRecognizer.delegate = self SFSpeechRecognizer.requestAuthorization { authStatus in OperationQueue.main.addOperation { switch authStatus { case .authorized: print("Authorized") case .denied: print("Denied") case .restricted: print("Restricted") case .notDetermined: print("Not Determined") default: print("Default") } } } } private func startRecording() throws { // Cancel the previous task if it's running. recognitionTask?.cancel() self.recognitionTask = nil // Configure the audio session for the app. let audioSession = AVAudioSession.sharedInstance() try audioSession.setCategory(.record, mode: .measurement, options: .duckOthers) try audioSession.setActive(true, options: .notifyOthersOnDeactivation) let inputNode = audioEngine.inputNode // Create and configure the speech recognition request. recognitionRequest = SFSpeechAudioBufferRecognitionRequest() guard let recognitionRequest = recognitionRequest else { fatalError("Unable to create a SFSpeechAudioBufferRecognitionRequest object") } recognitionRequest.shouldReportPartialResults = true self.speechRecognizer.defaultTaskHint = .dictation // Keep speech recognition data on device if #available(iOS 13, *) { recognitionRequest.requiresOnDeviceRecognition = false } // Create a recognition task for the speech recognition session. // Keep a reference to the task so that it can be canceled. recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { result, error in var isFinal = false if let result = result { // Update the text view with the results. isFinal = result.isFinal self.whatYouSay = result.bestTranscription.formattedString print("Text \(self.whatYouSay)") var isQueueEmpty: Bool var dispatchGroup = DispatchGroup.init() if !self.isQueueRunning { self.check() } } if error != nil || isFinal { // Stop recognizing speech if there is a problem. self.audioEngine.stop() inputNode.removeTap(onBus: 0) } } // Configure the microphone input. let recordingFormat = inputNode.outputFormat(forBus: 0) inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in self.recognitionRequest?.append(buffer) } audioEngine.prepare() try audioEngine.start() } func check() { let wordsYouSay = whatYouSay.split(separator: " ").map {String($0)} let lowerWords = wordsYouSay.map { $0.lowercased()} if lowerWords.contains(wordLabel!.text!.lowercased()) { print("Match") wordLabel.textColor = UIColor(red: 170/255.0, green: 242/255.0, blue: 85/255.0, alpha: 1) wordLabel.text = words[wordCount] let seconds = 1.0 audioEngine.stop() recognitionRequest?.endAudio() isQueueRunning = true DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { self.wordCount += 1 if self.wordCount == self.words.count { self.wordCount = 0 } self.wordLabel.text = self.words[self.wordCount] self.wordLabel.textColor = UIColor.white self.isQueueRunning = false do { try self.startRecording() print("Listening....") } catch { print("Oh no") } } } } } //class SaveMyShit: NSObject, NSCoding { // let names : [String] // // init(names:[String]) { // self.names = names // } // // func encode(with coder: NSCoder) { // coder.encode(names, forKey: "names") // } // // convenience required init?(coder: NSCoder) { // guard let names = coder.decodeObject(forKey: "names") as? [String] else { // return nil // } // self.init(names: names) // } //} // //class Util { // func storeCustomObjectToUserDefault(names: [String]) { // let data = try NSKeyedArchiver.archivedData(withRootObject: names, requiringSecureCoding: false) // UserDefaults.standard.set(data, forKey: "names") // } // // func getCustomObjectFromUserDefault() -> [String]{ // let data = UserDefaults.standard.value(forKey: "names") // let names = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSCoding.Protocol(SaveMyShit), from: data as! Data) // return names // } //}
32.961905
144
0.557064
cc7c1edcc03f52602b0af26c91059ad48cc7f8b8
543
// // AppDelegate.swift // viperb // // Created by Tibor Bödecs on 2018. 03. 08.. // Copyright © 2018. Tibor Bödecs. All rights reserved. // import UIKit //Link: https://theswiftdev.com/2018/03/12/the-ultimate-viper-architecture-tutorial/ @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } }
23.608696
114
0.701657
2825b2cc98483c2ba137de3c1ec411579ca70c30
787
// // AdmobNativeSampleApp.swift // AdmobNativeSample // // Created by Sakura on 2021/04/28. // import SwiftUI import UIKit import GoogleMobileAds class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // Initialize Mobile Ads SDK GADMobileAds.sharedInstance().start(completionHandler: nil) // GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = // [ kGADSimulatorID ] as? [String] return true } } @main struct AdmobNativeSampleApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { ContentView() } } }
22.485714
149
0.735705
0afb66841ed38b132fcca383b18a079417a02683
33,956
// VirtualMachineSizeTypes enumerates the values for virtual machine size types. // 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. public enum VirtualMachineSizeTypesEnum: String, Codable { // VirtualMachineSizeTypesBasicA0 specifies the virtual machine size types basic a0 state for virtual machine size // types. case VirtualMachineSizeTypesBasicA0 = "Basic_A0" // VirtualMachineSizeTypesBasicA1 specifies the virtual machine size types basic a1 state for virtual machine size // types. case VirtualMachineSizeTypesBasicA1 = "Basic_A1" // VirtualMachineSizeTypesBasicA2 specifies the virtual machine size types basic a2 state for virtual machine size // types. case VirtualMachineSizeTypesBasicA2 = "Basic_A2" // VirtualMachineSizeTypesBasicA3 specifies the virtual machine size types basic a3 state for virtual machine size // types. case VirtualMachineSizeTypesBasicA3 = "Basic_A3" // VirtualMachineSizeTypesBasicA4 specifies the virtual machine size types basic a4 state for virtual machine size // types. case VirtualMachineSizeTypesBasicA4 = "Basic_A4" // VirtualMachineSizeTypesStandardA0 specifies the virtual machine size types standard a0 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA0 = "Standard_A0" // VirtualMachineSizeTypesStandardA1 specifies the virtual machine size types standard a1 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA1 = "Standard_A1" // VirtualMachineSizeTypesStandardA10 specifies the virtual machine size types standard a10 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA10 = "Standard_A10" // VirtualMachineSizeTypesStandardA11 specifies the virtual machine size types standard a11 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA11 = "Standard_A11" // VirtualMachineSizeTypesStandardA1V2 specifies the virtual machine size types standard a1v2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA1V2 = "Standard_A1_v2" // VirtualMachineSizeTypesStandardA2 specifies the virtual machine size types standard a2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA2 = "Standard_A2" // VirtualMachineSizeTypesStandardA2mV2 specifies the virtual machine size types standard a2mv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardA2mV2 = "Standard_A2m_v2" // VirtualMachineSizeTypesStandardA2V2 specifies the virtual machine size types standard a2v2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA2V2 = "Standard_A2_v2" // VirtualMachineSizeTypesStandardA3 specifies the virtual machine size types standard a3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA3 = "Standard_A3" // VirtualMachineSizeTypesStandardA4 specifies the virtual machine size types standard a4 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA4 = "Standard_A4" // VirtualMachineSizeTypesStandardA4mV2 specifies the virtual machine size types standard a4mv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardA4mV2 = "Standard_A4m_v2" // VirtualMachineSizeTypesStandardA4V2 specifies the virtual machine size types standard a4v2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA4V2 = "Standard_A4_v2" // VirtualMachineSizeTypesStandardA5 specifies the virtual machine size types standard a5 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA5 = "Standard_A5" // VirtualMachineSizeTypesStandardA6 specifies the virtual machine size types standard a6 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA6 = "Standard_A6" // VirtualMachineSizeTypesStandardA7 specifies the virtual machine size types standard a7 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA7 = "Standard_A7" // VirtualMachineSizeTypesStandardA8 specifies the virtual machine size types standard a8 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA8 = "Standard_A8" // VirtualMachineSizeTypesStandardA8mV2 specifies the virtual machine size types standard a8mv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardA8mV2 = "Standard_A8m_v2" // VirtualMachineSizeTypesStandardA8V2 specifies the virtual machine size types standard a8v2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA8V2 = "Standard_A8_v2" // VirtualMachineSizeTypesStandardA9 specifies the virtual machine size types standard a9 state for virtual machine // size types. case VirtualMachineSizeTypesStandardA9 = "Standard_A9" // VirtualMachineSizeTypesStandardB1ms specifies the virtual machine size types standard b1ms state for virtual machine // size types. case VirtualMachineSizeTypesStandardB1ms = "Standard_B1ms" // VirtualMachineSizeTypesStandardB1s specifies the virtual machine size types standard b1s state for virtual machine // size types. case VirtualMachineSizeTypesStandardB1s = "Standard_B1s" // VirtualMachineSizeTypesStandardB2ms specifies the virtual machine size types standard b2ms state for virtual machine // size types. case VirtualMachineSizeTypesStandardB2ms = "Standard_B2ms" // VirtualMachineSizeTypesStandardB2s specifies the virtual machine size types standard b2s state for virtual machine // size types. case VirtualMachineSizeTypesStandardB2s = "Standard_B2s" // VirtualMachineSizeTypesStandardB4ms specifies the virtual machine size types standard b4ms state for virtual machine // size types. case VirtualMachineSizeTypesStandardB4ms = "Standard_B4ms" // VirtualMachineSizeTypesStandardB8ms specifies the virtual machine size types standard b8ms state for virtual machine // size types. case VirtualMachineSizeTypesStandardB8ms = "Standard_B8ms" // VirtualMachineSizeTypesStandardD1 specifies the virtual machine size types standard d1 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD1 = "Standard_D1" // VirtualMachineSizeTypesStandardD11 specifies the virtual machine size types standard d11 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD11 = "Standard_D11" // VirtualMachineSizeTypesStandardD11V2 specifies the virtual machine size types standard d11v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD11V2 = "Standard_D11_v2" // VirtualMachineSizeTypesStandardD12 specifies the virtual machine size types standard d12 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD12 = "Standard_D12" // VirtualMachineSizeTypesStandardD12V2 specifies the virtual machine size types standard d12v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD12V2 = "Standard_D12_v2" // VirtualMachineSizeTypesStandardD13 specifies the virtual machine size types standard d13 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD13 = "Standard_D13" // VirtualMachineSizeTypesStandardD13V2 specifies the virtual machine size types standard d13v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD13V2 = "Standard_D13_v2" // VirtualMachineSizeTypesStandardD14 specifies the virtual machine size types standard d14 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD14 = "Standard_D14" // VirtualMachineSizeTypesStandardD14V2 specifies the virtual machine size types standard d14v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD14V2 = "Standard_D14_v2" // VirtualMachineSizeTypesStandardD15V2 specifies the virtual machine size types standard d15v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD15V2 = "Standard_D15_v2" // VirtualMachineSizeTypesStandardD16sV3 specifies the virtual machine size types standard d16sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD16sV3 = "Standard_D16s_v3" // VirtualMachineSizeTypesStandardD16V3 specifies the virtual machine size types standard d16v3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD16V3 = "Standard_D16_v3" // VirtualMachineSizeTypesStandardD1V2 specifies the virtual machine size types standard d1v2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD1V2 = "Standard_D1_v2" // VirtualMachineSizeTypesStandardD2 specifies the virtual machine size types standard d2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD2 = "Standard_D2" // VirtualMachineSizeTypesStandardD2sV3 specifies the virtual machine size types standard d2sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD2sV3 = "Standard_D2s_v3" // VirtualMachineSizeTypesStandardD2V2 specifies the virtual machine size types standard d2v2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD2V2 = "Standard_D2_v2" // VirtualMachineSizeTypesStandardD2V3 specifies the virtual machine size types standard d2v3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD2V3 = "Standard_D2_v3" // VirtualMachineSizeTypesStandardD3 specifies the virtual machine size types standard d3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD3 = "Standard_D3" // VirtualMachineSizeTypesStandardD32sV3 specifies the virtual machine size types standard d32sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD32sV3 = "Standard_D32s_v3" // VirtualMachineSizeTypesStandardD32V3 specifies the virtual machine size types standard d32v3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD32V3 = "Standard_D32_v3" // VirtualMachineSizeTypesStandardD3V2 specifies the virtual machine size types standard d3v2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD3V2 = "Standard_D3_v2" // VirtualMachineSizeTypesStandardD4 specifies the virtual machine size types standard d4 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD4 = "Standard_D4" // VirtualMachineSizeTypesStandardD4sV3 specifies the virtual machine size types standard d4sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD4sV3 = "Standard_D4s_v3" // VirtualMachineSizeTypesStandardD4V2 specifies the virtual machine size types standard d4v2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD4V2 = "Standard_D4_v2" // VirtualMachineSizeTypesStandardD4V3 specifies the virtual machine size types standard d4v3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD4V3 = "Standard_D4_v3" // VirtualMachineSizeTypesStandardD5V2 specifies the virtual machine size types standard d5v2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD5V2 = "Standard_D5_v2" // VirtualMachineSizeTypesStandardD64sV3 specifies the virtual machine size types standard d64sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD64sV3 = "Standard_D64s_v3" // VirtualMachineSizeTypesStandardD64V3 specifies the virtual machine size types standard d64v3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD64V3 = "Standard_D64_v3" // VirtualMachineSizeTypesStandardD8sV3 specifies the virtual machine size types standard d8sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardD8sV3 = "Standard_D8s_v3" // VirtualMachineSizeTypesStandardD8V3 specifies the virtual machine size types standard d8v3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardD8V3 = "Standard_D8_v3" // VirtualMachineSizeTypesStandardDS1 specifies the virtual machine size types standard ds1 state for virtual machine // size types. case VirtualMachineSizeTypesStandardDS1 = "Standard_DS1" // VirtualMachineSizeTypesStandardDS11 specifies the virtual machine size types standard ds11 state for virtual machine // size types. case VirtualMachineSizeTypesStandardDS11 = "Standard_DS11" // VirtualMachineSizeTypesStandardDS11V2 specifies the virtual machine size types standard ds11v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS11V2 = "Standard_DS11_v2" // VirtualMachineSizeTypesStandardDS12 specifies the virtual machine size types standard ds12 state for virtual machine // size types. case VirtualMachineSizeTypesStandardDS12 = "Standard_DS12" // VirtualMachineSizeTypesStandardDS12V2 specifies the virtual machine size types standard ds12v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS12V2 = "Standard_DS12_v2" // VirtualMachineSizeTypesStandardDS13 specifies the virtual machine size types standard ds13 state for virtual machine // size types. case VirtualMachineSizeTypesStandardDS13 = "Standard_DS13" // VirtualMachineSizeTypesStandardDS132V2 specifies the virtual machine size types standard ds132v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS132V2 = "Standard_DS13-2_v2" // VirtualMachineSizeTypesStandardDS134V2 specifies the virtual machine size types standard ds134v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS134V2 = "Standard_DS13-4_v2" // VirtualMachineSizeTypesStandardDS13V2 specifies the virtual machine size types standard ds13v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS13V2 = "Standard_DS13_v2" // VirtualMachineSizeTypesStandardDS14 specifies the virtual machine size types standard ds14 state for virtual machine // size types. case VirtualMachineSizeTypesStandardDS14 = "Standard_DS14" // VirtualMachineSizeTypesStandardDS144V2 specifies the virtual machine size types standard ds144v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS144V2 = "Standard_DS14-4_v2" // VirtualMachineSizeTypesStandardDS148V2 specifies the virtual machine size types standard ds148v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS148V2 = "Standard_DS14-8_v2" // VirtualMachineSizeTypesStandardDS14V2 specifies the virtual machine size types standard ds14v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS14V2 = "Standard_DS14_v2" // VirtualMachineSizeTypesStandardDS15V2 specifies the virtual machine size types standard ds15v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS15V2 = "Standard_DS15_v2" // VirtualMachineSizeTypesStandardDS1V2 specifies the virtual machine size types standard ds1v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS1V2 = "Standard_DS1_v2" // VirtualMachineSizeTypesStandardDS2 specifies the virtual machine size types standard ds2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardDS2 = "Standard_DS2" // VirtualMachineSizeTypesStandardDS2V2 specifies the virtual machine size types standard ds2v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS2V2 = "Standard_DS2_v2" // VirtualMachineSizeTypesStandardDS3 specifies the virtual machine size types standard ds3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardDS3 = "Standard_DS3" // VirtualMachineSizeTypesStandardDS3V2 specifies the virtual machine size types standard ds3v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS3V2 = "Standard_DS3_v2" // VirtualMachineSizeTypesStandardDS4 specifies the virtual machine size types standard ds4 state for virtual machine // size types. case VirtualMachineSizeTypesStandardDS4 = "Standard_DS4" // VirtualMachineSizeTypesStandardDS4V2 specifies the virtual machine size types standard ds4v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS4V2 = "Standard_DS4_v2" // VirtualMachineSizeTypesStandardDS5V2 specifies the virtual machine size types standard ds5v2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardDS5V2 = "Standard_DS5_v2" // VirtualMachineSizeTypesStandardE16sV3 specifies the virtual machine size types standard e16sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE16sV3 = "Standard_E16s_v3" // VirtualMachineSizeTypesStandardE16V3 specifies the virtual machine size types standard e16v3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE16V3 = "Standard_E16_v3" // VirtualMachineSizeTypesStandardE2sV3 specifies the virtual machine size types standard e2sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE2sV3 = "Standard_E2s_v3" // VirtualMachineSizeTypesStandardE2V3 specifies the virtual machine size types standard e2v3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardE2V3 = "Standard_E2_v3" // VirtualMachineSizeTypesStandardE3216V3 specifies the virtual machine size types standard e3216v3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE3216V3 = "Standard_E32-16_v3" // VirtualMachineSizeTypesStandardE328sV3 specifies the virtual machine size types standard e328sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE328sV3 = "Standard_E32-8s_v3" // VirtualMachineSizeTypesStandardE32sV3 specifies the virtual machine size types standard e32sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE32sV3 = "Standard_E32s_v3" // VirtualMachineSizeTypesStandardE32V3 specifies the virtual machine size types standard e32v3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE32V3 = "Standard_E32_v3" // VirtualMachineSizeTypesStandardE4sV3 specifies the virtual machine size types standard e4sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE4sV3 = "Standard_E4s_v3" // VirtualMachineSizeTypesStandardE4V3 specifies the virtual machine size types standard e4v3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardE4V3 = "Standard_E4_v3" // VirtualMachineSizeTypesStandardE6416sV3 specifies the virtual machine size types standard e6416sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE6416sV3 = "Standard_E64-16s_v3" // VirtualMachineSizeTypesStandardE6432sV3 specifies the virtual machine size types standard e6432sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE6432sV3 = "Standard_E64-32s_v3" // VirtualMachineSizeTypesStandardE64sV3 specifies the virtual machine size types standard e64sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE64sV3 = "Standard_E64s_v3" // VirtualMachineSizeTypesStandardE64V3 specifies the virtual machine size types standard e64v3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE64V3 = "Standard_E64_v3" // VirtualMachineSizeTypesStandardE8sV3 specifies the virtual machine size types standard e8sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardE8sV3 = "Standard_E8s_v3" // VirtualMachineSizeTypesStandardE8V3 specifies the virtual machine size types standard e8v3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardE8V3 = "Standard_E8_v3" // VirtualMachineSizeTypesStandardF1 specifies the virtual machine size types standard f1 state for virtual machine // size types. case VirtualMachineSizeTypesStandardF1 = "Standard_F1" // VirtualMachineSizeTypesStandardF16 specifies the virtual machine size types standard f16 state for virtual machine // size types. case VirtualMachineSizeTypesStandardF16 = "Standard_F16" // VirtualMachineSizeTypesStandardF16s specifies the virtual machine size types standard f16s state for virtual machine // size types. case VirtualMachineSizeTypesStandardF16s = "Standard_F16s" // VirtualMachineSizeTypesStandardF16sV2 specifies the virtual machine size types standard f16sv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardF16sV2 = "Standard_F16s_v2" // VirtualMachineSizeTypesStandardF1s specifies the virtual machine size types standard f1s state for virtual machine // size types. case VirtualMachineSizeTypesStandardF1s = "Standard_F1s" // VirtualMachineSizeTypesStandardF2 specifies the virtual machine size types standard f2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardF2 = "Standard_F2" // VirtualMachineSizeTypesStandardF2s specifies the virtual machine size types standard f2s state for virtual machine // size types. case VirtualMachineSizeTypesStandardF2s = "Standard_F2s" // VirtualMachineSizeTypesStandardF2sV2 specifies the virtual machine size types standard f2sv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardF2sV2 = "Standard_F2s_v2" // VirtualMachineSizeTypesStandardF32sV2 specifies the virtual machine size types standard f32sv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardF32sV2 = "Standard_F32s_v2" // VirtualMachineSizeTypesStandardF4 specifies the virtual machine size types standard f4 state for virtual machine // size types. case VirtualMachineSizeTypesStandardF4 = "Standard_F4" // VirtualMachineSizeTypesStandardF4s specifies the virtual machine size types standard f4s state for virtual machine // size types. case VirtualMachineSizeTypesStandardF4s = "Standard_F4s" // VirtualMachineSizeTypesStandardF4sV2 specifies the virtual machine size types standard f4sv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardF4sV2 = "Standard_F4s_v2" // VirtualMachineSizeTypesStandardF64sV2 specifies the virtual machine size types standard f64sv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardF64sV2 = "Standard_F64s_v2" // VirtualMachineSizeTypesStandardF72sV2 specifies the virtual machine size types standard f72sv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardF72sV2 = "Standard_F72s_v2" // VirtualMachineSizeTypesStandardF8 specifies the virtual machine size types standard f8 state for virtual machine // size types. case VirtualMachineSizeTypesStandardF8 = "Standard_F8" // VirtualMachineSizeTypesStandardF8s specifies the virtual machine size types standard f8s state for virtual machine // size types. case VirtualMachineSizeTypesStandardF8s = "Standard_F8s" // VirtualMachineSizeTypesStandardF8sV2 specifies the virtual machine size types standard f8sv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardF8sV2 = "Standard_F8s_v2" // VirtualMachineSizeTypesStandardG1 specifies the virtual machine size types standard g1 state for virtual machine // size types. case VirtualMachineSizeTypesStandardG1 = "Standard_G1" // VirtualMachineSizeTypesStandardG2 specifies the virtual machine size types standard g2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardG2 = "Standard_G2" // VirtualMachineSizeTypesStandardG3 specifies the virtual machine size types standard g3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardG3 = "Standard_G3" // VirtualMachineSizeTypesStandardG4 specifies the virtual machine size types standard g4 state for virtual machine // size types. case VirtualMachineSizeTypesStandardG4 = "Standard_G4" // VirtualMachineSizeTypesStandardG5 specifies the virtual machine size types standard g5 state for virtual machine // size types. case VirtualMachineSizeTypesStandardG5 = "Standard_G5" // VirtualMachineSizeTypesStandardGS1 specifies the virtual machine size types standard gs1 state for virtual machine // size types. case VirtualMachineSizeTypesStandardGS1 = "Standard_GS1" // VirtualMachineSizeTypesStandardGS2 specifies the virtual machine size types standard gs2 state for virtual machine // size types. case VirtualMachineSizeTypesStandardGS2 = "Standard_GS2" // VirtualMachineSizeTypesStandardGS3 specifies the virtual machine size types standard gs3 state for virtual machine // size types. case VirtualMachineSizeTypesStandardGS3 = "Standard_GS3" // VirtualMachineSizeTypesStandardGS4 specifies the virtual machine size types standard gs4 state for virtual machine // size types. case VirtualMachineSizeTypesStandardGS4 = "Standard_GS4" // VirtualMachineSizeTypesStandardGS44 specifies the virtual machine size types standard gs44 state for virtual machine // size types. case VirtualMachineSizeTypesStandardGS44 = "Standard_GS4-4" // VirtualMachineSizeTypesStandardGS48 specifies the virtual machine size types standard gs48 state for virtual machine // size types. case VirtualMachineSizeTypesStandardGS48 = "Standard_GS4-8" // VirtualMachineSizeTypesStandardGS5 specifies the virtual machine size types standard gs5 state for virtual machine // size types. case VirtualMachineSizeTypesStandardGS5 = "Standard_GS5" // VirtualMachineSizeTypesStandardGS516 specifies the virtual machine size types standard gs516 state for virtual // machine size types. case VirtualMachineSizeTypesStandardGS516 = "Standard_GS5-16" // VirtualMachineSizeTypesStandardGS58 specifies the virtual machine size types standard gs58 state for virtual machine // size types. case VirtualMachineSizeTypesStandardGS58 = "Standard_GS5-8" // VirtualMachineSizeTypesStandardH16 specifies the virtual machine size types standard h16 state for virtual machine // size types. case VirtualMachineSizeTypesStandardH16 = "Standard_H16" // VirtualMachineSizeTypesStandardH16m specifies the virtual machine size types standard h16m state for virtual machine // size types. case VirtualMachineSizeTypesStandardH16m = "Standard_H16m" // VirtualMachineSizeTypesStandardH16mr specifies the virtual machine size types standard h16mr state for virtual // machine size types. case VirtualMachineSizeTypesStandardH16mr = "Standard_H16mr" // VirtualMachineSizeTypesStandardH16r specifies the virtual machine size types standard h16r state for virtual machine // size types. case VirtualMachineSizeTypesStandardH16r = "Standard_H16r" // VirtualMachineSizeTypesStandardH8 specifies the virtual machine size types standard h8 state for virtual machine // size types. case VirtualMachineSizeTypesStandardH8 = "Standard_H8" // VirtualMachineSizeTypesStandardH8m specifies the virtual machine size types standard h8m state for virtual machine // size types. case VirtualMachineSizeTypesStandardH8m = "Standard_H8m" // VirtualMachineSizeTypesStandardL16s specifies the virtual machine size types standard l16s state for virtual machine // size types. case VirtualMachineSizeTypesStandardL16s = "Standard_L16s" // VirtualMachineSizeTypesStandardL32s specifies the virtual machine size types standard l32s state for virtual machine // size types. case VirtualMachineSizeTypesStandardL32s = "Standard_L32s" // VirtualMachineSizeTypesStandardL4s specifies the virtual machine size types standard l4s state for virtual machine // size types. case VirtualMachineSizeTypesStandardL4s = "Standard_L4s" // VirtualMachineSizeTypesStandardL8s specifies the virtual machine size types standard l8s state for virtual machine // size types. case VirtualMachineSizeTypesStandardL8s = "Standard_L8s" // VirtualMachineSizeTypesStandardM12832ms specifies the virtual machine size types standard m12832ms state for virtual // machine size types. case VirtualMachineSizeTypesStandardM12832ms = "Standard_M128-32ms" // VirtualMachineSizeTypesStandardM12864ms specifies the virtual machine size types standard m12864ms state for virtual // machine size types. case VirtualMachineSizeTypesStandardM12864ms = "Standard_M128-64ms" // VirtualMachineSizeTypesStandardM128ms specifies the virtual machine size types standard m128ms state for virtual // machine size types. case VirtualMachineSizeTypesStandardM128ms = "Standard_M128ms" // VirtualMachineSizeTypesStandardM128s specifies the virtual machine size types standard m128s state for virtual // machine size types. case VirtualMachineSizeTypesStandardM128s = "Standard_M128s" // VirtualMachineSizeTypesStandardM6416ms specifies the virtual machine size types standard m6416ms state for virtual // machine size types. case VirtualMachineSizeTypesStandardM6416ms = "Standard_M64-16ms" // VirtualMachineSizeTypesStandardM6432ms specifies the virtual machine size types standard m6432ms state for virtual // machine size types. case VirtualMachineSizeTypesStandardM6432ms = "Standard_M64-32ms" // VirtualMachineSizeTypesStandardM64ms specifies the virtual machine size types standard m64ms state for virtual // machine size types. case VirtualMachineSizeTypesStandardM64ms = "Standard_M64ms" // VirtualMachineSizeTypesStandardM64s specifies the virtual machine size types standard m64s state for virtual machine // size types. case VirtualMachineSizeTypesStandardM64s = "Standard_M64s" // VirtualMachineSizeTypesStandardNC12 specifies the virtual machine size types standard nc12 state for virtual machine // size types. case VirtualMachineSizeTypesStandardNC12 = "Standard_NC12" // VirtualMachineSizeTypesStandardNC12sV2 specifies the virtual machine size types standard nc12sv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardNC12sV2 = "Standard_NC12s_v2" // VirtualMachineSizeTypesStandardNC12sV3 specifies the virtual machine size types standard nc12sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardNC12sV3 = "Standard_NC12s_v3" // VirtualMachineSizeTypesStandardNC24 specifies the virtual machine size types standard nc24 state for virtual machine // size types. case VirtualMachineSizeTypesStandardNC24 = "Standard_NC24" // VirtualMachineSizeTypesStandardNC24r specifies the virtual machine size types standard nc24r state for virtual // machine size types. case VirtualMachineSizeTypesStandardNC24r = "Standard_NC24r" // VirtualMachineSizeTypesStandardNC24rsV2 specifies the virtual machine size types standard nc24rsv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardNC24rsV2 = "Standard_NC24rs_v2" // VirtualMachineSizeTypesStandardNC24rsV3 specifies the virtual machine size types standard nc24rsv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardNC24rsV3 = "Standard_NC24rs_v3" // VirtualMachineSizeTypesStandardNC24sV2 specifies the virtual machine size types standard nc24sv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardNC24sV2 = "Standard_NC24s_v2" // VirtualMachineSizeTypesStandardNC24sV3 specifies the virtual machine size types standard nc24sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardNC24sV3 = "Standard_NC24s_v3" // VirtualMachineSizeTypesStandardNC6 specifies the virtual machine size types standard nc6 state for virtual machine // size types. case VirtualMachineSizeTypesStandardNC6 = "Standard_NC6" // VirtualMachineSizeTypesStandardNC6sV2 specifies the virtual machine size types standard nc6sv2 state for virtual // machine size types. case VirtualMachineSizeTypesStandardNC6sV2 = "Standard_NC6s_v2" // VirtualMachineSizeTypesStandardNC6sV3 specifies the virtual machine size types standard nc6sv3 state for virtual // machine size types. case VirtualMachineSizeTypesStandardNC6sV3 = "Standard_NC6s_v3" // VirtualMachineSizeTypesStandardND12s specifies the virtual machine size types standard nd12s state for virtual // machine size types. case VirtualMachineSizeTypesStandardND12s = "Standard_ND12s" // VirtualMachineSizeTypesStandardND24rs specifies the virtual machine size types standard nd24rs state for virtual // machine size types. case VirtualMachineSizeTypesStandardND24rs = "Standard_ND24rs" // VirtualMachineSizeTypesStandardND24s specifies the virtual machine size types standard nd24s state for virtual // machine size types. case VirtualMachineSizeTypesStandardND24s = "Standard_ND24s" // VirtualMachineSizeTypesStandardND6s specifies the virtual machine size types standard nd6s state for virtual machine // size types. case VirtualMachineSizeTypesStandardND6s = "Standard_ND6s" // VirtualMachineSizeTypesStandardNV12 specifies the virtual machine size types standard nv12 state for virtual machine // size types. case VirtualMachineSizeTypesStandardNV12 = "Standard_NV12" // VirtualMachineSizeTypesStandardNV24 specifies the virtual machine size types standard nv24 state for virtual machine // size types. case VirtualMachineSizeTypesStandardNV24 = "Standard_NV24" // VirtualMachineSizeTypesStandardNV6 specifies the virtual machine size types standard nv6 state for virtual machine // size types. case VirtualMachineSizeTypesStandardNV6 = "Standard_NV6" }
66.84252
120
0.821033
899a2c1a3e3a7f361790513474efc686925970af
1,776
// // CJNetRequest.swift // CJSwiftBasicProject // // Created by 陈吉 on 2019/8/27. // Copyright © 2019 陈吉. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class CJNetRequest: NSObject { struct responseData { var request: URLRequest? var response: URLResponse? var data: Data? var json: JSON? var error: NSError? var success = false } class func requestWith(method: HTTPMethod, url: String, param: [String: Any]?, token: String?, complete: @escaping (responseData) -> Void) { // var dicToken:[String:String]! // if token != nil { // dicToken = ["tokenId":token!] // } var paramDic = [String:Any]() if let param = param { paramDic.merge(param: param) paramDic["platform"] = "Iph" paramDic["version"] = "4.8.2" paramDic["hospitalId"] = "-3" paramDic["nurseId"] = "11359" } let manager = Alamofire.SessionManager.default manager.session.configuration.timeoutIntervalForRequest = 10; manager.request(url, method: method, parameters: paramDic, encoding: URLEncoding.default, headers: nil).response { (response) in do{ let json = try JSON(data: response.data!) let suc = json["success"].bool! if JSON.null != json { let res = responseData(request: response.request, response: response.response, data: response.data, json: json, error: response.error as NSError?, success: suc) complete(res) } }catch{} } } }
32.290909
180
0.539977
e8a4a73fea185ca5ed810e1f690a2052ea207781
1,187
/* Copyright 2017-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation extension MotionObservableConvertible { /** Emits a string representation of the incoming value. */ public func toString() -> MotionObservable<String> { return _map { String(describing: $0) } } } extension MotionObservableConvertible where T == CGFloat { /** Emits a string representation of the incoming value. The incoming value may optionally be formatted according to the provided format string. */ public func toString(format: String) -> MotionObservable<String> { return _map { String(format: format, $0) } } }
29.675
90
0.748104
756c51e6fbb66151607d04afc3ca9b1435edd6e3
2,498
// // URLRequest+Convenience.swift // // // Created by Vladislav Fitc on 02/03/2020. // import Foundation extension URLRequest: Builder {} extension CharacterSet { static var uriAllowed = CharacterSet.urlQueryAllowed.subtracting(.init(charactersIn: "+")) } extension URLRequest { subscript(header key: HTTPHeaderKey) -> String? { get { return allHTTPHeaderFields?[key.rawValue] } set(newValue) { setValue(newValue, forHTTPHeaderField: key.rawValue) } } init<PC: PathComponent>(method: HTTPMethod, path: PC, body: Data? = nil, requestOptions: RequestOptions? = nil) { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.path = path.fullPath if let urlParameters = requestOptions?.urlParameters { urlComponents.queryItems = urlParameters.map { (key, value) in .init(name: key.rawValue, value: value) } } var request = URLRequest(url: urlComponents.url!) request.httpMethod = method.rawValue request.httpBody = body if let requestOptions = requestOptions { requestOptions.headers.forEach { header in let (value, field) = (header.value, header.key.rawValue) request.setValue(value, forHTTPHeaderField: field) } // If body is set in query parameters, it will override the body passed as parameter to this function if let body = requestOptions.body, !body.isEmpty { let jsonEncodedBody = try? JSONSerialization.data(withJSONObject: body, options: []) request.httpBody = jsonEncodedBody } } request.httpBody = body self = request } } extension URLRequest { var credentials: Credentials? { get { guard let appID = applicationID, let apiKey = apiKey else { return nil } return AlgoliaCredentials(applicationID: appID, apiKey: apiKey) } set { guard let newValue = newValue else { applicationID = nil apiKey = nil return } applicationID = newValue.applicationID apiKey = newValue.apiKey } } var applicationID: ApplicationID? { get { return self[header: .applicationID].flatMap(ApplicationID.init) } set { self[header: .applicationID] = newValue?.rawValue } } var apiKey: APIKey? { get { return self[header: .apiKey].flatMap(APIKey.init) } set { self[header: .apiKey] = newValue?.rawValue } } }
21.721739
115
0.644516
5b3f02aa2bbd49e394be40a0cfd15d09661cdbff
1,043
// // CommonAuthorizationButton.swift // goland // // Created by Kusyumov Nikita on 22.09.2020. // Copyright © 2020 [email protected]. All rights reserved. // import Foundation import UIKit class CommonAuthorizationButton: UIButton { // MARK: - Internal properties private struct Appearance: Grid { let buttonCornerRadius: CGFloat = 5 } private let appearance = Appearance() // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { setupStyle() } private func setupStyle() { cornerRadius = appearance.buttonCornerRadius backgroundColor = .goSlime bonMotStyle = .regular20(.white) } } extension CommonAuthorizationButton: Configurable { func configure(with text: String) { self.styledText = text } }
20.45098
61
0.622244
466b29e415799d23d0c0dd97fb7e334553775b98
5,395
// // AFNetworkingIntegration.swift // AXPhotoViewer // // Created by Alex Hill on 5/20/17. // Copyright © 2017 Alex Hill. All rights reserved. // #if canImport(AFNetworking) import AFNetworking import ImageIO class AFNetworkingIntegration: NSObject, AXNetworkIntegrationProtocol { weak public var delegate: AXNetworkIntegrationDelegate? fileprivate var downloadTasks = NSMapTable<AXPhotoProtocol, URLSessionDataTask>(keyOptions: .strongMemory, valueOptions: .strongMemory) public func loadPhoto(_ photo: AXPhotoProtocol) { if photo.imageData != nil || photo.image != nil { AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration(self, loadDidFinishWith: photo) } return } guard let url = photo.url else { return } let progress: (_ progress: Progress) -> Void = { [weak self] (progress) in AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration?(self, didUpdateLoadingProgress: CGFloat(progress.fractionCompleted), for: photo) } } let success: (_ dataTask: URLSessionDataTask, _ responseObject: Any?) -> Void = { [weak self] (dataTask, responseObject) in guard let `self` = self else { return } self.downloadTasks.removeObject(forKey: photo) if let responseGIFData = responseObject as? Data { photo.imageData = responseGIFData AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration(self, loadDidFinishWith: photo) } } else if let responseImage = responseObject as? UIImage { photo.image = responseImage AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration(self, loadDidFinishWith: photo) } } else { let error = NSError( domain: AXNetworkIntegrationErrorDomain, code: AXNetworkIntegrationFailedToLoadErrorCode, userInfo: nil ) AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration(self, loadDidFailWith: error, for: photo) } } } let failure: (_ dataTask: URLSessionDataTask?, _ error: Error) -> Void = { [weak self] (dataTask, error) in guard let `self` = self else { return } self.downloadTasks.removeObject(forKey: photo) let error = NSError( domain: AXNetworkIntegrationErrorDomain, code: AXNetworkIntegrationFailedToLoadErrorCode, userInfo: nil ) AXDispatchUtils.executeInBackground { [weak self] in guard let `self` = self else { return } self.delegate?.networkIntegration(self, loadDidFailWith: error, for: photo) } } guard let dataTask = AXHTTPSessionManager.shared.get(url.absoluteString, parameters: nil, progress: progress, success: success, failure: failure) else { return } self.downloadTasks.setObject(dataTask, forKey: photo) } func cancelLoad(for photo: AXPhotoProtocol) { guard let dataTask = self.downloadTasks.object(forKey: photo) else { return } dataTask.cancel() self.downloadTasks.removeObject(forKey: photo) } func cancelAllLoads() { let enumerator = self.downloadTasks.objectEnumerator() while let dataTask = enumerator?.nextObject() as? URLSessionDataTask { dataTask.cancel() } self.downloadTasks.removeAllObjects() } } /// An `AFHTTPSesssionManager` with our subclassed `AXImageResponseSerializer`. class AXHTTPSessionManager: AFHTTPSessionManager { static let shared = AXHTTPSessionManager() init() { super.init(baseURL: nil, sessionConfiguration: .default) self.responseSerializer = AXImageResponseSerializer() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } /// A subclassed `AFImageResponseSerializer` that returns GIF data if it exists. class AXImageResponseSerializer: AFImageResponseSerializer { override func responseObject(for response: URLResponse?, data: Data?, error: NSErrorPointer) -> Any? { if let `data` = data, data.containsGIF() { return data } return super.responseObject(for: response, data: data, error: error) } } #endif
38.81295
139
0.576089
2869150ee3e4fd24757ad8a12eeeaa709eff17e4
1,261
// // iOSChartsSampleUITests.swift // iOSChartsSampleUITests // // Created by satorun on 2017/04/30. // Copyright © 2017年 satorun. All rights reserved. // import XCTest class iOSChartsSampleUITests: XCTestCase { override func setUp() { super.setUp() // 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 // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // 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 tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.081081
182
0.668517
fc42f710d78f17d022afdb73114c37b9b15d9029
917
final class UGCAddReviewTextCell: MWMTableViewCell { private enum Const { static let maxCharactersCount = 600 } @IBOutlet private weak var textView: MWMTextView! { didSet { textView.placeholder = L("placepage_reviews_hint") textView.font = UIFont.regular16() textView.textColor = UIColor.blackPrimaryText() textView.placeholderView.textColor = UIColor.blackSecondaryText() } } var reviewText: String! { get { return textView.text } set { textView.text = newValue } } var reviewLanguage: String? { get { return textView.textInputMode?.primaryLanguage } } } extension UGCAddReviewTextCell: UITextViewDelegate { func textView(_: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let isNewLengthValid = reviewText.count + text.count - range.length <= Const.maxCharactersCount return isNewLengthValid } }
29.580645
105
0.7241
5b57fe5b91c855a6cb3c250631abdd5506128468
947
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test var a = true if (a) { 5 } else { 7 } for i in 0..<3 { i } // CHECK: [{{.*}}] $builtin_log[a='true'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='5'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='0'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='1'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='2'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit
30.548387
139
0.607181
ded08aab58c5c6cfea2418ee1f0b5b19e3b278ed
583
import XCTest @testable import SOQLQueryBuilder final class SelectTests: XCTestCase { override class func setUp() { super.setUp() SOQLFunctionBuilder.whitespaceCharacter = .space } @SOQLFunctionBuilder func makeQuery() -> PartialQuery { Select(from: Test1Table.self) { test1 in test1.Field.allFields } } func test1() { let queryString = makeQuery().build() let expectedString = #"SELECT Id,Name,Field1__c,Field2__c FROM Test1__c"# XCTAssertEqual(queryString, expectedString) } static var allTests = [ ("test1", test1), ] }
21.592593
77
0.692967
500fd23e6aef82a505d6e5fe4742924082868108
1,492
// // AppDelegate.swift // Geo // // Created by Damian Durzyński on 25/02/2022. // import UIKit import IQKeyboardManagerSwift import Firebase @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. IQKeyboardManager.shared.enable = true FirebaseApp.configure() 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. } }
34.697674
179
0.737936
21264797391f9a3603190057f1f0e6b48ddd2266
2,991
// // AppDelegate.swift // // Copyright (c) 2017 OpenLocate // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import OpenLocate import Fabric import Crashlytics import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool { Fabric.with([Crashlytics.self]) configureOpenLocate() return true } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { OpenLocate.shared.performFetchWithCompletionHandler(completionHandler) } func configureOpenLocate() { UserDefaults.standard.register(defaults: ["TransmissionInterval": Configuration.defaultTransmissionInterval, "AuthorizationStatus": CLAuthorizationStatus.authorizedAlways.rawValue]) let url = URL(string: "http://35.164.252.47:4000/api/v1/data")! let transmissionInterval = UserDefaults.standard.double(forKey: "TransmissionInterval") let endpoint = Configuration.Endpoint(url: url, headers: [:]) let configuration = Configuration(endpoints: [endpoint], transmissionInterval: transmissionInterval, authorizationStatus: storedAuthorizationStatus()) try? OpenLocate.shared.initialize(with: configuration) } private func storedAuthorizationStatus() -> CLAuthorizationStatus { let authorizationStatusRaw = Int32(UserDefaults.standard.integer(forKey: "AuthorizationStatus")) return CLAuthorizationStatus(rawValue: authorizationStatusRaw) ?? .authorizedAlways } }
40.972603
122
0.708124
bffe4ba60ffb4544d78fa8e882df19c18711b3b2
1,133
// // EventDates.swift // Exposure // // Created by Udaya Sri Senarathne on 2019-09-16. // Copyright © 2019 emp. All rights reserved. // import Foundation /// Defines an *Exposure Event request* date parameters. public protocol FilteredEventDates { var eventDateFilter: EventDateFilter { get set } } /// Used internally to configure the event date filter public struct EventDateFilter { /// Days backwards internal let daysBackward: Int64 /// Days forward internal let daysForward: Int64 internal init(daysBackward: Int64 = 0, daysForward: Int64 = 85) { self.daysBackward = daysBackward self.daysForward = daysForward } } extension FilteredEventDates { /// Filter the event in a date range /// /// - Parameters: /// - daysBackward: days backward /// - daysForward: days forward /// - Returns: `Self` public func filter(daysBackward: Int64 = 0, daysForward: Int64 = 85) -> Self { var old = self old.eventDateFilter = EventDateFilter(daysBackward: daysBackward,daysForward: daysForward ) return old } }
25.177778
99
0.660194
6479c0adbf3391df03c27490b70d0dbe02f250ac
795
// // TableViewCell.swift // BasicTableView // // Created by 이봉원 on 11/04/2019. // Copyright © 2019 giftbot. All rights reserved. // import UIKit class MyTableViewCell: UITableViewCell { // 스토리보드일 때는 awakeFromNib() override func awakeFromNib() { super.awakeFromNib() } // 코드로 생성 시 override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) print("\n---------- [ init(style:reuserIdentifier) ] ----------") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() print("\n---------- [ prepareForReuse ] ----------") } deinit { print("Deinit") } }
21.486486
77
0.632704
efb651714b028912c93c3ee6ddd6d980ffb15bfb
1,522
import Foundation import PathLib import ProcessController import SimulatorPoolModels public final class SimulatorVideoRecorder { public enum CodecType: String { case h264 case hevc } private let processControllerProvider: ProcessControllerProvider private let simulatorUuid: UDID private let simulatorSetPath: AbsolutePath public init( processControllerProvider: ProcessControllerProvider, simulatorUuid: UDID, simulatorSetPath: AbsolutePath ) { self.processControllerProvider = processControllerProvider self.simulatorUuid = simulatorUuid self.simulatorSetPath = simulatorSetPath } public func startRecording( codecType: CodecType, outputPath: AbsolutePath ) throws -> CancellableRecording { let processController = try processControllerProvider.createProcessController( subprocess: Subprocess( arguments: [ "/usr/bin/xcrun", "simctl", "--set", simulatorSetPath, "io", simulatorUuid.value, "recordVideo", "--codec=\(codecType.rawValue)", outputPath ] ) ) try processController.start() return CancellableRecordingImpl( outputPath: outputPath, recordingProcess: processController ) } }
28.716981
86
0.593298
dbd730abdd5deb9bf41efac6e229c405072aa3ca
2,896
// // GetAllUnreadMessagesCountCallbacks.swift // FanapPodChatSDK // // Created by MahyarZhiani on 12/25/1398 AP. // Copyright © 1398 Mahyar Zhiani. All rights reserved. // import Foundation import SwiftyJSON import SwiftyBeaver import FanapPodAsyncSDK extension Chat { /// GetAllUnreadMessageCount Response comes from server /// /// - Outputs: /// - it doesn't have direct output, /// - but on the situation where the response is valid, /// - it will call the "onResultCallback" callback to getAllUnreadMessageCount function (by using "getAllUnreadMessagesCountCallbackToUser") func responseOfAllUnreadMessageCount(withMessage message: ChatMessage) { log.verbose("Message of type 'ALL_UNREAD_MESSAGE_COUNT' recieved", context: "Chat") let returnData = CreateReturnData(hasError: false, errorMessage: "", errorCode: 0, result: nil, resultAsArray: nil, resultAsString: message.content, contentCount: message.contentCount, subjectId: message.subjectId) if Chat.map[message.uniqueId] != nil { let callback: CallbackProtocol = Chat.map[message.uniqueId]! callback.onResultCallback(uID: message.uniqueId, response: returnData, success: { (successJSON) in self.getAllUnreadMessagesCountCallbackToUser?(successJSON) }) { _ in } Chat.map.removeValue(forKey: message.uniqueId) } } public class GetAllUnreadMessagesCountCallbacks: CallbackProtocol { func onResultCallback(uID: String, response: CreateReturnData, success: @escaping callbackTypeAlias, failure: @escaping callbackTypeAlias) { log.verbose("GetAllUnreadMessagesCountCallbacks", context: "Chat") if let unreadCountStr = response.resultAsString, let unreadCount = Int(unreadCountStr) { let unreadMessageCountModel = GetAllUnreadMessageCountResponse(unreadCount: unreadCount, hasError: false, errorMessage: "", errorCode: 0) success(unreadMessageCountModel) } } } }
43.223881
147
0.502072
0ebfa7efeca00a83e71142df7850e7ceb69e77d1
699
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #if os(Linux) import XCTest XCTMain([ testCase(SimpleTests.allTests), ]) #endif
31.772727
75
0.745351
dd8280eb4855142b69064240eb5a323845ac262a
2,656
// // StatusMenuController.swift // WcStatus // // Created by Michel Georgy on 04/04/16. // Copyright © 2016 Michel Georgy. All rights reserved. // import Cocoa class StatusMenuController: NSObject { @IBOutlet weak var statusMenu: NSMenu! @IBOutlet weak var occupiedTime: NSMenuItem! let disconnectedCachedTime = 10 let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) override func awakeFromNib() { let icon = NSImage(named: "menu-na") icon?.isTemplate = true // best for dark mode statusItem.button!.image = icon statusItem.menu = statusMenu // start timer with interval configured in settings // mainrunloop? Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(StatusMenuController.updateStatus), userInfo: nil, repeats: true) } @objc func updateStatus(){ // get status from server let statusApi = StatusApi() statusApi.fetchStatus( success: { status in NSLog("\(status)") var iconName = "menu-na" var timeString = "-" if(status.occupied == 1){ iconName = "menu-occupied" let minutes = status.time / 60; let seconds = status.time - (minutes * 60); timeString = String(format: "%dm %ds", minutes, seconds) } else { iconName = "menu-free" timeString = "" } // update image // Update time, set title to occupiedtime DispatchQueue.global(qos: .background).async { // Background Thread DispatchQueue.main.async { self.statusItem.button!.image = NSImage(named: iconName) self.occupiedTime.title = timeString } } } , failure: { error in let iconName = "menu-na" let timeString = "-" DispatchQueue.global(qos: .background).async { // Background Thread DispatchQueue.main.async { self.statusItem.button!.image = NSImage(named: iconName) self.occupiedTime.title = timeString } } } ) } @IBAction func quitClicked(sender: NSMenuItem) { NSApplication.shared.terminate(self) } }
34.051282
147
0.515813
1c8062b77c196e99e90026f04860344931323aaf
16,528
// Copyright (C) 2019 Parrot Drones SAS // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the Parrot Company nor the names // of its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. import XCTest @testable import GroundSdk /// Test DevToolbox peripheral. class DevToolboxTests: XCTestCase { private var store: ComponentStoreCore! private var impl: DevToolboxCore! private var backend: Backend! override func setUp() { super.setUp() store = ComponentStoreCore() backend = Backend() impl = DevToolboxCore(store: store!, backend: backend!) } func testPublishUnpublish() { impl.publish() assertThat(store!.get(Peripherals.devToolbox), present()) impl.unpublish() assertThat(store!.get(Peripherals.devToolbox), nilValue()) } func testDebugSettings() { impl.publish() var cnt = 0 let devToolbox = store.get(Peripherals.devToolbox)! _ = store.register(desc: Peripherals.devToolbox) { cnt += 1 } // test initial values assertThat(cnt, `is`(0)) assertThat(devToolbox.debugSettings, empty()) // update debug settings list var debugSettings: [DebugSettingCore] = [] debugSettings.append(impl.createDebugSetting(uid: 1, name: "1", readOnly: false, value: false)) debugSettings.append(impl.createDebugSetting(uid: 2, name: "2", readOnly: false, value: "value2")) debugSettings.append(impl.createDebugSetting(uid: 3, name: "3", readOnly: false, range: 5...6, step: 7, value: 5.5)) impl.update(debugSettings: debugSettings).notifyUpdated() assertThat(cnt, `is`(1)) assertThat(devToolbox.debugSettings, contains( allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: false), has(value: false)), allOf(has(name: "2"), `is`(readOnly: false), `is`(updating: false), has(value: "value2")), allOf(has(name: "3"), `is`(readOnly: false), `is`(updating: false), has(value: 5.5)) )) // update with en empty list debugSettings.removeAll() impl.update(debugSettings: debugSettings).notifyUpdated() assertThat(cnt, `is`(2)) assertThat(devToolbox.debugSettings, empty()) } func testWritableBooleanDebugSetting() { impl.publish() var cnt = 0 let devToolbox = store.get(Peripherals.devToolbox)! _ = store.register(desc: Peripherals.devToolbox) { cnt += 1 } // test initial values assertThat(cnt, `is`(0)) assertThat(devToolbox.debugSettings, empty()) assertThat(backend.boolSetting, nilValue()) // update debug settings list var debugSettings: [DebugSettingCore] = [] debugSettings.append(impl.createDebugSetting(uid: 1, name: "1", readOnly: false, value: false)) impl.update(debugSettings: debugSettings).notifyUpdated() assertThat(cnt, `is`(1)) assertThat(devToolbox.debugSettings.count, `is`(1)) assertThat(devToolbox.debugSettings, contains( allOf(has(name: "1"), `is`(readOnly: false), has(value: false)) )) // get debug setting and change its value let debugSetting = devToolbox.debugSettings[0] as? BoolDebugSettingCore assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: false), has(value: false)))) debugSetting?.value = true assertThat(cnt, `is`(2)) assertThat(backend.boolSetting, equalTo(debugSetting)) assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: true), has(value: true)))) // update value from low-level impl.update(debugSetting: debugSetting!, value: true).notifyUpdated() assertThat(cnt, `is`(3)) assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: false), has(value: true)))) // update to same value, nothing should change impl.update(debugSetting: debugSetting!, value: true).notifyUpdated() assertThat(cnt, `is`(3)) assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: false), has(value: true)))) } func testReadOnlyBooleanDebugSetting() { impl.publish() var cnt = 0 let devToolbox = store.get(Peripherals.devToolbox)! _ = store.register(desc: Peripherals.devToolbox) { cnt += 1 } // test initial values assertThat(cnt, `is`(0)) assertThat(devToolbox.debugSettings, empty()) assertThat(backend.boolSetting, nilValue()) // update debug settings list var debugSettings: [DebugSettingCore] = [] debugSettings.append(impl.createDebugSetting(uid: 1, name: "1", readOnly: true, value: false)) impl.update(debugSettings: debugSettings).notifyUpdated() assertThat(cnt, `is`(1)) assertThat(devToolbox.debugSettings.count, `is`(1)) assertThat(devToolbox.debugSettings, contains( allOf(has(name: "1"), `is`(readOnly: true), has(value: false)) )) // get debug setting and try to change its value let debugSetting = devToolbox.debugSettings[0] as? BoolDebugSettingCore assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: true), `is`(updating: false), has(value: false)))) debugSetting?.value = true assertThat(cnt, `is`(1)) assertThat(backend.boolSetting, nilValue()) assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: true), `is`(updating: false), has(value: false)))) } func testWritableTextDebugSetting() { impl.publish() var cnt = 0 let devToolbox = store.get(Peripherals.devToolbox)! _ = store.register(desc: Peripherals.devToolbox) { cnt += 1 } // test initial values assertThat(cnt, `is`(0)) assertThat(devToolbox.debugSettings, empty()) assertThat(backend.textSetting, nilValue()) // update debug settings list var debugSettings: [DebugSettingCore] = [] debugSettings.append(impl.createDebugSetting(uid: 1, name: "1", readOnly: false, value: "value")) impl.update(debugSettings: debugSettings).notifyUpdated() assertThat(cnt, `is`(1)) assertThat(devToolbox.debugSettings.count, `is`(1)) assertThat(devToolbox.debugSettings, contains( allOf(has(name: "1"), `is`(readOnly: false), has(value: "value")) )) // get debug setting and change its value let debugSetting = devToolbox.debugSettings[0] as? TextDebugSettingCore assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: false), has(value: "value")))) debugSetting?.value = "newValue" assertThat(cnt, `is`(2)) assertThat(backend.textSetting, equalTo(debugSetting)) assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: true), has(value: "newValue")))) // update value from low-level impl.update(debugSetting: debugSetting!, value: "newValue").notifyUpdated() assertThat(cnt, `is`(3)) assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: false), has(value: "newValue")))) // update to same value, nothing should change impl.update(debugSetting: debugSetting!, value: "newValue").notifyUpdated() assertThat(cnt, `is`(3)) assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: false), has(value: "newValue")))) } func testReadOnlyTextDebugSetting() { impl.publish() var cnt = 0 let devToolbox = store.get(Peripherals.devToolbox)! _ = store.register(desc: Peripherals.devToolbox) { cnt += 1 } // test initial values assertThat(cnt, `is`(0)) assertThat(devToolbox.debugSettings, empty()) assertThat(backend.textSetting, nilValue()) // update debug settings list var debugSettings: [DebugSettingCore] = [] debugSettings.append(impl.createDebugSetting(uid: 1, name: "1", readOnly: true, value: "value")) impl.update(debugSettings: debugSettings).notifyUpdated() assertThat(cnt, `is`(1)) assertThat(devToolbox.debugSettings.count, `is`(1)) assertThat(devToolbox.debugSettings, contains( allOf(has(name: "1"), `is`(readOnly: true), has(value: "value")) )) // get debug setting and try to change its value let debugSetting = devToolbox.debugSettings[0] as? TextDebugSettingCore assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: true), `is`(updating: false), has(value: "value")))) debugSetting?.value = "newValue" assertThat(cnt, `is`(1)) assertThat(backend.textSetting, nilValue()) assertThat(debugSetting, presentAnd( allOf(has(name: "1"), `is`(readOnly: true), `is`(updating: false), has(value: "value")))) } func testWritableNumericDebugSetting() { impl.publish() var cnt = 0 let devToolbox = store.get(Peripherals.devToolbox)! _ = store.register(desc: Peripherals.devToolbox) { cnt += 1 } // test initial values assertThat(cnt, `is`(0)) assertThat(devToolbox.debugSettings, empty()) assertThat(backend.numericSetting, nilValue()) // update debug settings list var debugSettings: [DebugSettingCore] = [] debugSettings.append(impl.createDebugSetting(uid: 1, name: "1", readOnly: false, range: 1...10, step: 0.2, value: 1.1)) impl.update(debugSettings: debugSettings).notifyUpdated() assertThat(cnt, `is`(1)) assertThat(devToolbox.debugSettings.count, `is`(1)) assertThat(devToolbox.debugSettings, contains( allOf(has(name: "1"), `is`(readOnly: false), has(value: 1.1)) )) // get debug setting and change its value let debugSetting = devToolbox.debugSettings[0] as? NumericDebugSettingCore assertThat(debugSetting, presentAnd(allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: false), has(value: 1.1), has(range: 1.0...10.0), has(step: 0.2)))) debugSetting?.value = 2.2 assertThat(cnt, `is`(2)) assertThat(backend.numericSetting, equalTo(debugSetting)) assertThat(debugSetting, presentAnd(allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: true), has(value: 2.2), has(range: 1.0...10.0), has(step: 0.2)))) // update value from low-level impl.update(debugSetting: debugSetting!, value: 2.2).notifyUpdated() assertThat(cnt, `is`(3)) assertThat(debugSetting, presentAnd(allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: false), has(value: 2.2), has(range: 1.0...10.0), has(step: 0.2)))) // update to same value, nothing should change impl.update(debugSetting: debugSetting!, value: 2.2).notifyUpdated() assertThat(cnt, `is`(3)) assertThat(debugSetting, presentAnd(allOf(has(name: "1"), `is`(readOnly: false), `is`(updating: false), has(value: 2.2), has(range: 1.0...10.0), has(step: 0.2)))) } func testReadOnlyNumericDebugSetting() { impl.publish() var cnt = 0 let devToolbox = store.get(Peripherals.devToolbox)! _ = store.register(desc: Peripherals.devToolbox) { cnt += 1 } // test initial values assertThat(cnt, `is`(0)) assertThat(devToolbox.debugSettings, empty()) assertThat(backend.numericSetting, nilValue()) // update debug settings list var debugSettings: [DebugSettingCore] = [] debugSettings.append(impl.createDebugSetting(uid: 1, name: "1", readOnly: true, range: 1...10, step: 0.2, value: 1.1)) impl.update(debugSettings: debugSettings).notifyUpdated() assertThat(cnt, `is`(1)) assertThat(devToolbox.debugSettings.count, `is`(1)) assertThat(devToolbox.debugSettings, contains( allOf(has(name: "1"), `is`(readOnly: true), has(value: 1.1)) )) // get debug setting and try to change its value let debugSetting = devToolbox.debugSettings[0] as? NumericDebugSettingCore assertThat(debugSetting, presentAnd(allOf(has(name: "1"), `is`(readOnly: true), `is`(updating: false), has(value: 1.1), has(range: 1.0...10.0), has(step: 0.2)))) debugSetting?.value = 2.2 assertThat(cnt, `is`(1)) assertThat(backend.textSetting, nilValue()) assertThat(debugSetting, presentAnd(allOf(has(name: "1"), `is`(readOnly: true), `is`(updating: false), has(value: 1.1), has(range: 1.0...10.0), has(step: 0.2)))) } func testDebugTag() { impl.publish() var cnt = 0 let devToolbox = store.get(Peripherals.devToolbox)! _ = store.register(desc: Peripherals.devToolbox) { cnt += 1 } // test initial values assertThat(cnt, `is`(0)) assertThat(devToolbox.latestDebugTagId, nilValue()) assertThat(backend.debugTag, nilValue()) // send a debug tag devToolbox.sendDebugTag(tag: "debug tag 1") assertThat(cnt, `is`(0)) assertThat(backend.debugTag, `is`("debug tag 1")) // receive debug tag id from drone impl.update(debugTagId: "debugTagId1").notifyUpdated() assertThat(cnt, `is`(1)) assertThat(devToolbox.latestDebugTagId, `is`("debugTagId1")) // update with same debug tag id, nothing should change impl.update(debugTagId: "debugTagId1").notifyUpdated() assertThat(cnt, `is`(1)) assertThat(devToolbox.latestDebugTagId, `is`("debugTagId1")) } } private class Backend: DevToolboxBackend { var boolSetting: BoolDebugSettingCore? var textSetting: TextDebugSettingCore? var numericSetting: NumericDebugSettingCore? var debugTag: String? func set(setting: BoolDebugSettingCore) { boolSetting = setting } func set(setting: TextDebugSettingCore) { textSetting = setting } func set(setting: NumericDebugSettingCore) { numericSetting = setting } func sendDebugTag(tag: String) { debugTag = tag } }
41.423559
114
0.6178
23e09ef46223f218987bcf2175502c9659c62077
6,938
// // NearestDeparturesDigitransitTests.swift // NearestDeparturesDigitransitTests // // Created by Toni Suominen on 11/01/2019. // Copyright © 2019 Toni Suominen. All rights reserved. // import XCTest @testable import NearestDeparturesDigitransit class NearestDeparturesDigitransitTests: XCTestCase { let lat = 62.914898 let lon = 27.707004 let timeout = 10.0 override func setUp() { _TransitData.httpClient = HTTP() } override func tearDown() { super.tearDown() } func test_stop_count() { let ex = self.expectation(description: "Returns correct amount of stops") TransitData.nearestStopsAndDepartures(lat, lon: lon, callback: {stops in XCTAssert(stops.count > 20 && stops.count < 35) // Note: API randomly returns a different amount of stops ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_stop_name() { let ex = self.expectation(description: "Returns stop name") TransitData.nearestStopsAndDepartures(lat, lon: lon, callback: {stops in XCTAssertEqual(stops[0].name, "Ankkuritie E") ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_stop_distance() { let ex = self.expectation(description: "Returns stop distance") TransitData.nearestStopsAndDepartures(lat, lon: lon, callback: {stops in XCTAssertEqual(stops[0].distance, "<50") XCTAssert(stops[1].distance == "59" || stops[1].distance == "60") ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_stop_coordinates() { let ex = self.expectation(description: "Returns stop coordinates") TransitData.nearestStopsAndDepartures(lat, lon: lon, callback: {stops in XCTAssertEqual(stops[0].lat, 62.914877) XCTAssertEqual(stops[0].lon, 27.706835) ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_stop_codes() { let ex = self.expectation(description: "Returns stop codes") TransitData.nearestStopsAndDepartures(lat, lon: lon, callback: {stops in XCTAssertEqual(stops[0].codeLong, "MATKA:7_201269") XCTAssertEqual(stops[0].codeShort, "1641") ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_departure_count() { let ex = self.expectation(description: "Returns correct amount of departures") TransitData.nearestStopsAndDepartures(lat, lon: lon, callback: {stops in XCTAssertEqual(stops.first?.departures.count ?? 0, 30) ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_departure_information() { let ex = self.expectation(description: "Returns departure information") TransitData.nearestStopsAndDepartures(lat, lon: lon, callback: {stops in // Destinations vary depending on the time of the day XCTAssertTrue( stops[0].departures[0].line.destination == "Neulamäki P" || stops[0].departures[0].line.destination == "Tukkipoika I" ) XCTAssertEqual(stops[0].departures[0].line.codeShort, "4") // Destinations vary depending on the time of the day XCTAssertTrue( stops[0].departures.destinations().contains("Neulamäki P") || stops[0].departures.destinations().contains("Tukkipoika I") ) ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_error_on_invalid_departures_update() { let ex = self.expectation(description: "Returns departure information") let invalidStop = Stop(name: "invalid stop", lat: 0.0, lon: 0.0, distance: "0", codeLong: "invalid long code", codeShort: "invalid short code", departures: []) TransitData.updateDeparturesForStops([invalidStop], callback: {stops, error in XCTAssertEqual(stops, [Optional(invalidStop)]) XCTAssertEqual(error!.localizedDescription, "The operation couldn’t be completed. (NearestDeparturesDigitransit.TransitDataError error 0.)") ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_coordinates_for_stop() { let ex = self.expectation(description: "Returns departure information") let stop = Stop(name: "Hovioikeus", lat: 0.0, lon: 0.0, distance: "", codeLong: "MATKA:201312", codeShort: "10 161", departures: []) TransitData.coordinatesForStop(stop, callback: {lat, lon in XCTAssertEqual(lat, 62.890472) XCTAssertEqual(lon, 27.672057) ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_departures_for_stop() { let ex = self.expectation(description: "Returns departure information") TransitData.departuresForStop("MATKA:7_201834", callback: {departures in XCTAssertEqual(departures.first?.line.destination ?? "", "Touvitie") ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_stops_for_rect() { let ex = self.expectation(description: "Returns departure information") TransitData.stopsForRect(minLat: 62.914700, minLon: 27.706297, maxLat: 62.915477, maxLon: 27.707981, callback: {stops in XCTAssertEqual(stops.count, 2) XCTAssertTrue(stops.contains(where: {$0.name == "Ankkuritie P"})) XCTAssertTrue(stops.contains(where: {$0.name == "Ankkuritie E"})) ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_stops_by_codes() { let ex = self.expectation(description: "Returns departure information") TransitData.stopsByCodes(codes: ["MATKA:7_201270", "MATKA:7_201269"], callback: {stops, error in XCTAssertEqual(stops.count, 2) XCTAssertTrue(stops.contains(where: {$0.name == "Ankkuritie P"})) XCTAssertTrue(stops.contains(where: {$0.name == "Ankkuritie E"})) ex.fulfill() }) self.wait(for: [ex], timeout: timeout) } func test_unwrapAndStripNils() { let ex = self.expectation(description: "Returns departure information") let stop1: Stop? = Stop(name: "foo", lat: 0, lon: 0, distance: "1", codeLong: "", codeShort: "", departures: []) let stop2: Stop? = Stop(name: "bar", lat: 0, lon: 0, distance: "1", codeLong: "", codeShort: "", departures: []) let nilStop: Stop? = nil let stops = [stop1, stop2, nilStop] let expected = [stop1!, stop2!] XCTAssertEqual(stops.unwrapAndStripNils(), expected) ex.fulfill() self.wait(for: [ex], timeout: timeout) } }
41.795181
167
0.616604
33ba6dacc4931a048f7ba204413b3c52ac2fc89b
7,266
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.A -always-argument-labels > %t.printed.A.txt // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.B -always-argument-labels > %t.printed.B.txt // RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt // RUN: %FileCheck %s -check-prefix=PRINTB -strict-whitespace < %t.printed.B.txt // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.APINotes -swift-version 3 -always-argument-labels | %FileCheck %s -check-prefix=PRINT-APINOTES-3 -strict-whitespace // RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=ImportAsMember.APINotes -swift-version 4 -always-argument-labels | %FileCheck %s -check-prefix=PRINT-APINOTES-4 -strict-whitespace // RUN: %target-typecheck-verify-swift -I %S/Inputs/custom-modules // PRINT: struct Struct1 { // PRINT-NEXT: var x: Double // PRINT-NEXT: var y: Double // PRINT-NEXT: var z: Double // PRINT-NEXT: init() // PRINT-NEXT: init(x x: Double, y y: Double, z z: Double) // PRINT-NEXT: } // Make sure the other extension isn't here. // PRINT-NOT: static var static1: Double // PRINT: extension Struct1 { // PRINT-NEXT: static var globalVar: Double // PRINT-NEXT: init(value value: Double) // PRINT-NEXT: init(specialLabel specialLabel: ()) // PRINT-NEXT: func inverted() -> Struct1 // PRINT-NEXT: mutating func invert() // PRINT-NEXT: func translate(radians radians: Double) -> Struct1 // PRINT-NEXT: func scale(_ radians: Double) -> Struct1 // PRINT-NEXT: var radius: Double { get nonmutating set } // PRINT-NEXT: var altitude: Double{{$}} // PRINT-NEXT: var magnitude: Double { get } // PRINT-NEXT: static func staticMethod() -> Int32 // PRINT-NEXT: static var property: Int32 // PRINT-NEXT: static var getOnlyProperty: Int32 { get } // PRINT-NEXT: func selfComesLast(x x: Double) // PRINT-NEXT: func selfComesThird(a a: Int32, b b: Float, x x: Double) // PRINT-NEXT: } // PRINT-NOT: static var static1: Double // Make sure the other extension isn't here. // PRINTB-NOT: static var globalVar: Double // PRINTB: extension Struct1 { // PRINTB: static var static1: Double // PRINTB-NEXT: static var static2: Float // PRINTB-NEXT: init(float value: Float) // PRINTB-NEXT: static var zero: Struct1 { get } // PRINTB-NEXT: } // PRINTB: var currentStruct1: Struct1 // PRINTB-NOT: static var globalVar: Double // PRINT-APINOTES-3: @available(swift, obsoleted: 3, renamed: "Struct1.oldApiNoteVar") // PRINT-APINOTES-3-NEXT: var IAMStruct1APINoteVar: Double // PRINT-APINOTES-3: extension Struct1 { // PRINT-APINOTES-3-NEXT: var oldApiNoteVar: Double // PRINT-APINOTES-3-NEXT: @available(swift, introduced: 4, renamed: "Struct1.oldApiNoteVar") // PRINT-APINOTES-3-NEXT: var newApiNoteVar: Double // PRINT-APINOTES-3-NEXT: @available(swift, introduced: 4, renamed: "IAMStruct1APINoteVarInSwift4") // PRINT-APINOTES-3-NEXT: var apiNoteVarInSwift4: Double // PRINT-APINOTES-3-NEXT: static func oldApiNoteMethod() // PRINT-APINOTES-3-NEXT: @available(swift, introduced: 4, renamed: "Struct1.oldApiNoteMethod()") // PRINT-APINOTES-3-NEXT: static func newApiNoteMethod() // PRINT-APINOTES-3-NEXT: init(oldLabel _: Int32) // PRINT-APINOTES-3-NEXT: @available(swift, introduced: 4, renamed: "Struct1.init(oldLabel:)") // PRINT-APINOTES-3-NEXT: init(newLabel _: Int32) // PRINT-APINOTES-3-NEXT: typealias OldApiNoteType = Double // PRINT-APINOTES-3-NEXT: @available(swift, introduced: 4, renamed: "Struct1.OldApiNoteType") // PRINT-APINOTES-3-NEXT: typealias NewApiNoteType = Struct1.OldApiNoteType // PRINT-APINOTES-3-NEXT: } // PRINT-APINOTES-3-NOT: @available // PRINT-APINOTES-3: var IAMStruct1APINoteVarInSwift4: Double // PRINT-APINOTES-3: @available(swift, obsoleted: 3, renamed: "Struct1.oldApiNoteMethod()") // PRINT-APINOTES-3-NEXT: func IAMStruct1APINoteFunction() // PRINT-APINOTES-3: @available(swift, obsoleted: 3, renamed: "Struct1.init(oldLabel:)") // PRINT-APINOTES-3-NEXT: func IAMStruct1APINoteCreateFunction(_ _: Int32) -> Struct1 // PRINT-APINOTES-3: @available(swift, obsoleted: 3, renamed: "Struct1.OldApiNoteType") // PRINT-APINOTES-3-NEXT: typealias IAMStruct1APINoteType = Struct1.OldApiNoteType // PRINT-APINOTES-4: @available(swift, obsoleted: 3, renamed: "Struct1.newApiNoteVar") // PRINT-APINOTES-4-NEXT: var IAMStruct1APINoteVar: Double // PRINT-APINOTES-4: extension Struct1 { // PRINT-APINOTES-4-NEXT: var newApiNoteVar: Double // PRINT-APINOTES-4-NEXT: @available(swift, obsoleted: 4, renamed: "Struct1.newApiNoteVar") // PRINT-APINOTES-4-NEXT: var oldApiNoteVar: Double // PRINT-APINOTES-4-NEXT: var apiNoteVarInSwift4: Double // PRINT-APINOTES-4-NEXT: static func newApiNoteMethod() // PRINT-APINOTES-4-NEXT: @available(swift, obsoleted: 4, renamed: "Struct1.newApiNoteMethod()") // PRINT-APINOTES-4-NEXT: static func oldApiNoteMethod() // PRINT-APINOTES-4-NEXT: init(newLabel _: Int32) // PRINT-APINOTES-4-NEXT: @available(swift, obsoleted: 4, renamed: "Struct1.init(newLabel:)") // PRINT-APINOTES-4-NEXT: init(oldLabel _: Int32) // PRINT-APINOTES-4-NEXT: typealias NewApiNoteType = Double // PRINT-APINOTES-4-NEXT: @available(swift, obsoleted: 4, renamed: "Struct1.NewApiNoteType") // PRINT-APINOTES-4-NEXT: typealias OldApiNoteType = Struct1.NewApiNoteType // PRINT-APINOTES-4-NEXT: } // PRINT-APINOTES-4: @available(swift, obsoleted: 4, renamed: "Struct1.apiNoteVarInSwift4") // PRINT-APINOTES-4-NEXT: var IAMStruct1APINoteVarInSwift4: Double // PRINT-APINOTES-4: @available(swift, obsoleted: 3, renamed: "Struct1.newApiNoteMethod()") // PRINT-APINOTES-4-NEXT: func IAMStruct1APINoteFunction() // PRINT-APINOTES-4: @available(swift, obsoleted: 3, renamed: "Struct1.init(newLabel:)") // PRINT-APINOTES-4-NEXT: func IAMStruct1APINoteCreateFunction(_ _: Int32) -> Struct1 // PRINT-APINOTES-4: @available(swift, obsoleted: 3, renamed: "Struct1.NewApiNoteType") // PRINT-APINOTES-4-NEXT: typealias IAMStruct1APINoteType = Struct1.NewApiNoteType import ImportAsMember.A import ImportAsMember.B import ImportAsMember.APINotes let iamStructFail = IAMStruct1CreateSimple() // expected-error@-1{{missing argument for parameter #1 in call}} var iamStruct = Struct1(x: 1.0, y: 1.0, z: 1.0) let gVarFail = IAMStruct1GlobalVar // expected-error@-1{{IAMStruct1GlobalVar' has been renamed to 'Struct1.globalVar'}} let gVar = Struct1.globalVar print("\(gVar)") let iamStructInitFail = IAMStruct1CreateSimple(42) // expected-error@-1{{'IAMStruct1CreateSimple' has been replaced by 'Struct1.init(value:)'}} let iamStructInitFail2 = Struct1(value: 42) let gVar2 = Struct1.static2 // Instance properties iamStruct.radius += 1.5 _ = iamStruct.magnitude // Static properties iamStruct = Struct1.zero // Global properties currentStruct1.x += 1.5
52.652174
277
0.726672
ef1224affc54e4d14ab3ed50be11350ab7f53d3b
3,122
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 XCTest class TabViewSteps: CucumberStepsDefinition { var application: XCUIApplication? func loadSteps() { let screen = ScreenRobot() before { scenarioDefinition in if scenarioDefinition?.tags.contains("tabview") ?? false { let url = "http://localhost:8080/tabview" self.application = TestUtils.launchBeagleApplication(url: url) } } Given("^the app did load tabview screen$") { _, _ -> Void in XCTAssertTrue(ScreenElements.TAB_1.element.exists) } Then("^my tabview components should render their respective tabs attributes correctly$") { _, _ -> Void in XCTAssertTrue(ScreenElements.TAB_1.element.exists) XCTAssertTrue(ScreenElements.TAB_1_TEXT.element.exists) XCTAssertTrue(ScreenElements.TAB_1_TEXT_2.element.exists) self.application?.swipeLeft() XCTAssertTrue(ScreenElements.TAB_2.element.exists) XCTAssertTrue(ScreenElements.TAB_2_TEXT.element.exists) XCTAssertTrue(ScreenElements.TAB_2_TEXT_2.element.exists) self.application?.swipeLeft() XCTAssertTrue(ScreenElements.TAB_3.element.exists) XCTAssertTrue(ScreenElements.TAB_3_TEXT.element.exists) XCTAssertTrue(ScreenElements.TAB_3_TEXT_2.element.exists) self.application?.swipeLeft() XCTAssertTrue(ScreenElements.TAB_4.element.exists) XCTAssertTrue(ScreenElements.TAB_4_TEXT.element.exists) XCTAssertTrue(ScreenElements.TAB_4_TEXT_2.element.exists) self.application?.swipeRight() self.application?.swipeRight() self.application?.swipeRight() } When("^I click on \"([^\\\"]*)\"$") { args, _ -> Void in guard let param = args?[0], let text: ScreenElements = ScreenElements(rawValue: param) else { return } screen.clickOnText(textOption: text) } Then("^my tab should render the text \"([^\\\"]*)\" and \"([^\\\"]*)\" correctly$") { args, _ -> Void in guard let text1: String = (args?[0]), let text2: String = (args?[1]) else { return } screen.selectedTextIsPresented(selectedText1: text1, selectedText2: text2) } } }
37.166667
114
0.623639
4a1cae79c8005a6198a2a9d6c612b9bd76797688
328
// // GithubRepoSearchSettings.swift // GithubDemo // // Created by Nhan Nguyen on 5/12/15. // Copyright (c) 2015 codepath. All rights reserved. // import Foundation // Model class that represents the user's search settings class GithubRepoSearchSettings { var searchString: String? var minStars = 0 init() { } }
16.4
57
0.707317
91f50a13cce97fb683030b63829a00c89a7caecd
1,376
// // Result.swift // DNWebSocket // // Created by Gleb Radchenko on 2/5/18. // import Foundation typealias Completion<T> = (Result<T>) -> Void enum Result<T> { case value(T) case error(Error) } extension Result { public var empty: Result<Void> { switch self { case let .error(error): return error.result() case .value: return .success } } public func onPositive(_ handler: (_ value: T) -> Void) { switch self { case .value(let value): handler(value) default: break } } public func onNegative(_ handler: (_ error: Error) -> Void) { switch self { case .error(let error): handler(error) default: break } } public func map<R>(_ transform: (T) throws -> R) -> Result<R> { do { switch self { case .value(let value): return .value(try transform(value)) case .error(let error): return error.result() } } catch { return error.result() } } } extension Result where T == Void { static var success: Result<T> { return .value(()) } } extension Error { func result<T>() -> Result<T> { return .error(self) } }
19.657143
67
0.493459
e866f05befe2c880dc52d91521e00c68185e0767
1,556
// // MainTabBarController.swift // HandicapCalculator // // Created by Артём on 21.09.2021. // import UIKit class MainTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() configureAppearance() setupViewControllers() } private func configureAppearance() { view.backgroundColor = .systemBackground } private func setupViewControllers() { viewControllers = [ createNavController(for: ModuleBuilder.createHandicapModule(), title: "Handicap", image: UIImage(named: "ScoreIcon")!), createNavController(for: ModuleBuilder.createScoreModule(), title: "Scores", image: UIImage(named: "CourseIcon")!) ] } private func createNavController(for rootViewController: UIViewController, title: String, image: UIImage) -> UINavigationController { let navViewController = UINavigationController(rootViewController: rootViewController) navigationController?.setNavigationBarHidden(true, animated: false) navViewController.tabBarItem.title = title navViewController.tabBarItem.image = image navViewController.navigationBar.prefersLargeTitles = true rootViewController.navigationItem.title = title return navViewController } }
32.416667
94
0.600257
e4d0527dfb02faf4425edad610824cd7696c380b
1,598
import UIKit import Accelerate func sqrtq(_ x: [Float]) -> [Float] { var results = [Float](repeating: 0.0, count: x.count) vvsqrtf(&results, x, [Int32(x.count)]) return results } let sliceSize = 128 var inputSlice = [Float](repeating: 0, count: sliceSize) var window = [Float](repeating: 0, count: sliceSize) var transfer = [Float](repeating: 0, count: sliceSize) vDSP_hann_window(&window, vDSP_Length(sliceSize), Int32(vDSP_HANN_NORM)) let log2n = UInt(round(log2(Double(sliceSize)))) let fftSetup = vDSP_create_fftsetup(log2n, Int32(kFFTRadix2)) var realp = [Float](repeating: 0, count: sliceSize/2) var imagp = [Float](repeating: 0, count: sliceSize/2) var outputSlice = DSPSplitComplex(realp: &realp, imagp: &imagp) let f1:Float = 8.1 for i in 0...sliceSize-1{ let x:Float = 2 * .pi * Float(i)/Float(sliceSize) inputSlice[i] = sin(f1*x) } //vDSP_vmul(&inputSlice, 1, &window, 1, &transfer, 1, vDSP_Length(sliceSize)) let temp = UnsafePointer<Float>(inputSlice) temp.withMemoryRebound(to: DSPComplex.self, capacity: transfer.count) { (typeConvertedTransferBuffer) -> Void in vDSP_ctoz(typeConvertedTransferBuffer, 2, &outputSlice, 1, vDSP_Length(sliceSize/2)) } vDSP_fft_zrip(fftSetup!, &outputSlice, 1, log2n, FFTDirection(FFT_FORWARD)) var magnitudes = [Float](repeating: 0.0, count: sliceSize/2) vDSP_zvmags(&outputSlice, 1, &magnitudes, 1, vDSP_Length(Int(sliceSize/2))) var normalizedMagnitudes = [Float](repeating: 0.0, count: sliceSize/2) let csize = sliceSize/2 for i in 0...csize-1{ normalizedMagnitudes[i] = sqrt(magnitudes[i])/Float(csize) }
34.73913
112
0.723404
ebc7ed43c13d47ee3cc806de825c6652fd65f860
2,175
// // AppDelegate.swift // SwiftWeibo // // Created by guyuanshan on 2018/10/26. // Copyright © 2018年 guyuanshan. 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.276596
285
0.756322
f86a67e21ffa7fee9210caff0cbe3209f3a3bb14
6,680
/* * Copyright 2017 WalmartLabs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit let kElectrodeBridgeRequestTimeoutTime = 10 let objectiveCPrimitives = [ String.self, String?.self, Double.self, Float.self, Bool.self, Int.self, Int?.self, Int8.self, Int16.self, Int32.self, Int64.self, ] as [Any.Type] enum Property<AnyClass> { case Class(AnyClass) case Struct } public enum GenerateObjectError: Error { case arrayTypeMissmatch case emptyArrayItemType case unsupportedType case unBridgeable case deserializationError } extension NSObject { // Returns the property type func getTypeOfProperty(_ name: String) -> Property<Any>? { var type: Mirror = Mirror(reflecting: self) for child in type.children { if child.label! == name { #if swift(>=4.0) let res = Swift.type(of: child.value) #else let res = type(of: child.value) #endif let tmp = ElectrodeUtilities.isObjectiveCPrimitives(type: res) return (!tmp) ? .Class(res) : .Struct } } while let parent = type.superclassMirror { for child in parent.children { if child.label! == name { #if swift(>=4.0) let res = Swift.type(of: child.value) #else let res = type(of: child.value) #endif let tmp = ElectrodeUtilities.isObjectiveCPrimitives(type: res) return (tmp) ? .Class(res) : .Struct } } type = parent } return nil } func toNSDictionary() -> NSDictionary { let type: Mirror = Mirror(reflecting: self) var res = [AnyHashable: Any]() for case let (label, value) in type.children { res[label!] = value } return res as NSDictionary } static func generateObjectFromDict(data: [AnyHashable: Any], passedClass: AnyClass) throws -> AnyObject { let stringForClass = String(reflecting: passedClass) guard let obj = NSClassFromString(stringForClass) as? ElectrodeObject.Type else { assertionFailure("Cannot proceed to convert dictionary to object type \(passedClass)") return NSObject() } let res = obj.init(dictionary: data) return res } public static func generateObject(data: Any, classType: Any.Type, itemType: Any.Type? = nil) throws -> Any { var res: Any // check to see if the type already matches. so no need to serialize or deserialize if type(of: data) == classType && !(data is Array<Any>) { return data } if ElectrodeUtilities.isObjectiveCPrimitives(type: classType) { res = data } else if data is NSDictionary { if let convertableData = data as? [AnyHashable: AnyObject] { let obj = try NSObject.generateObjectFromDict(data: convertableData, passedClass: classType as! AnyClass) res = obj } else { assertionFailure("failed here") return NSString() } } else if data is Array<Any> { if let arrayData = data as? Array<Any> { var tmpRes = Array<AnyObject>() guard let validItemType = itemType else { throw GenerateObjectError.emptyArrayItemType } for item in arrayData { var obj: AnyObject if ElectrodeUtilities.isObjectiveCPrimitives(type: validItemType) { obj = item as AnyObject } else { obj = try NSObject.generateObject(data: item as AnyObject, classType: validItemType) as AnyObject } tmpRes.append(obj) } res = tmpRes as AnyObject } else { throw GenerateObjectError.unsupportedType } } else { throw GenerateObjectError.unsupportedType } return res } } @objc class ElectrodeUtilities: NSObject { static func isObjectiveCPrimitives(type: Any.Type) -> Bool { return (objectiveCPrimitives.contains(where: { (aClass) -> Bool in aClass == type })) } static func convertObjectToBridgeMessageData(object: Any?) -> Any? { if let objectArray = object as? NSArray { let converted = ElectrodeUtilities.convertArrayToDictionary(object: objectArray) return converted } let convertedData = ElectrodeUtilities.convertSingleItemToBridgeReadyData(object: object) return convertedData } private static func convertArrayToDictionary(object: NSArray) -> Array<Any?> { var res = [Any?]() for item in object { if let itemArray = item as? NSArray { let convertedArray = ElectrodeUtilities.convertArrayToDictionary(object: itemArray) res.append(convertedArray) } else { let convertedItem = ElectrodeUtilities.convertSingleItemToBridgeReadyData(object: item) res.append(convertedItem) } } return res } private static func convertSingleItemToBridgeReadyData(object: Any?) -> Any? { let bridgeMessageReadyDictionary: Any? guard let validObject = object else { bridgeMessageReadyDictionary = nil return bridgeMessageReadyDictionary } #if swift(>=4.0) let type = Swift.type(of: validObject) #else let type = type(of: validObject) #endif if ElectrodeUtilities.isObjectiveCPrimitives(type: type) { return validObject } if let bridgeableObject = validObject as? Bridgeable { bridgeMessageReadyDictionary = bridgeableObject.toDictionary() return bridgeMessageReadyDictionary } return nil } }
33.4
121
0.591317
5bb246ac17e16536a01c07a4bd8feb988894f25b
3,406
import UIKit public struct TableViewAnimations { public typealias Animation = UITableView.RowAnimation public var sectionDelete = Animation.automatic public var sectionInsert = Animation.automatic public var sectionReload = Animation.automatic public var rowDelete = Animation.automatic public var rowInsert = Animation.automatic public var rowReload = Animation.automatic } public extension TableViewAnimations { static func automatic() -> Self { TableViewAnimations() } } public extension UITableView { func performUpdates(with diff: SectionedCollectionDiff, animations: TableViewAnimations = .automatic(), completion: @escaping () -> Void) { guard window != nil else { reloadData() return } let movedFromSections = IndexSet(diff.section.moves.map(\.from)) var sectionUpdates = diff.section.updatesBefore var sectionInsertions = diff.section.insertions var sectionRemovals = diff.section.removals var rowInsertions = diff.item.insertions var rowRemovals = diff.item.removals var rowUpdates = diff.item.updatesBefore var finalUpdatedSectionIndexes = IndexSet() for move in diff.item.moves { if movedFromSections.contains(move.from.section) { sectionUpdates.insert(move.from.section) finalUpdatedSectionIndexes.insert(move.to.section) rowInsertions.insert(move.to) } } for indexPath in rowRemovals { let section = indexPath.section if movedFromSections.contains(section) { sectionUpdates.insert(section) } } let sectionMoves = diff.section.moves.filter { move in if sectionUpdates.remove(move.from) == nil { return true } sectionRemovals.insert(move.from) sectionInsertions.insert(move.to) return false } let rowMoves = diff.item.moves.filter { move in if sectionRemovals.contains(move.from.section), !sectionInsertions.contains(move.to.section) { rowInsertions.insert(move.to) return false } if sectionInsertions.contains(move.to.section), !sectionRemovals.contains(move.from.section) { rowRemovals.insert(move.from) return false } if finalUpdatedSectionIndexes.contains(move.to.section) { rowRemovals.insert(move.from) return false } if sectionUpdates.contains(move.from.section) { return false } if rowUpdates.remove(move.from) == nil { return true } rowRemovals.insert(move.from) rowInsertions.insert(move.to) return false } performBatchUpdates { deleteSections(sectionRemovals, with: animations.sectionDelete) insertSections(sectionInsertions, with: animations.sectionInsert) deleteRows(at: Array(rowRemovals), with: animations.rowDelete) insertRows(at: Array(rowInsertions), with: animations.rowInsert) for move in sectionMoves { moveSection(move.from, toSection: move.to) } for move in rowMoves { moveRow(at: move.from, to: move.to) } if !rowUpdates.isEmpty { reloadRows(at: Array(rowUpdates), with: animations.rowReload) } if !sectionUpdates.isEmpty { reloadSections(sectionUpdates, with: animations.sectionReload) } } completion: { _ in completion() } } }
28.14876
100
0.677041
7aa1b6d9df3a5e58e56d5d93adb4dcaf877dca81
14,410
/*  * LocFileDocument.swift  * LocMapper App  *  * Created by François Lamboley on 12/2/15.  * Copyright © 2015 happn. All rights reserved.  */ import Cocoa import os.log import LocMapper private extension NSStoryboard.Name { static let main = "Main" } private extension NSStoryboard.SceneIdentifier { static let documentWindowController = "Document Window Controller" } private extension NSNib.Name { static let accessoryViewForImportReferenceTranslations = "AccessoryViewForImportReferenceTranslations" static let accessoryViewForImportKeyStructure = "AccessoryViewForImportKeyStructure" } class LocFileDocument: NSDocument, NSTokenFieldDelegate { /** If nil, the file is loading. */ var csvLocFile: LocFile? { didSet { sendRepresentedObjectToSubControllers(csvLocFile) } } override init() { csvLocFile = LocFile() super.init() } override func windowControllerDidLoadNib(_ aController: NSWindowController) { super.windowControllerDidLoadNib(aController) } override class var autosavesInPlace: Bool { return false } override func makeWindowControllers() { let storyboard = NSStoryboard(name: .main, bundle: nil) let windowController = storyboard.instantiateController(withIdentifier: .documentWindowController) as! NSWindowController addWindowController(windowController) mainViewController.handlerNotifyDocumentModification = { [weak self] in self?.updateChangeCount(.changeDone) } sendRepresentedObjectToSubControllers(csvLocFile) if let windowFrame = windowFrameToRestore { windowController.window?.setFrame(from: windowFrame) windowFrameToRestore = nil } if let uiState = uiStateToRestore { mainViewController.restoreUIState(with: uiState) } } override func write(to url: URL, ofType typeName: String) throws { /* Let's save the UI state */ if let frameStr = mainWindowController?.window?.frameDescriptor {csvLocFile?.setMetadataValue(frameStr, forKey: "UIWindowFrame")} else {csvLocFile?.removeMetadata(forKey: "UIWindowFrame")} do {try csvLocFile?.setMetadataValue(mainViewController.uiState, forKey: "UIState")} catch { os_log("Cannot save UIState metadata", type: .info) } /* We ask super to write the file. In effect this will call the method  * below to get the data to write in the file, then write those data. */ try super.write(to: url, ofType: typeName) /* We still need to save the metadata which are not saved in the data  * (anymore; we used to save them along the data). */ guard let metadata = csvLocFile?.serializedMetadata() else {return} metadata.withUnsafeBytes{ (ptr: UnsafeRawBufferPointer) -> Void in setxattr(url.absoluteURL.path, xattrMetadataName, ptr.baseAddress!, metadata.count, 0 /* Reserved, should be 0 */, 0 /* No options */) } } override func data(ofType typeName: String) throws -> Data { guard let csvLocFile = csvLocFile else { return Data() } var strData = "" csvLocFile.serializationStyle = .gitFriendly Swift.print(csvLocFile, terminator: "", to: &strData) return Data(strData.utf8) } override func read(from url: URL, ofType typeName: String) throws { assert(unserializedMetadata == nil) if url.isFileURL { let s = getxattr(url.absoluteURL.path, xattrMetadataName, nil, 0 /* Size */, 0 /* Reserved, should be 0 */, 0 /* No options */) if s >= 0 { /* We have the size of the xattr we want to read. Let's read it. */ var serializedMetadata = Data(count: s) let s2 = serializedMetadata.withUnsafeMutableBytes{ (ptr: UnsafeMutableRawBufferPointer) -> Int in return getxattr(url.absoluteURL.path, xattrMetadataName, ptr.baseAddress!, s, 0 /* Reserved, should be 0 */, 0 /* No options */) } if s2 >= 0 { /* We have read the xattr. Let's unserialize them! */ unserializedMetadata = LocFile.unserializedMetadata(from: serializedMetadata) } } windowFrameToRestore = (unserializedMetadata as? [String: Any?])?["UIWindowFrame"] as? String let uiState = (unserializedMetadata as? [String: Any?])?["UIState"] as? String uiStateToRestore = uiState.flatMap{ (try? JSONSerialization.jsonObject(with: Data($0.utf8), options: [])) as? [String: Any] } } try super.read(from: url, ofType: typeName) } override func read(from data: Data, ofType typeName: String) throws { /* Note: We may wanna move this in the read from url method (above) so the  * reading of the file is also done asynchronously to avoid blocking when  * big files or files on slow networks are opened. */ let metadata = unserializedMetadata unserializedMetadata = nil csvLocFile = nil DispatchQueue.global(qos: .userInitiated).async{ do { let locFile = try LocFile(filecontent: data, csvSeparator: ",", metadata: metadata) DispatchQueue.main.async{ self.csvLocFile = locFile } } catch { DispatchQueue.main.async{ let alert = NSAlert(error: error as NSError) alert.runModal() self.close() } } } } /* ***************    MARK: - Actions    *************** */ @IBAction func importReferenceTranslations(sender: AnyObject) { guard currentOpenPanel == nil, let csvLocFile = csvLocFile else { NSSound.beep() return } /* Getting accessory view. */ var objects: NSArray? Bundle.main.loadNibNamed(.accessoryViewForImportReferenceTranslations, owner: nil, topLevelObjects: &objects) let accessoryView = (objects ?? []).compactMap{ $0 as? NSView }.first! let tokenField = accessoryView.viewWithTag(1) as! NSTokenField tokenField.delegate = self tokenField.stringValue = csvLocFile.languages.joined(separator: ",") let openPanel = NSOpenPanel() currentOpenPanel = openPanel openPanel.canChooseFiles = true openPanel.allowedFileTypes = ["csv"] openPanel.canChooseDirectories = false if let u = latestURLToRefLocDir {openPanel.directoryURL = u} configureAccessoryView(accessoryView, forOpenPanel: openPanel) openPanel.beginSheetModal(for: windowForSheet!){ response in self.currentOpenPanel = nil guard response == .OK, let url = openPanel.url else {return} if url != self.latestURLToRefLocDir { self.latestURLToRefLocDir = url self.updateChangeCount(.changeDone) } let loadingWindow = UINavigationUtilities.createLoadingWindow() self.windowForSheet?.beginSheet(loadingWindow, completionHandler: nil) let languages = tokenField.stringValue.split(separator: ",").map(String.init) DispatchQueue.global().async { defer { DispatchQueue.main.async { self.mainViewController.noteContentHasChanged() self.windowForSheet?.endSheet(loadingWindow) self.updateChangeCount(.changeDone) } } do { let referenceTranslations = try XibRefLocFile(fromURL: url, languages: languages, csvSeparator: ",") csvLocFile.mergeRefLocsWithXibRefLocFile(referenceTranslations, mergeStyle: .add) } catch let error { DispatchQueue.main.async { NSAlert(error: error as NSError).beginSheetModal(for: self.windowForSheet!, completionHandler: nil) } } } } } @IBAction func importKeyStructure(sender: AnyObject) { guard currentOpenPanel == nil, let csvLocFile = csvLocFile else { NSSound.beep() return } let openPanel = NSOpenPanel() if let u = latestURLToKeyStructureImport {openPanel.directoryURL = u} /* Getting accessory view. */ let controller = ImportKeyStructurePanelController(nibName: .accessoryViewForImportKeyStructure, bundle: nil, csvLocFile: csvLocFile, openPanel: openPanel)! currentOpenPanel = openPanel configureAccessoryView(controller.view, forOpenPanel: openPanel) openPanel.beginSheetModal(for: windowForSheet!){ response in assert(Thread.isMainThread) openPanel.accessoryView = nil /* Fixes a crash... (macOS 10.12 (16A239j) */ self.currentOpenPanel = nil guard response == .OK else {return} if let url = openPanel.url {self.latestURLToKeyStructureImport = url} controller.saveImportSettings() self.updateChangeCount(.changeDone) /* Let's fetch all the data from the controller before dispatching  * async as we want the controller to be released on the main thread. */ let selectedImportType = controller.selectedImportType let excludedPaths = controller.excludedPaths let languageName = controller.importedLanguageName let importedFolder = controller.importedFolderForXcode let loadingWindow = UINavigationUtilities.createLoadingWindow() self.windowForSheet?.beginSheet(loadingWindow, completionHandler: nil) let url = openPanel.url let urls = openPanel.urls DispatchQueue.global().async{ defer { DispatchQueue.main.async{ self.mainViewController.noteContentHasChanged() self.windowForSheet?.endSheet(loadingWindow) self.updateChangeCount(.changeDone) } } do { switch selectedImportType { case .Xcode: guard let url = url else {return} let stringsFiles = try XcodeStringsFile.stringsFilesInProject(url.absoluteURL.path, excludedPaths: excludedPaths, includedPaths: ["/"+importedFolder+"/"]) csvLocFile.mergeXcodeStringsFiles(stringsFiles, folderNameToLanguageName: [importedFolder: languageName]) case .Android: for url in urls { let urlPath = url.absoluteURL.path let noFilename = url.deletingLastPathComponent() let folderName = noFilename.lastPathComponent let noFolderName = noFilename.deletingLastPathComponent() let relativePath = "./" + urlPath.dropFirst(noFolderName.absoluteURL.path.count + 1) if let androidXMLLocFile = try? AndroidXMLLocFile(fromPath: relativePath, relativeToProjectPath: noFolderName.absoluteURL.path) { csvLocFile.mergeAndroidXMLLocStringsFiles([androidXMLLocFile], folderNameToLanguageName: [folderName: languageName]) } } } } catch { DispatchQueue.main.async{ NSAlert(error: error as NSError).beginSheetModal(for: self.windowForSheet!, completionHandler: nil) } } } } } @IBAction func exportTranslations(sender: AnyObject) { let alert = NSAlert() alert.messageText = "Unimplemented" alert.informativeText = "This feature has not yet been implemented. Please check with the dev!" alert.addButton(withTitle: "OK") alert.beginSheetModal(for: windowForSheet!, completionHandler: nil) } /* ****************************    MARK: - Token Field Delegate    **************************** */ /* Implementing this method disables the whitespace-trimming behavior. */ func tokenField(_ tokenField: NSTokenField, representedObjectForEditing editingString: String) -> Any? { return editingString } /* ***************    MARK: - Private    *************** */ private let xattrMetadataName = "fr.ftw-and-co.LocMapperApp.LocFile.doc-metadata" private var uiStateToRestore: [String: Any]? private var windowFrameToRestore: String? private var unserializedMetadata: Any? private var currentOpenPanel: NSOpenPanel? private var latestURLToKeyStructureImport: URL? { get {return csvLocFile?.urlMetadataValueForKey("Key Structure Import — Latest Dir")} set { if let v = newValue {csvLocFile?.setMetadataValue(v, forKey: "Key Structure Import — Latest Dir")} else {csvLocFile?.removeMetadata(forKey: "Key Structure Import — Latest Dir")} } } private var latestURLToRefLocDir: URL? { get {return csvLocFile?.urlMetadataValueForKey("RefLoc Import — Latest Dir")} set { if let v = newValue {csvLocFile?.setMetadataValue(v, forKey: "RefLoc Import — Latest Dir")} else {csvLocFile?.removeMetadata(forKey: "RefLoc Import — Latest Dir")} } } private func sendRepresentedObjectToSubControllers(_ object: AnyObject?) { for w in windowControllers { w.contentViewController?.representedObject = csvLocFile } } private func configureAccessoryView(_ accessoryView: NSView, forOpenPanel openPanel: NSOpenPanel) { openPanel.accessoryView = accessoryView openPanel.isAccessoryViewDisclosed = true if let superview = accessoryView.superview { /* Adjust size of accessory view. */ accessoryView.frame.origin.x = superview.bounds.minX accessoryView.frame.size.width = superview.bounds.width accessoryView.autoresizingMask = [.width] /* Doesn't work though :( */ } } /* **********    MARK: → UI    ********** */ /* Root Window Controller */ private var mainWindowController: NSWindowController! { return windowControllers.first } /* Document Root & Loading UI */ private var mainViewController: LocFileDocTabViewController! { return mainWindowController.contentViewController as? LocFileDocTabViewController } /* Left Pane (Filters) */ private var filtersSplitViewController: LocFileDocFiltersSplitViewController! { return mainViewController.tabViewItemDocContent.viewController as? LocFileDocFiltersSplitViewController } private var filtersViewController: LocFileDocFiltersViewController! { return filtersSplitViewController.splitItemFilters.viewController as? LocFileDocFiltersViewController } /* Top-Right Pane (Translations) */ private var contentSplitViewController: LocFileDocContentSplitViewController! { return filtersSplitViewController.splitItemContent.viewController as? LocFileDocContentSplitViewController } private var tableViewController: LocFileDocTableViewController! { return contentSplitViewController.splitItemTableView.viewController as? LocFileDocTableViewController } /* Bottom-Right Pane (Details) */ private var locEntrySplitViewController: LocEntryViewController! { return contentSplitViewController.splitItemLocEntry.viewController as? LocEntryViewController } private var locEntryContextViewController: LocEntryContextViewController! { return locEntrySplitViewController.tabViewItemContext.viewController as? LocEntryContextViewController } private var locEntryMappingViewController: LocEntryMappingViewController! { return locEntrySplitViewController.tabViewItemMapping.viewController as? LocEntryMappingViewController } private var locEntryAdvancedMappingViewController: LocEntryAdvancedMappingViewController! { return locEntrySplitViewController.tabViewItemAdvancedMapping.viewController as? LocEntryAdvancedMappingViewController } }
35.060827
160
0.731298
394a560bb821d022c838a824cfd122099bdb16f5
791
// // CoreDataStore.swift // OceanTemperature // // Created by Kirby on 5/23/17. // Copyright © 2017 Kirby. All rights reserved. // import Foundation import CoreData class CoreDataStore { var persistentContainer: NSPersistentContainer var context: NSManagedObjectContext { return persistentContainer.viewContext } init(dataModel: String) { persistentContainer = NSPersistentContainer(name: dataModel) persistentContainer.loadPersistentStores { desc, error in if let error = error as NSError? { print("Persist container failed", error.localizedDescription) } } } func save() { guard context.hasChanges else { return } do { try context.save() } catch { print("Saving didn't work!", error) } } }
19.775
69
0.673831
ef448b1257787e5fc26612e870da327e5991e755
887
/** * Problem Link: https://leetcode.com/problems/roman-to-integer/ * * */ class Solution { func romanToInt(_ s: String) -> Int { let currency = [ "M" : 1000, "CM" : 900, "D" : 500, "CD" : 400, "C" : 100, "XC" : 90, "L" : 50, "XL" : 40, "X" : 10, "IX" : 9, "V" : 5, "IV" : 4, "I" : 1] let list = s.characters.map() {"\($0)"} var num = 0 var i = 0 while i < list.count { if i + 1 < list.count, let x = currency[list[i]], let y = currency[list[i+1]], x < y { num += currency[list[i] + list[i+1]]! i += 2 } else { num += currency[list[i]]! i += 1 } } return num } }
23.972973
98
0.337091
22caeb49b0d7aebef31e2f5279e19f02e2151c2c
13,206
import UIKit import MLBusinessComponents class PXBusinessResultViewModel: NSObject { let businessResult: PXBusinessResult let pointsAndDiscounts: PXPointsAndDiscounts? let paymentData: PXPaymentData let amountHelper: PXAmountHelper let debinBankName: String? var callback: ((PaymentResult.CongratsState, String?) -> Void)? // Default Image private lazy var approvedIconName = "default_item_icon" init(businessResult: PXBusinessResult, paymentData: PXPaymentData, amountHelper: PXAmountHelper, pointsAndDiscounts: PXPointsAndDiscounts?, debinBankName: String? = nil) { self.businessResult = businessResult self.paymentData = paymentData self.amountHelper = amountHelper self.pointsAndDiscounts = pointsAndDiscounts self.debinBankName = debinBankName super.init() } func getPaymentId() -> String? { guard let firstPaymentId = businessResult.getReceiptIdList()?.first else { return businessResult.getReceiptId() } return firstPaymentId } func headerCloseAction() -> (() -> Void) { let action = { [weak self] in guard let self = self else { return } if let callback = self.callback { var autoReturnUrl: URL? if let backUrl = self.pointsAndDiscounts?.backUrl, let url = URL(string: backUrl) { autoReturnUrl = url } else if let url = self.getBackUrl() { autoReturnUrl = url } if let autoReturnUrl = autoReturnUrl { PXNewResultUtil.openURL(url: autoReturnUrl, success: { _ in callback(PaymentResult.CongratsState.EXIT, nil) }) } else { callback(PaymentResult.CongratsState.EXIT, nil) } } } return action } func primaryResultColor() -> UIColor { return ResourceManager.shared.getResultColorWith(status: businessResult.getBusinessStatus().getDescription()) } func setCallback(callback: @escaping ((PaymentResult.CongratsState, String?) -> Void)) { self.callback = callback } func getBadgeImage() -> UIImage? { return ResourceManager.shared.getBadgeImageWith(status: businessResult.getBusinessStatus().getDescription()) } func getAttributedTitle(forNewResult: Bool = false) -> NSAttributedString { let title = businessResult.getTitle() let fontSize = forNewResult ? PXNewResultHeader.TITLE_FONT_SIZE : PXHeaderRenderer.TITLE_FONT_SIZE let attributes = [NSAttributedString.Key.font: Utils.getFont(size: fontSize)] let attributedString = NSAttributedString(string: title, attributes: attributes) return attributedString } func getErrorComponent() -> PXErrorComponent? { guard let labelInstruction = self.businessResult.getHelpMessage() else { return nil } let title = PXResourceProvider.getTitleForErrorBody() let props = PXErrorProps(title: title.toAttributedString(), message: labelInstruction.toAttributedString()) return PXErrorComponent(props: props) } func errorBodyView() -> UIView? { if let errorComponent = getErrorComponent() { return errorComponent.render() } return nil } func getHeaderDefaultIcon() -> UIImage? { if let brIcon = businessResult.getIcon() { return brIcon } else if let defaultImage = ResourceManager.shared.getImage(approvedIconName) { return defaultImage } return nil } func creditsExpectationView() -> UIView? { guard paymentData.paymentMethod?.id == PXPaymentTypes.CONSUMER_CREDITS.rawValue else { return nil } if let resultInfo = amountHelper.getPaymentData().getPaymentMethod()?.creditsDisplayInfo?.resultInfo, let title = resultInfo.title, let subtitle = resultInfo.subtitle, businessResult.isApproved() { return PXCreditsExpectationView(title: title, subtitle: subtitle) } return nil } private func getCongratsType() -> PXCongratsType { switch businessResult.getBusinessStatus() { case .APPROVED: return PXCongratsType.approved case .REJECTED: return PXCongratsType.rejected case .IN_PROGRESS: return PXCongratsType.inProgress case .PENDING: return PXCongratsType.pending default: return PXCongratsType.pending } } private func paymentMethodShouldBeShown() -> Bool { return businessResult.isApproved() } func getPaymentMethodsImageURLs() -> [String: String]? { return pointsAndDiscounts?.paymentMethodsImages } private func getLinkAction() -> PXAction? { return businessResult.getSecondaryAction() != nil ? businessResult.getSecondaryAction() : PXCloseLinkAction() } func getRedirectUrl() -> URL? { if let redirectURL = pointsAndDiscounts?.redirectUrl, !redirectURL.isEmpty { return getUrl(url: redirectURL, appendLanding: true) } return getUrl(backUrls: amountHelper.preference.redirectUrls, appendLanding: true) } private func shouldAutoReturn() -> Bool { guard let autoReturn = amountHelper.preference.autoReturn, let fieldId = PXNewResultUtil.PXAutoReturnTypes(rawValue: autoReturn), getBackUrl() != nil else { return false } let status = businessResult.getBusinessStatus() switch status { case .APPROVED: return fieldId == .APPROVED default: return fieldId == .ALL } } private func getUrl(url: String, appendLanding: Bool = false) -> URL? { if appendLanding { let landingURL = MLBusinessAppDataService().appendLandingURLToString(url) return URL(string: landingURL) } return URL(string: url) } private func getUrl(backUrls: PXBackUrls?, appendLanding: Bool = false) -> URL? { var urlString: String? let status = businessResult.getBusinessStatus() switch status { case .APPROVED: urlString = backUrls?.success case .PENDING: urlString = backUrls?.pending case .REJECTED: urlString = backUrls?.failure default: return nil } if let urlString = urlString, !urlString.isEmpty { if appendLanding { let landingURL = MLBusinessAppDataService().appendLandingURLToString(urlString) return URL(string: landingURL) } return URL(string: urlString) } return nil } func getBackUrl() -> URL? { return getUrl(backUrls: amountHelper.preference.backUrls) } } extension PXBusinessResultViewModel { func toPaymentCongrats() -> PXPaymentCongrats { let paymentCongratsData = PXPaymentCongrats() .withCongratsType(getCongratsType()) paymentCongratsData.withHeader(title: getAttributedTitle().string, imageURL: businessResult.getImageUrl(), closeAction: headerCloseAction()) .withHeaderColor(primaryResultColor()) .withHeaderImage(getHeaderDefaultIcon()) .withHeaderBadgeImage(getBadgeImage()) // Receipt paymentCongratsData.withReceipt(shouldShowReceipt: businessResult.mustShowReceipt(), receiptId: businessResult.getReceiptId(), action: pointsAndDiscounts?.viewReceiptAction) // Points & Discounts paymentCongratsData.withLoyalty(pointsAndDiscounts?.points) .withDiscounts(pointsAndDiscounts?.discounts) .withCrossSelling(pointsAndDiscounts?.crossSelling) .withCustomSorting(pointsAndDiscounts?.customOrder) .withExpenseSplit(pointsAndDiscounts?.expenseSplit) .withAutoReturn(pointsAndDiscounts?.autoReturn) paymentCongratsData.withInstructions(pointsAndDiscounts?.instruction) // Payment Info if let paymentMethodTypeId = paymentData.paymentMethod?.paymentTypeId, let paymentType = PXPaymentTypes(rawValue: paymentMethodTypeId) { paymentCongratsData.withPaymentMethodInfo(assemblePaymentMethodInfo(paymentData: paymentData, amountHelper: amountHelper, currency: SiteManager.shared.getCurrency(), paymentMethodType: paymentType)) } // Split PaymentInfo if amountHelper.isSplitPayment, let splitPaymentData = amountHelper.splitAccountMoney, let splitPaymentMethodTypeId = splitPaymentData.paymentMethod?.paymentTypeId, let splitPaymentType = PXPaymentTypes(rawValue: splitPaymentMethodTypeId) { paymentCongratsData.withSplitPaymentInfo(assemblePaymentMethodInfo(paymentData: splitPaymentData, amountHelper: amountHelper, currency: SiteManager.shared.getCurrency(), paymentMethodType: splitPaymentType)) } paymentCongratsData.shouldShowPaymentMethod(paymentMethodShouldBeShown()) .withStatementDescription(businessResult.getStatementDescription()) // Actions paymentCongratsData.withFooterMainAction(businessResult.getMainAction()).withFooterSecondaryAction(getLinkAction()) // Views paymentCongratsData.withTopView(businessResult.getTopCustomView()) .withImportantView(businessResult.getImportantCustomView()) .withBottomView(businessResult.getBottomCustomView()) .withCreditsExpectationView(creditsExpectationView()) .withErrorBodyView(errorBodyView()) // Tracking paymentCongratsData.withTrackingProperties(getTrackingProperties()) .withFlowBehaviorResult(getFlowBehaviourResult()) .withTrackingPath(getTrackingPath()) if let debinProperties = getDebinProperties() { paymentCongratsData.withBankTransferTrackingProperties(properties: debinProperties) } // URL Managment paymentCongratsData.withRedirectURLs(getRedirectUrl()) .shouldAutoReturn(shouldAutoReturn()) if let infoOperation = pointsAndDiscounts?.infoOperation { paymentCongratsData.withInfoOperation(infoOperation) } return paymentCongratsData } private func assemblePaymentMethodInfo(paymentData: PXPaymentData, amountHelper: PXAmountHelper, currency: PXCurrency, paymentMethodType: PXPaymentTypes/*, paymentMethodId: String*/) -> PXCongratsPaymentInfo { var paidAmount = "" if let transactionAmountWithDiscount = paymentData.getTransactionAmountWithDiscount() { paidAmount = Utils.getAmountFormated(amount: transactionAmountWithDiscount, forCurrency: currency) } else { paidAmount = Utils.getAmountFormated(amount: amountHelper.amountToPay, forCurrency: currency) } let lastFourDigits = paymentData.token?.lastFourDigits let transactionAmount = Utils.getAmountFormated(amount: paymentData.transactionAmount?.doubleValue ?? 0.0, forCurrency: currency) let installmentRate = paymentData.payerCost?.installmentRate let installmentsCount = paymentData.payerCost?.installments ?? 0 let installmentAmount = Utils.getAmountFormated(amount: paymentData.payerCost?.installmentAmount ?? 0.0, forCurrency: currency) let installmentsTotalAmount = Utils.getAmountFormated(amount: paymentData.payerCost?.totalAmount ?? 0.0, forCurrency: currency) let paymentMethodExtraInfo = paymentData.paymentMethod?.creditsDisplayInfo?.description?.message let discountName = paymentData.discount?.name var iconURL: String? if let paymentMethod = paymentData.paymentMethod, let paymentMethodsImageURLs = getPaymentMethodsImageURLs(), !paymentMethodsImageURLs.isEmpty { iconURL = PXNewResultUtil.getPaymentMethodIconURL(for: paymentMethod.id, using: paymentMethodsImageURLs) } return PXCongratsPaymentInfo(paidAmount: paidAmount, rawAmount: transactionAmount, paymentMethodName: paymentData.paymentMethod?.name, paymentMethodLastFourDigits: lastFourDigits, paymentMethodDescription: paymentMethodExtraInfo, paymentMethodIconURL: iconURL, paymentMethodType: paymentMethodType, installmentsRate: installmentRate, installmentsCount: installmentsCount, installmentsAmount: installmentAmount, installmentsTotalAmount: installmentsTotalAmount, discountName: discountName, displayInfo: paymentData.paymentMethod?.bankTransferDisplayInfo) } }
42.876623
219
0.661139
29a38a30c52acd928fa3e3fb3911c47a2a05aa26
220
// 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 A{{}protocol B{class B<a:b}}enum a<U{func a
36.666667
87
0.754545
eddf681618f55a8b8289571000dd42581c18e27a
604
#if MIXBOX_ENABLE_IN_APP_SERVICES import Foundation import MixboxFoundation import MixboxTestability final class AccessibilityUniqueObjectMap { static let shared = AccessibilityUniqueObjectMap() private init() {} private var weaklyBoxedElements = [String: WeakBox<TestabilityElement>]() func register(element: TestabilityElement) { weaklyBoxedElements[element.mb_testability_uniqueIdentifier()] = WeakBox(element) } func locate(uniqueIdentifier: String) -> TestabilityElement? { return weaklyBoxedElements[uniqueIdentifier]?.value } } #endif
26.26087
89
0.75
71eb0410cf9215f10749a598ae047105daa98c81
1,926
// // TodayViewController.swift // wemo_widget_today // // Created by Chris Kuburlis on 28/09/2014. // Copyright (c) 2014 Chris Kuburlis. All rights reserved. // import UIKit import NotificationCenter class TodayViewController: UIViewController, NCWidgetProviding, NSURLConnectionDataDelegate, WemoWidgetDelegate { var ww :WemoWidget? @IBOutlet weak var segmentOutlet: UISegmentedControl! @IBAction func segmentAction(sender: AnyObject) { // set the light status to the selected segment // segment 0 = off, 1 = on ww?.setStatus(LightState(rawValue: segmentOutlet.selectedSegmentIndex)!) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view from its nib. // initialise backend ww = WemoWidget(delegate: self) // deselect segment & disable user interaction segmentOutlet.selectedSegmentIndex = UISegmentedControlNoSegment segmentOutlet.userInteractionEnabled = false // if WeMo avaliable then enable user interaction if (ww!.avaliable) { segmentOutlet.userInteractionEnabled = true } } func newStatus(state: Bool?) { if let light = state { // if there's a valid light state, // false = off (segment 0), true = on (segment 1) segmentOutlet.selectedSegmentIndex = (light ? LightState.On.rawValue : LightState.Off.rawValue) } else { // deselect segmentOutlet.selectedSegmentIndex = UISegmentedControlNoSegment } } // needed so that the widget fills the whole super view area (doesn't have the weird offset & border) func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets { return UIEdgeInsetsZero } }
31.57377
113
0.65161
db7d8fc20d9323e5433d3852fa283ebb5ef4d42e
2,789
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /// /// This implementation of _org.antlr.v4.runtime.ANTLRErrorListener_ dispatches all calls to a /// collection of delegate listeners. This reduces the effort required to support multiple /// listeners. /// /// - Author: Sam Harwell /// public class ProxyErrorListener: ANTLRErrorListener { private final var delegates: [ANTLRErrorListener] public init(_ delegates: [ANTLRErrorListener]) { self.delegates = delegates } public func syntaxError<T>(_ recognizer: Recognizer<T>, _ offendingSymbol: AnyObject?, _ line: Int, _ charPositionInLine: Int, _ msg: String, _ e: AnyObject?) { for listener in delegates { listener.syntaxError(recognizer, offendingSymbol, line, charPositionInLine, msg, e) } } public func reportAmbiguity(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, _ stopIndex: Int, _ exact: Bool, _ ambigAlts: BitSet, _ configs: ATNConfigSet) { for listener in delegates { listener.reportAmbiguity(recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) } } public func reportAttemptingFullContext(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, _ stopIndex: Int, _ conflictingAlts: BitSet?, _ configs: ATNConfigSet) { for listener in delegates { listener.reportAttemptingFullContext(recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) } } public func reportContextSensitivity(_ recognizer: Parser, _ dfa: DFA, _ startIndex: Int, _ stopIndex: Int, _ prediction: Int, _ configs: ATNConfigSet) { for listener in delegates { listener.reportContextSensitivity(recognizer, dfa, startIndex, stopIndex, prediction, configs) } } }
39.28169
115
0.489423
d95ff8da51d44101303db9295e58680951e6bc57
690
// // Question.swift // Sample Marbella // // Created by KRISH JAIN on 22/11/2020. // import Foundation class Question { let questionImage: String let question: String let optionA: String let optionB: String let optionC: String let optionD: String let correctAnswer: Int init(image:String, questionText: String, choiceA: String, choiceB:String, choiceC: String, choiceD: String, answer: Int) { questionImage = image question = questionText optionA = choiceA optionB = choiceB optionC = choiceC optionD = choiceD correctAnswer = answer } }
21.5625
126
0.598551
ddee07ec8ca37f0ce419fa2324b80cf16b170516
3,893
// // AgentsOnline.swift // kayako-messenger-SDK // // Created by Robin Malhotra on 14/03/17. // Copyright © 2017 Robin Malhotra. All rights reserved. // import AsyncDisplayKit import PINCacheTexture class AgentsOnlineNode: ASCellNode { let backgroundNode = ASDisplayNode { () -> UIView in let effect = UIBlurEffect(style: .extraLight) let vibrancyEffect = UIVibrancyEffect(blurEffect: effect) let visualEffectView = UIVisualEffectView(effect: effect) let vibrancyView = UIVisualEffectView(effect: vibrancyEffect) vibrancyView.autoresizingMask = [.flexibleWidth, .flexibleHeight] visualEffectView.backgroundColor = .clear visualEffectView.contentView.addSubview(vibrancyView) return visualEffectView } let agents: [UserMinimal] var agentAvatars: [ASNetworkImageNode] = [] let headerNode = ConversationHeaderCell(headingText: "WE ARE HERE TO HELP", subheadingText: "") let onlineStatusText = ASTextNode() let container = ASDisplayNode() init(agents: [UserMinimal]) { self.agents = agents super.init() self.backgroundColor = .clear self.selectionStyle = .none let agentsToShow = agents.filter{ $0.firstName != nil } self.agentAvatars = [agentsToShow.first, agentsToShow.second, agentsToShow.third].flatMap{$0}.map { let node = ASNetworkImageNode() node.style.height = ASDimensionMake(50) node.style.width = ASDimensionMake(50) node.clipsToBounds = true node.layer.cornerRadius = 25.0 // node.url = $0.avatar node.setImageVM(.url($0.avatar)) return node } let onlineStatusString: String = { let agentFirstNames = agentsToShow.flatMap{ $0.firstName } if agentFirstNames.count > 2 { return "\(agentFirstNames.first!), \(agentFirstNames.second!) and \(agentFirstNames.third!) are online" } else if agentFirstNames.count == 2 { return "\(agentFirstNames.first!) and \(agentFirstNames.second!) are online" } else if agentFirstNames.count == 1 { return "\(agentFirstNames.first!) is online" } else { return "" } }() onlineStatusText.attributedText = NSAttributedString(string: onlineStatusString, attributes: KayakoLightStyle.HomescreenAttributes.widgetSubHeadingStyle) container.addSubnode(backgroundNode) container.addSubnode(headerNode) container.addSubnode(onlineStatusText) self.addSubnode(container) container.clipsToBounds = true container.layer.cornerRadius = 6.0 for node in self.agentAvatars { container.addSubnode(node) } container.layoutSpecBlock = { [weak self] _,size in guard let strongSelf = self else { return ASLayoutSpec() } var elements: [ASLayoutElement] = [strongSelf.headerNode] strongSelf.headerNode.style.spacingAfter = 6.0 let avatarStack = ASStackLayoutSpec(direction: .horizontal, spacing: 9, justifyContent: .start, alignItems: .center, children: strongSelf.agentAvatars) let avatarStackInset = ASInsetLayoutSpec(insets: UIEdgeInsetsMake(0, 18, 0, 9), child: avatarStack) elements.append(avatarStackInset) let onlineStatusInset = ASInsetLayoutSpec(insets: UIEdgeInsetsMake(0, 18, 9, 9), child: strongSelf.onlineStatusText) elements.append(onlineStatusInset) let stack = ASStackLayoutSpec(direction: .vertical, spacing: 7.0, justifyContent: .start, alignItems: .stretch, children: elements) let bg = ASBackgroundLayoutSpec(child: stack, background: strongSelf.backgroundNode) return ASInsetLayoutSpec(insets: UIEdgeInsetsMake(0, 0, 0, 0), child: bg) } self.transitionLayout(withAnimation: true, shouldMeasureAsync: true, measurementCompletion: nil) } open override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let stack = ASStackLayoutSpec(direction: .vertical, spacing: 0.0, justifyContent: .start, alignItems: .stretch, children: [container]) return ASInsetLayoutSpec(insets: UIEdgeInsetsMake(9, 0, 9, 0), child: stack) } }
38.166667
155
0.747752
480bf27ea4d3d12112b175d517def5c7b5f8c4f5
1,454
/** * (C) Copyright IBM Corp. 2018, 2019. * * 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 /** An error associated with a word from a custom language model. */ public struct WordError: Codable, Equatable { /** A key-value pair that describes an error associated with the definition of a word in the words resource. The pair has the format `"element": "message"`, where `element` is the aspect of the definition that caused the problem and `message` describes the problem. The following example describes a problem with one of the word's sounds-like definitions: `"{sounds_like_string}": "Numbers are not allowed in sounds-like. You can try for example '{suggested_string}'."`. */ public var element: String // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case element = "element" } }
37.282051
119
0.718707
2fde9b63e7060df8a97172891c47c53266272bf5
7,150
// // SIDProfileService.swift // StoryID // // Created by Sergey Ryazanov on 07.05.2020. // Copyright © 2020 breffi. All rights reserved. // import Foundation public class SIDProfileService: SIDServiceProtocol { public var isSynchronizable: Bool = true public private(set) var isSynchronizing: Bool = false private let observers = SIDObserveManager() public func synchronize(completion: @escaping SIDServiceHelper.SynchronizeBlock) { guard isSynchronizing == false else { completion(.alreadyInSync) return } func complete(error: SIDServiceHelper.ServiceError?) { completion(error) self.clearDeleted() self.isSynchronizing = false } self.isSynchronizing = true ProfileAPI.getProfile { serverProfile, error in if let error = error { complete(error: error.asServiceError) } else if let serverProfile = serverProfile { let localProfile = self.profile() let updateBehaviour = SIDServiceHelper.updateBehaviour(localModel: localProfile, serverDate: serverProfile.modifiedAt) switch updateBehaviour { case .update: let updatedModel = self.updateLocalModel(localProfile, with: serverProfile) self.notifyObservers(with: updatedModel) complete(error: nil) case .send: if let profile = localProfile { self.sendProfile(email: profile.email, emailVerified: profile.emailVerified, phone: profile.phone, phoneVerified: profile.phoneVerified, userName: profile.username) { _, error in complete(error: error?.asServiceError) } } case .skip: complete(error: nil) } } else { complete(error: nil) } } } @discardableResult private func updateLocalModel(_ localModel: IDContentProfile?, with serverModel: StoryProfile, isCreateIfNeeded: Bool = true) -> IDContentProfile? { var localModel = localModel if isCreateIfNeeded, localModel == nil { localModel = IDContentSNILS.create() } guard let lModel = localModel else { return nil } lModel.username = serverModel.username lModel.email = serverModel.email lModel.emailVerified = serverModel.emailVerified ?? false lModel.phone = serverModel.phone lModel.phoneVerified = serverModel.phoneVerified ?? false lModel.isEntityDeleted = false lModel.id = serverModel._id lModel.modifiedAt = serverModel.modifiedAt lModel.modifiedBy = serverModel.modifiedBy lModel.createdAt = serverModel.createdAt lModel.createdBy = serverModel.createdBy SIDCoreDataManager.instance.saveContext() return lModel } private func sendProfile(email: String?, emailVerified: Bool?, phone: String?, phoneVerified: Bool?, userName: String?, completion: @escaping (StoryProfile?, Error?) -> Void) { let body = StoryProfileDTO(email: email, emailVerified: emailVerified, phone: phone, phoneVerified: phoneVerified, username: userName) ProfileAPI.updateProfile(body: body, completion: completion) } private func clearDeleted() { guard let modelsForDeletion: [IDContentProfile] = IDContentProfile.models(userID: nil, deleteConduct: SIDDeleteConduct.only) else { return } let serverGroup = DispatchGroup() var deletedModels: [IDContentProfile] = [] for model in modelsForDeletion { serverGroup.enter() self.sendProfile(email: nil, emailVerified: nil, phone: nil, phoneVerified: nil, userName: nil) { _, error in if error == nil { deletedModels.append(model) } serverGroup.leave() } } serverGroup.notify(queue: DispatchQueue.main) { deletedModels.forEach { $0.deleteModel() } } SIDCoreDataManager.instance.saveContext() } // MARK: - Observer public func addObserver(_ observer: AnyObject, callback: @escaping (IDContentProfile?) -> Void) { callback(self.profile()) self.observers.addObserver(observer, type: SIDObserveManager.SIDObserver.ObserveType.both) { model in guard let model = model as? IDContentProfile else { return } callback(model) } } public func removeObserver(_ observer: AnyObject) { self.observers.removeObserver(observer) } private func notifyObservers(with model: IDContentProfile?) { for observer in self.observers.allObserver(with: .model) { observer.value.callback(model as AnyObject?) } } // MARK: - Public public func profile() -> IDContentProfile? { return IDContentProfile.firstModel() } public func setProfile(email: String?, emailVerified: Bool, phone: String?, phoneVerified: Bool, username: String?) { let profileModel = self.profile() ?? IDContentProfile.create() profileModel.email = email profileModel.emailVerified = emailVerified profileModel.phone = phone profileModel.phoneVerified = phoneVerified profileModel.username = username profileModel.modifiedAt = Date() profileModel.isEntityDeleted = false SIDCoreDataManager.instance.saveContext() } public func updateProfile(email: String?, emailVerified: Bool?, phone: String?, phoneVerified: Bool?, username: String?) { let profileModel = self.profile() ?? IDContentProfile.create() if let email = email { profileModel.email = email } if let emailVerified = emailVerified { profileModel.emailVerified = emailVerified } if let phone = phone { profileModel.phone = phone } if let phoneVerified = phoneVerified { profileModel.phoneVerified = phoneVerified } if let username = username { profileModel.username = username } profileModel.modifiedAt = Date() profileModel.isEntityDeleted = false SIDCoreDataManager.instance.saveContext() } public func markProfileAsDeleted() { self.profile()?.isEntityDeleted = true SIDCoreDataManager.instance.saveContext() } public func deleteProfile() { self.profile()?.deleteModel() SIDCoreDataManager.instance.saveContext() } }
35.75
152
0.590909
1d3e367ddf21173804b16382c75a3bfa0331ada4
4,194
// // InputSourceBarItem.swift // MTMR // // Created by Daniel Apatin on 22.04.2018. // Copyright © 2018 Anton Palgunov. All rights reserved. // import Cocoa class InputSourceBarItem: CustomButtonTouchBarItem { fileprivate var notificationCenter: CFNotificationCenter let buttonSize = NSSize(width: 21, height: 21) init(identifier: NSTouchBarItem.Identifier) { notificationCenter = CFNotificationCenterGetDistributedCenter() super.init(identifier: identifier, title: "⏳") observeIputSourceChangedNotification() textInputSourceDidChange() actions.append(ItemAction(trigger: .singleTap) { [weak self] in self?.switchInputSource() }) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { CFNotificationCenterRemoveEveryObserver(notificationCenter, UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque())) } @objc public func textInputSourceDidChange() { let currentSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue() var iconImage: NSImage? if let imageURL = currentSource.iconImageURL, let image = NSImage(contentsOf: imageURL) { iconImage = image } else if let iconRef = currentSource.iconRef { iconImage = NSImage(iconRef: iconRef) } if let iconImage = iconImage { iconImage.size = buttonSize image = iconImage title = "" } else { title = currentSource.name } } @objc private func switchInputSource() { var inputSources: [TISInputSource] = [] let currentSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue() let inputSourceNSArray = TISCreateInputSourceList(nil, false).takeRetainedValue() as NSArray let elements = inputSourceNSArray as! [TISInputSource] inputSources = elements.filter({ $0.category == TISInputSource.Category.keyboardInputSource && $0.isSelectable }) for item in inputSources { if item.id != currentSource.id { TISSelectInputSource(item) break } } } @objc public func observeIputSourceChangedNotification() { let callback: CFNotificationCallback = { _, observer, _, _, _ in let mySelf = Unmanaged<InputSourceBarItem>.fromOpaque(observer!).takeUnretainedValue() mySelf.textInputSourceDidChange() } CFNotificationCenterAddObserver(notificationCenter, UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()), callback, kTISNotifySelectedKeyboardInputSourceChanged, nil, .deliverImmediately) } } extension TISInputSource { enum Category { static var keyboardInputSource: String { return kTISCategoryKeyboardInputSource as String } } private func getProperty(_ key: CFString) -> AnyObject? { let cfType = TISGetInputSourceProperty(self, key) if cfType != nil { return Unmanaged<AnyObject>.fromOpaque(cfType!).takeUnretainedValue() } else { return nil } } var id: String { return getProperty(kTISPropertyInputSourceID) as! String } var name: String { return getProperty(kTISPropertyLocalizedName) as! String } var category: String { return getProperty(kTISPropertyInputSourceCategory) as! String } var isSelectable: Bool { return getProperty(kTISPropertyInputSourceIsSelectCapable) as! Bool } var sourceLanguages: [String] { return getProperty(kTISPropertyInputSourceLanguages) as! [String] } var iconImageURL: URL? { return getProperty(kTISPropertyIconImageURL) as! URL? } var iconRef: IconRef? { return OpaquePointer(TISGetInputSourceProperty(self, kTISPropertyIconRef)) as IconRef? } }
31.298507
128
0.628278
9bbf523c9e64802f3c647f14bb4451615c178a2b
1,731
// // TVShowNetworkEndPoint.swift // NetworkLayer // // Created by Ishtiak Ahmed on 04.04.20. // Copyright © 2020 Ishtiak Ahmed. All rights reserved. // import Foundation enum TVShowNetworkEndPoint { case latest case credits(tvId: String) case addRating(tvId: String) case deleteRating(tvId: String, value: Float) } extension TVShowNetworkEndPoint: NetworkEndPoint { var path: String { switch self { case .latest: return Constants.EndPoint.TVShow.Path.latest case .credits(let tvId): return Constants.EndPoint.TVShow.SemiPath.tv .appendPath(tvId) .appendPath(Constants.EndPoint.TVShow.SemiPath.credits) case .addRating(let tvId), .deleteRating(let tvId, _): return Constants.EndPoint.TVShow.SemiPath.tv .appendPath(tvId) .appendPath(Constants.EndPoint.TVShow.SemiPath.rating) } } var restMethod: RESTMethod { switch self { case .latest, .credits: return .get case .addRating: return .post case .deleteRating: return .delete } } var task: Task { let urlParameters = [Constants.EndPoint.Movie.URLParameter.apiKey: Constants.EndPoint.Movie.URLParameter.apiKeyValue] switch self { case .latest, .credits, .addRating: return .parameterizedRequest(urlParameters: urlParameters, bodyParameters: nil) case .deleteRating(_, let value): return .parameterizedRequest(urlParameters: urlParameters, bodyParameters: [Constants.EndPoint.TVShow.BodyParameter.valueKey: value]) } } }
30.910714
125
0.62565
e64e0f76579ddf7b03b3ddc2d81703c6dcfdad0d
1,197
//: Playground - noun: a place where people can play import UIKit let allComponents : NSCalendarUnit = [ .Era, .Year, .Month, .Day, .Hour, .Minute, .Second, .Weekday, .WeekdayOrdinal, .Quarter, .WeekOfMonth, .WeekOfYear, .YearForWeekOfYear, .Nanosecond, .Calendar, .TimeZone ] var today = NSDate(timeIntervalSince1970: -2207540000) var cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierChinese) cal?.component(.Year, fromDate: today) cal?.component(.Month, fromDate: today) cal?.component(.Day, fromDate: today) cal?.component(.Era, fromDate: today) let all = cal?.components(allComponents, fromDate: today) print(all) let fmt = NSDateFormatter() fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") fmt.dateStyle = .FullStyle fmt.calendar = cal print(fmt.stringFromDate(today)) let chineseCal = NSCalendar(calendarIdentifier: NSCalendarIdentifierChinese)! let year = chineseCal.component(.Year, fromDate: today) let month = chineseCal.component(.Month, fromDate: today) let day = chineseCal.component(.Day, fromDate: today) debugPrint(year,month,day) let y = ( (year - 1) % 12) year - 1 debugPrint("year",year,y)
23.94
77
0.715957
62a5a04bf6da77105696e39703e111d3733131f8
238
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache 2.0 */ import Foundation enum NetworkUnitError: Error { case serviceUnavailable case brokenServiceEndpoint case typeMappingMissing }
18.307692
52
0.752101
64185a3f1f665bc265f9b744593f395a07471d03
3,132
// // NTNavigationController.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 2/12/17. // open class NTNavigationController: UINavigationController, UINavigationControllerDelegate { // MARK: - Initialization public convenience init() { self.init(nibName: nil, bundle: nil) } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) navigationBar.tintColor = Color.Default.Tint.NavigationBar navigationBar.barTintColor = Color.Default.Background.NavigationBar navigationBar.backgroundColor = Color.Default.Background.NavigationBar navigationBar.isTranslucent = false navigationBar.shadowImage = UIImage() navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navigationBar.setDefaultShadow() setup() } open func setup() { delegate = self updateStatusBarStyle() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Updates the status bar style to light or default based on the background color of the navigation bar open func updateStatusBarStyle() { guard let color = navigationBar.backgroundColor else { return } if color.isLight { UIApplication.shared.statusBarStyle = .default } else { UIApplication.shared.statusBarStyle = .lightContent } } open func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { viewController.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil) } }
39.64557
143
0.706577
33f5e4b60cd144c6c257bb1ef33346bbe27dc146
192
// // Rest.swift // // Created by Igor Shelopaev on 04.05.2021. // import Foundation //The Rest proxy simply maps the four actions (create, read, update and destroy) to RESTful HTTP verbs
19.2
102
0.713542
480f9808a2ee445d612ee2b25a271c682e3246c5
4,538
// SwiftHEXColors.swift // // Copyright (c) 2014 Doan Truong Thi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) import UIKit typealias SWColor = UIColor #else import Cocoa typealias SWColor = NSColor #endif /// An extension of UIColor (on iOS) or NSColor (on OSX) providing HEX color handling. public extension SWColor { /** Create non-autoreleased color with in the given hex string. Alpha will be set as 1 by default. - parameter hexString: The hex string, with or without the hash character. - returns: A color with the given hex string. */ public convenience init?(hexString: String) { self.init(hexString: hexString, alpha: 1.0) } /** Create non-autoreleased color with in the given hex string and alpha. - parameter hexString: The hex string, with or without the hash character. - parameter alpha: The alpha value, a floating value between 0 and 1. - returns: A color with the given hex string and alpha. */ public convenience init?(hexString: String, alpha: Float) { var hex = hexString // Check for hash and remove the hash if hex.hasPrefix("#") { hex = hex.substringFromIndex(hex.startIndex.advancedBy(1)) } if (hex.rangeOfString("(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .RegularExpressionSearch) != nil) { // Deal with 3 character Hex strings if hex.characters.count == 3 { let redHex = hex.substringToIndex(hex.startIndex.advancedBy(1)) let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(2))) let blueHex = hex.substringFromIndex(hex.startIndex.advancedBy(2)) hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex } let redHex = hex.substringToIndex(hex.startIndex.advancedBy(2)) let greenHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(2), end: hex.startIndex.advancedBy(4))) let blueHex = hex.substringWithRange(Range<String.Index>(start: hex.startIndex.advancedBy(4), end: hex.startIndex.advancedBy(6))) var redInt: CUnsignedInt = 0 var greenInt: CUnsignedInt = 0 var blueInt: CUnsignedInt = 0 NSScanner(string: redHex).scanHexInt(&redInt) NSScanner(string: greenHex).scanHexInt(&greenInt) NSScanner(string: blueHex).scanHexInt(&blueInt) self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha)) } else { // Note: // The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases, // so it disallows formation of a situation where it would have to. We consider this a bug to be fixed // in future releases, not a feature. -- Apple Forum self.init() return nil } } /** Create non-autoreleased color with in the given hex value. Alpha will be set as 1 by default. - parameter hex: The hex value. For example: 0xff8942 (no quotation). - returns: A color with the given hex value */ public convenience init?(hex: Int) { self.init(hex: hex, alpha: 1.0) } /** Create non-autoreleased color with in the given hex value and alpha - parameter hex: The hex value. For example: 0xff8942 (no quotation). - parameter alpha: The alpha value, a floating value between 0 and 1. - returns: color with the given hex value and alpha */ public convenience init?(hex: Int, alpha: Float) { let hexString = NSString(format: "%2X", hex) self.init(hexString: hexString as String , alpha: alpha) } }
39.46087
134
0.724769
0aaf75e2f79180a894d59d025c97fca86682b32e
2,322
import XCTest import GRDB class FoundationNSUUIDTests: GRDBTestCase { private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: NSUUID?) throws { try makeDatabaseQueue().read { db in if let expectedUUID = expectedUUID { let decodedUUID = try NSUUID.fetchOne(db, sql: "SELECT ?", arguments: [value]) XCTAssertEqual(decodedUUID, expectedUUID) } else if value == nil { let decodedUUID = try Optional<NSUUID>.fetchAll(db, sql: "SELECT NULL")[0] XCTAssertNil(decodedUUID) } } let decodedUUID = NSUUID.fromDatabaseValue(value?.databaseValue ?? .null) XCTAssertEqual(decodedUUID, expectedUUID) } private func assertRoundTrip(_ uuid: UUID) throws { let string = uuid.uuidString var uuid_t = uuid.uuid let data = withUnsafeBytes(of: &uuid_t) { Data(bytes: $0.baseAddress!, count: $0.count) } try assert(string, isDecodedAs: uuid as NSUUID) try assert(string.lowercased(), isDecodedAs: uuid as NSUUID) try assert(string.uppercased(), isDecodedAs: uuid as NSUUID) try assert(uuid, isDecodedAs: uuid as NSUUID) try assert(uuid as NSUUID, isDecodedAs: uuid as NSUUID) try assert(data, isDecodedAs: uuid as NSUUID) } func testSuccess() throws { try assertRoundTrip(UUID(uuidString: "56e7d8d3-e9e4-48b6-968e-8d102833af00")!) try assertRoundTrip(UUID()) try assert("abcdefghijklmnop".data(using: .utf8)!, isDecodedAs: NSUUID(uuidString: "61626364-6566-6768-696A-6B6C6D6E6F70")) } func testFailure() throws { try assert(nil, isDecodedAs: nil) try assert(DatabaseValue.null, isDecodedAs: nil) try assert(1, isDecodedAs: nil) try assert(100000.1, isDecodedAs: nil) try assert("56e7d8d3e9e448b6968e8d102833af0", isDecodedAs: nil) try assert("56e7d8d3-e9e4-48b6-968e-8d102833af0!", isDecodedAs: nil) try assert("foo", isDecodedAs: nil) try assert("bar".data(using: .utf8)!, isDecodedAs: nil) try assert("abcdefghijklmno".data(using: .utf8)!, isDecodedAs: nil) try assert("abcdefghijklmnopq".data(using: .utf8)!, isDecodedAs: nil) } }
43.811321
131
0.643842
793ddac639793af03d9842a0f9b598a3f656a51e
11,010
// // 🦠 Corona-Warn-App // import FMDB import Foundation final class DownloadedPackagesSQLLiteStoreV1 { struct StoreError: Error { init(_ message: String) { self.message = message } let message: String } // MARK: Creating a Store init( database: FMDatabase, migrator: SerialMigratorProtocol, latestVersion: Int ) { self.database = database self.migrator = migrator self.latestVersion = latestVersion } private func _beginTransaction() { database.beginExclusiveTransaction() } private func _commit() { database.commit() } // MARK: Properties #if !RELEASE var keyValueStore: Store? #endif private let latestVersion: Int private let queue = DispatchQueue(label: "com.sap.DownloadedPackagesSQLLiteStore") private let database: FMDatabase private let migrator: SerialMigratorProtocol } extension DownloadedPackagesSQLLiteStoreV1: DownloadedPackagesStoreV1 { func open() { queue.sync { self.database.open() if self.database.tableExists("Z_DOWNLOADED_PACKAGE") { do { try self.migrator.migrate() } catch { Log.error("Migration failed!", log: .localData, error: error) fatalError("Migration failed! \(error)") } } else { self.database.executeStatements( """ PRAGMA locking_mode=EXCLUSIVE; PRAGMA auto_vacuum=2; PRAGMA journal_mode=WAL; CREATE TABLE Z_DOWNLOADED_PACKAGE ( Z_BIN BLOB NOT NULL, Z_SIGNATURE BLOB NOT NULL, Z_DAY TEXT NOT NULL, Z_HOUR INTEGER, Z_COUNTRY STRING NOT NULL, PRIMARY KEY ( Z_COUNTRY, Z_DAY, Z_HOUR ) ); """ ) self.database.userVersion = UInt32(self.latestVersion) } } } func close() { _ = queue.sync { self.database.close() } } @discardableResult func set( country: Country.ID, day: String, package: SAPDownloadedPackage ) -> Result<Void, SQLiteErrorCode> { #if !RELEASE if let store = keyValueStore, let errorCode = store.fakeSQLiteError { return .failure(error(for: errorCode)) } #endif func deleteHours() -> Bool { database.executeUpdate( """ DELETE FROM Z_DOWNLOADED_PACKAGE WHERE Z_COUNTRY = :country AND Z_DAY = :day AND Z_HOUR IS NOT NULL ; """, withParameterDictionary: [ "country": country, "day": day ] ) } func insertDay() -> Bool { database.executeUpdate( """ INSERT INTO Z_DOWNLOADED_PACKAGE ( Z_BIN, Z_SIGNATURE, Z_DAY, Z_HOUR, Z_COUNTRY ) VALUES ( :bin, :signature, :day, NULL, :country ) ON CONFLICT ( Z_COUNTRY, Z_DAY, Z_HOUR ) DO UPDATE SET Z_BIN = :bin, Z_SIGNATURE = :signature ; """, withParameterDictionary: [ "bin": package.bin, "signature": package.signature, "day": day, "country": country ] ) } queue.sync { self._beginTransaction() guard deleteHours() else { self.database.rollback() return } guard insertDay() else { self.database.rollback() return } self._commit() } let lastErrorCode = database.lastErrorCode() if lastErrorCode == 0 { return .success(()) } else { return .failure(error(for: lastErrorCode)) } } private func error(for sqliteErrorCode: Int32) -> SQLiteErrorCode { if let error = SQLiteErrorCode(rawValue: sqliteErrorCode) { return error } else { return .unknown } } @discardableResult func set( country: Country.ID, hour: Int, day: String, package: SAPDownloadedPackage ) -> Result<Void, SQLiteErrorCode> { queue.sync { let sql = """ INSERT INTO Z_DOWNLOADED_PACKAGE( Z_BIN, Z_SIGNATURE, Z_DAY, Z_HOUR, Z_COUNTRY ) VALUES ( :bin, :signature, :day, :hour, :country ) ON CONFLICT( Z_COUNTRY, Z_DAY, Z_HOUR ) DO UPDATE SET Z_BIN = :bin, Z_SIGNATURE = :signature ; """ let parameters: [String: Any] = [ "bin": package.bin, "signature": package.signature, "day": day, "hour": hour, "country": country ] self.database.executeUpdate(sql, withParameterDictionary: parameters) } let lastErrorCode = database.lastErrorCode() if lastErrorCode == 0 { return .success(()) } else { return .failure(error(for: lastErrorCode)) } } func package(for day: String, country: Country.ID) -> SAPDownloadedPackage? { queue.sync { let sql = """ SELECT Z_BIN, Z_SIGNATURE FROM Z_DOWNLOADED_PACKAGE WHERE Z_COUNTRY = :country AND Z_DAY = :day AND Z_HOUR IS NULL ; """ let parameters: [String: Any] = [ "day": day, "country": country ] guard let result = self.database.execute(query: sql, parameters: parameters) else { return nil } defer { result.close() } return result .map { $0.downloadedPackage() } .compactMap { $0 } .first } } func hourlyPackages(for day: String, country: Country.ID) -> [SAPDownloadedPackage] { queue.sync { let sql = """ SELECT Z_BIN, Z_SIGNATURE, Z_HOUR FROM Z_DOWNLOADED_PACKAGE WHERE Z_COUNTRY = :country AND Z_DAY = :day AND Z_HOUR IS NOT NULL ORDER BY Z_HOUR DESC ; """ let parameters: [String: Any] = [ "day": day, "country": country ] guard let result = self.database.execute(query: sql, parameters: parameters) else { return [] } defer { result.close() } return result .map { $0.downloadedPackage() } .compactMap { $0 } } } func allDays(country: Country.ID) -> [String] { queue.sync { let sql = """ SELECT Z_DAY FROM Z_DOWNLOADED_PACKAGE WHERE Z_COUNTRY = :country AND Z_HOUR IS NULL ; """ let parameters: [String: Any] = [ "country": country ] guard let result = self.database.execute(query: sql, parameters: parameters) else { return [] } defer { result.close() } return result .map { $0.string(forColumn: "Z_DAY") } .compactMap { $0 } } } func hours(for day: String, country: Country.ID) -> [Int] { let sql = """ SELECT Z_HOUR FROM Z_DOWNLOADED_PACKAGE WHERE Z_HOUR IS NOT NULL AND Z_DAY = :day AND Z_COUNTRY = :country ; """ let parameters: [String: Any] = [ "day": day, "country": country ] return queue.sync { guard let result = self.database.execute(query: sql, parameters: parameters) else { return [] } defer { result.close() } return result.map { Int($0.int(forColumn: "Z_HOUR")) } } } func reset() { _ = queue.sync { self.database.executeStatements( """ PRAGMA journal_mode=OFF; DROP TABLE Z_DOWNLOADED_PACKAGE; VACUUM; """ ) } } func deleteDayPackage(for day: String, country: Country.ID) { queue.sync { let sql = """ DELETE FROM Z_DOWNLOADED_PACKAGE WHERE Z_COUNTRY = :country AND Z_DAY = :day AND Z_HOUR IS NULL ; """ let parameters: [String: Any] = ["country": country, "day": day] self.database.executeUpdate(sql, withParameterDictionary: parameters) } } func deleteHourPackage(for day: String, hour: Int, country: Country.ID) { queue.sync { let sql = """ DELETE FROM Z_DOWNLOADED_PACKAGE WHERE Z_COUNTRY = :country AND Z_DAY = :day AND Z_HOUR = :hour ; """ let parameters: [String: Any] = [ "country": country, "day": day, "hour": hour ] self.database.executeUpdate(sql, withParameterDictionary: parameters) } } } private extension FMDatabase { func execute( query sql: String, parameters: [AnyHashable: Any] = [:] ) -> FMResultSet? { executeQuery(sql, withParameterDictionary: parameters) } } private extension FMResultSet { func map<T>(transform: (FMResultSet) -> T) -> [T] { var mapped = [T]() while next() { mapped.append(transform(self)) } return mapped } func downloadedPackage() -> SAPDownloadedPackage? { guard let bin = data(forColumn: "Z_BIN"), let signature = data(forColumn: "Z_SIGNATURE") else { return nil } return SAPDownloadedPackage(keysBin: bin, signature: signature) } } extension DownloadedPackagesSQLLiteStoreV1 { convenience init(fileName: String) { let fileManager = FileManager() guard let documentDir = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { fatalError("unable to determine document dir") } let storeURL = documentDir .appendingPathComponent(fileName) .appendingPathExtension("sqlite3") Self.migrate(fileName: fileName, to: storeURL) let db = FMDatabase(url: storeURL) let latestDBVersion = 1 let migration0To1 = Migration0To1(database: db) let migrator = SerialMigrator(latestVersion: latestDBVersion, database: db, migrations: [migration0To1]) self.init(database: db, migrator: migrator, latestVersion: latestDBVersion) self.open() } // Quick and dirty private static func migrate(fileName: String, to newURL: URL) { let fileManager = FileManager.default guard let documentDir = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else { fatalError("unable to determine document dir") } let oldStoreURL = documentDir .appendingPathComponent(fileName) .appendingPathExtension("sqlite3") if fileManager.fileExists(atPath: oldStoreURL.path) { do { try fileManager.moveItem(atPath: oldStoreURL.path, toPath: newURL.path) } catch { Log.error("Cannot move file to new location. Error: \(error)", log: .localData, error: error) } } } } extension DownloadedPackagesStoreV1 { @discardableResult func addFetchedDays(_ dayPackages: [String: SAPDownloadedPackage], country: Country.ID) -> Result<Void, SQLiteErrorCode> { var errors = [SQLiteErrorCode]() dayPackages.forEach { day, bucket in let result = self.set(country: country, day: day, package: bucket) switch result { case .success: break case .failure(let error): errors.append(error) } } if let error = errors.first { return .failure(error) } else { return .success(()) } } @discardableResult func addFetchedHours(_ hourPackages: [Int: SAPDownloadedPackage], day: String, country: Country.ID) -> Result<Void, SQLiteErrorCode> { var errors = [SQLiteErrorCode]() hourPackages.forEach { hour, bucket in let result = self.set(country: country, hour: hour, day: day, package: bucket) switch result { case .success: break case .failure(let error): errors.append(error) } } if let error = errors.first { return .failure(error) } else { return .success(()) } } }
20.852273
135
0.624342
14b0201baf05a1bda119724bb4e2b5e4a97d063b
11,587
// /* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 Beagle import BeagleSchema import UIKit let componentInteractionScreen: Screen = { return Screen(navigationBar: NavigationBar(title: "Component Interaction", showBackButton: true)) { Container { Button( text: "Declarative", onPress: [Navigate.pushView(.declarative(declarativeScreen))] ) Button( text: "Display", onPress: [Navigate.pushView(.declarative(displayScreen))] ) Button( text: "Text (JSON)", onPress: [Navigate.openNativeRoute(.init(route: .componentInterationEndpoint))] ) } } }() let declarativeScreen: Screen = { return Screen(navigationBar: NavigationBar(title: "Component Interaction", showBackButton: true)) { Container(context: Context(id: "context2", value: nil)) { Container(context: Context(id: "context1", value: "Joao")) { TextInput( onChange: [ SetContext( contextId: "context1", value: "@{onChange.value}" ) ] ) Text("context: @{context1} + \\@{context1}") Text("@{context1}") Text("\\@{context1}") Text("\\\\@{context1}") Text("\\\\\\@{context1}") Text("\\\\\\\\@{context1}") Text("\\\\\\\\\\@{context1}") Button( text: "1", onPress: [ SetContext( contextId: "context1", value: ["name": "nameUpdated"] ) ] ) MyComponent(person: "@{context1}", personOpt: nil, action: nil, widgetProperties: WidgetProperties()) Container(widgetProperties: WidgetProperties(style: Style(cornerRadius: CornerRadius(radius: 16), borderColor: "#000000", borderWidth: 6, size: Size(width: 100, height: 100), padding: EdgeValue().all(8)))) { Text("@{context1}") } } } } }() var displayScreen: Screen { Screen( navigationBar: NavigationBar(title: "Display"), child: Container { Button(text: "display = NONE", onPress: [SetContext(contextId: "display", value: "NONE")]) Button(text: "display = FLEX", onPress: [SetContext(contextId: "display", value: "FLEX")]) Text( #"style: {display: "@{display}"}"#, alignment: .value(.center), textColor: "#333", widgetProperties: WidgetProperties( style: Style() .display("@{display}") .backgroundColor("#ccc") .margin(EdgeValue().all(10)) ) ) }, context: Context(id: "display", value: "") ) } struct ComponentInteractionText: DeeplinkScreen { init(path: String, data: [String: String]?) { } func screenController() -> UIViewController { return BeagleScreenViewController(.declarativeText( """ { "_beagleComponent_" : "beagle:screenComponent", "navigationBar" : { "title" : "Beagle Context", "showBackButton" : true }, "child" : { "_beagleComponent_" : "beagle:container", "children" : [ { "_beagleComponent_" : "beagle:textInput", "value" : "@{address.data.zip}", "placeholder" : "CEP", "type": "NUMBER", "onChange" : [ { "_beagleAction_" : "beagle:setContext", "contextId" : "address", "value" : "@{onChange.value}", "path" : "data.zip" } ], "onBlur" : [ { "_beagleAction_" : "beagle:sendRequest", "url" : "https://viacep.com.br/ws/@{onBlur.value}/json", "method" : "GET", "onSuccess" : [ { "_beagleAction_" : "beagle:setContext", "contextId" : "address", "value" : { "zip" : "@{onBlur.value}", "street" : "@{onSuccess.data.logradouro}", "number" : "@{address.data.number}", "neighborhood" : "@{onSuccess.data.bairro}", "city" : "@{onSuccess.data.localidade}", "state" : "@{onSuccess.data.uf}", "complement" : "@{address.data.complement}" }, "path" : "data" } ] } ], "style" : { "margin" : { "bottom" : { "value" : 15.0, "type" : "REAL" } } } }, { "_beagleComponent_" : "beagle:textInput", "value" : "@{address.data.street}", "placeholder" : "Rua", "onChange" : [ { "_beagleAction_" : "beagle:setContext", "contextId" : "address", "value" : "@{onChange.value}", "path" : "data.street" } ], "style" : { "margin" : { "bottom" : { "value" : 15.0, "type" : "REAL" } } } }, { "_beagleComponent_" : "beagle:textInput", "value" : "@{address.data.number}", "placeholder" : "Número", "onChange" : [ { "_beagleAction_" : "beagle:setContext", "contextId" : "address", "value" : "@{onChange.value}", "path" : "data.number" } ], "style" : { "margin" : { "bottom" : { "value" : 15.0, "type" : "REAL" } } } }, { "_beagleComponent_" : "beagle:textInput", "value" : "@{address.data.neighborhood}", "placeholder" : "Bairro", "onChange" : [ { "_beagleAction_" : "beagle:setContext", "contextId" : "address", "value" : "@{onChange.value}", "path" : "data.neighborhood" } ], "style" : { "margin" : { "bottom" : { "value" : 15.0, "type" : "REAL" } } } }, { "_beagleComponent_" : "beagle:textInput", "value" : "@{address.data.city}", "placeholder" : "Cidade", "onChange" : [ { "_beagleAction_" : "beagle:setContext", "contextId" : "address", "value" : "@{onChange.value}", "path" : "data.city" } ], "style" : { "margin" : { "bottom" : { "value" : 15.0, "type" : "REAL" } } } }, { "_beagleComponent_" : "beagle:textInput", "value" : "@{address.data.state}", "placeholder" : "Estado", "onChange" : [ { "_beagleAction_" : "beagle:setContext", "contextId" : "address", "value" : "@{onChange.value}", "path" : "data.state" } ], "style" : { "margin" : { "bottom" : { "value" : 15.0, "type" : "REAL" } } } }, { "_beagleComponent_" : "beagle:textInput", "value" : "@{address.data.complement}", "placeholder" : "Complemento", "onChange" : [ { "_beagleAction_" : "beagle:setContext", "contextId" : "address", "value" : "@{onChange.value}", "path" : "data.complement" } ], "style" : { "margin" : { "bottom" : { "value" : 15.0, "type" : "REAL" } } } } ], "context" : { "id" : "address", "value" : { "data" : { "zip" : "", "street" : "", "number" : "", "neighborhood" : "", "city" : "", "state" : "", "complement" : "" } } } } } """ )) } } struct Person { let name: String } extension Person: Decodable {} struct MyComponent { let person: Expression<Person> let personOpt: Expression<Person>? let action: Expression<CustomConsoleLogAction>? var widgetProperties: WidgetProperties } extension MyComponent: Widget { func toView(renderer: BeagleRenderer) -> UIView { let view = UILabel() renderer.observe(person, andUpdate: \.text, in: view) { $0?.name } return view } }
37.257235
223
0.368775
4b5e8ecad4d971810c4baefba1800ac5054b45cc
2,673
// File created from ScreenTemplate // $ createScreen.sh Modal2/RoomCreation RoomCreationEventsModal /* Copyright 2020 New Vector Ltd 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 UIKit final class RoomCreationEventsModalCoordinator: RoomCreationEventsModalCoordinatorType { // MARK: - Properties // MARK: Private private let session: MXSession private var roomCreationEventsModalViewModel: RoomCreationEventsModalViewModelType private let roomCreationEventsModalViewController: RoomCreationEventsModalViewController // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: RoomCreationEventsModalCoordinatorDelegate? // MARK: - Setup init(session: MXSession, bubbleData: MXKRoomBubbleCellDataStoring, roomState: MXRoomState) { self.session = session let roomCreationEventsModalViewModel = RoomCreationEventsModalViewModel(session: self.session, bubbleData: bubbleData, roomState: roomState) let roomCreationEventsModalViewController = RoomCreationEventsModalViewController.instantiate(with: roomCreationEventsModalViewModel) self.roomCreationEventsModalViewModel = roomCreationEventsModalViewModel self.roomCreationEventsModalViewController = roomCreationEventsModalViewController } // MARK: - Public methods func start() { self.roomCreationEventsModalViewModel.coordinatorDelegate = self } func toPresentable() -> UIViewController { return self.roomCreationEventsModalViewController } func toSlidingModalPresentable() -> UIViewController & SlidingModalPresentable { return self.roomCreationEventsModalViewController } } // MARK: - RoomCreationEventsModalViewModelCoordinatorDelegate extension RoomCreationEventsModalCoordinator: RoomCreationEventsModalViewModelCoordinatorDelegate { func roomCreationEventsModalViewModelDidTapClose(_ viewModel: RoomCreationEventsModalViewModelType) { self.delegate?.roomCreationEventsModalCoordinatorDidTapClose(self) } }
36.616438
148
0.766929
0e1f935942e922ee13efb8cf55ae81aa0e3b2104
1,267
// // LiteDataExampleUITests.swift // LiteDataExampleUITests // // Created by Kyle Bashour on 6/12/16. // Copyright © 2016 Kyle Bashour. All rights reserved. // import XCTest class LiteDataExampleUITests: XCTestCase { override func setUp() { super.setUp() // 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 // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // 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 tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.243243
182
0.668508
0a0acf63420b2ad8c04a50d5ca3c0400a24b34dd
2,302
// // File.swift // Renetik // // Created by Rene Dohan on 3/9/19. // import UIKit import RenetikObjc public extension UIButton { @discardableResult class func construct(image: UIImage) -> Self { construct().image(image) } @discardableResult override open func construct() -> Self { super.construct().aspectFit().resizeToFit() return self } @discardableResult public func alignContent(_ alignment: ContentHorizontalAlignment) -> Self { contentHorizontalAlignment = alignment return self } @discardableResult override func aspectFit() -> Self { imageView?.aspectFit() return self } @discardableResult override func aspectFill() -> Self { imageView?.aspectFill() return self } func floatingDown(distance: CGFloat = 25) -> Self { from(bottom: distance, right: distance) if UIDevice.isTablet { resize(padding: 5) } imageEdgeInsets = UIEdgeInsets(UIDevice.isTablet ? 20 : 15) return self } func floatingUp(distance: CGFloat = 25) -> Self { from(top: distance, right: distance) if UIDevice.isTablet { resize(padding: 5) } imageEdgeInsets = UIEdgeInsets(UIDevice.isTablet ? 20 : 15) return self } } extension UIButton: CSHasTextProtocol { public func text() -> String? { title(for: .normal) } public func text(_ text: String?) { setTitle(text, for: .normal) } } extension UIButton: CSHasFontProtocol { public func font() -> UIFont? { titleLabel?.font } public func font(_ font: UIFont?) { titleLabel?.font = font } } extension UIButton: CSHasImageProtocol { public func image() -> UIImage? { image(for: .normal) } public func image(_ image: UIImage?) { setImage(image, for: .normal) } } extension UIButton: CSHasAttributedTextProtocol { public func attributedText() -> NSAttributedString? { attributedTitle(for: .normal) } public func attributed(text: NSAttributedString?) { setAttributedTitle(text, for: .normal) } } extension UIButton: CSHasTextColorProtocol { public func textColor() -> UIColor? { titleColor(for: .normal) } @discardableResult public func text(color: UIColor?) -> Self { setTitleColor(color, for: .normal); return self } }
27.082353
97
0.661599
5db4750f39d0c30565463ad7514fba04c8a20c8b
5,358
/* * Copyright 2018 ICON Foundation * * 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 protocol Sendable { var provider: String { get set } var method: ICON.METHOD { get set } var params: [String: Any]? { get set } } extension Sendable { public func getID() -> Int { return Int(arc4random_uniform(9999)) } func switchEndpointToDebug(provider: URL) -> URL { var provider = provider while provider.lastPathComponent != ICONService.API_VER { provider = provider.deletingLastPathComponent() } provider = provider.deletingLastPathComponent() provider = provider.appendingPathComponent("v3d") return provider } func send() -> Result<Data, ICError> { guard var provider = URL(string: self.provider) else { return .failure(ICError.fail(reason: .convert(to: .url(string: self.provider)))) } if method == .estimateStep { provider = switchEndpointToDebug(provider: provider) } let request = ICONRequest(provider: provider, method: method, params: params, id: self.getID()) let config = URLSessionConfiguration.default let session = URLSession(configuration: config) var data: Data? var response: HTTPURLResponse? var error: Error? let semaphore = DispatchSemaphore(value: 0) let task = session.dataTask(with: request.asURLRequest()) { data = $0 response = $1 as? HTTPURLResponse error = $2 semaphore.signal() } task.resume() _ = semaphore.wait(timeout: .distantFuture) if let connectError = error { return .failure(ICError.error(error: connectError)) } guard let value = data else { return .failure(ICError.message(error: "Unknown Error")) } guard response?.statusCode == 200 || response?.statusCode == 400 || response?.statusCode == 500 else { let message = String(data: value, encoding: .utf8) return .failure(ICError.message(error: message ?? "Unknown Error")) } return .success(value) } func send(_ completion: @escaping ((Result<Data, ICError>) -> Void)) { guard var provider = URL(string: self.provider) else { completion(.failure(ICError.fail(reason: .convert(to: .url(string: self.provider))))) return } if method == .estimateStep { provider = switchEndpointToDebug(provider: provider) } let request = ICONRequest(provider: provider, method: method, params: params, id: self.getID()) let task = URLSession.shared.dataTask(with: request.asURLRequest()) { (data, response, error) in if let connectError = error { completion(.failure(ICError.error(error: connectError))) } guard let value = data else { completion(.failure(ICError.message(error: "Unknown Error"))) return } guard let response = response as? HTTPURLResponse, response.statusCode == 200 || response.statusCode == 400 || response.statusCode == 500 else { let message = String(data: value, encoding: .utf8) completion(.failure(ICError.message(error: message ?? "Unknown Error"))) return } completion(.success(value)) return } task.resume() } } private class ICONRequest { var provider: URL var method: ICON.METHOD var params: [String: Any]? var id: Int var timestamp: String public func asURLRequest() -> URLRequest { var request = URLRequest(url: self.provider, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60) request.httpMethod = "POST" var req = ["jsonrpc": "2.0", "method": method.rawValue, "id": id] as [String: Any] if let param = params { req["params"] = param } do { let data = try JSONSerialization.data(withJSONObject: req, options: []) request.httpBody = data } catch { return request } if request.value(forHTTPHeaderField: "Content-Type") == nil { request.setValue("application/json", forHTTPHeaderField: "Content-Type") } return request } init(provider: URL, method: ICON.METHOD, params: [String: Any]?, id: Int) { self.provider = provider self.method = method self.params = params self.id = id self.timestamp = Date.timestampString } }
34.792208
156
0.592385
64c8a2a67f4e6e12fc01c4144810dadc527439cc
10,138
import Cocoa /** Convenience function for initializing an object and modifying its properties. ``` let label = with(NSTextField()) { $0.stringValue = "Foo" $0.textColor = .systemBlue view.addSubview($0) } ``` */ @discardableResult func with<T>(_ item: T, update: (inout T) throws -> Void) rethrows -> T { var this = item try update(&this) return this } extension NSColor { /// macOS 10.14 polyfill static let controlAccentColorPolyfill: NSColor = { if #available(macOS 10.14, *) { return .controlAccentColor } else { // swiftlint:disable:next object_literal return NSColor(red: 0.10, green: 0.47, blue: 0.98, alpha: 1) } }() func withAlpha(_ alpha: Double) -> NSColor { withAlphaComponent(alpha) } typealias HSBAColor = (hue: Double, saturation: Double, brightness: Double, alpha: Double) var hsba: HSBAColor { var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 let color = usingColorSpace(.deviceRGB) ?? self color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) // TODO: Seems like the Swift 5.5 compiler cannot infer the `Double` here. Open an issue if it's still a problem in Swift 6. return HSBAColor(Double(hue), Double(saturation), Double(brightness), Double(alpha)) } /// Adjust color components by ratio. func adjusting( hue: Double = 0, saturation: Double = 0, brightness: Double = 0, alpha: Double = 0 ) -> NSColor { let color = hsba return NSColor( hue: color.hue * (hue + 1), saturation: color.saturation * (saturation + 1), brightness: color.brightness * (brightness + 1), alpha: color.alpha * (alpha + 1) ) } } extension Comparable { /** ``` 20.5.clamped(to: 10.3...15) //=> 15 ``` */ func clamped(to range: ClosedRange<Self>) -> Self { min(max(self, range.lowerBound), range.upperBound) } } extension CGRect { var center: CGPoint { get { CGPoint(x: midX, y: midY) } set { origin = CGPoint( x: newValue.x - (size.width / 2), y: newValue.y - (size.height / 2) ) } } } extension DispatchQueue { /** ``` DispatchQueue.main.asyncAfter(duration: 100.milliseconds) { print("100 ms later") } ``` */ func asyncAfter(duration: TimeInterval, execute: @escaping () -> Void) { asyncAfter(deadline: .now() + duration, execute: execute) } } extension CAMediaTimingFunction { static let `default` = CAMediaTimingFunction(name: .default) static let linear = CAMediaTimingFunction(name: .linear) static let easeIn = CAMediaTimingFunction(name: .easeIn) static let easeOut = CAMediaTimingFunction(name: .easeOut) static let easeInOut = CAMediaTimingFunction(name: .easeInEaseOut) } extension CALayer { static func animate( duration: TimeInterval = 1, delay: TimeInterval = 0, timingFunction: CAMediaTimingFunction = .default, animations: @escaping (() -> Void), completion: (() -> Void)? = nil ) { DispatchQueue.main.asyncAfter(duration: delay) { CATransaction.begin() CATransaction.setAnimationDuration(duration) CATransaction.setAnimationTimingFunction(timingFunction) if let completion = completion { CATransaction.setCompletionBlock(completion) } animations() CATransaction.commit() } } } extension CALayer { /** Set CALayer properties without the implicit animation ``` CALayer.withoutImplicitAnimations { view.layer?.opacity = 0.4 } ``` */ static func withoutImplicitAnimations(closure: () -> Void) { CATransaction.begin() CATransaction.setDisableActions(true) closure() CATransaction.commit() } /** Toggle the implicit CALayer animation Can be useful for text layers */ var implicitAnimations: Bool { get { actions == nil } set { if newValue { actions = nil } else { actions = ["contents": NSNull()] } } } } extension CALayer { /// This is required for CALayers that are created independently of a view func setAutomaticContentsScale() { contentsScale = NSScreen.main?.backingScaleFactor ?? 2 } } extension NSFont { static let helveticaNeueLight = NSFont(name: "HelveticaNeue-Light", size: 0) } extension NSBezierPath { static func circle( radius: Double, center: CGPoint, startAngle: Double = 0, endAngle: Double = 360 ) -> Self { let path = self.init() path.appendArc( withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle ) return path } /// For making a circle progress indicator static func progressCircle(radius: Double, center: CGPoint) -> Self { let startAngle = 90.0 let path = self.init() path.appendArc( withCenter: center, radius: radius, startAngle: startAngle, endAngle: startAngle - 360, clockwise: true ) return path } } extension CAShapeLayer { static func circle(radius: Double, center: CGPoint) -> Self { let layer = self.init() layer.path = NSBezierPath.circle(radius: radius, center: center).cgPath return layer } convenience init(path: NSBezierPath) { self.init() self.path = path.cgPath } } extension CATextLayer { /// Initializer with better defaults. convenience init(text: String, fontSize: Double? = nil, color: NSColor? = nil) { self.init() string = text if let fontSize = fontSize { self.fontSize = fontSize } self.color = color implicitAnimations = false setAutomaticContentsScale() } var color: NSColor? { get { guard let color = foregroundColor else { return nil } return NSColor(cgColor: color) } set { foregroundColor = newValue?.cgColor } } } final class ProgressCircleShapeLayer: CAShapeLayer { convenience init(radius: Double, center: CGPoint) { self.init() fillColor = nil lineCap = .round path = NSBezierPath.progressCircle(radius: radius, center: center).cgPath strokeEnd = 0 } var progress: Double { get { strokeEnd } set { strokeEnd = newValue } } func resetProgress() { CALayer.withoutImplicitAnimations { strokeEnd = 0 } } } /** Shows the indeterminate state, when it's activated. It draws part of a circle that gets animated into a looping motion around its core. */ final class IndeterminateProgressCircleShapeLayer: CAShapeLayer { convenience init(radius: Double, center: CGPoint) { self.init() fillColor = nil path = NSBezierPath.circle(radius: radius, center: bounds.center, startAngle: 270).cgPath anchorPoint = CGPoint(x: 0.5, y: 0.5) position = center } } extension NSBezierPath { /// UIKit polyfill. var cgPath: CGPath { let path = CGMutablePath() var points = [CGPoint](repeating: .zero, count: 3) for index in 0..<elementCount { let type = element(at: index, associatedPoints: &points) switch type { case .moveTo: path.move(to: points[0]) case .lineTo: path.addLine(to: points[0]) case .curveTo: path.addCurve(to: points[2], control1: points[0], control2: points[1]) case .closePath: path.closeSubpath() @unknown default: assertionFailure("NSBezierPath received a new enum case. Please handle it.") } } return path } /// UIKit polyfill. convenience init(roundedRect rect: CGRect, cornerRadius: CGFloat) { self.init(roundedRect: rect, xRadius: cornerRadius, yRadius: cornerRadius) } } final class AssociatedObject<T: Any> { subscript(index: AnyObject) -> T? { get { objc_getAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque()) as! T? } set { objc_setAssociatedObject(index, Unmanaged.passUnretained(self).toOpaque(), newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } extension NSControl { typealias ActionClosure = ((NSControl) -> Void) private enum AssociatedKeys { static let onActionClosure = AssociatedObject<ActionClosure>() } @objc private func callClosure(_ sender: NSControl) { onAction?(sender) } /** Closure version of `.action`. ``` let button = NSButton(title: "Unicorn", target: nil, action: nil) button.onAction = { sender in print("Button action: \(sender)") } ``` */ var onAction: ActionClosure? { get { AssociatedKeys.onActionClosure[self] } set { AssociatedKeys.onActionClosure[self] = newValue action = #selector(callClosure) target = self } } } extension NSView { static func animate( duration: TimeInterval = 1, delay: TimeInterval = 0, timingFunction: CAMediaTimingFunction = .default, animations: @escaping (() -> Void), completion: (() -> Void)? = nil ) { DispatchQueue.main.asyncAfter(duration: delay) { NSAnimationContext.runAnimationGroup({ context in context.allowsImplicitAnimation = true context.duration = duration context.timingFunction = timingFunction animations() }, completionHandler: completion) } } func fadeIn( duration: TimeInterval = 1, delay: TimeInterval = 0, completion: (() -> Void)? = nil ) { isHidden = true NSView.animate( duration: duration, delay: delay, animations: { [self] in isHidden = false }, completion: completion ) } } extension CABasicAnimation { /// Rotates the element around its center point infinitely. static var rotate: Self { let animation = self.init(keyPath: #keyPath(CAShapeLayer.transform)) animation.valueFunction = CAValueFunction(name: .rotateZ) animation.fromValue = 0 animation.toValue = -(Double.pi * 2) animation.duration = 1 animation.repeatCount = .infinity animation.timingFunction = .linear return animation } } extension NSWindow { /// Whether the window or its owning app is showing a modal or sheet. /// This can be useful to disable any unintended interaction underneath it, /// for example, drag and drop or mouse hover. var isShowingModalOrSheet: Bool { NSApp.modalWindow != nil || attachedSheet != nil } } func assertMainThread( function: StaticString = #function, file: StaticString = #fileID, line: Int = #line ) { assert(Thread.isMainThread, "\(function) in \(file):\(line) must run on the main thread!") } extension KeyPath where Root: NSObject { /// Get the string version of the key path when the root is an `NSObject`. var toString: String { NSExpression(forKeyPath: self).keyPath } }
22.135371
126
0.693036
ddb48c6f583db2af45764f5d8288b2160a8ce0c1
709
// // LinuxTestable.swift // ServasaurusTesting // // Created by Brian Strobach on 5/11/18. // import Foundation import XCTest public protocol LinuxTestable{ func assertLinuxTestCoverage(tests: [Any]) } extension LinuxTestable where Self: XCTestCase{ public typealias LinuxTestCase = (String, (XCTestCase) -> () throws -> Void) public func assertLinuxTestCoverage(tests: [Any]) { #if !os(Linux) let thisClass = type(of: self) let linuxCount = tests.count let darwinCount = Int(thisClass.defaultTestSuite.testCaseCount) let failureMessage = "\(darwinCount - linuxCount) tests are missing from allTests in \(thisClass)." XCTAssertEqual(linuxCount, darwinCount,failureMessage) #endif } }
26.259259
101
0.747532
085c3215fd90b6f8d3d43181a18da34750aa1d53
436
// // ExampleDataFetcher.swift // MVCVM-ios // // Created by RouterInViewModel on 18/03/2017. // Copyright © 2017 routerInViewModel. All rights reserved. // import Foundation class ExampleDataFetcher { func fetchData(completion: (([ExampleData]) -> Void)) { var models = [ExampleData]() for i in 0...5 { let model = ExampleData(identifier: i, imageName: "\(i)") models.append(model) } completion(models) } }
16.148148
60
0.669725
d5cf7c380fad89a67a290968a4f191bffdc034ac
7,578
import Foundation class StoryScreenPresenter: StoryScreenModuleInput { weak var output: StoryScreenModuleOutput! weak var view: StoryScreenViewInput! var storiesService: StoriesService! var cacheManager: CacheServiceInput! var storyModel: StoryModel! var isTransitionInProgress = false var isContentDownloaded = false private var player: Player? private var isViewDidAppear = false private var slideSwitchTimer = PauseTimer() deinit { NotificationCenter.default.removeObserver(self) } } extension StoryScreenPresenter: StoryScreenViewOutput { func viewDidLoad() { view.addSlideView() view.addGestureRecognizers() view.addCloseButton() addObserver() } func viewWillAppear(_ animated: Bool) { view.updateProgressView(storyModel: storyModel, needProgressAnimation: false) updateAnimationOnSlide(needAnimation: false) showSlide() pauseTimer() } func viewDidLayoutSubviews() { view.updateLoadViewFrame() view.layoutSlideViewIfNeeded() } func viewDidAppear(_ animated: Bool) { isViewDidAppear = true if storyModel.data.dataSlides.count > storyModel.currentIndex { let slideModel = self.storyModel.data.dataSlides[self.storyModel.currentIndex] if isContentDownloaded { runStoryActivity(slideModel: slideModel) } } } func touchesBegan() { pauseStoryScreen() } func touchesCancelled() { resumeStoryScreen() } func touchesEnded() { resumeStoryScreen() } func tapOnLeftSide() { guard !isTransitionInProgress else { return } showPrevSlide() } func tapOnRightSide() { guard !isTransitionInProgress else { return } showNextSlide() } func closeButtonDidTap() { view.stopAnimation() output.closeButtonDidTap() } func networkErrorViewDidTapRetryButton() { showSlide() } } extension StoryScreenPresenter { private func showSlide() { guard storyModel.data.dataSlides.count > storyModel.currentIndex else { return } let slideModel = self.storyModel.data.dataSlides[self.storyModel.currentIndex] if storyModel.data.dataSlides.count > storyModel.currentIndex + 1 { storiesService.addDownloadQueue(slideModel: self.storyModel.data.dataSlides[self.storyModel.currentIndex + 1]) } isContentDownloaded = false self.view.updateProgressView(storyModel: self.storyModel, needProgressAnimation: false) updateAnimationOnSlide(needAnimation: false) self.invalidateTimer() self.player?.stop() self.view.removeNetworkErrorView() if let viewModel = cacheManager.getViewModel(slideModel: slideModel) { self.showSlide(viewModel: viewModel, slideModel: slideModel) } else { self.view.addLoadingView() self.storiesService.getData(slideModel, success: { [weak self, index = storyModel.currentIndex] viewModel in guard let self = self, let viewModel = viewModel as? SlideViewModel, index == self.storyModel.currentIndex else { return } self.showSlide(viewModel: viewModel, slideModel: slideModel) }, failure: { [weak self] error in DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self?.view.addNetworkErrorView() } print(error) }) } } private func showSlide(viewModel: SlideViewModel, slideModel: SlideModel) { var viewModel = viewModel self.view.removeLoadingView() self.isContentDownloaded = true self.player = nil let playerUrl = viewModel.videoUrl ?? viewModel.trackUrl if let url = playerUrl { self.player = Player(url: url) viewModel.player = self.player } self.showSlide(model: viewModel) if self.isViewDidAppear, !self.isTransitionInProgress { self.runStoryActivity(slideModel: slideModel) } } private func showSlide(model: SlideViewModel) { view.showSlide(model: model) } private func runTimerForSlide(slideModel: SlideModel) { self.slideSwitchTimer.scheduledTimer(withTimeInterval: TimeInterval(slideModel.duration), repeats: false, block: { [weak self] timer in self?.showNextSlide() }) } private func updateAnimationOnSlide(needAnimation: Bool) { guard storyModel.data.dataSlides.count > storyModel.currentIndex else { return } let slideModel = self.storyModel.data.dataSlides[self.storyModel.currentIndex] if let viewModel = cacheManager.getViewModel(slideModel: slideModel) { view.updateAnimationOnSlide(model: viewModel, needAnimation: needAnimation) } } func pauseAnimation() { view.pauseAnimation() } func resumeAnimation() { guard !isTransitionInProgress else { return } view.resumeAnimation() } func stopAnimation() { view.stopAnimation() } func invalidateTimer() { self.slideSwitchTimer.invalidate() } func pauseTimer() { self.slideSwitchTimer.pause() } func resumeTimer() { guard !isTransitionInProgress else { return } self.slideSwitchTimer.resume() } func pausePlayer() { player?.pause() } func playPlayer() { guard !isTransitionInProgress else { return } player?.play() } func pauseStoryScreen() { pauseTimer() pauseAnimation() pausePlayer() } func resumeStoryScreen() { resumeTimer() resumeAnimation() playPlayer() } private func runStoryActivity(slideModel: SlideModel) { self.runTimerForSlide(slideModel: slideModel) self.view.updateProgressView(storyModel: self.storyModel, needProgressAnimation: true) self.updateAnimationOnSlide(needAnimation: true) self.playPlayer() guard let viewModel = cacheManager.getViewModel(slideModel: slideModel) else { return } self.notifyOutputIfNeeded(viewModel: viewModel) } private func notifyOutputIfNeeded(viewModel: SlideViewModel) { switch viewModel.type { case .image: output.didShowStoryWithImage() case .video, .track: output.didShowStoryWithVideoOrTrack() } } func runStoryActivityIfNeeded() { if storyModel.data.dataSlides.count > storyModel.currentIndex { let slideModel = self.storyModel.data.dataSlides[self.storyModel.currentIndex] if isContentDownloaded, !slideSwitchTimer.isTimerScheduled { runStoryActivity(slideModel: slideModel) } } } private func showNextSlide() { if storyModel.data.dataSlides.count > storyModel.currentIndex, storyModel.data.dataSlides.count > storyModel.currentIndex + 1 { storyModel.currentIndex += 1 showSlide() } else if storyModel.data.dataSlides.count > storyModel.currentIndex, storyModel.data.dataSlides.count == storyModel.currentIndex + 1 { output?.needShowNextStory() } } private func showPrevSlide() { if storyModel.data.dataSlides.count > storyModel.currentIndex, storyModel.currentIndex - 1 >= 0 { storyModel.currentIndex -= 1 showSlide() } else if storyModel.currentIndex == 0 { output?.needShowPrevStory() } } private func addObserver() { NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackgroundHandler), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForegroundHandler), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } @objc private func applicationDidEnterBackgroundHandler() { updateAnimationFractionComplete() pauseStoryScreen() } @objc private func applicationWillEnterForegroundHandler() { if #available(iOS 11.0, *) { } else { restartAnimationForIOS10() } resumeStoryScreen() } private func updateAnimationFractionComplete() { view.updateAnimationFractionComplete() } private func restartAnimationForIOS10() { view.restartAnimationForIOS10() } }
27.357401
137
0.746767
9b8a9d0ef2709688512aa6a8f98513afb498bcce
272
// // CyLogging.swift // Customerly // // Created by Paolo Musolino on 06/11/16. // // class CyLogging: NSObject { } func cyPrint(_ items: Any...){ if Customerly.sharedInstance.verboseLogging == true{ print("CustomerlyLogging🤖:", items) } }
14.315789
56
0.613971
8a199b377bed1763886ddbdf1cee36c01edb760f
3,065
// // iModelTests.swift // iModelTests // // Created by jzaczek on 27.12.2015. // Copyright © 2015 jzaczek. All rights reserved. // import XCTest @testable import iModel class ModelTests: JZTestCase { func testPropertyObserving() { class Testable: Model { dynamic var id: Int = 0 dynamic var name: String = "" private override func property<T>(property: String, changedFromValue oldValue: T, toValue newValue: T) { XCTAssertEqual(property, "name") XCTAssertEqual(newValue as? String, "new name") XCTAssertEqual(oldValue as? String, "") } } let instance = Testable() instance.name = "new name" } func testValidation() { class Testable: Model { dynamic var id: Int = 0 dynamic var name: String = "" class func validateId(id: Int) -> (Bool, String) { return (id > 0, "Id should be > 0") } class func validateName(name: String) -> (Bool, String) { return (name.characters.count > 0, "Name should be longer than 0 chars") } override class func debug() -> Bool { return true } } Testable.setValidationMethod(Testable.validateId, forField: "id") Testable.setValidationMethod(Testable.validateName, forField: "name") // this should fail silently Testable.setValidationMethod(Testable.validateName, forField: "noProperty") let instance = Testable() XCTAssert(instance.validationState == Model.ValidationState.Empty) instance.id = 10 instance.name = "Name" instance.validate() XCTAssert(instance.validationState == Model.ValidationState.Clean) instance.id = -1 XCTAssert(instance.validationState == Model.ValidationState.Dirty) XCTAssertEqual(["id"], instance.dirtyProperties) instance.name = "string" XCTAssert(instance.dirtyProperties.contains("id")) XCTAssert(instance.dirtyProperties.contains("name")) XCTAssert(instance.validationState == Model.ValidationState.Dirty) instance.validate() XCTAssert(instance.validationState == Model.ValidationState.Invalid) XCTAssert(instance.validationErrors.keys.contains("id")) XCTAssert(!instance.validationErrors.keys.contains("name")) instance.undo() XCTAssertEqual(instance.id, 10) XCTAssertEqual(instance.name, "Name") } func testClassProperties() { class Testable: Model { dynamic var id: Int = 0 dynamic var name: String = "" } XCTAssert(Testable.classProperties.contains("id")) XCTAssert(Testable.classProperties.contains("name")) XCTAssertFalse(Testable.classProperties.contains("noSuchProperty")) } }
33.315217
116
0.588581
fb7e6391df5a528f59cfa8792d4a6abcfacf4556
1,048
// // File.swift // Fastflix // // Created by Jeon-heaji on 26/07/2019. // Copyright © 2019 hyeoktae kwon. All rights reserved. // import Foundation import UIKit extension UIViewController { func alert(title: String, message: String, okCompletion: @escaping () -> ()) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let cencelAction = UIAlertAction(title: "아니오", style: .default, handler: nil) let oKAction = UIAlertAction(title: title, style: .destructive) { _ in okCompletion() self.dismiss(animated: true) } alert.addAction(cencelAction) alert.addAction(oKAction) present(alert, animated: true, completion: nil) } func oneAlert(title: String, message: String, okButton: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let oKAction = UIAlertAction(title: okButton, style: .default) alert.addAction(oKAction) present(alert, animated: true, completion: nil) } }
27.578947
89
0.68416
46022805c2d43f8ce824a19c2d36c9f6331a10bd
980
// // AlertAppTests.swift // AlertAppTests // // Created by HinovaMobile on 14/11/16. // Copyright © 2016 HinovaMobile. All rights reserved. // import XCTest @testable import AlertApp class AlertAppTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // 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.measureBlock { // Put the code you want to measure the time of here. } } }
26.486486
111
0.637755
d9009973d801805eed2154205ea74b5e3517d603
789
// // Tests_macOSLaunchTests.swift // Tests macOS // // Created by Ivan Markov on 28.02.2022. // import XCTest class Tests_macOSLaunchTests: XCTestCase { override class var runsForEachTargetApplicationUIConfiguration: Bool { true } override func setUpWithError() throws { continueAfterFailure = false } func testLaunch() throws { let app = XCUIApplication() app.launch() // Insert steps here to perform after app launch but before taking a screenshot, // such as logging into a test account or navigating somewhere in the app let attachment = XCTAttachment(screenshot: app.screenshot()) attachment.name = "Launch Screen" attachment.lifetime = .keepAlways add(attachment) } }
23.909091
88
0.667934
0350ba0c77652e18f428773a94ff2f4b4821e576
3,091
// // PetTests.swift // CodableTests // // Created by Nate Walczak on 9/27/18. // Copyright © 2018 Detroit Labs. All rights reserved. // import XCTest @testable import Codable class PetTests: XCTestCase { func testDecodable() { // Given let json = """ { "name": "Gizmo", "kind": "dog", "age": 14, "isFriendly": true } """.data(using: .utf8)! // When let pet: Pet do { pet = try JSONDecoder().decode(Pet.self, from: json) } catch { XCTFail(error.localizedDescription) return } // Then XCTAssertEqual(pet.name, "Gizmo") XCTAssertEqual(pet.kind, .dog) XCTAssertEqual(pet.age, 14) XCTAssertEqual(pet.isFriendly, true) } func testArrayDecodable() { // Given let json = """ [ { "name": "Gizmo", "kind": "dog", "age": 14, "isFriendly": true }, { "name": "Mr. White", "kind": "cat", "age": 3, "isFriendly": false } ] """.data(using: .utf8)! // When let pets: [Pet] do { pets = try JSONDecoder().decode([Pet].self, from: json) } catch { XCTFail(error.localizedDescription) return } // Then XCTAssertEqual(pets.count, 2) XCTAssertEqual(pets.first?.name, "Gizmo") XCTAssertEqual(pets.first?.kind, .dog) XCTAssertEqual(pets.first?.age, 14) XCTAssertEqual(pets.first?.isFriendly, true) XCTAssertEqual(pets.second?.name, "Mr. White") XCTAssertEqual(pets.second?.kind, .cat) XCTAssertEqual(pets.second?.age, 3) XCTAssertEqual(pets.second?.isFriendly, false) } func testEmptyArrayDecodable() { // Given let json = """ [ ] """.data(using: .utf8)! // When let pets: [Pet] do { pets = try JSONDecoder().decode([Pet].self, from: json) } catch { XCTFail(error.localizedDescription) return } // Then XCTAssertEqual(pets.count, 0) } func testEncodable() { // Given let pet = Pet(name: "Gizmo", kind: .dog, age: 14, isFriendly: true) // When let data: Data let json: [String: Any]? do { data = try JSONEncoder().encode(pet) json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch { XCTFail(error.localizedDescription) return } // Then XCTAssertNotNil(json) XCTAssertEqual(json?.count, 4) XCTAssertEqual(json?["name"] as? String, "Gizmo") XCTAssertEqual(json?["kind"] as? String, "dog") XCTAssertEqual(json?["age"] as? Int, 14) XCTAssertEqual(json?["isFriendly"] as? Bool, true) } }
25.97479
94
0.492397
890a488e94de26fcfe34f3376345f8a542d2dec9
1,664
// // Color.swift // SyntaxKit // // Created by Sam Soffes on 6/14/15. // Copyright © 2015 Sam Soffes. All rights reserved. // import Foundation import Darwin #if os(OSX) import AppKit typealias Color = NSColor #else import UIKit typealias Color = UIColor #endif extension Color { #if os(OSX) public convenience init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { self.init(SRGBRed: red, green: green, blue: blue, alpha: alpha) } #endif convenience init?(hex s: String) { var hex: NSString = s // Remove `#` and `0x` if hex.hasPrefix("#") { hex = hex.substringFromIndex(1) } else if hex.hasPrefix("0x") { hex = hex.substringFromIndex(2) } // Invalid if not 3, 6, or 8 characters let length = hex.length if length != 3 && length != 6 && length != 8 { return nil } // Make the string 8 characters long for easier parsing if length == 3 { let r = hex.substringWithRange(NSMakeRange(0, 1)) let g = hex.substringWithRange(NSMakeRange(1, 1)) let b = hex.substringWithRange(NSMakeRange(2, 1)) hex = r + r + g + g + b + b + "ff" } else if length == 6 { hex = String(hex) + "ff" } // Convert 2 character strings to CGFloats func hexValue(string: String) -> CGFloat { let value = Double(strtoul(string, nil, 16)) return CGFloat(value / 255.0) } let red = hexValue(hex.substringWithRange(NSMakeRange(0, 2))) let green = hexValue(hex.substringWithRange(NSMakeRange(2, 2))) let blue = hexValue(hex.substringWithRange(NSMakeRange(4, 2))) let alpha = hexValue(hex.substringWithRange(NSMakeRange(6, 2))) self.init(red: red, green: green, blue: blue, alpha: alpha) } }
24.835821
87
0.664063
3a3370ecf2d79a517b897ae511108cb8d051eb1c
4,223
import Foundation //extension UICollectionView { // // /// Create a collection view with frame = .zero. // /// // /// - Parameter layout: Layout of collection view. // convenience init(layout: UICollectionViewLayout) { // self.init(frame: .zero, collectionViewLayout: layout) // } // // /// Register table cells or headers/footers by given class. // /// // /// - Parameter aClass: UITableViewCell class. // func register(_ cells: UICollectionViewCell.Type...) { // for cell in cells { // self.register(cell, forCellWithReuseIdentifier: cell.className) // } // } // // /// Register collection header view by given UICollectionReusableView class. // /// // /// - Parameter aClass: UICollectionReusableView class. // func register(headerView aClass: UICollectionReusableView.Type) { // self.register(aClass, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: aClass.className) // } // // /// Register collection footer view by given UICollectionReusableView class. // /// // /// - Parameter aClass: UICollectionReusableView class. // func register(footerView aClass: UICollectionReusableView.Type) { // self.register(aClass, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: aClass.className) // } // // /// Dequeue cell by given UICollectionViewCell class // /// // /// - Parameters: // /// - fromClass: UICollectionViewCell class. // /// - indexPath: Index path of cell. // /// - Returns: Dequeued cell. // func dequeue<T: UICollectionViewCell>(cell fromClass: T.Type, at indexPath: IndexPath) -> T { // let cell = self.dequeueReusableCell(withReuseIdentifier: fromClass.className, for: indexPath) as! T // let base = cell as? BaseCollectionCell // base?.row = indexPath.row // base?.section = indexPath.section // base?.lastRowInSection = self.numberOfItems(inSection: indexPath.section) == indexPath.row + 1 // // return cell // } // // /// Dequeue table header view by given UICollectionReusableView class. // /// // /// - Parameter fromClass: UICollectionReusableView class. // /// - Returns: Dequeued collection header view. // func dequeue<T: UICollectionReusableView>(headerView fromClass: T.Type, at indexPath: IndexPath) -> T { // return self.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: fromClass.className, for: indexPath) as! T // } // // /// Dequeue table footer view by given UICollectionReusableView class. // /// // /// - Parameter fromClass: UICollectionReusableView class. // /// - Returns: Dequeued collection footer view. // func dequeue<T: UICollectionReusableView>(footerView fromClass: T.Type, at indexPath: IndexPath) -> T { // return self.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: fromClass.className, for: indexPath) as! T // } // // /// Reload section from collection view. // /// // /// - Parameters: // /// - section: Section to be reloaded. // /// - animation: Animation of reloading. // func reloadSection(_ section: Int) { // self.reloadSections(IndexSet(integer: section)) // } // // /// Reload sections in collection view. // /// // /// - Parameters: // /// - section: Sections to be reloaded. // /// - animation: Animation of reloading. // func reloadSections(_ sections: [Int]) { // self.reloadSections(IndexSet(sections)) // } // // // /// Perform reload & callback when finish to get the correct contentSize. // /// // /// - Parameter completion: Callback. // func reloadData(completion: @escaping VoidBlock) { // self.reloadData() // dispatch_main { // completion() // } // } //} // MARK: - UICollectionViewCell //extension UICollectionViewCell { // // /// Return a blank cell. // static var empty: UICollectionViewCell { // return UICollectionViewCell() // } //}
38.743119
169
0.647881
c13b1e882d35a4a1c16c8dbc133fd15e9f59c30e
13,799
// // UnConfirmTransactionController.swift // AElfApp // // Created by 晋先森 on 2019/12/1. // Copyright © 2019 AELF. All rights reserved. // import UIKit class UnConfirmTransactionController: BaseTableViewController { enum Const { static let closeCellHeight: CGFloat = 120 // 这里2条修改了, xib 上也得改。 static let openCellHeight: CGFloat = 240 } var cellHeights: [CGFloat] = [] let viewModel = UnConfirmTransactionViewModel() let fetchChainsTripper = PublishSubject<Void>() let chains = BehaviorRelay<[ChainItem]>(value: []) var items = [UnConfirmTransactionItem]() override func viewDidLoad() { super.viewDidLoad() makeUI() bindViewModel() } func makeUI() { title = "To be confirmed transfer".localized() tableView.register(nibWithCellClass: UnConfirmTransactionCell.self) tableView.estimatedRowHeight = Const.closeCellHeight tableView.tableFooterView = UIView() tableView.backgroundColor = UIColor.groupTableViewBackground tableView.estimatedSectionFooterHeight = 0 tableView.estimatedSectionHeaderHeight = 0 tableView.delegate = self tableView.dataSource = self tableView.footRefreshControl = nil tableView.snp.makeConstraints { maker in maker.edges.equalToSuperview() } } func bindViewModel() { let fetchChains = Observable.of(Observable.just(()), fetchChainsTripper).merge() let input = UnConfirmTransactionViewModel.Input(address: App.address, headerRefresh: headerRefresh(),fetchChains: fetchChains) let output = viewModel.transform(input: input) viewModel.loading.asObservable().bind(to: isLoading).disposed(by: rx.disposeBag) viewModel.headerLoading.asObservable().bind(to: isHeaderLoading).disposed(by: rx.disposeBag) viewModel.parseError.map{ $0.msg ?? "" }.bind(to: emptyDataSetDescription).disposed(by: rx.disposeBag) emptyDataSetDescription.accept("No pending transactions".localized()) emptyDataSetImage = UIImage(named: "success") output.chains.subscribe(onNext: { [weak self] (items) in guard let self = self else { return } self.chains <= items SVProgressHUD.dismiss() }).disposed(by: rx.disposeBag) output.items.subscribe(onNext: { [weak self] items in guard let self = self else { return } self.items = items self.cellHeights = Array(repeating: Const.closeCellHeight, count: items.count) self.tableView.reloadData() }).disposed(by: rx.disposeBag) } /// 检查在 ToChain 链上,我的 fee 是否足够。 /// - Parameters: /// - contractAddress: Tochain 链的合约地址 /// - toChainID: ToChain 链 ID func checkToChainFee(item: ChainItem, confirmClosure:(() -> ())?) { SVProgressHUD.show() self.viewModel.requestMyBalance(address: App.address, contractAddress: item.contractAddress, symbol: item.symbol, chainID: item.name).subscribe(onNext: { balanceItem in let b = balanceItem.balance?.balance let f = balanceItem.fee?.first?.fee if let balance = b?.double(),let fee = f?.double() { // "33.00" 转 int 会失败,需先转为 double,再转int。 if balance >= fee { SVProgressHUD.dismiss() confirmClosure?() } else { SVProgressHUD.showInfo(withStatus: "%@ Balances for transfer are insufficient".localizedFormat(item.name)) } }else { SVProgressHUD.showInfo(withStatus: "Parsing failed".localized()) } }, onError: { e in SVProgressHUD.showInfo(withStatus: e.localizedDescription) }).disposed(by: rx.disposeBag) } func showPasswordAlertView(item: UnConfirmTransactionItem) { SecurityVerifyManager.verifyPaymentPassword(completion: { (pwd) in if let pwd = pwd { self.fetchToTxID(pwd: pwd,item: item) } }) } func fetchToTxID(pwd: String, item: UnConfirmTransactionItem) { SVProgressHUD.show(withStatus: nil) SVProgressHUD.setDefaultMaskType(.none) var tempFromItem: ChainItem? var tempToItem: ChainItem? var mainID = "9992731" // 默认 AELF 的 id chains.value.forEach({ if $0.name.lowercased() == item.fromChain.lowercased() { tempFromItem = $0 } if $0.name.lowercased() == item.toChain.lowercased() { tempToItem = $0 } if $0.name.lowercased() == "AELF".lowercased() { mainID = $0.issueID } }) guard let fromItem = tempFromItem,let toItem = tempToItem else { SVProgressHUD.showInfo(withStatus: "No node address found for %@ or %@".localizedFormat(item.fromChain,item.toChain)) return } AElfWallet.transferCrossReceive(pwd: pwd, fromNode: fromItem.node.removeSlash(), toNode: toItem.node.removeSlash(), mainChainID: mainID, issueChainID: fromItem.issueID, fromTokenContractAddress: fromItem.contractAddress, fromCrossChainContractAddress: fromItem.crossChainContractAddress, toTokenContractAddress: toItem.contractAddress, toCrossChainContractAddress: toItem.crossChainContractAddress, fromChainName: fromItem.name, toChainName: toItem.name, txID: item.txid) { [weak self] result in guard let self = self else { return } guard let res = result else { SVProgressHUD.showError(withStatus: "Parsing failed".localized()) return } logInfo("跨链返回结果:\(res)") if res.success == 1 { self.linkTxID(fromTxID: item.txid, toTxID: res.txId,fromChainID: fromItem.name) }else { SVProgressHUD.showError(withStatus: res.err) } } } func linkTxID(fromTxID: String,toTxID: String,fromChainID: String) { viewModel.requestLinkTransaction(fromTxID: fromTxID, toTxID: toTxID) .subscribe(onNext: { [weak self] result in if result.isOk { // SVProgressHUD.showInfo(withStatus: "Confirm success".localized()) self?.enterDetailController(txID: fromTxID, fromChainID: fromChainID) self?.headerRefreshTrigger.onNext(()) } else { if let msg = result.msg { SVProgressHUD.showInfo(withStatus: msg) } } logInfo(result) }, onError: { e in SVProgressHUD.showError(withStatus: e.localizedDescription) logDebug(e) }).disposed(by: rx.disposeBag) } } // MARK: - TableView extension UnConfirmTransactionController: UITableViewDelegate,UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return items.count } // There is just one row in every section func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView() headerView.backgroundColor = UIColor.clear return headerView } func tableView(_: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard case let cell as UnConfirmTransactionCell = cell else { return } cell.backgroundColor = .clear if cellHeights[indexPath.section] == Const.closeCellHeight { cell.unfold(false, animated: false, completion: nil) } else { cell.unfold(true, animated: false, completion: nil) } cell.item = items[indexPath.section] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withClass: UnConfirmTransactionCell.self) // let durations: [TimeInterval] = [0.16, 0.1, 0.1,0.15] let durations: [TimeInterval] = [0,0, 0,0] cell.durationsForExpandedState = durations cell.durationsForCollapsedState = durations cell.seeMoreClosure = { [weak self] item in guard let self = self,let item = item else { return } self.enterWebController(item: item) } cell.confirmClosure = { [weak self] item in guard let self = self,let item = item else { return } self.confirmTransfer(item: item) } return cell } func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeights[indexPath.section] } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 10 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! UnConfirmTransactionCell if cell.isAnimating() { return } var duration = 0.0 let cellIsCollapsed = cellHeights[indexPath.section] == Const.closeCellHeight if cellIsCollapsed { cellHeights[indexPath.section] = Const.openCellHeight cell.unfold(true, animated: true, completion: nil) duration = 0.5 } else { cellHeights[indexPath.section] = Const.closeCellHeight cell.unfold(false, animated: true, completion: nil) duration = 0.8 } UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { () -> Void in tableView.beginUpdates() tableView.endUpdates() // fix https://github.com/Ramotion/folding-cell/issues/169 if cell.frame.maxY > tableView.frame.maxY { tableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.bottom, animated: true) } }, completion: nil) } } extension UnConfirmTransactionController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.appBlack] } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) SVProgressHUD.dismiss() } } extension UnConfirmTransactionController { func enterDetailController(txID: String, fromChainID: String) { let recordVC = UIStoryboard.loadController(TransactionDetailController.self, storyType: .setting) recordVC.txId = txID recordVC.fromChainID = fromChainID push(controller: recordVC) } func enterWebController(item: UnConfirmTransactionItem) { // https://explorer-test.aelf.io/tx/9f74c44dde052cd456216b00fd387d4e66d65e0120654055b09ec351604e69c9 guard let chain = ChainItem.getItem(chainID: item.fromChain) else { return } let url = chain.explorer.removeSlash() + "/tx/\(item.txid)" logDebug("拼接的 TX 浏览器地址: \(url)") let webVC = WebViewController(urlStr: url) push(controller: webVC) } func getChainItem(chainID: String) -> ChainItem? { var item: ChainItem? self.chains.value.forEach({ if $0.name.lowercased() == chainID.lowercased() { item = $0 } }) return item } func confirmTransfer(item: UnConfirmTransactionItem) { logDebug("TxID: \(item.txid)") if self.chains.value.count > 0 { if let chainItem = self.getChainItem(chainID: item.toChain) { self.checkToChainFee(item: chainItem) { self.showPasswordAlertView(item: item) } }else { SVProgressHUD.showInfo(withStatus: "Chain ID: %@ not supported".localizedFormat(item.toChain)) } }else { // 网络问题,没有取到 chains 数据。 SVProgressHUD.show() self.fetchChainsTripper.onNext(()) // } } }
38.437326
158
0.555982
acc68d6ecb255bbb0727ff4b89967ecfdfea3ea3
8,358
// // AddPokemonViewController.swift // pokemongotradcenterios // // Created by Radi Barq on 12/25/16. // Copyright © 2016 Radi Barq. All rights reserved. // import UIKit import Firebase import CoreLocation import GeoFire // class AddPokemonViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, CLLocationManagerDelegate{ @IBOutlet weak var picker: UIPickerView! @IBOutlet weak var cpTextField: UITextField! @IBOutlet weak var textFieldCp: UITextField! var pokemonsNames = PokemonsNames() var pickerData = Array<String>() var ref: FIRDatabaseReference! var chosenPokemon = "Bulbasaur" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. textFieldCp.addTarget(self, action: "addDoneButtonOnKeyboard", for: UIControlEvents.touchDown) let buttonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout)) buttonItem.tintColor = UIColor.white navigationItem.leftBarButtonItem = buttonItem pickerData = pokemonsNames.getPokomensNames() picker.dataSource = self picker.delegate = self ref = FIRDatabase.database().reference() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @available(iOS 2.0, *) public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1; } @available(iOS 2.0, *) public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerData.count } @available(iOS 2.0, *) public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerData[row] } // This is when the user select a row @available(iOS 2.0, *) public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { chosenPokemon = pickerData[row] } @IBAction func buttonTrade(_ sender: UIButton) { let alertController = UIAlertController(title: "Cp Is Wrong!", message: "please check pokemon cp", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "Ok", style: .default, handler: nil) alertController.addAction(defaultAction) let cp = textFieldCp.text! if (cp == "") { present(alertController, animated: true, completion: nil) } else { if (rightCp(number: Int(cp)!) == true) { //TODO firebase wor // This is when getting the location failed. if FirstViewController.stringLocation == "" { let alertController = UIAlertController(title: "Location Problem!", message: "Please check your location service and try again", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "Ok", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } // This is when everything works well else { // This is awsome addNewUser(pokemon: chosenPokemon, cp: cp, location: FirstViewController.stringLocation, publicName: ThirdViewController.displayName) } } else { present(alertController, animated: true, completion: nil) } } } func rightCp(number: Int) -> Bool { if number <= 0 || number >= 5000 { return false } else { return true } } func addNewUser(pokemon: String, cp: String, location: String, publicName: String) { let pokemon = Pokemon(pokemon: pokemon, cp: cp, location: location, publicName: publicName) ref = ref.child("Pokemons").childByAutoId() var autoId = ref.key var userRefrence = FIRDatabase.database().reference().child("Users").child(ThirdViewController.displayName).child("pokemons").child(autoId) ref.setValue(pokemon.pokemonDictionary) userRefrence.setValue(pokemon.pokemonDictionary) let geofireRef = FIRDatabase.database().reference().child("Pokemons Location") let geoFire = GeoFire(firebaseRef: geofireRef) ref = FIRDatabase.database().reference() var userCoordinates = location.components(separatedBy: " ") var lat = CLLocationDegrees(userCoordinates[0])! var lon = CLLocationDegrees(userCoordinates[1])! geoFire?.setLocation(CLLocation(latitude: lat, longitude: lon), forKey: autoId) { (error) in if error != nil { print("An error occured: \(error)") } else { print("Saved location successfully!") } } // And this is to present the alert view let alertController = UIAlertController(title: "Great Trainer!", message: "Your pokemon has been added!", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "Ok", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) // This is to go to neraby screen let storyboard = UIStoryboard(name: "Main", bundle: nil) let firstViewController = storyboard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController self.present(firstViewController, animated: true, completion: nil) } func handleLogout() { do { try FIRAuth.auth()?.signOut() } catch let logoutError { print(logoutError) } let storyboard = UIStoryboard(name: "Main", bundle: nil) let firstViewController = storyboard.instantiateViewController(withIdentifier: "ThirdViewController") self.present(firstViewController, animated: true, completion: nil) } func addDoneButtonOnKeyboard() { let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 50)) doneToolbar.barStyle = UIBarStyle.default var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) var done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(doneButtonAction)) done.tintColor = UIColor.orange var items = [UIBarButtonItem]() items.append(done) items.append(flexSpace) doneToolbar.items = items doneToolbar.sizeToFit() self.textFieldCp.inputAccessoryView = doneToolbar } func doneButtonAction() { self.textFieldCp.resignFirstResponder() } /* // 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. } */ }
29.020833
172
0.572146
e27d14d426ea4459ca7f6796cfa8ef226d8bc249
2,154
// // MovieListItem.swift // SearchMovie // // Created by J_Min on 2022/03/12. // import SwiftUI struct MovieItemView: View { let movie: Movie let index: Int? var isIndexNil: Bool { if index == nil { return true } else { return false } } @State var isSheetOn: Bool = false var body: some View { ZStack(alignment: .top) { Rectangle() .frame(width: 150, height: 255) .foregroundColor(.secondary) .overlay( Image(systemName: "info.circle") .offset(x: -53, y: 105) .foregroundColor(.white) .font(.title3) ) VStack { Image(uiImage: movie.image) .resizable() .scaledToFit() .frame(width:150) .padding(.bottom, -10) .overlay(alignment: .bottomLeading) { if isIndexNil { EmptyView() } else { Text("\(index!)") .font(.system(size: 90)) .fontWeight(.heavy) .foregroundColor(.white) .shadow(color: .black, radius: 0, x: 4, y: 4) .frame(alignment: .bottomLeading) .offset(x: 5 ,y: 20) } //: isIndexNil } //: OVERLAY } //: VSTACK } //: ZSTACK .clipShape(RoundedRectangle(cornerRadius: 12)) .onTapGesture { isSheetOn = true } .sheet(isPresented: $isSheetOn) { MovieDetailView(movie: movie) } } } struct MovieListItem_Previews: PreviewProvider { static var previews: some View { MovieItemView(movie: movieSample, index: 10) .previewLayout(.sizeThatFits) .padding() } }
28.342105
77
0.412256
1e6c25d6101683f593b3c039642757d934adbb6e
1,638
// // Formatter+Extension.swift // FinService // // Created by Rodion Baglay on 18/07/2019. // Copyright © 2019 MTS IT. All rights reserved. // import Foundation extension Formatter { static let withSeparator: NumberFormatter = { let formatter = NumberFormatter() formatter.locale = Locale(identifier: "ru_RU") formatter.groupingSeparator = " " formatter.numberStyle = .decimal formatter.decimalSeparator = "," return formatter }() static let withPointAndSeparator: NumberFormatter = { let formatter = NumberFormatter() formatter.locale = Locale(identifier: "ru_RU") formatter.groupingSeparator = " " formatter.numberStyle = .decimal formatter.decimalSeparator = "." return formatter }() static let withComma: NumberFormatter = { let formatter = NumberFormatter() formatter.locale = Locale(identifier: "ru_RU") formatter.groupingSeparator = " " formatter.numberStyle = .decimal formatter.decimalSeparator = "," return formatter }() static let decimalFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 2 formatter.locale = Locale.current return formatter }() static let roundedFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 0 formatter.locale = Locale.current return formatter }() }
29.781818
57
0.642247
c13baa2835c9435cceda19167e7876e523a605e5
1,254
// // iOS_Tip_CalculatorTests.swift // iOS Tip CalculatorTests // // Created by Kan Wang on 1/18/22. // import XCTest @testable import iOS_Tip_Calculator class iOS_Tip_CalculatorTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } 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 { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Any test you write for XCTest can be annotated as throws and async. // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
33.891892
130
0.69059
21881c596f22b59c407f5fa3fe5a9dcf5f5e71ec
611
class Solution { func findPairs(_ nums: [Int], _ k: Int) -> Int { guard !nums.isEmpty && k >= 0 else { return 0 } var dict: [Int: Int] = [:] for num in nums { dict[num, default: 0] += 1 } var res = 0 for (num, count) in dict { if k == 0 { if count > 1 { res += 1 } } else { if dict[num - k] != nil { res += 1 } } } return res } } Solution().findPairs([-2,-1,-3], 1)
22.62963
52
0.332242
d56585e4450a037de83b88ff5eb37d4724677bbb
293
// // Copyright (c) 2017 Commercetools. All rights reserved. // import UIKit class ProductTypeCell: UICollectionViewCell { @IBOutlet weak var productImageView: UIImageView! @IBOutlet weak var selectedProductImageView: UIImageView! @IBOutlet weak var productNameLabel: UILabel! }
24.416667
61
0.767918
e21dec10465ad5fa1278baa49fa79a74f90f2c99
1,111
/*: # 78. Subsets https://leetcode.com/problems/subsets/ --- ### Problem Statement: Given a set of distinct integers, nums, return all possible subsets (the power set). ### Example: ``` Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] ``` ### Notes: + The solution set must not contain duplicate subsets. */ import UIKit // 10 / 10 test cases passed. // Status: Accepted // Runtime: 24 ms // Memory Usage: 21 MB extension Collection { public var powerSet: [[Element]] { guard let fisrt = self.first else {return [[]]} return self.dropFirst().powerSet.flatMap{[$0, [fisrt] + $0]} } } class Solution { func subsets(_ nums: [Int]) -> [[Int]] { return nums.powerSet } // 10 / 10 test cases passed. // Status: Accepted // Runtime: 16 ms // Memory Usage: 21.5 MB func subsets2(_ nums: [Int]) -> [[Int]] { return nums.reduce([[]]) { result, num in result + result.map{ $0 + [num] } } } } let sol = Solution() sol.subsets([1,2,3])
16.101449
85
0.542754
dd16e30587de494668d32974309af7e7daea7902
237
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var d { Void{ { struct Q { } } } { } extension NSData { func a(a( }
13.941176
87
0.704641
14b74ec19de50a050dcb6988ce78c7bb7da1f6e9
4,219
// // TabBarViewController.swift // CustomizingTabBarExample // // Created by hintoz on 02.05.17. // Copyright © 2017 Evgeny Dats. All rights reserved. // import UIKit class TabBarViewController: UITabBarController, UITabBarControllerDelegate { let tabBarOrderKey = "tabBarOrderKey" override func viewDidLoad() { super.viewDidLoad() self.delegate = self configItewControllers() setUpTabBarItemTags() getSavedTabBarItemsOrder() guard AppDelegate.isDark else { return } tabBar.tintColor = UIColor.green tabBar.barTintColor = UIColor.black } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard AppDelegate.isDark else { return } configMoreViewController() } func configItewControllers() { let storyBoard = UIStoryboard(name: "Main", bundle: nil) var conrollers = [NavigationViewController]() for index in 0..<TabBarItemTag.allCases.count { let conroller = storyBoard.instantiateViewController(withIdentifier: "navVC") as! NavigationViewController let item = TabBarItemTag.allCases[index] conroller.viewControllers.first?.tabBarItem = UITabBarItem.init(title: item.title, image: UIImage(named: item.image), selectedImage: UIImage(named: item.selectedImage)) conrollers.append(conroller) } self.viewControllers = conrollers } func configMoreViewController() { moreNavigationController.navigationBar.barStyle = .black moreNavigationController.navigationBar.tintColor = UIColor.white moreNavigationController.topViewController?.view.backgroundColor = UIColor.black (moreNavigationController.topViewController?.view as? UITableView)?.separatorStyle = .none (moreNavigationController.topViewController?.view as? UITableView)?.tintColor = UIColor.lightGray if let cells = (moreNavigationController.topViewController?.view as? UITableView)?.visibleCells { for cell in cells { cell.backgroundColor = UIColor.clear cell.textLabel?.textColor = UIColor.lightGray } } } func setUpTabBarItemTags() { guard let viewControllers = viewControllers else { return } for (index, view) in viewControllers.enumerated() { view.tabBarItem.tag = index } } func getSavedTabBarItemsOrder() { guard let initialViewControllers = viewControllers else { return } guard let tabBarOrder = UserDefaults.standard.object(forKey: tabBarOrderKey) as? [Int] else { return } guard tabBarOrder.count == initialViewControllers.count else { UserDefaults.standard.set(nil, forKey: tabBarOrderKey) return } var newViewControllerOrder = [UIViewController]() for tag in tabBarOrder { newViewControllerOrder.append(initialViewControllers[tag]) } setViewControllers(newViewControllerOrder, animated: false) print("loaded ViewControllers from UserDefaults") } func tabBarController(_ tabBarController: UITabBarController, didEndCustomizing viewControllers: [UIViewController], changed: Bool) { guard changed else { print("not changed"); return } var orderedTagItems = [Int]() for viewController in viewControllers { orderedTagItems.append(viewController.tabBarItem.tag) } UserDefaults.standard.set(orderedTagItems, forKey: tabBarOrderKey) print("changed") print(orderedTagItems) } func tabBarController(_ tabBarController: UITabBarController, willBeginCustomizing viewControllers: [UIViewController]) { guard AppDelegate.isDark else { return } (tabBarController.view.subviews[1].subviews[1] as? UINavigationBar)?.barStyle = .black (tabBarController.view.subviews[1].subviews[1] as? UINavigationBar)?.tintColor = UIColor.white tabBarController.view.subviews[1].backgroundColor = UIColor.black tabBarController.view.subviews[1].tintColor = UIColor.green } }
40.180952
180
0.68073
61d7dc84174fd274dd71f6d4683eb53f68191850
3,049
// // TPOSTransactionSummary.swift // TillhubPointOfSaleSDK // // Created by Andreas Hilbert on 29.04.19. // import Foundation /// Monetary summary information about a TPOSTransaction public struct TPOSTransactionSummary: Codable { /// The three letter [ISO currency](https://en.wikipedia.org/wiki/ISO_4217) of this transaction public let currency: String /// The total payable amount, including taxes public let amountTotalGross: Decimal /// The total amount excluding taxes public let amountTotalNet: Decimal /// The total value of the transaction before discounts /// (and before taxes in case of TPOSTaxType.exclusive) public let subTotal: Decimal /// The total amount of any applied discounts public let discountAmountTotal: Decimal ///The total amount of taxes public let taxAmountTotal: Decimal /// The total amount of tips included in this transaction public let tipAmountTotal: Decimal /// The total amount of all payments (including tips, before change) public let paymentAmountTotal: Decimal /// The total amount of change given back to the customer /// changeAmountTotal = paymentAmountTotal - amountTotalGross public let changeAmountTotal: Decimal /// Designated initializer for a transaction summary /// /// - Parameters: /// - currency: The three letter [ISO currency](https://en.wikipedia.org/wiki/ISO_4217) of this transaction /// - amountTotalGross: The total payable amount, including taxes /// - amountTotalNet: The total amount excluding taxes /// - subTotal: The total value of the transaction before discounts /// - discountAmountTotal: the total amount of any applied discounts /// - taxAmountTotal: the total amount of taxes /// - tipAmountTotal: The total amount of tips included in this transaction /// - paymentAmountTotal: The total amount of all payments (including tips, before change) /// - changeAmountTotal: The total amount of change given back to the customer public init(currency: String, amountTotalGross: Decimal, amountTotalNet: Decimal = 0.0, subTotal: Decimal = 0.0, discountAmountTotal: Decimal = 0.0, taxAmountTotal: Decimal = 0.0, tipAmountTotal: Decimal = 0.0, paymentAmountTotal: Decimal = 0.0, changeAmountTotal: Decimal = 0.0 ) throws { guard Locale.isoCurrencyCodes.contains(currency) else { throw TPOSPayloadError.currencyIsoCodeNotFound } self.currency = currency self.amountTotalGross = amountTotalGross self.amountTotalNet = amountTotalNet self.subTotal = subTotal self.discountAmountTotal = discountAmountTotal self.taxAmountTotal = taxAmountTotal self.tipAmountTotal = tipAmountTotal self.paymentAmountTotal = paymentAmountTotal self.changeAmountTotal = changeAmountTotal } }
40.653333
113
0.683831
e83809aea20357672401675f7d1c2da830c5357d
1,196
// // ChallengeiOSTests.swift // ChallengeiOSTests // // Created by Carlos Garcia on 16/06/2021. // import XCTest @testable import ChallengeiOS class ChallengeiOSTests: XCTestCase { let mockPresenter = MockHomePresenter() override func setUp() { } func testSuccessfullPayments (){ let expectation = self.expectation(description: "completed") expectation.isInverted = true mockPresenter.service.currentResult = mockPresenter.service.resultSuccess mockPresenter.getAPIPaymentsData() waitForExpectations(timeout: 2.0, handler: { (error) in expectation.fulfill() }) XCTAssertTrue(mockPresenter.getPaymentsCount() == 3, "") } func testErrorPayments (){ let expectation = self.expectation(description: "completed") expectation.isInverted = true mockPresenter.service.currentResult = mockPresenter.service.resultError mockPresenter.getAPIPaymentsData() waitForExpectations(timeout: 2.0, handler: { (error) in expectation.fulfill() }) XCTAssertTrue(mockPresenter.getPaymentsCount() == 0, "") } }
27.813953
81
0.655518
67dd18ef489f1be3e8dad0be873e6beebdc334cf
1,730
// // TimePeriod.swift // SwaggerToSwift // // Created by mac-246 on 10/09/17. // Copyright © 2017 Anton Plebanovich. All rights reserved. // import Foundation import ObjectMapper import ObjectMapper_Realm import ObjectMapperAdditions import RealmSwift import RealmAdditions class TimePeriod: Object, Mappable { dynamic var id: String! dynamic var name: String! dynamic var startTime: String! dynamic var endTime: String! required convenience init?(map: Map) { guard map.assureValuePresent(forKey: "id") else { return nil } guard map.assureValuePresent(forKey: "name") else { return nil } guard map.assureValuePresent(forKey: "startTime") else { return nil } guard map.assureValuePresent(forKey: "endTime") else { return nil } self.init() } func mapping(map: Map) { let isWriteRequired = realm != nil && realm?.isInWriteTransaction == false isWriteRequired ? realm?.beginWrite() : () id <- (map["id"], StringTransform()) name <- (map["name"], StringTransform()) startTime <- (map["startTime"], StringTransform()) endTime <- (map["endTime"], StringTransform()) isWriteRequired ? try? realm?.commitWrite() : () } //----------------------------------------------------------------------------- // MARK: - Equatable //----------------------------------------------------------------------------- override func isEqual(_ object: Any?) -> Bool { guard let object = object as? TimePeriod else { return false } return id == object.id && name == object.name && startTime == object.startTime && endTime == object.endTime } }
30.350877
83
0.573988
649db1eba91942bf4adc71b54f2194c298c3ac89
9,362
/* * The MIT License (MIT) * * Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>. * 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 XCTest @testable import Algorithm class SortedSetTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testInt() { var s = SortedSet<Int>() XCTAssert(0 == s.count, "Test failed, got \(s.count).") for _ in 0..<1000 { s.insert(1) s.insert(2) s.insert(3) } XCTAssert(3 == s.count, "Test failed.\(s)") XCTAssert(1 == s[0], "Test failed.") XCTAssert(2 == s[1], "Test failed.") XCTAssert(3 == s[2], "Test failed.") for _ in 0..<500 { s.remove(1) s.remove(3) } XCTAssert(1 == s.count, "Test failed.") s.remove(2) s.insert(10) XCTAssert(1 == s.count, "Test failed.") s.remove(10) XCTAssert(0 == s.count, "Test failed.") s.insert(1) s.insert(2) s.insert(3) s.remove(1, 2) XCTAssert(1 == s.count, "Test failed.") s.removeAll() XCTAssert(0 == s.count, "Test failed.") } func testRemove() { var s1 = SortedSet<Int>(elements: 22, 23, 1, 2, 3, 4, 5) s1.remove(1, 2, 3) XCTAssert(4 == s1.count, "Test failed.") } func testIntersect() { let s1 = SortedSet<Int>(elements: 22, 23, 1, 2, 3, 4, 5) let s2 = SortedSet<Int>(elements: 22, 23, 5, 6, 7, 8, 9, 10) XCTAssert(SortedSet<Int>(elements: 22, 23, 5) == s1.intersection(s2), "Test failed. \(s1.intersection(s2))") XCTAssert(SortedSet<Int>() == s1.intersection(SortedSet<Int>()), "Test failed. \(s1)") let s3 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9) let s4 = SortedSet<Int>(elements: 11, 9, 7, 3, 8, 100, 99, 88, 77) XCTAssert(SortedSet<Int>(elements: 9, 3, 7, 8) == s3.intersection(s4), "Test failed.") } func testIntersectInPlace() { var s1 = SortedSet<Int>(elements: 22, 23, 1, 2, 3, 4, 5) let s2 = SortedSet<Int>(elements: 22, 23, 5, 6, 7, 8, 9, 10) s1.formIntersection(s2) XCTAssert(SortedSet<Int>(elements: 22, 23, 5) == s1, "Test failed. \(s1)") s1.formIntersection(SortedSet<Int>()) XCTAssert(SortedSet<Int>() == s1, "Test failed. \(s1)") var s3 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9) let s4 = SortedSet<Int>(elements: 11, 9, 7, 3, 8, 100, 99, 88, 77) s3.formIntersection(s4) XCTAssert(SortedSet<Int>(elements: 9, 3, 7, 8) == s3, "Test failed.") } func testSubtract() { let s1 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 7, 8, 9, 10) let s2 = SortedSet<Int>(elements: 4, 5, 6, 7) XCTAssert(SortedSet<Int>(elements: 1, 2, 3, 8, 9, 10) == s1.subtracting(s2), "Test failed. \(s1.subtracting(s2))") let s3 = SortedSet<Int>(elements: 0, -1, -2, -7, 99, 100) let s4 = SortedSet<Int>(elements: -3, -5, -7, 99) XCTAssert(SortedSet<Int>(elements: 0, -1, -2, 100) == s3.subtracting(s4), "Test failed. \(s3.subtracting(s4))") } func testSubtractInPlace() { var s1 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 7, 8, 9, 10) let s2 = SortedSet<Int>(elements: 4, 5, 6, 7) s1.subtract(s2) XCTAssert(SortedSet<Int>(elements: 1, 2, 3, 8, 9, 10) == s1, "Test failed. \(s1)") var s3 = SortedSet<Int>(elements: 0, -1, -2, -7, 99, 100) let s4 = SortedSet<Int>(elements: -3, -5, -7, 99) s3.subtract(s4) XCTAssert(SortedSet<Int>(elements: 0, -1, -2, 100) == s3, "Test failed. \(s3)") } func testUnion() { let s1 = SortedSet<Int>(elements: 1, 2, 3, 4, 5) let s2 = SortedSet<Int>(elements: 5, 6, 7, 8, 9) let s3 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7, 8, 9) XCTAssert(s3 == s1.union(s2), "Test failed.") } func testUnionInPlace() { var s1 = SortedSet<Int>(elements: 1, 2, 3, 4, 5) let s2 = SortedSet<Int>(elements: 5, 6, 7, 8, 9) let s3 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7, 8, 9) s1.formUnion(s2) XCTAssert(s3 == s1, "Test failed.") } func testExclusiveOr() { let s1 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7) let s2 = SortedSet<Int>(elements: 1, 2, 3, 4, 5) let s3 = SortedSet<Int>(elements: 5, 6, 7, 8) XCTAssert(SortedSet<Int>(elements: 6, 7) == s1.symmetricDifference(s2), "Test failed. \(s1.symmetricDifference(s2))") XCTAssert(SortedSet<Int>(elements: 1, 2, 3, 4, 8) == s1.symmetricDifference(s3), "Test failed.") XCTAssert(SortedSet<Int>(elements: 1, 2, 3, 4, 6, 7, 8) == s2.symmetricDifference(s3), "Test failed.") } func testExclusiveOrInPlace() { var s1 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7) var s2 = SortedSet<Int>(elements: 1, 2, 3, 4, 5) let s3 = SortedSet<Int>(elements: 5, 6, 7, 8) s1.formSymmetricDifference(s2) XCTAssert(SortedSet<Int>(elements: 6, 7) == s1, "Test failed. \(s1)") s1 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7) s1.formSymmetricDifference(s3) XCTAssert(SortedSet<Int>(elements: 1, 2, 3, 4, 8) == s1, "Test failed. \(s1)") s2.formSymmetricDifference(s3) XCTAssert(SortedSet<Int>(elements: 1, 2, 3, 4, 6, 7, 8) == s2, "Test failed. \(s2)") } func testIsDisjointWith() { let s1 = SortedSet<Int>(elements: 1, 2, 3) let s2 = SortedSet<Int>(elements: 3, 4, 5) let s3 = SortedSet<Int>(elements: 5, 6, 7) XCTAssertFalse(s1.isDisjoint(with: s2), "Test failed. \(s1.isDisjoint(with: s2))") XCTAssert(s1.isDisjoint(with: s3), "Test failed.") XCTAssertFalse(s2.isDisjoint(with: s3), "Test failed.") } func testIsSubsetOf() { let s1 = SortedSet<Int>(elements: 1, 2, 3) let s2 = SortedSet<Int>(elements: 1, 2, 3, 4, 5) let s3 = SortedSet<Int>(elements: 2, 3, 4, 5) XCTAssert(s1 <= s1, "Test failed.") XCTAssert(s1 <= s2, "Test failed.") XCTAssertFalse(s1 <= s3, "Test failed.") } func testIsSupersetOf() { let s1 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7) let s2 = SortedSet<Int>(elements: 1, 2, 3, 4, 5) let s3 = SortedSet<Int>(elements: 5, 6, 7, 8) XCTAssert(s1 >= s1, "Test failed.") XCTAssert(s1 >= s2, "Test failed.") XCTAssertFalse(s1 >= s3, "Test failed.") } func testIsStrictSubsetOf() { let s1 = SortedSet<Int>(elements: 1, 2, 3) let s2 = SortedSet<Int>(elements: 1, 2, 3, 4, 5) let s3 = SortedSet<Int>(elements: 2, 3, 4, 5) XCTAssert(s1 < s2, "Test failed.") XCTAssertFalse(s1 < s3, "Test failed.") } func testIsStrictSupersetOf() { let s1 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7) let s2 = SortedSet<Int>(elements: 1, 2, 3, 4, 5) let s3 = SortedSet<Int>(elements: 5, 6, 7, 8) XCTAssert(s1 > s2, "Test failed.") XCTAssertFalse(s1 > s3, "Test failed.") } func testContains() { let s1 = SortedSet<Int>(elements: 1, 2, 3, 4, 5, 6, 7) XCTAssert(s1.contains(1, 2, 3), "Test failed.") XCTAssertFalse(s1.contains(1, 2, 3, 10), "Test failed.") } func testIndexOf() { var s1 = SortedSet<Int>() s1.insert(1, 2, 3, 4, 5, 6, 7) XCTAssert(0 == s1.index(of: 1), "Test failed.") XCTAssert(5 == s1.index(of: 6), "Test failed.") XCTAssert(-1 == s1.index(of: 100), "Test failed.") } func testExample() { let setA = SortedSet<Int>(elements: 1, 2, 3) // Sorted: [1, 2, 3] let setB = SortedSet<Int>(elements: 4, 3, 6) // Sorted: [3, 4, 6] let setC = SortedSet<Int>(elements: 7, 1, 2) // Sorted: [1, 2, 7] let setD = SortedSet<Int>(elements: 1, 7) // Sorted: [1, 7] let setE = SortedSet<Int>(elements: 1, 6, 7) // Sorted: [1, 6, 7] // Union. print((setA + setB).count) // Output: 5 print(setA.union(setB).count) // Output: 5 // Intersect. print(setC.intersection(setD).count) // Output: 2 // Subset. print(setD < setC) // true print(setD.isSubset(of: setC)) // true // Superset. print(setD > setC) // false print(setD.isSuperset(of: setC)) // false // Contains. print(setE.contains(setA.first!)) // true // Probability. print(setE.probability(of: setA.first!, setA.last!)) // 0.333333333333333 } func testPerformance() { self.measure() {} } }
33.555556
121
0.594638
62c964989567427d02ae54bfb5cb468eaa13f643
5,008
// // MoviesDatabaseAPIClient.swift // Flicks // // Created by Manuel Deschamps on 5/17/16. // // import Foundation import UIKit enum MoviesList { case NowPlaying case TopRated } extension MoviesList { var path: String { switch self { case .NowPlaying: return "/3/movie/now_playing" case .TopRated: return "/3/movie/top_rated" } } } extension Movie { var path: String { return "/3/movie/\(self.id!)" } var videosPath: String { return self.path + "/videos" } } enum MoviesResponse { case Success(movies: [Movie]) case Error(e: ErrorType) } enum MovieResponse { case Success(movie: Movie) case Error(e: ErrorType) } class MoviesDatabaseAPIClient { static let BaseUrl = NSURL(string: "https://api.themoviedb.org") private let apiKeyParamName = "api_key" private let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed" func fetchMovies(moviesList: MoviesList, completion: (response: MoviesResponse) -> Void ) { let moviesListUrl = NSURLComponents(URL: MoviesDatabaseAPIClient.BaseUrl!, resolvingAgainstBaseURL: true) moviesListUrl?.path = moviesList.path fireRequest(moviesListUrl) { (responseDictionaryOrNil, error) in if let responseDictionary = responseDictionaryOrNil { if let results = responseDictionary["results"] as? [NSDictionary] { let movies = results.map { (movieDic) -> Movie in return Movie(dictionary: movieDic) } completion(response: .Success(movies: movies)) return } } completion(response: .Error(e: (error ?? NSError(domain: "Parsing Error", code: 1, userInfo: nil)))) } } func fetchMovie(movie: Movie, completion: (response: MovieResponse) -> Void) { let movieUrl = NSURLComponents(URL: MoviesDatabaseAPIClient.BaseUrl!, resolvingAgainstBaseURL: true) movieUrl?.path = movie.path fireRequest(movieUrl) { (responseDictionaryOrNil, error) in if let responseDictionary = responseDictionaryOrNil { completion(response: .Success(movie: Movie(dictionary: responseDictionary))) return } completion(response: .Error(e: (error ?? NSError(domain: "Parsing Error", code: 1, userInfo: nil)))) } } func fetchMovieWithVideos(movie: Movie, completion: (response: MovieResponse) -> Void) { let movieUrl = NSURLComponents(URL: MoviesDatabaseAPIClient.BaseUrl!, resolvingAgainstBaseURL: true) movieUrl?.path = movie.path let movieVideosUrl = NSURLComponents(URL: MoviesDatabaseAPIClient.BaseUrl!, resolvingAgainstBaseURL: true) movieVideosUrl?.path = movie.videosPath // fetch movie first fireRequest(movieUrl) { (movieDictionaryOrNil, error) in if let movieDictionary = movieDictionaryOrNil { // fetch the videos and merge dictionaries self.fireRequest(movieVideosUrl) { (videosDictionaryOrNil, error) in if let videosDictionary = videosDictionaryOrNil, moviesWithVideos = movieDictionary.mutableCopy() as? NSMutableDictionary { moviesWithVideos["videos"] = videosDictionary["results"] completion(response: .Success(movie: Movie(dictionary: moviesWithVideos))) return } completion(response: .Error(e: (error ?? NSError(domain: "Video not found", code: 1, userInfo: nil)))) } } else { completion(response: .Error(e: (error ?? NSError(domain: "Movie not found", code: 1, userInfo: nil)))) } } } private func fireRequest(urlComponents: NSURLComponents?, completionHandler: (NSDictionary?, NSError?) -> Void) { guard let urlComponents = urlComponents else { completionHandler(nil, NSError(domain: "Invalid URL", code: 1, userInfo: nil)) return } let apiKeyParam = NSURLQueryItem(name: apiKeyParamName, value: apiKey) if urlComponents.queryItems == nil { urlComponents.queryItems = [] } urlComponents.queryItems?.append(apiKeyParam) let request = NSURLRequest( URL: urlComponents.URL!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 10) let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue()) UIApplication.sharedApplication().networkActivityIndicatorVisible = true let task: NSURLSessionDataTask = session.dataTaskWithRequest(request){ (dataOrNil, response, error) in UIApplication.sharedApplication().networkActivityIndicatorVisible = false var responseDictionary: NSDictionary? if let httpResponse = response as? NSHTTPURLResponse, data = dataOrNil { if httpResponse.statusCode == 200 { if let jsonDictionary = try? NSJSONSerialization.JSONObjectWithData(data, options:[]) as? NSDictionary { responseDictionary = jsonDictionary } } } completionHandler(responseDictionary, error) } task.resume() } }
33.165563
133
0.693291
1a7f5c61e5e4bfe001d164614e932f6cdac35258
4,282
// // Ball.swift // Pool Scoreboard // // Created by HarveyHu on 15/06/2017. // Copyright © 2017 HarveyHu. All rights reserved. // import UIKit import RxCocoa class Ball { var ballViews: Array<UIView> let diameter: Double let gap = Double(UIScreen.main.bounds.height / 50) let touchDiameter: Double init(diameter: Double, touchDiameter: Double) { ballViews = Array<UIView>() self.diameter = diameter self.touchDiameter = touchDiameter self.ballViews = self.setupBallViews() } private func setupBallViews() -> Array<UIView> { var newViews = Array<UIView>() for index in 0...15 { let ballView = createBallView(number: index) ballView.tag = index newViews.append(ballView) } return newViews } private func createBallView(number: Int) -> UIView { let touchView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: touchDiameter, height: touchDiameter)) touchView.bounds = touchView.frame touchView.backgroundColor = UIColor.clear let ballView = UIView() touchView.addSubview(ballView) // Size needs to be set up before Center, otherwise, Origin will be set as the same point as Center. ballView.frame.size = CGSize(width: diameter, height: diameter) ballView.center = CGPoint(x: touchView.bounds.width / 2, y: touchView.bounds.height / 2) ballView.layer.cornerRadius = CGFloat(diameter / 2) ballView.layer.masksToBounds = true if number < 9 { ballView.backgroundColor = getColorFromNumber(number: number) } else { ballView.backgroundColor = UIColor.white } let centerView = UIView(frame: CGRect(x: diameter * 0.2, y: 0.0, width: diameter * 0.6, height: diameter)) ballView.addSubview(centerView) centerView.backgroundColor = getColorFromNumber(number: number) let circleLable = UILabel(frame: CGRect(x: diameter * 0.2, y: diameter * 0.2, width: diameter * 0.6, height: diameter * 0.6)) circleLable.text = number == 0 ? "": "\(number)" circleLable.adjustsFontSizeToFitWidth = true circleLable.textAlignment = .center circleLable.layer.cornerRadius = CGFloat(diameter * 0.6 / 2) circleLable.layer.masksToBounds = true circleLable.backgroundColor = UIColor.white ballView.addSubview(circleLable) return touchView } private func getColorFromNumber(number: Int) -> UIColor { switch number { case 0: return UIColor.white case 1, 9: return UIColor.yellow case 2, 10: return UIColor.blue case 3, 11: return UIColor.red case 4, 12: return UIColor.purple case 5, 13: return UIColor.orange case 6, 14: return UIColor.grassGreen() case 7, 15: return UIColor.lightBlue() case 8: return UIColor.black default: break } return UIColor.white } func getLocationCenterPoint(number: Int) -> CGPoint { let userDefault = UserDefault() var centerPoint = CGPoint.zero if let list = userDefault.ballPositionList, let x = list["\(number)"]?[0], let y = list["\(number)"]?[1] { centerPoint = CGPoint(x: x, y: y) } else { centerPoint = CGPoint(x: gap + diameter, y: (diameter + gap) * Double(number + 1)) } return centerPoint } func updateLocation(number: Int, center: CGPoint) { var userDefault = UserDefault() if userDefault.ballPositionList == nil { userDefault.ballPositionList = ["\(number)": [Double(center.x), Double(center.y)]] } else { userDefault.ballPositionList?["\(number)"] = [Double(center.x), Double(center.y)] } } func resetLocations() { for number in 0...15 { let ballCenter = CGPoint(x: gap + diameter, y: (diameter + gap) * Double(number + 1)) updateLocation(number: number, center: ballCenter) } } }
34.256
133
0.589678
266e3154c88c11a1ad80edc55fa8afeb07761f56
2,270
// Copyright © 2019 Optimove. All rights reserved. import Foundation import OptimoveCore final class TenantConfigFixture { struct Constants { static let maxActionCustomDimensions = 10 } func build(_ options: Options = Options.default) -> TenantConfig { return TenantConfig( realtime: tenantRealtimeConfigFixture(), optitrack: tenantOptitrackConfigFixture(), events: createTenantEventFixture(), isEnableRealtime: options.isEnableRealtime, isSupportedAirship: false, isEnableRealtimeThroughOptistream: options.isEnableRealtimeThroughOptistream, isProductionLogsEnabled: false ) } func tenantRealtimeConfigFixture() -> TenantRealtimeConfig { return TenantRealtimeConfig( realtimeGateway: StubVariables.url ) } func tenantOptitrackConfigFixture() -> TenantOptitrackConfig { return TenantOptitrackConfig( optitrackEndpoint: StubVariables.url, siteId: StubVariables.int, maxActionCustomDimensions: Constants.maxActionCustomDimensions ) } func createTenantEventFixture() -> [String: EventsConfig] { return [ StubEvent.Constnats.name: EventsConfig( id: StubEvent.Constnats.id, supportedOnOptitrack: true, supportedOnRealTime: true, parameters: [ StubEvent.Constnats.key: Parameter( type: "String", optional: false ), "event_platform": Parameter( type: "String", optional: true ), "event_device_type": Parameter( type: "String", optional: true ), "event_os": Parameter( type: "String", optional: true ), "event_native_mobile": Parameter( type: "Boolean", optional: true ) ] ) ] } }
31.971831
89
0.523348