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
|
---|---|---|---|---|---|
754258ba507b70ceda09826446b9bcb9af8d8677 | 2,741 | // DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: syft_proto/execution/v1/placeholder_id.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
struct SyftProto_Execution_V1_PlaceholderId {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var id: SyftProto_Types_Syft_V1_Id {
get {return _id ?? SyftProto_Types_Syft_V1_Id()}
set {_id = newValue}
}
/// Returns true if `id` has been explicitly set.
var hasID: Bool {return self._id != nil}
/// Clears the value of `id`. Subsequent reads from it will return its default value.
mutating func clearID() {self._id = nil}
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _id: SyftProto_Types_Syft_V1_Id? = nil
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "syft_proto.execution.v1"
extension SyftProto_Execution_V1_PlaceholderId: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".PlaceholderId"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "id"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularMessageField(value: &self._id)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if let v = self._id {
try visitor.visitSingularMessageField(value: v, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: SyftProto_Execution_V1_PlaceholderId, rhs: SyftProto_Execution_V1_PlaceholderId) -> Bool {
if lhs._id != rhs._id {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 36.546667 | 148 | 0.747902 |
01f783a6cb8055df76caea47843f70b6a6233cd5 | 462 | //
// Act.swift
// Demo-MVVM
//
// Created by wangliang on 16/6/13.
// Copyright © 2016年 wangliang. All rights reserved.
//
import UIKit
class Acts: NSObject {
var name: String = ""
var url: String = ""
var image: String = ""
init(dict: [String: AnyObject])
{
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
| 17.769231 | 76 | 0.588745 |
56ef76a5855b1a2f281762921ddede4a8fbd43be | 601 | //
// ID3ItunesMovementNameFrameCreator.swift
//
// Created by Nolaine Crusher on 02/24/2020.
// 2018 Fabrizio Duroni.
//
import Foundation
class ID3ItunesMovementNameFrameCreator: ID3StringFrameCreator {
override func createFrames(id3Tag: ID3Tag, tag: [UInt8]) -> [UInt8] {
if let movementNameFrame = id3Tag.frames[.iTunesMovementName] as? ID3FrameWithStringContent {
return createFrameUsing(frameType: .iTunesMovementName, content: movementNameFrame.content, id3Tag: id3Tag, andAddItTo: tag)
}
return super.createFrames(id3Tag: id3Tag, tag: tag)
}
}
| 33.388889 | 136 | 0.728785 |
38b1177a7cb14f2142bcb5e3bb3b18d24871132c | 1,577 | //
// TrackingReactorTests.swift
// RxLocationTests
//
// Created by Vadym Brusko on 11/3/17.
// Copyright © 2017 Vadim Inc. All rights reserved.
//
@testable import RxLocation
import CoreLocation
import XCTest
class TrackingReactorTests: XCTestCase {
var reactor: TrackingReactor!
var trackingService: MockTrackingService!
var locationServive: MockLocationService!
override func setUp() {
trackingService = MockTrackingService()
locationServive = MockLocationService()
reactor = TrackingReactor(trackingService: trackingService, locationService: locationServive)
}
func test_reduce_toggleAutoTrackingTrue_changeAutoTrackingState() {
// arrange
_ = reactor.state
// act
reactor.action.onNext(.toggleAutoTracking(true))
// assert
XCTAssert(reactor.currentState.isAutoTrackingActive)
}
func test_reduce_toggleAutoTrackingFalse_changeAutoTrackingState() {
// arrange
_ = reactor.state
// act
reactor.action.onNext(.toggleAutoTracking(false))
// assert
XCTAssertFalse(reactor.currentState.isAutoTrackingActive)
}
func test_transformMutation_emitActiveTransmition_changePositionState() {
// arrange
let location = CLLocation(latitude: 1.01, longitude: 2.02)
trackingService.trackReturnValue = .just(location)
// act
_ = reactor.state
reactor.action.onNext(.toggleAutoTracking(true))
// assert
XCTAssertEqual(reactor.currentState.activePosition, location)
XCTAssertEqual(reactor.currentState.lastPosition, reactor.initialState.activePosition)
}
}
| 25.435484 | 97 | 0.751427 |
e4fc0a3e2e3efec98087d5d51112f435cb91b9d7 | 10,394 | import Foundation
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
let animationProducer = AnimationProducer()
class AnimationProducer {
var storedAnimations = [Node: BasicAnimation]() // is used to make sure node is in view hierarchy before actually creating the animation
var delayedAnimations = [BasicAnimation: Timer]()
var displayLink: MDisplayLinkProtocol?
struct ContentAnimationDesc {
let animation: ContentsAnimation
let startDate: Date
let finishDate: Date
let completion: (() -> Void)?
}
var contentsAnimations = [ContentAnimationDesc]()
func play(_ animation: BasicAnimation, _ context: AnimationContext, withoutDelay: Bool = false) {
// Delay - launching timer
if animation.delay > 0.0 && !withoutDelay {
let timer = Timer.schedule(delay: animation.delay) { [weak self] _ in
self?.play(animation, context, withoutDelay: true)
_ = self?.delayedAnimations.removeValue(forKey: animation)
animation.delayed = false
}
animation.delayed = true
delayedAnimations[animation] = timer
return
}
// Empty - executing completion
if animation.type == .empty {
executeCompletion(animation)
return
}
// Cycle - attaching "re-add animation" logic
if animation.cycled {
if animation.manualStop {
return
}
let reAdd = EmptyAnimation {
self.play(animation, context)
}
if let nextAnimation = animation.next {
nextAnimation.next = reAdd
} else {
animation.next = reAdd
}
}
// General case
guard let node = animation.node else {
return
}
for observer in node.animationObservers {
observer.processAnimation(animation)
}
switch animation.type {
case .unknown:
return
case .empty:
executeCompletion(animation)
case .sequence:
addAnimationSequence(animation, context)
case .combine:
addCombineAnimation(animation, context)
default:
break
}
guard let macawView = animation.nodeRenderer?.view else {
storedAnimations[node] = animation
return
}
guard let layer = macawView.mLayer else {
return
}
// swiftlint:disable superfluous_disable_command switch_case_alignment
switch animation.type {
case .affineTransformation:
addTransformAnimation(animation, context, sceneLayer: layer, completion: {
if let next = animation.next {
self.play(next, context)
}
})
case .opacity:
addOpacityAnimation(animation, context, sceneLayer: layer, completion: {
if let next = animation.next {
self.play(next, context)
}
})
case .contents:
addContentsAnimation(animation, context) {
if let next = animation.next {
self.play(next, context)
}
}
case .morphing:
addMorphingAnimation(animation, context, sceneLayer: layer) {
if let next = animation.next {
self.play(next, context)
}
}
case .shape:
addShapeAnimation(animation, context, sceneLayer: layer) {
if let next = animation.next {
self.play(next, context)
}
}
default:
break
}
// swiftlint:enable superfluous_disable_command switch_case_alignment
}
func removeDelayed(animation: BasicAnimation) {
guard let timer = delayedAnimations[animation] else {
return
}
timer.invalidate()
animation.delayed = false
delayedAnimations.removeValue(forKey: animation)
}
// MARK: - Sequence animation
func addAnimationSequence(_ animationSequnce: Animation,
_ context: AnimationContext) {
guard let sequence = animationSequnce as? AnimationSequence else {
return
}
// Generating sequence
var sequenceAnimations = [BasicAnimation]()
var cycleAnimations = sequence.animations
if sequence.autoreverses {
cycleAnimations.append(contentsOf: sequence.animations.reversed())
}
if sequence.repeatCount > 0.0001 {
for _ in 0..<Int(sequence.repeatCount) {
sequenceAnimations.append(contentsOf: cycleAnimations)
}
} else {
sequenceAnimations.append(contentsOf: cycleAnimations)
}
// Connecting animations
for i in 0..<(sequenceAnimations.count - 1) {
let animation = sequenceAnimations[i]
animation.next = sequenceAnimations[i + 1]
}
// Completion
if let completion = sequence.completion {
let completionAnimation = EmptyAnimation(completion: completion)
if let next = sequence.next {
completionAnimation.next = next
}
sequenceAnimations.last?.next = completionAnimation
} else {
if let next = sequence.next {
sequenceAnimations.last?.next = next
}
}
// Launching
if let firstAnimation = sequence.animations.first {
self.play(firstAnimation, context)
}
}
// MARK: - Empty Animation
fileprivate func executeCompletion(_ emptyAnimation: BasicAnimation) {
emptyAnimation.completion?()
}
// MARK: - Stored animation
func addStoredAnimations(_ node: Node, _ view: MacawView) {
addStoredAnimations(node, AnimationContext())
}
func addStoredAnimations(_ node: Node, _ context: AnimationContext) {
if let animation = storedAnimations[node] {
play(animation, context)
storedAnimations.removeValue(forKey: node)
}
guard let group = node as? Group else {
return
}
group.contents.forEach { child in
addStoredAnimations(child, context)
}
}
// MARK: - Contents animation
func addContentsAnimation(_ animation: BasicAnimation, _ context: AnimationContext, completion: @escaping (() -> Void)) {
guard let contentsAnimation = animation as? ContentsAnimation else {
return
}
if animation.autoreverses {
animation.autoreverses = false
play([animation, animation.reverse()].sequence() as! BasicAnimation, context)
return
}
if animation.repeatCount > 0.0001 {
animation.repeatCount = 0.0
var animSequence = [Animation]()
for _ in 0...Int(animation.repeatCount) {
animSequence.append(animation)
}
play(animSequence.sequence() as! BasicAnimation, context)
return
}
let startDate = Date(timeInterval: contentsAnimation.delay, since: Date())
let animationDesc = ContentAnimationDesc(
animation: contentsAnimation,
startDate: Date(),
finishDate: Date(timeInterval: contentsAnimation.duration, since: startDate),
completion: completion
)
contentsAnimations.append(animationDesc)
if displayLink == nil {
displayLink = MDisplayLink()
displayLink?.startUpdates { [weak self] in
DispatchQueue.main.async {
self?.updateContentAnimations(context)
}
}
}
}
func updateContentAnimations(_ context: AnimationContext) {
if contentsAnimations.isEmpty {
displayLink?.invalidate()
displayLink = .none
}
let currentDate = Date()
let count = contentsAnimations.count
for (index, animationDesc) in contentsAnimations.reversed().enumerated() {
let animation = animationDesc.animation
guard let group = animation.node as? Group, let renderer = animation.nodeRenderer else {
continue
}
defer {
renderer.sceneLayer?.setNeedsDisplay()
}
let progress = currentDate.timeIntervalSince(animationDesc.startDate) / animation.duration + animation.pausedProgress
// Completion
if progress >= 1.0 {
// Final update
group.contents = animation.getVFunc()(1.0)
animation.onProgressUpdate?(1.0)
animation.pausedProgress = 0.0
// Finishing animation
if !animation.cycled {
animation.completion?()
}
contentsAnimations.remove(at: count - 1 - index)
renderer.freeLayer()
animationDesc.completion?()
continue
}
let t = animation.easing.progressFor(time: progress)
group.contents = animation.getVFunc()(t)
animation.onProgressUpdate?(progress)
// Manual stop
if animation.manualStop || animation.paused {
defer {
contentsAnimations.remove(at: count - 1 - index)
renderer.freeLayer()
}
if animation.manualStop {
animation.pausedProgress = 0.0
group.contents = animation.getVFunc()(0)
} else if animation.paused {
animation.pausedProgress = progress
}
}
}
}
}
class AnimationContext {
var rootTransform: Transform?
func getLayoutTransform(_ renderer: NodeRenderer?) -> Transform {
if rootTransform == nil {
if let view = renderer?.view {
rootTransform = view.place
}
}
return rootTransform ?? Transform.identity
}
}
| 30.480938 | 140 | 0.560227 |
4b6382156768a691e5865640478ad757b4313a50 | 520 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "VRMKit",
platforms: [.iOS(.v11)],
products: [
.library(name: "VRMKit", targets: ["VRMKit"]),
.library(name: "VRMSceneKit", targets: ["VRMSceneKit"])
],
targets: [
.target(
name: "VRMKit",
path: "Sources/VRMKit"
),
.target(
name: "VRMSceneKit",
dependencies: ["VRMKit"],
path: "Sources/VRMSceneKit"
)
]
)
| 22.608696 | 63 | 0.507692 |
e5d2bf52e876a58e781241cf9f9d4d6bd292747d | 67 | import Foundation
typealias Slot = UInt64
typealias Epoch = UInt64 | 16.75 | 24 | 0.820896 |
0ede48782dafd2fe66f46cf1d55363da4f6b0390 | 10,443 |
import UIKit
import RxSwift
example(of: "just") {
// .just() - Returns an observable sequence that contains a single element.
// Array<Element>
// let array = [1, 2, 3, 4] <-- Array<Int>
// let other = ["a", "b"] <-- Array<String>
// Observer : RX :: Functions : Swift
let observable = Observable.just("Hello, World!")
// Observable<String>
// subscribe takes a closure that receives the emitted event and executes each time this event is emitted.
observable.subscribe({ (event: Event<String>) in
// print out each event as it is emitted
print(event)
// result ends up being a single next() event with the string sequence
// followed by the completed() event
// when either the completed() or the error() events occur, the observed
// sequence can no longer emit more events
})
}
// the "of" observer
example(of: "of") {
let observable = Observable.of(1, 2, 3, 4, 5)
// result of this is 3 next() events
// followed by the completed() event
observable.subscribe {
// $0 -> Event<Int>
print($0)
}
/*
observable.subscribe(onNext: (Int) -> Void?,
onError: (Error) -> Void?,
onCompleted: () -> Void?,
onDisposed: () -> Void?)
*/
observable
.subscribe(onNext: {
print($0)
}, onCompleted: {
print("other subscription completed")
})
}
example(of: "from") {
let disposeBag = DisposeBag()
/*
subscribe() returns a type of Disposable. This is an object
that conforms to a particular protocol to indicate it can be disposed.
*/
let observable = Observable.from([1, 2, 3, 4, 5, 6])
let subscription: Disposable = observable.subscribe {
print($0)
}
subscription.disposed(by: disposeBag)
let subscription2: Disposable = observable.subscribe {
print("This is the other subscribe", $0)
}
observable
.subscribe { print("checking on another sub", $0) }
.disposed(by: disposeBag)
// disposing of a subscription causes the underlying sequence to emit a completed event and to terminate. The sequence here was determined ahead of time, and so the completed event gets called automatically. However, in most cases you want the observer to continually emit events.
// To remove a subscription properly, you'd need to call .dispose() on the Disposable object. But convention is to add observables to a DisposeBag and then to call dispose on all items in the DisposeBag in the deinit of a class.
}
example(of: "error") {
enum MyError: Error {
case testError
}
Observable<Void>.error(MyError.testError)
.subscribe(onError: { (error: Error) in
print(error)
})
}
/*
Subject in RxSwift
- Subject: acts as both an observable sequence (can be subscribed to) and observer (to add new elements, which will be emitted to the subject’s subscribers.
1. PublishSubject
- you need to specify the type of the PublishSubject on init
- subscribers only receives events after they subscribe
- but still receives onComplete and onError
2. BehaviorSubject
- subscriber receives the last event emitted, or the initialized value
- but they still send/receive onComplete and onError
3. ReplaySubject
- receives a buffer of previous events, so it could the last n-number of events on a stream
- receives them in the same order they occurred.
4. Variable
- Wraps a BehaviorSubject
- Replays most recent next() event
- Will not emit error event
- Automatically completes when it is about to be deallocated
- Uses dot-syntax to get or set latest value
*/
// Only gets the events going forward
example(of: "PublishSubject") {
let disposeBag: DisposeBag = DisposeBag()
// <Int> describes the .value of the Event(s) this observable stream will emit
// This is analogous to saying that
//
// let values = [1, 2, 3].map { $0 * $0 }
//
// values would be Array<Int> because map returns a type of Array<T> where
// T is the Element type of result of the map closure
let observable = PublishSubject<Int>()
observable
.subscribe {
print("get all of them", $0)
}
.disposed(by: disposeBag)
observable.onNext(1)
observable.onNext(2)
observable.onNext(3)
// this only receives events that come after subscription
observable
.subscribe(onNext: {
print($0)
}, onCompleted: {
print("Stream completed")
})
.disposed(by: disposeBag)
observable.onNext(4)
observable.onNext(5)
// PublishSubjects do not send a complete() event automatically, you have to
// specifically call it
observable.onCompleted()
}
// Sends subscribers either the most recent event, or the initial value of the stream
example(of: "BehaviorSubject") {
let disposeBag = DisposeBag()
// doesn't need to be given an explicit Element type, it gets inferred from the initial value
// BehaviorSubject<String>
let observable = BehaviorSubject(value: "Hello")
observable.onNext("World")
observable.onNext("Nice to meet you")
// this only receives the initial value OR the most recent one
observable
.subscribe {
print($0)
}
.disposed(by: disposeBag)
}
// It replays a buffer of events, you determine the size of the buffer
example(of: "ReplaySubject") {
let disposeBag = DisposeBag()
let observable = ReplaySubject<Int>.create(bufferSize: 4)
observable.onNext(1)
observable.onNext(2)
observable.onNext(3)
observable.onNext(4)
observable.onNext(5)
observable.onNext(6)
observable.onNext(7)
observable.subscribe {
print($0)
}.disposed(by: disposeBag)
observable
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
}
// Wrapper on a BehaviorSubject
example(of: "Variable") {
let disposeBag = DisposeBag()
// Variable<String>
let observable = Variable("cat")
// Observable<String>
let behaviorSubject = observable.asObservable()
observable.value = "dog"
//observable.value = "mouse"
//observable.value = "kitten"
// only "kitten" gets outputted because it was the last value that was emitted before the subscription occured.
// but all subsequent events get outputted as well because they come after the subscription has occurred
behaviorSubject.subscribe {
print($0)
}
observable.value = "bird"
observable.value = "snake"
observable.value = "rabbit"
}
/*
It's your party, and you're opening presents. But your mother leaves the room to get cupcakes,
and you open three presents.
- Your friends that are present for you receiving events since the start, just observe the events the entire time you open presents. They're subscribed to your opening present observations
- Your mother requesting info on the presents opened is like a *ReplaySubject*: she wants you to replay the present you received. In this case the presents are the events in your opening observation
- Your friend that comes in and asks about your previous presents, you give him the last one you opened to shut him up and continue. Your friend is a BehaviorSubject, receiving info on the last present you got, plus everything going forward
- Your other not so good friend just comes in for the cake/ambience. So they don't care about what has already occurred, but they pay attention to all further present opening events. They are like a PublishSubject
*/
example(of: "map") {
let disposeBag = DisposeBag()
Observable.of(1, 2, 3, 10) // returns Observable<Int>
.map{ $0 * $0 } // Observable<Int> still
.subscribe(onNext: { // now we subscribe to the result of the map() func call, which is Observable<Int>
print($0)
})
.disposed(by: disposeBag)
}
example(of: "filter") {
let disposeBag = DisposeBag()
Observable.generate(initialState: 0,
condition: { $0 < 100 },
iterate: { $0 + 1} )
.filter{ $0 % 2 == 0 }
.filter{ $0 % 4 == 0 }
.map{ $0 + 1000 }
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
example(of: "distinctUntilChanged") {
let disposeBag = DisposeBag()
let observable = PublishSubject<String>()
// does order matter? yes: try moving around the .map call before/after the distinctUntilChanged function
observable
//.map{ $0.lowercased() }
.distinctUntilChanged()
.map{ $0.lowercased() }
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
observable.onNext("Hello")
observable.onNext("HELLO")
observable.onNext("hello")
observable.onNext("There")
observable.onNext("There")
}
// continue to observe events until a specific predicate is met
example(of: "takeWhile") {
let disposeBag = DisposeBag()
Observable.generate(initialState: 1,
condition: { $0 < 10 },
iterate: { $0 + 1 })
.takeWhile { $0 < 5 }
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
}
// scan: like reduce in that it performs an aggregate function on a sequence of values. but it differs because you can access each step of that aggregation as an observable object. Reduce just returns the since obversable with the aggregated value
// buffer: gathers emitted events based on time or a specified number
example(of: "scan & buffer") {
let disposeBag = DisposeBag()
let observable = PublishSubject<Int>()
/*
observable
.buffer(timeSpan: 0.0,
count: 2,
scheduler: MainScheduler.instance)
.subscribe(onNext: {
print($0)
})
.disposed(by: disposeBag)
*/
// it's all about what function you
// use on the returned value of the prior function
observable
.scan(501, accumulator: -)
.buffer(timeSpan: 0.0, count: 3, scheduler: MainScheduler.instance)
.map{
print($0)
return $0.reduce(0, +)
}
.subscribe(onNext: { print($0) })
observable.onNext(5)
observable.onNext(9)
observable.onNext(22)
/*
.buffer(timeSpan: 0.0, count: 3, scheduler: MainScheduler.instance)
.map{ // [Int]
print($0)
return $0.reduce(0, +)
}
.subscribe(onNext: {
print("Elements =>", $0)
})
.disposed(by: disposeBag)
observable.onNext(10)
observable.onNext(20)
observable.onNext(30)
observable.onNext(40)
observable.onNext(50)
observable.onNext(60)
observable.onNext(500)
observable.onNext(40)
observable.onNext(40)
*/
}
// flatMap, flatMapLast
| 28.768595 | 282 | 0.674998 |
ace8af9edac76be2feb0c9d1fe395e9bb322aa85 | 529 | //
// Body.swift
// SwiftHtml
//
// Created by Tibor Bodecs on 2021. 07. 19..
//
/// The `<body>` tag defines the document's body.
///
/// The `<body>` element contains all the contents of an HTML document, such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
///
/// **Note:** There can only be one `<body>` element in an HTML document.
open class Body: Tag {
public init(@TagBuilder _ builder: () -> [Tag]) {
super.init(Node(type: .standard, name: "body"), children: builder())
}
}
| 26.45 | 141 | 0.623819 |
d6f28ea189a9676996328b987d96093184f1a416 | 623 | import Foundation
import RxSwift
class CMAccessForExistingUsersViewModel
{
// MARK: Public Properties
private(set) lazy var hideOverlayObservable : Observable<Void> =
{
return self.motionService.motionAuthorizationGranted
.mapTo(())
}()
// MARK: Private Properties
private let settingsService : SettingsService
private let motionService : MotionService
// MARK: Initializers
init(settingsService: SettingsService,
motionService: MotionService)
{
self.settingsService = settingsService
self.motionService = motionService
}
}
| 22.25 | 68 | 0.690209 |
711af9e531cd67a448fea2ad323d413889a60b12 | 4,142 | import Foundation
/// Help formatting a `PhoneNumber` into a `String` based on pattern rules
///
/// Example:
///
/// `NumberFormatter(international: "\(.code)\(1) \(2) \(2) \(2) \(2)")`
/// would give "+331 02 03 04 05" with a french number
public struct PhoneNumberFormatter {
/// Rules to define a pattern to display data from `PhoneNumber`
public enum Rule: Equatable {
/// international or national code depending on selected `Format`
case code
/// add a literal string to formatter
case literal(String)
/// take at most Int argument from subscriber number
case subscriber(Int)
/// group subscriber number by packer of count using separator
case subscriberGrouped(by: Int, separator: String)
}
/// Formats into which a `Number` can be rendered
public enum FormattingStyle {
case international
case national
}
private let patterns: (international: [Rule], national: [Rule])
/// - Parameter international: list of chained rules to create pattern in international format
/// - Parameter international: list of chained rules to create pattern in national format
public init(international: [Rule], national: [Rule]) {
self.patterns = (international, national)
}
/// Init formatter with same pattern for both internaional and national format
public init(_ pattern: [Rule]) {
self.init(international: pattern, national: pattern)
}
/// Transform number into `String` for given format
/// - Parameter number: the number to stringify
/// - Parameter style: the number desired string style
/// - Parameter metadata: phone metadata to use to generate the string. If nil default number metadata will be used
public func string(from number: PhoneNumber, style: FormattingStyle, metadata: PhoneCountry? = nil) -> String {
let subscriber = number.subscriberNumber
let metadata = metadata ?? number.country.phone.metadata
return string(from: subscriber, metadata: metadata, style: style)
}
/// Apply string formatting to a partial string number
func partial(string: String, style: FormattingStyle, metadata: PhoneCountry) -> String {
let subscriber = string.hasPrefix("+")
? string.dropFirst("+".count + metadata.internationalCode.count)
: string.dropFirst(metadata.nationalCode?.count ?? 0)
return self.string(from: String(subscriber), metadata: metadata, style: style)
}
private func string(from subscriber: String, metadata: PhoneCountry, style: FormattingStyle) -> String {
let pattern: [Rule]
var code: String
var subscriber = subscriber
switch style {
case .international:
pattern = patterns.international
code = "+" + metadata.internationalCode
case .national:
pattern = patterns.national
code = metadata.nationalCode ?? ""
}
return pattern.reduce(into: "") { result, rule in
switch rule {
case .code:
result += code
code.removeAll()
case let .literal(separator) where !subscriber.isEmpty:
result += separator
case let .subscriber(count) where !subscriber.isEmpty:
result += subscriber.prefix(count)
subscriber.removeFirst(min(count, subscriber.count))
case let .subscriberGrouped(count, separator) where !subscriber.isEmpty:
result += subscriber.grouped(by: count, separator: separator)
subscriber.removeAll()
default:
break
}
}
}
}
private extension String {
func grouped(by offset: Int, separator: String) -> String {
enumerated().reduce(into: "") { result, iterator in
let addSeparator = iterator.offset % offset == 0 && iterator.offset > 0
result += (addSeparator ? separator : "") + String(iterator.element)
}
}
}
| 39.447619 | 119 | 0.622646 |
1646705bd772bbf160715fdd03e6559075de07d8 | 4,857 | //
// SdaiUnownedWrap.swift
//
//
// Created by Yoshida on 2021/07/22.
// Copyright © 2021 Tsutomu Yoshida, Minokamo, Japan. All rights reserved.
//
import Foundation
//MARK: - SDAI.UnownedWrap
extension SDAI {
public struct UnownedWrap<REF: SdaiObjectReference>: Hashable {
public unowned let reference: REF
public let objectId: ObjectIdentifier
public var object: REF.Object { reference.object }
public init(_ ref: REF) {
self.reference = ref
objectId = ref.objectId
}
public static func == (lhs: UnownedWrap<REF>, rhs: UnownedWrap<REF>) -> Bool {
return lhs.objectId == rhs.objectId
}
public func hash(into hasher: inout Hasher) {
objectId.hash(into: &hasher)
}
}
}
extension SDAI.UnownedWrap: InitializableBySelecttype where REF: InitializableBySelecttype {
public init?<S: SDAISelectType>(possiblyFrom select: S?) {
guard let obj = REF.init(possiblyFrom: select) else { return nil }
self.init(obj)
}
}
extension SDAI.UnownedWrap: InitializableByGenerictype where REF: InitializableByGenerictype {
public init?<G: SDAIGenericType>(fromGeneric generic: G?) {
guard let obj = REF.init(fromGeneric: generic) else { return nil }
self.init(obj)
}
public static func convert<G: SDAIGenericType>(fromGeneric generic: G?) -> Self? {
guard let obj = REF.convert(fromGeneric: generic) else { return nil }
return Self(obj)
}
}
extension SDAI.UnownedWrap: InitializableByP21Parameter where REF: InitializableByP21Parameter {
public static var bareTypeName: String { REF.bareTypeName }
public init?(p21param: P21Decode.ExchangeStructure.Parameter, from exchangeStructure: P21Decode.ExchangeStructure) {
guard let obj = REF.init(p21param: p21param, from: exchangeStructure) else { return nil }
self.init(obj)
}
public init?(p21typedParam: P21Decode.ExchangeStructure.TypedParameter, from exchangeStructure: P21Decode.ExchangeStructure) {
guard let obj = REF.init(p21typedParam: p21typedParam, from: exchangeStructure) else { return nil }
self.init(obj)
}
public init?(p21untypedParam: P21Decode.ExchangeStructure.UntypedParameter, from exchangeStructure: P21Decode.ExchangeStructure) {
guard let obj = REF.init(p21untypedParam: p21untypedParam, from: exchangeStructure) else { return nil }
self.init(obj)
}
public init?(p21omittedParamfrom exchangeStructure: P21Decode.ExchangeStructure) {
guard let obj = REF.init(p21omittedParamfrom: exchangeStructure) else { return nil }
self.init(obj)
}
}
extension SDAI.UnownedWrap: SDAIGenericType, SdaiCachableSource where REF: SDAIGenericType {
public typealias FundamentalType = REF.FundamentalType
public typealias Value = REF.Value
public func copy() -> Self {
let obj = self.reference.copy()
return Self(obj)
}
public var isCachable: Bool { reference.isCachable }
public var asFundamentalType: FundamentalType { reference.asFundamentalType }
public init(fundamental: FundamentalType) {
let obj = REF.init(fundamental: fundamental)
self.init(obj)
}
public static var typeName: String { REF.typeName }
public var typeMembers: Set<SDAI.STRING> { reference.typeMembers }
public var value: Value { reference.value }
public var entityReference: SDAI.EntityReference? { reference.entityReference }
public var stringValue: SDAI.STRING? { reference.stringValue }
public var binaryValue: SDAI.BINARY? { reference.binaryValue }
public var logicalValue: SDAI.LOGICAL? { reference.logicalValue }
public var booleanValue: SDAI.BOOLEAN? { reference.booleanValue }
public var numberValue: SDAI.NUMBER? { reference.numberValue }
public var realValue: SDAI.REAL? { reference.realValue }
public var integerValue: SDAI.INTEGER? { reference.integerValue }
public var genericEnumValue: SDAI.GenericEnumValue? { reference.genericEnumValue }
public func arrayOptionalValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.ARRAY_OPTIONAL<ELEM>? {
reference.arrayOptionalValue(elementType: elementType)
}
public func arrayValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.ARRAY<ELEM>? {
reference.arrayValue(elementType: elementType)
}
public func listValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.LIST<ELEM>? {
reference.listValue(elementType: elementType)
}
public func bagValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.BAG<ELEM>? {
reference.bagValue(elementType: elementType)
}
public func setValue<ELEM:SDAIGenericType>(elementType:ELEM.Type) -> SDAI.SET<ELEM>? {
reference.setValue(elementType: elementType)
}
public func enumValue<ENUM:SDAIEnumerationType>(enumType:ENUM.Type) -> ENUM? {
reference.enumValue(enumType: enumType)
}
public static func validateWhereRules(instance:Self?, prefix:SDAI.WhereLabel) -> [SDAI.WhereLabel:SDAI.LOGICAL] {
REF.validateWhereRules(instance: instance?.reference, prefix: prefix)
}
}
| 35.452555 | 131 | 0.761375 |
4aa0869d43173d3ec8a39a91e585d342b8ed5342 | 4,396 | import XCTest
import Quick
import Nimble
private enum AroundEachType {
case around0Prefix
case around0Suffix
case around1Prefix
case around1Suffix
case before0
case before1
case before2
case after0
case after1
case after2
case innerBefore
case innerAfter
case innerAroundPrefix
case innerAroundSuffix
}
private var aroundEachOrder = [AroundEachType]()
class FunctionalTests_AroundEachSpec: QuickSpec {
override func spec() {
describe("aroundEach ordering") {
beforeEach { aroundEachOrder.append(.before0) }
afterEach { aroundEachOrder.append(.after0) }
aroundEach { run in
aroundEachOrder.append(.around0Prefix)
run()
aroundEachOrder.append(.around0Suffix)
}
beforeEach { aroundEachOrder.append(.before1) }
afterEach { aroundEachOrder.append(.after1) }
aroundEach { run in
aroundEachOrder.append(.around1Prefix)
run()
aroundEachOrder.append(.around1Suffix)
}
beforeEach { aroundEachOrder.append(.before2) }
afterEach { aroundEachOrder.append(.after2) }
it("executes the prefix portion before each example, but not the suffix portion [1]") {
expect(aroundEachOrder).to(equal([
.before0, .around0Prefix,
.before1, .around1Prefix,
.before2,
]))
}
context("when there are nested aroundEach") {
beforeEach { aroundEachOrder.append(.innerBefore) }
afterEach { aroundEachOrder.append(.innerAfter) }
aroundEach { run in
aroundEachOrder.append(.innerAroundPrefix)
run()
aroundEachOrder.append(.innerAroundSuffix)
}
it("executes the outer and inner aroundEach closures, but not before this closure [2]") {
expect(aroundEachOrder).to(contain(.innerAroundPrefix, .innerBefore))
expect(aroundEachOrder).notTo(contain(.innerAroundSuffix))
expect(aroundEachOrder).notTo(contain(.innerAfter))
}
}
}
#if canImport(Darwin) && !SWIFT_PACKAGE
describe("error handling when misusing ordering") {
it("should throw an exception when including aroundEach in it block") {
expect {
aroundEach { _ in }
}.to(raiseException { (exception: NSException) in
expect(exception.name).to(equal(NSExceptionName.internalInconsistencyException))
expect(exception.reason).to(equal("'aroundEach' cannot be used inside 'it', 'aroundEach' may only be used inside 'context' or 'describe'. "))
})
}
}
#endif
}
}
final class AroundEachTests: XCTestCase, XCTestCaseProvider {
static var allTests: [(String, (AroundEachTests) -> () throws -> Void)] {
return [
("testAroundEachIsExecutedInTheCorrectOrder", testAroundEachIsExecutedInTheCorrectOrder),
]
}
func testAroundEachIsExecutedInTheCorrectOrder() {
aroundEachOrder = []
qck_runSpec(FunctionalTests_AroundEachSpec.self)
let expectedOrder: [AroundEachType] = [
// First spec [1]
.before0, .around0Prefix, // All beforeEaches and aroundEach prefixes happen in order...
.before1, .around1Prefix,
.before2,
.around1Suffix, // ...then aroundEaches suffixes resolve in order...
.around0Suffix,
.after0, .after1, .after2, // ...then afterEaches all come last.
.before0, .around0Prefix, // Outer setup happens first...
.before1, .around1Prefix,
.before2,
.innerBefore, .innerAroundPrefix, // ...then inner setup...
.innerAroundSuffix, .innerAfter, // ...then inner cleanup, happily inner after...
.around1Suffix, // ...then the outer cleanup, as before.
.around0Suffix,
.after0, .after1, .after2,
]
XCTAssertEqual(aroundEachOrder, expectedOrder)
aroundEachOrder = []
}
}
| 37.57265 | 161 | 0.580755 |
16df01530c858f3ce976b781b5ec62da79696d83 | 4,942 | // RUN: %target-typecheck-verify-swift -D FOO -D BAZ -swift-version 4
#if FOO == BAZ // expected-error{{expected '&&' or '||' expression}}
var x = 0
#endif
#if ^FOO // expected-error {{expected unary '!' expression}}
var y = 0
#endif
#if foo(BAR) // expected-error {{unexpected platform condition (expected 'os', 'arch', or 'swift')}}
var z = 0
#endif
#if FOO || !FOO
func f() {}
#endif ; f() // expected-error {{extra tokens following conditional compilation directive}}
#if FOO || !FOO
func g() {}
#else g() // expected-error {{extra tokens following conditional compilation directive}}
#endif
#if FOO || !FOO
func h() {}
#else /* aaa */
#endif /* bbb */
#if foo.bar()
.baz() // expected-error {{unexpected platform condition (expected 'os', 'arch', or 'swift')}}
#endif
// <https://twitter.com/practicalswift/status/829066902869786625>
#if // expected-error {{incomplete condition in conditional compilation directive}}
#if 0 == // expected-error {{incomplete condition in conditional compilation directive}}
#if 0= // expected-error {{incomplete condition in conditional compilation directive}} expected-error {{'=' must have consistent whitespace on both sides}}
class Foo {
#if // expected-error {{incomplete condition in conditional compilation directive}}
#if 0 == // expected-error {{incomplete condition in conditional compilation directive}}
#if 0= // expected-error {{incomplete condition in conditional compilation directive}} expected-error {{'=' must have consistent whitespace on both sides}}
}
struct S {
#if FOO
#else
#else // expected-error {{further conditions after #else are unreachable}}
#endif
#if FOO
#elseif BAR
#elseif BAZ
#else
#endif
}
#if FOO
#else
#else // expected-error {{further conditions after #else are unreachable}}
#endif
#if FOO
#elseif BAR
#elseif BAZ
#else
#endif
#if os(ios) // expected-warning {{unknown operating system for build configuration 'os'}} expected-note{{did you mean 'iOS'?}} {{8-11=iOS}}
#endif
#if os(uOS) // expected-warning {{unknown operating system for build configuration 'os'}} expected-note{{did you mean 'iOS'?}} {{8-11=iOS}}
#endif
#if os(xxxxxxd) // expected-warning {{unknown operating system for build configuration 'os'}}
// expected-note@-1{{did you mean 'Linux'?}} {{8-15=Linux}}
// expected-note@-2{{did you mean 'FreeBSD'?}} {{8-15=FreeBSD}}
// expected-note@-3{{did you mean 'Android'?}} {{8-15=Android}}
// expected-note@-4{{did you mean 'OSX'?}} {{8-15=OSX}}
#endif
#if arch(leg) // expected-warning {{unknown architecture for build configuration 'arch'}} expected-note{{did you mean 'arm'?}} {{10-13=arm}}
#endif
#if _endian(mid) // expected-warning {{unknown endianness for build configuration '_endian'}} expected-note{{did you mean 'big'?}} {{13-16=big}}
#endif
LABEL: #if true // expected-error {{expected statement}}
func fn_i() {}
#endif
fn_i() // OK
try #if false // expected-error {{expected expression}}
#else
func fn_j() {}
#endif
fn_j() // OK
#if foo || bar || nonExistent() // expected-error {{expected only one argument to platform condition}}
#endif
#if FOO = false
// expected-error @-1 {{invalid conditional compilation expression}}
undefinedFunc() // ignored.
#else
undefinedFunc() // expected-error {{use of unresolved identifier 'undefinedFunc'}}
#endif
#if false
#elseif FOO ? true : false
// expected-error @-1 {{invalid conditional compilation expression}}
undefinedFunc() // ignored.
#else
undefinedFunc() // expected-error {{use of unresolved identifier 'undefinedFunc'}}
#endif
/// Invalid platform condition arguments don't invalidate the whole condition.
#if !arch(tecture) && !os(ystem) && !_endian(ness)
// expected-warning@-1 {{unknown architecture for build configuration 'arch'}}
// expected-note@-2 {{did you mean 'arm'?}} {{11-18=arm}}
// expected-warning@-3 {{unknown operating system for build configuration 'os'}}
// expected-note@-4 {{did you mean 'OSX'?}} {{27-32=OSX}}
// expected-note@-5 {{did you mean 'PS4'?}} {{27-32=PS4}}
// expected-warning@-6 {{unknown endianness for build configuration '_endian'}}
// expected-note@-7 {{did you mean 'big'?}} {{46-50=big}}
func fn_k() {}
#endif
fn_k()
#if os(cillator) || arch(ive)
// expected-warning@-1 {{unknown operating system for build configuration 'os'}}
// expected-note@-2 {{did you mean 'macOS'?}} {{8-16=macOS}}
// expected-note@-3 {{did you mean 'iOS'?}} {{8-16=iOS}}
// expected-warning@-4 {{unknown architecture for build configuration 'arch'}}
// expected-note@-5 {{did you mean 'arm'?}} {{26-29=arm}}
// expected-note@-6 {{did you mean 'i386'?}} {{26-29=i386}}
func undefinedFunc() // ignored.
#endif
undefinedFunc() // expected-error {{use of unresolved identifier 'undefinedFunc'}}
#if FOO
#else if BAR
// expected-error@-1 {{unexpected 'if' keyword following '#else' conditional compilation directive; did you mean '#elseif'?}} {{1-9=#elseif}}
#else
#endif
#if FOO
#else
if true {}
#endif // OK
| 32.513158 | 157 | 0.688992 |
3355ff3f8cc0eff2b77bd5aeb350c7d88eaa27b8 | 847 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Amplify
import Foundation
extension MutationSyncMetadata {
// MARK: - CodingKeys
public enum CodingKeys: String, ModelKey {
case id
case deleted
case lastChangedAt
case version
}
public static let keys = CodingKeys.self
// MARK: - ModelSchema
public static let schema = defineSchema { definition in
let sync = MutationSyncMetadata.keys
definition.attributes(.isSystem)
definition.fields(
.id(),
.field(sync.deleted, is: .required, ofType: .bool),
.field(sync.lastChangedAt, is: .required, ofType: .int),
.field(sync.version, is: .required, ofType: .int)
)
}
}
| 21.717949 | 68 | 0.617473 |
20539aac90e220b6f29eee8f3f25342a2e1c4d0d | 1,068 | import Shared
/// The logic interface, which is available to the display for informing about user initiated processes.
protocol Scene1LogicInterface: AnyObject {
/**
Updates the display with initial data by performing an initial search with an empty query string.
*/
func updateInitialDisplay()
/**
Informs that the display has been rotated so the rotation counter gets increased.
*/
func displayRotated()
/**
Searches for a given text and updates the display accordingly.
- parameter text: The text to search for.
*/
func searchForText(_ text: String)
/**
Dismisses the keyboard when it is shown.
*/
func dismissKeyboard()
/**
Takes the suggestion's term, passes it to the display for showing in the search field and performs a new search with it.
- parameter suggestion: The suggestion to adopt.
*/
func adoptSuggestion(_ suggestion: Suggestion)
/**
Routes to `Scene2` with the given suggestion passed to it.
- parameter suggestion: The suggestion to pass.
*/
func showSuggestionDetails(_ suggestion: Suggestion)
}
| 26.04878 | 122 | 0.741573 |
5d9e2a75bffb59df4fe0540b823a9f548fbd8316 | 11,464 | //
// MeasurementTextField.swift
// MeasurementTextField
//
// Created by Siarhei Fedartsou on 1/13/18.
//
import UIKit
private enum Layout {
static let measureUnitLabelRightInset: CGFloat = 10.0
}
public final class MeasurementTextField<UnitType: Dimension>: UITextField, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
private lazy var pickerView: UIPickerView = {
let pickerView = UIPickerView()
pickerView.delegate = self
return pickerView
}()
private lazy var unitLabel: UILabel = {
let unitLabel = UILabel()
unitLabel.textColor = tintColor
unitLabel.font = font
return unitLabel
}()
private let inputType: InputType<UnitType>
public init(inputType: InputType<UnitType>) {
#if DEBUG
if case let .picker(columns) = inputType {
var lastValue = Double.greatestFiniteMagnitude
for column in columns {
let value = Measurement(value: 1.0, unit: column.unit).converted(to: UnitType.baseUnit()).value
assert(value < lastValue, "Columns should be ordered from largest to smallest units")
lastValue = value
}
}
#endif
self.inputType = inputType
super.init(frame: .zero)
setup()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var showCaret: Bool = true {
didSet {
setNeedsLayout()
}
}
public override func caretRect(for position: UITextPosition) -> CGRect {
return showCaret ? super.caretRect(for: position) : .zero
}
private weak var realDelegate: UITextFieldDelegate?
public override weak var delegate: UITextFieldDelegate? {
set {
realDelegate = newValue
}
get {
return realDelegate
}
}
private func setup() {
keyboardType = .decimalPad
super.delegate = self
addTarget(self, action: #selector(onTextChanged), for: .editingChanged)
switch inputType {
case let .keyboardInput(unit, showMeasureUnit):
guard showMeasureUnit else { return }
let formatter = MeasurementFormatter()
formatter.unitStyle = .short
unitLabel.text = formatter.string(from: unit)
unitLabel.sizeToFit()
unitLabel.frame.size.width += Layout.measureUnitLabelRightInset
rightView = unitLabel
rightViewMode = .always
case .picker:
inputView = pickerView
showCaret = false
clearButtonMode = .whileEditing
}
}
public override func tintColorDidChange() {
super.tintColorDidChange()
unitLabel.textColor = tintColor
}
public override var font: UIFont? {
didSet {
unitLabel.font = font
}
}
public var value: Measurement<UnitType>? {
set {
internalValue = newValue
switch inputType {
case let .keyboardInput(unit, _):
guard let value = value else {
text = ""
return
}
let convertedValue = value.converted(to: unit)
text = stringFromDouble(convertedValue.value)
case let .picker(columns):
setPicker(to: value, columns: columns)
}
}
get {
return internalValue
}
}
private var internalValue: Measurement<UnitType>?
@objc private func onTextChanged() {
guard let text = self.text else { return }
if case .picker = inputType { // handle "clear" button
if text.isEmpty {
internalValue = nil
sendActions(for: .valueChanged)
}
return
}
guard case let .keyboardInput(unit, _) = inputType else { return }
guard let decimalValue = doubleFromString(text) else {
internalValue = nil
sendActions(for: .valueChanged)
return
}
internalValue = Measurement(value: decimalValue, unit: unit)
sendActions(for: .valueChanged)
}
private func value(at columnPath: ColumnPath, in columns: [PickerColumn<UnitType>]) -> Measurement<UnitType>? {
var measurements: [Measurement<UnitType>] = []
for (columnIndex, rowIndex) in columnPath.enumerated() {
let column = columns[columnIndex]
let value = column.rows[rowIndex]
let measurement = Measurement(value: value, unit: column.unit)
measurements.append(measurement)
}
return sumOf(measurements)
}
private func showValue(for path: ColumnPath, columns: [PickerColumn<UnitType>]) {
var formattedValues: [String] = []
let formatter = MeasurementFormatter()
formatter.unitOptions = .providedUnit
formatter.unitStyle = .short
for (columnIndex, rowIndex) in path.enumerated() {
let column = columns[columnIndex]
let row = column.rows[rowIndex]
let measurement = Measurement(value: row, unit: column.unit)
formattedValues.append(formatter.string(from: measurement))
}
text = formattedValues.joined(separator: " ")
}
private func setPicker(to value: Measurement<UnitType>?, columns: [PickerColumn<UnitType>]) {
guard let value = value else { return }
var columnPath: ColumnPath = []
var accumulator: Measurement<UnitType>?
let threshold = 0.0001
for (columnIndex, column) in columns.enumerated() {
columnPath.append(0)
let convertedValue: Measurement<UnitType>
if let accumulator = accumulator {
convertedValue = value.converted(to: column.unit) - accumulator.converted(to: column.unit)
} else {
let value = floor(value.converted(to: column.unit).value)
convertedValue = Measurement(value: value, unit: column.unit)
}
for (rowIndex, row) in column.rows.enumerated() {
if abs(row - convertedValue.value) < threshold {
columnPath[columnIndex] = rowIndex
break
}
}
// handle edge cases
if let first = column.rows.first, (first > convertedValue.value || abs(first - convertedValue.value) < threshold) {
columnPath[columnIndex] = 0
} else if let last = column.rows.last, (last < convertedValue.value || abs(last - convertedValue.value) < threshold) {
columnPath[columnIndex] = column.rows.count - 1
}
let selectedValue = column.rows[columnPath[columnIndex]]
let selectedMeasurement = Measurement(value: selectedValue, unit: column.unit)
accumulator = accumulator.flatMap { $0 + selectedMeasurement } ?? selectedMeasurement
}
assert(columnPath.count == columns.count)
for (column, row) in columnPath.enumerated() {
pickerView.selectRow(row, inComponent: column, animated: false)
}
showValue(for: columnPath, columns: columns)
}
private func sumOf(_ measurements: [Measurement<UnitType>]) -> Measurement<UnitType>? {
guard measurements.count > 1 else { return measurements.first }
return measurements[1...].reduce(measurements[0], +)
}
private func doubleFromString(_ string: String) -> Double? {
let numberFormatter = NumberFormatter()
return numberFormatter.number(from: string).flatMap { $0.doubleValue }
}
private func stringFromDouble(_ double: Double) -> String? {
let numberFormatter = NumberFormatter()
return numberFormatter.string(from: double as NSNumber)
}
// MARK UIPickerViewDelegate/UIPickerViewDataSource
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
guard case let .picker(columns) = inputType else {
assert(false)
return 0
}
return columns.count
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
guard case let .picker(columns) = inputType else {
assert(false)
return 0
}
let column = columns[component]
return column.rows.count
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
guard case let .picker(columns) = inputType else {
assert(false)
return nil
}
let column = columns[component]
let formatter = MeasurementFormatter()
formatter.unitStyle = .short
formatter.unitOptions = .providedUnit
let measurement = Measurement(value: column.rows[row], unit: column.unit)
return formatter.string(from: measurement)
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
guard case let .picker(columns) = inputType else {
assert(false)
return
}
let path = pickerView.columnPath
showValue(for: path, columns: columns)
self.internalValue = value(at: path, in: columns)
sendActions(for: .valueChanged)
}
// MARK: UITextFieldDelegate
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard case .keyboardInput = inputType else { return false }
guard let text = textField.text as NSString? else { return false }
let newText = text.replacingCharacters(in: range, with: string)
return doubleFromString(newText) != nil || newText.isEmpty
}
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return realDelegate?.textFieldShouldBeginEditing?(textField) ?? true
}
public func textFieldDidBeginEditing(_ textField: UITextField) {
realDelegate?.textFieldDidBeginEditing?(textField)
}
public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return realDelegate?.textFieldShouldEndEditing?(textField) ?? true
}
public func textFieldDidEndEditing(_ textField: UITextField) {
realDelegate?.textFieldDidEndEditing?(textField)
}
public func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
realDelegate?.textFieldDidEndEditing?(textField, reason: reason)
}
public func textFieldShouldClear(_ textField: UITextField) -> Bool {
return realDelegate?.textFieldShouldClear?(textField) ?? true
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return realDelegate?.textFieldShouldReturn?(textField) ?? true
}
}
| 34.95122 | 142 | 0.599703 |
effd1dc0944f9ce0cbb39d5587e5a3f00d48c2c0 | 14,621 | import Foundation
public final class PBXProject: PBXObject {
// MARK: - Attributes
/// Project name
public var name: String
/// Build configuration list reference.
var buildConfigurationListReference: PBXObjectReference
/// Build configuration list.
public var buildConfigurationList: XCConfigurationList! {
set {
buildConfigurationListReference = newValue.reference
}
get {
return buildConfigurationListReference.getObject()
}
}
/// A string representation of the XcodeCompatibilityVersion.
public var compatibilityVersion: String
/// The region of development.
public var developmentRegion: String?
/// Whether file encodings have been scanned.
public var hasScannedForEncodings: Int
/// The known regions for localized files.
public var knownRegions: [String]
/// The object is a reference to a PBXGroup element.
var mainGroupReference: PBXObjectReference
/// Project main group.
public var mainGroup: PBXGroup! {
set {
mainGroupReference = newValue.reference
}
get {
return mainGroupReference.getObject()
}
}
/// The object is a reference to a PBXGroup element.
var productsGroupReference: PBXObjectReference?
/// Products group.
public var productsGroup: PBXGroup? {
set {
productsGroupReference = newValue?.reference
}
get {
return productsGroupReference?.getObject()
}
}
/// The relative path of the project.
public var projectDirPath: String
/// Project references.
var projectReferences: [[String: PBXObjectReference]]
/// Project projects.
// {
// ProductGroup = B900DB69213936CC004AEC3E /* Products group reference */;
// ProjectRef = B900DB68213936CC004AEC3E /* Project file reference */;
// },
public var projects: [[String: PBXFileElement]] {
set {
projectReferences = newValue.map { project in
project.mapValues({ $0.reference })
}
}
get {
return projectReferences.map { project in
project.mapValues({ $0.getObject()! })
}
}
}
private static let targetAttributesKey = "TargetAttributes"
/// The relative root paths of the project.
public var projectRoots: [String]
/// The objects are a reference to a PBXTarget element.
var targetReferences: [PBXObjectReference]
/// Project targets.
public var targets: [PBXTarget] {
set {
targetReferences = newValue.references()
}
get {
return targetReferences.objects()
}
}
/// Project attributes.
/// Target attributes will be merged into this
public var attributes: [String: Any]
/// Target attribute references.
var targetAttributeReferences: [PBXObjectReference: [String: Any]]
/// Target attributes.
public var targetAttributes: [PBXTarget: [String: Any]] {
set {
targetAttributeReferences = [:]
newValue.forEach {
targetAttributeReferences[$0.key.reference] = $0.value
}
} get {
var attributes: [PBXTarget: [String: Any]] = [:]
targetAttributeReferences.forEach {
if let object: PBXTarget = $0.key.getObject() {
attributes[object] = $0.value
}
}
return attributes
}
}
/// Sets the attributes for the given target.
///
/// - Parameters:
/// - attributes: attributes that will be set.
/// - target: target.
public func setTargetAttributes(_ attributes: [String: Any], target: PBXTarget) {
targetAttributeReferences[target.reference] = attributes
}
/// Removes the attributes for the given target.
///
/// - Parameter target: target whose attributes will be removed.
public func removeTargetAttributes(target: PBXTarget) {
targetAttributeReferences.removeValue(forKey: target.reference)
}
/// Removes the all the target attributes
public func clearAllTargetAttributes() {
targetAttributeReferences.removeAll()
}
/// Returns the attributes of a given target.
///
/// - Parameter for: target whose attributes will be returned.
/// - Returns: target attributes.
public func attributes(for target: PBXTarget) -> [String: Any]? {
return targetAttributeReferences[target.reference]
}
// MARK: - Init
/// Initializes the project with its attributes
///
/// - Parameters:
/// - name: xcodeproj's name.
/// - buildConfigurationList: project build configuration list.
/// - compatibilityVersion: project compatibility version.
/// - mainGroup: project main group.
/// - developmentRegion: project has development region.
/// - hasScannedForEncodings: project has scanned for encodings.
/// - knownRegions: project known regions.
/// - productsGroup: products group.
/// - projectDirPath: project dir path.
/// - projects: projects.
/// - projectRoots: project roots.
/// - targets: project targets.
public init(name: String,
buildConfigurationList: XCConfigurationList,
compatibilityVersion: String,
mainGroup: PBXGroup,
developmentRegion: String? = nil,
hasScannedForEncodings: Int = 0,
knownRegions: [String] = [],
productsGroup: PBXGroup? = nil,
projectDirPath: String = "",
projects: [[String: PBXFileElement]] = [],
projectRoots: [String] = [],
targets: [PBXTarget] = [],
attributes: [String: Any] = [:],
targetAttributes: [PBXTarget: [String: Any]] = [:]) {
self.name = name
buildConfigurationListReference = buildConfigurationList.reference
self.compatibilityVersion = compatibilityVersion
mainGroupReference = mainGroup.reference
self.developmentRegion = developmentRegion
self.hasScannedForEncodings = hasScannedForEncodings
self.knownRegions = knownRegions
productsGroupReference = productsGroup?.reference
self.projectDirPath = projectDirPath
projectReferences = projects.map({ project in project.mapValues({ $0.reference }) })
self.projectRoots = projectRoots
targetReferences = targets.references()
self.attributes = attributes
targetAttributeReferences = [:]
super.init()
self.targetAttributes = targetAttributes
}
// MARK: - Decodable
fileprivate enum CodingKeys: String, CodingKey {
case name
case buildConfigurationList
case compatibilityVersion
case developmentRegion
case hasScannedForEncodings
case knownRegions
case mainGroup
case productRefGroup
case projectDirPath
case projectReferences
case projectRoot
case projectRoots
case targets
case attributes
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let referenceRepository = decoder.context.objectReferenceRepository
let objects = decoder.context.objects
name = (try container.decodeIfPresent(.name)) ?? ""
let buildConfigurationListReference: String = try container.decode(.buildConfigurationList)
self.buildConfigurationListReference = referenceRepository.getOrCreate(reference: buildConfigurationListReference, objects: objects)
compatibilityVersion = try container.decode(.compatibilityVersion)
developmentRegion = try container.decodeIfPresent(.developmentRegion)
let hasScannedForEncodingsString: String? = try container.decodeIfPresent(.hasScannedForEncodings)
hasScannedForEncodings = hasScannedForEncodingsString.flatMap({ Int($0) }) ?? 0
knownRegions = (try container.decodeIfPresent(.knownRegions)) ?? []
let mainGroupReference: String = try container.decode(.mainGroup)
self.mainGroupReference = referenceRepository.getOrCreate(reference: mainGroupReference, objects: objects)
if let productRefGroupReference: String = try container.decodeIfPresent(.productRefGroup) {
productsGroupReference = referenceRepository.getOrCreate(reference: productRefGroupReference, objects: objects)
} else {
productsGroupReference = nil
}
projectDirPath = try container.decodeIfPresent(.projectDirPath) ?? ""
let projectReferences: [[String: String]] = (try container.decodeIfPresent(.projectReferences)) ?? []
self.projectReferences = projectReferences.map({ references in
references.mapValues({ referenceRepository.getOrCreate(reference: $0, objects: objects) })
})
if let projectRoots: [String] = try container.decodeIfPresent(.projectRoots) {
self.projectRoots = projectRoots
} else if let projectRoot: String = try container.decodeIfPresent(.projectRoot) {
projectRoots = [projectRoot]
} else {
projectRoots = []
}
let targetReferences: [String] = (try container.decodeIfPresent(.targets)) ?? []
self.targetReferences = targetReferences.map({ referenceRepository.getOrCreate(reference: $0, objects: objects) })
var attributes = (try container.decodeIfPresent([String: Any].self, forKey: .attributes) ?? [:])
var targetAttributeReferences: [PBXObjectReference: [String: Any]] = [:]
if let targetAttributes = attributes[PBXProject.targetAttributesKey] as? [String: [String: Any]] {
targetAttributes.forEach { targetAttributeReferences[referenceRepository.getOrCreate(reference: $0.key, objects: objects)] = $0.value }
attributes[PBXProject.targetAttributesKey] = nil
}
self.attributes = attributes
self.targetAttributeReferences = targetAttributeReferences
try super.init(from: decoder)
}
}
// MARK: - PlistSerializable
extension PBXProject: PlistSerializable {
// swiftlint:disable:next function_body_length
func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) {
var dictionary: [CommentedString: PlistValue] = [:]
dictionary["isa"] = .string(CommentedString(PBXProject.isa))
let buildConfigurationListComment = "Build configuration list for PBXProject \"\(name)\""
let buildConfigurationListCommentedString = CommentedString(buildConfigurationListReference.value,
comment: buildConfigurationListComment)
dictionary["buildConfigurationList"] = .string(buildConfigurationListCommentedString)
dictionary["compatibilityVersion"] = .string(CommentedString(compatibilityVersion))
if let developmentRegion = developmentRegion {
dictionary["developmentRegion"] = .string(CommentedString(developmentRegion))
}
dictionary["hasScannedForEncodings"] = .string(CommentedString("\(hasScannedForEncodings)"))
if !knownRegions.isEmpty {
dictionary["knownRegions"] = PlistValue.array(knownRegions
.map { .string(CommentedString("\($0)")) })
}
let mainGroupObject: PBXGroup? = mainGroupReference.getObject()
dictionary["mainGroup"] = .string(CommentedString(mainGroupReference.value, comment: mainGroupObject?.fileName()))
if let productsGroupReference = productsGroupReference {
let productRefGroupObject: PBXGroup? = productsGroupReference.getObject()
dictionary["productRefGroup"] = .string(CommentedString(productsGroupReference.value,
comment: productRefGroupObject?.fileName()))
}
dictionary["projectDirPath"] = .string(CommentedString(projectDirPath))
if projectRoots.count > 1 {
dictionary["projectRoots"] = projectRoots.plist()
} else {
dictionary["projectRoot"] = .string(CommentedString(projectRoots.first ?? ""))
}
if let projectReferences = try projectReferencesPlistValue(proj: proj) {
dictionary["projectReferences"] = projectReferences
}
dictionary["targets"] = PlistValue.array(targetReferences
.map { targetReference in
let target: PBXTarget? = targetReference.getObject()
return .string(CommentedString(targetReference.value, comment: target?.name))
})
var plistAttributes: [String: Any] = attributes
if !targetAttributeReferences.isEmpty {
// merge target attributes
var plistTargetAttributes: [String: Any] = [:]
for (reference, value) in targetAttributeReferences {
plistTargetAttributes[reference.value] = value.mapValues { value in
(value as? PBXObject)?.reference.value ?? value
}
}
plistAttributes[PBXProject.targetAttributesKey] = plistTargetAttributes
}
dictionary["attributes"] = plistAttributes.plist()
return (key: CommentedString(reference,
comment: "Project object"),
value: .dictionary(dictionary))
}
private func projectReferencesPlistValue(proj _: PBXProj) throws -> PlistValue? {
guard !projectReferences.isEmpty else {
return nil
}
return .array(projectReferences.compactMap { reference in
guard let productGroupReference = reference["ProductGroup"], let projectRef = reference["ProjectRef"] else {
return nil
}
let producGroup: PBXGroup? = productGroupReference.getObject()
let groupName = producGroup?.fileName()
let project: PBXFileElement? = projectRef.getObject()
let fileRefName = project?.fileName()
return [
CommentedString("ProductGroup"): PlistValue.string(CommentedString(productGroupReference.value, comment: groupName)),
CommentedString("ProjectRef"): PlistValue.string(CommentedString(projectRef.value, comment: fileRefName)),
]
})
}
}
| 41.536932 | 147 | 0.642774 |
f99ba7e5eae046ffb294f4537f583acf86c45acd | 4,470 | //
// SceneDelegate.swift
// HttpRequestMonitor
//
// Created by Eden on 2021/9/8.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate
{
var window: UIWindow?
var savedShortcutItem: UIApplicationShortcutItem?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
{
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else {
return
}
let frame: CGRect = windowScene.coordinateSpace.bounds
let rootViewController = RootViewController()
let navigationController = UINavigationController(rootViewController: rootViewController)
let splitController = UISplitViewController().fluent
.viewControllers([navigationController])
.presentsWithGesture(false)
.preferredDisplayMode(.oneBesideSecondary)
.primaryBackgroundStyle(.sidebar)
.subject
splitController.showDetailViewController(navigationController, sender: nil)
let window = UIWindow(frame: frame).fluent
.windowScene(windowScene)
.rootViewController(splitController)
.subject
window.makeKeyAndVisible()
self.window = window
self.savedShortcutItem = connectionOptions.shortcutItem
}
func sceneDidDisconnect(_ scene: UIScene)
{
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene)
{
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
self.savedShortcutItem.unwrapped {
self.handleSortcutItem($0)
self.savedShortcutItem = nil
}
}
func sceneWillResignActive(_ scene: UIScene)
{
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene)
{
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene)
{
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void)
{
let result: Bool = self.handleSortcutItem(shortcutItem)
completionHandler(result)
}
}
private extension SceneDelegate
{
@discardableResult
func handleSortcutItem(_ shortcutItem: UIApplicationShortcutItem) -> Bool
{
guard let actionType = ActionType(rawValue: shortcutItem.type), actionType == .startAction else {
return false
}
OperationQueue.main.addOperation {
NotificationCenter.default.post(name: RootViewController.startServerNoticationName, object: nil)
}
return true
}
}
| 38.205128 | 153 | 0.644295 |
8ae977c54aacca22d2e3c7296c13f70e7adb4fbb | 706 | import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if let window = sender.windows.first {
if flag {
window.orderFront(nil)
} else {
window.makeKeyAndOrderFront(nil)
}
}
return true
}
}
| 25.214286 | 103 | 0.630312 |
698642651865345b65dad5a522d73f16d25d8e1d | 616 | //
// WalletBnbCell.swift
// Cosmostation
//
// Created by yongjoo on 27/09/2019.
// Copyright © 2019 wannabit. All rights reserved.
//
import UIKit
class WalletBnbCell: UITableViewCell {
@IBOutlet weak var totalAmount: UILabel!
@IBOutlet weak var totalValue: UILabel!
@IBOutlet weak var availableAmount: UILabel!
@IBOutlet weak var lockedAmount: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
}
var actionWC: (() -> Void)? = nil
@IBAction func onClickWC(_ sender: Any) {
actionWC?()
}
}
| 21.241379 | 51 | 0.63961 |
33901258140510f27fd4b8fc4e0588fec970f113 | 598 | //
// Extensions.swift
// TruTracePOC
//
// Created by Republic Systems on 2019-11-26.
// Copyright © 2019 Republic Systems. All rights reserved.
//
import Foundation
import SwiftUI
extension Color {
init(hex: String) {
let scanner = Scanner(string: hex)
scanner.scanLocation = 1
var rgbValue: UInt64 = 0
scanner.scanHexInt64(&rgbValue)
let r = (rgbValue & 0xff0000) >> 16
let g = (rgbValue & 0xff00) >> 8
let b = rgbValue & 0xff
self.init(red: Double(r) / 0xff, green: Double(g) / 0xff, blue: Double(b) / 0xff)
}
}
| 21.357143 | 89 | 0.605351 |
f8db88f96442ccc87dc277c5b93704d75d7219a3 | 6,344 | //: Learning Swift
//: Chapter 4 – To Be or Not to Be: Optionals
//: ============================================================
//: How to define an optional
//: --------------------------
//: Optional versions of String, Array, and Int
//: Only possibleInt actually has a value while the other two are nil
var possibleString: String?
var possibleArray: [Int]?
var possibleInt: Int? = 10
//: Here we can see how the different types of variables print out. Optionals
//: with values still print out as an optional containing that value, while an
//: optional without a value just prints nil
var actualInt = 10
var nilInt: Int?
print(actualInt) // 10
print(possibleInt) // Optional(10)
print(nilInt) // nil
//: Updating the value of an optional
nilInt = 2
print(nilInt) // Optional(2)
//: Removing the value of an optional
nilInt = nil
print(nilInt) // nil
//: How to unwrap an optional
//: --------------------------
//: ### Optional binding
//: Here we optionally bind the value within possibleString to the
//: temporary constant "string". If it does have a value, the first
//: block of code is run and if it doesn't, the second block is run.
//: In this case, it does not happen to have a value so it prints out
//: "possibleString has no value"
if let string = possibleString {
print("possibleString has a value: \(string)")
}
else {
print("possibleString has no value")
}
//: Here we optionaly bind the value to a temporary variable.
//: Importantly, if we change the value of the temporary variable,
//: it does not affect the value of the original optional
possibleInt = 10
if var actualInt = possibleInt {
actualInt *= 2
print(actualInt) // 20
}
print(possibleInt) // Optional(10)
//: Here we ensure the original optional is updated by assigning the result
//: of the multiplication to it
if var actualInt = possibleInt {
actualInt *= 2
possibleInt = actualInt
}
print(possibleInt) // Optional(20)
//: Optionally binding multiple variables the verbose way
if let actualString = possibleString {
if let actualArray = possibleArray {
if let actualInt = possibleInt {
print(actualString)
print(actualArray)
print(actualInt)
}
}
}
//: Optionally binding multiple variables the concise way
if let actualString = possibleString,
let actualArray = possibleArray,
let actualInt = possibleInt
{
print(actualString)
print(actualArray)
print(actualInt)
}
//: Using a guard statment within a function even eliminates the need
//: to indent our code furhter
func someFunc2() {
guard let actualString = possibleString,
let actualArray = possibleArray,
let actualInt = possibleInt
else {
return
}
print(actualString)
print(actualArray)
print(actualInt)
}
//: ### Forced unwrapping
//: Modifying possibleInt using forced unwrapping (the unsafe version of unwrapping)
possibleInt = 10
possibleInt! *= 2
print(possibleInt) // Optional(20)
//: Force unwrapping an optional that happens to be nil, will crash the entire program
//nilInt! *= 2 // fatal error
//: An appropriate uses of forced unwrapping is when the logic guarantees a value will not be nil,
//: even though it is defined as optional. This example is a lazily calculated value. It has a
//: private property to store the real value that is optional. When other code tries to access
//: the external value it will first make sure that the real contents is not nil. If it is, it loads
//: in the value. At that point, we know for sure it has a value so we force unwrap it to return the
//: non-optional version
class FileSystemItem {}
class File: FileSystemItem {}
class Directory: FileSystemItem {
private var realContents: [FileSystemItem]?
var contents: [FileSystemItem] {
if self.realContents == nil {
self.realContents = self.loadContents()
}
return self.realContents!
}
private func loadContents() -> [FileSystemItem] {
// Do some loading
return []
}
}
//: ### Nil coalescing
//: With nil coalescing we can provide a default value in case the optional is nil. Then it will
//: print out as a non-optional
possibleString = "An actual string"
print(possibleString ?? "Default String") // "An actual string"
//: Optional chaining
//: ------------------
//: The verbose version of optionally assigning a new value to an optional
var invitee: String? = "Sarah"
var uppercaseInvitee: String?
if let actualInvitee = invitee {
uppercaseInvitee = actualInvitee.uppercaseString
}
//: The concise way with optional chaining. It only tries to acess the uppercaseString property
//: if invitee actually contains a value. Otherwise, it immediately returns nil
uppercaseInvitee = invitee?.uppercaseString
//: A longer chain where some elemnents are optional and others are not
//: A ? is only used when the previous method / property returns an optional
var invitees: [String]? = ["Sarah", "Jamison", "Marcos", "Roana"]
invitees?.first?.uppercaseString.hasPrefix("A")
//: If you forget to use a ? when necessary, the compiler will suggest it
//invitees.first // Value of optional type '[String]?' not unwrapped; did you mean to use '1' or '?'?
//: If you use a ? when you shouldn't have, the compiler will tell you
var otherInvitees = ["Kai", "Naya"]
//otherInvitees?.first // Cannot use optional chaining on non-optional value of type '[String]'
//: Optionally calling a method that doesn't actually return anything
invitees?.removeAll()
//: Implicitly unwrapped optionals
//: -------------------------------
//: Implicitly unwrapped optional string
var name: String!
//: Accessing a nil implicitly unwrapped optional crashes the program
//name.uppercaseString // Crash
//: An example of time to use implicitly unwrapped optionals. A UIView does not connect
//: any of its outlets until after initialization but always before awakeFromNib is called.
//: Because of this, we cannot set buttonOriginalWidth during initilization but we can guarentee
//: it will be set in awakeFromNib before any other code tries to use it
import UIKit
class MyView: UIView {
@IBOutlet var button: UIButton!
var buttonOriginalWidth: CGFloat!
override func awakeFromNib() {
self.buttonOriginalWidth = self.button.frame.size.width
}
}
| 32.701031 | 101 | 0.698298 |
f4c8428e555615ca3b553c2194472043a4f6ca01 | 2,357 | open class FullscreenButton: MediaControlPlugin {
public var fullscreenIcon = UIImage.fromName("fullscreen", for: FullscreenButton.self)
public var windowedIcon = UIImage.fromName("fullscreen_exit", for: FullscreenButton.self)
public var button: UIButton! {
didSet {
button.accessibilityIdentifier = "FullscreenButton"
button.setImage(fullscreenIcon, for: .normal)
button.imageView?.contentMode = .scaleAspectFit
button.contentVerticalAlignment = .fill
button.contentHorizontalAlignment = .fill
button.addTarget(self, action: #selector(toggleFullscreenButton), for: .touchUpInside)
view.isHidden = core?.options[kFullscreenDisabled] as? Bool ?? false
view.addSubview(button)
}
}
open var isOnFullscreen = false {
didSet {
let icon = isOnFullscreen ? windowedIcon : fullscreenIcon
button.setImage(icon, for: .normal)
}
}
override open var pluginName: String {
return "FullscreenButton"
}
override open var panel: MediaControlPanel {
return .bottom
}
override open var position: MediaControlPosition {
return .right
}
required public init(context: UIObject) {
super.init(context: context)
bindEvents()
}
required public init() {
super.init()
}
private func bindEvents() {
stopListening()
bindCoreEvents()
}
private func bindCoreEvents() {
guard let core = core else { return }
listenTo(core,
eventName: Event.didEnterFullscreen.rawValue) { [weak self] (_: EventUserInfo) in self?.isOnFullscreen = true }
listenTo(core,
eventName: Event.didExitFullscreen.rawValue) { [weak self] (_: EventUserInfo) in self?.isOnFullscreen = false }
}
override open func render() {
setupButton()
}
private func setupButton() {
button = UIButton(type: .custom)
button.bindFrameToSuperviewBounds()
}
@objc open func toggleFullscreenButton() {
let event: InternalEvent = isOnFullscreen ? .userRequestExitFullscreen : .userRequestEnterInFullscreen
core?.trigger(event.rawValue)
}
}
| 31.426667 | 128 | 0.619431 |
ebeb167ae58b047a33456246d16e13990f158a12 | 869 | //
// DetailViewController.swift
// Swift_UICollectionView
//
// Created by 全球蛙 on 2016/11/22.
// Copyright © 2016年 全球蛙. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 24.138889 | 106 | 0.674338 |
d6cc1fa9cc364aabf79cbe939ab5cf105a302689 | 2,167 | //
// TipBrain.swift
// Tipsy
//
// Created by Pradyot Prakash on 16/07/21.
// Copyright © 2021 The App Brewery. All rights reserved.
//
import Foundation
struct TipBrain {
var tip = Tip(amount: 0.0, tipPercentage: 0.10, tipSplit: 2, tipAmount: 0.0)
// Update the split value
mutating func updateSplit(value: Int) {
tip = Tip(amount: tip.amount, tipPercentage: tip.tipPercentage, tipSplit: value, tipAmount: tip.tipAmount)
}
// Get split value
func getSplitValue() -> String {
return "\(tip.tipSplit)"
}
// Get tip percentage
func getTipPercentage() -> Float {
return tip.tipPercentage
}
// Update tip percentage
mutating func updateTipPercentage(value: String) {
switch value {
case "0%":
tip = Tip(amount: tip.amount, tipPercentage: 0.0, tipSplit: tip.tipSplit, tipAmount: tip.tipAmount)
case "10%":
tip = Tip(amount: tip.amount, tipPercentage: 0.10, tipSplit: tip.tipSplit, tipAmount: tip.tipAmount)
default:
tip = Tip(amount: tip.amount, tipPercentage: 0.20, tipSplit: tip.tipSplit, tipAmount: tip.tipAmount)
}
}
// Update bill amount
mutating func updateBillAmount(value: String) {
let amount = Float(value) ?? 0.0
tip = Tip(amount: amount, tipPercentage: tip.tipPercentage, tipSplit: tip.tipSplit, tipAmount: tip.tipAmount)
}
// Calculate tip
mutating func calculateTip() {
let amount = tip.amount
let tipPercentage = tip.tipPercentage
let split = tip.tipSplit
let tipAmount = (amount * (1 + tipPercentage)) / Float(split)
tip = Tip(amount: tip.amount, tipPercentage: tip.tipPercentage, tipSplit: tip.tipSplit, tipAmount: tipAmount)
}
// Get tip amount
func getTipAmount() -> String {
return "\(String(format: "%.2f", tip.tipAmount))"
}
// Get tip split
func getTipSplit() -> String {
return "\(tip.tipSplit)"
}
// Get tip value
func getTipValue() -> String {
return "\(tip.tipPercentage * 100)"
}
}
| 29.684932 | 117 | 0.606368 |
dd0c380397163b8c0540afe5e38bd6375252d88a | 164 | #if !canImport(ObjectiveC)
import XCTest
public func allTests() -> [XCTestCaseEntry] {
return [
testCase(RuntimeIssuesTests.allTests),
]
}
#endif
| 14.909091 | 46 | 0.676829 |
14885e56caddd1113c652d2c098bc5f73f3dc04e | 1,975 | //
// ButtonStyle.swift
// Monza
//
// Created by Alexandre Thadeu on 23/08/19.
// Copyright © 2019 iCarros Ltda. All rights reserved.
//
import Foundation
/// Seguindo os padrões do iCarros feito pelo design disponível no link: https://projects.invisionapp.com/dsm/i-carros/i-carros-pf-v-1-0-1
/// Design Style para os botões
///
/// - whiteBlue: estilo para botão com fundo branco, e detalhes em azul (blueOne)
/// - whiteOrange: estilo para botão com fundo branco, e detalhes em laranja (orangeOne)
/// - blue: estilo para botão com fundo azul (blueOne), e texto em branco
/// - orange: estilo para botão com fundo azul (blueOne), e texto em branco
enum ButtonStyleId: Int {
case whiteBlueButton = 0, blueButton, whiteOrangeButton, orangeButton
}
protocol ButtonStyle {
func setup(button: Button)
}
class WhiteBlueButtonStyle: ButtonStyle {
func setup(button: Button) {
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.Monza.Primary.blueOne.cgColor
button.backgroundColor = .white
button.tintColor = UIColor.Monza.Primary.blueOne
button.layer.cornerRadius = 4
}
}
class WhiteOrangeButtonStyle: ButtonStyle {
func setup(button: Button) {
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.Monza.Secondary.orangeOne.cgColor
button.backgroundColor = .white
button.tintColor = UIColor.Monza.Secondary.orangeOne
button.layer.cornerRadius = 4
}
}
class BlueButtonStyle: ButtonStyle {
func setup(button: Button) {
button.backgroundColor = UIColor.Monza.Primary.blueOne
button.tintColor = .white
button.layer.cornerRadius = 4
button.addShadow()
}
}
class OrangeButtonStyle: ButtonStyle {
func setup(button: Button) {
button.backgroundColor = UIColor.Monza.Secondary.orangeOne
button.tintColor = .white
button.layer.cornerRadius = 4
button.addShadow()
}
}
| 30.859375 | 138 | 0.696709 |
f45dcdb91d86839d298213503cf9e385526e7f33 | 6,320 | // Created by Mauricio Santos on 3/28/15.
// Copyright (c) 2015 Mauricio Santos. All rights reserved.
/// A Multiset (sometimes called a bag) is a special kind of set in which
/// members are allowed to appear more than once. It's possible to convert a multiset
/// to a set: `let set = Set(multiset)`
///
/// Conforms to `Sequence`, `ExpressibleByArrayLiteral` and `Hashable`.
public struct MultiSet<T: Hashable> {
// MARK: Creating a Multiset
/// Constructs an empty multiset.
public init() {
}
/// Constructs a multiset from a sequence, such as an array.
public init<S: Swift.Sequence>(_ elements: S) where S.Iterator.Element == T {
for e in elements {
insert(e)
}
}
public init<S: Swift.Sequence>(_ keyValuePairs: S) where S.Iterator.Element == (T, Int) {
for (key, value) in keyValuePairs {
insert(key, occurrences: value)
}
}
public init(_ dictionary: Dictionary<T, Int>) {
for (key, value) in dictionary {
insert(key, occurrences: value)
}
}
// MARK: Querying a Multiset
/// Number of elements stored in the multiset, including multiple copies.
public fileprivate(set) var count = 0
/// Returns `true` if and only if `count == 0`.
public var isEmpty: Bool {
count == 0
}
/// Number of distinct elements stored in the multiset.
public var distinctCount: Int {
members.count
}
/// A sequence containing the multiset's distinct elements.
public var distinctElements: AnySequence<T> {
AnySequence(members.keys)
}
/// Returns `true` if the multiset contains the given element.
public func contains(_ element: T) -> Bool {
members[element] != nil
}
/// Returns the number of occurrences of an element in the multiset.
public func count(_ element: T) -> Int {
members[element] ?? 0
}
// MARK: Adding and Removing Elements
/// Inserts a single occurrence of an element into the multiset.
public mutating func insert(_ element: T) {
insert(element, occurrences: 1)
}
/// Inserts a number of occurrences of an element into the multiset.
public mutating func insert(_ element: T, occurrences: Int) {
guard occurrences > 0 else {
return
}
let previousNumber = members[element] ?? 0
members[element] = previousNumber + occurrences
count += occurrences
}
/// Removes a single occurrence of an element from the multiset, if present.
public mutating func remove(_ element: T) {
return remove(element, occurrences: 1)
}
/// Removes a number of occurrences of an element from the multiset.
/// If the multiset contains fewer than this number of occurrences to begin with,
/// all occurrences will be removed.
public mutating func remove(_ element: T, occurrences: Int) {
guard let currentOccurrences = members[element], occurrences > 0 else {
// remove nothing
return
}
if occurrences >= currentOccurrences {
// remove all
count -= currentOccurrences
members.removeValue(forKey: element)
} else {
// remove some, but not all
count -= occurrences
members[element] = currentOccurrences - occurrences
}
}
/// Removes all occurrences of an element from the multiset, if present.
public mutating func removeAllOf(_ element: T) {
remove(element, occurrences: count(element))
}
/// Removes all the elements from the multiset, and by default
/// clears the underlying storage buffer.
public mutating func removeAll(keepingCapacity keep: Bool = false) {
members.removeAll(keepingCapacity: keep)
count = 0
}
// MARK: Private Properties and Helper Methods
/// Internal dictionary holding the elements.
fileprivate var members = [T: Int]()
}
// MARK: -
extension MultiSet: Swift.Sequence {
// MARK: Sequence Protocol Conformance
/// Provides for-in loop functionality. Generates multiple occurrences per element.
///
/// - returns: A generator over the elements.
public func makeIterator() -> AnyIterator<T> {
var keyValueGenerator = members.makeIterator()
var elementCount = 0
var element: T?
return AnyIterator {
if elementCount > 0 {
elementCount -= 1
return element
}
let nextTuple = keyValueGenerator.next()
element = nextTuple?.0
elementCount = nextTuple?.1 ?? 1
elementCount -= 1
return element
}
}
}
extension MultiSet: CustomStringConvertible {
// MARK: CustomStringConvertible Protocol Conformance
/// A string containing a suitable textual
/// representation of the multiset.
public var description: String {
return "[" + map {
"\($0)"
}.joined(separator: ", ") + "]"
}
}
extension MultiSet: ExpressibleByArrayLiteral {
// MARK: ExpressibleByArrayLiteral Protocol Conformance
/// Constructs a multiset using an array literal.
/// Unlike a set, multiple copies of an element are inserted.
public init(arrayLiteral elements: T...) {
self.init(elements)
}
}
extension MultiSet: ExpressibleByDictionaryLiteral {
// MARK: ExpressibleByDictionaryLiteral Protocol Conformance
public init(dictionaryLiteral elements: (T,Int)...) {
self.init()
for (element, count) in elements {
self.insert(element, occurrences: count)
}
}
}
extension MultiSet: Hashable {
// MARK: Hashable Protocol Conformance
/// `x == y` implies `x.hashValue == y.hashValue`
public func hash(into hasher: inout Hasher) {
hasher.combine(distinctCount)
hasher.combine(count)
hasher.combine(members)
}
}
// MARK: Multiset Equatable Conformance
/// Returns `true` if and only if the multisets contain the same number of occurrences per element.
public func ==<T>(lhs: MultiSet<T>, rhs: MultiSet<T>) -> Bool {
guard lhs.count == rhs.count else {
return false
}
return lhs.members == rhs.members
}
| 29.811321 | 99 | 0.628797 |
64ee991c78108a6b89be76d49c1ccd3e7e844cac | 1,585 | //
// CardView.swift
// SwiftUICards
//
// Created by Lorenzo on 1/25/21.
//
import SwiftUI
struct CardView: View {
var image: String
var category: String
var heading: String
var author: String
var body: some View {
VStack {
Image(image)
.resizable()
.aspectRatio(contentMode: .fit)
HStack {
VStack(alignment: .leading) {
Text(category)
.font(.headline)
.foregroundColor(.secondary)
Text(heading)
.font(.title)
.fontWeight(.black)
.foregroundColor(.primary)
.lineLimit(3)
Text(author.uppercased())
.font(.caption)
.foregroundColor(.secondary)
}
.layoutPriority(100)
Spacer()
}
.padding()
}
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color(.sRGB, red: 150/255, green: 150/255, blue: 150/255, opacity: 0.3), lineWidth: 1)
)
.padding([.top, .horizontal])
}
}
struct CardView_Previews: PreviewProvider {
static var previews: some View {
CardView(image: "swiftui-button",
category: "SwiftUI",
heading: "Drawing a Border with Rounded Corners",
author: "Simon Ng")
}
}
| 26.864407 | 106 | 0.457413 |
e0d0521d64b80dc5b04881b83a3d5b08d07bd432 | 587 | //
// MyBudiProject.swift
// Budi
//
// Created by 인병윤 on 2022/01/09.
//
import Foundation
struct MyBudiProject: Codable {
let participatedPosts: [MyBudiPost]
let recruitedPosts: [MyBudiPost]
}
struct MyBudiPost: Codable {
let id: Int
let imageUrl: String
let title: String
let startDate: String
let endDate: String
let onlineInfo: String
let category: String
let likeCount: Int
}
struct PersonalProject: Codable {
let projectId: Int
let name: String
let startDate: String
let endDate: String
let description: String
}
| 17.264706 | 39 | 0.681431 |
0a69532eba19dcbba009dade08caacc8951ac798 | 2,039 | //
import AppKit
class SetDateController: NSWindowController {
@IBOutlet weak var fileDateLabel: NSTextField!
@IBOutlet weak var metadataDateLabel: NSTextField!
@IBOutlet weak var newDateField: NSTextField!
@IBOutlet weak var okButton: NSButton!
fileprivate var fileDate: Date!
fileprivate var metadataDate: Date!
let dateFormatter = DateFormatter()
func newDate() -> Date? {
return dateFormatter.date(from: newDateField.stringValue)
}
static func create(file: Date, metadata: Date) -> SetDateController {
let controller = SetDateController(windowNibName: NSNib.Name(stringLiteral: "SetDate"))
controller.fileDate = file
controller.metadataDate = metadata
return controller
}
override func awakeFromNib() {
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
fileDateLabel.stringValue = dateFormatter.string(from: fileDate)
metadataDateLabel.stringValue = dateFormatter.string(from: metadataDate)
}
@IBAction func useFile(_ sender: Any) {
newDateField.stringValue = dateFormatter.string(from: fileDate)
}
@IBAction func useMetadata(_ sender: Any) {
newDateField.stringValue = dateFormatter.string(from: metadataDate)
}
@IBAction func onCancel(_ sender: Any) {
newDateField.stringValue = ""
close()
NSApplication.shared.stopModal(withCode: NSApplication.ModalResponse.cancel)
}
@IBAction func onSetDate(_ sender: Any) {
let date = dateFormatter.date(from: newDateField.stringValue)
if date == nil {
let alert = NSAlert()
alert.messageText = "Invalid date format: '\(newDateField.stringValue)'; must match '\(dateFormatter.dateFormat!)'"
alert.alertStyle = NSAlert.Style.warning
alert.addButton(withTitle: "Close")
alert.runModal()
return
}
close()
NSApplication.shared.stopModal(withCode: NSApplication.ModalResponse.OK)
}
}
| 31.859375 | 127 | 0.671408 |
8ac9677af602bf530edf98a4e5e73a877dcf09da | 817 | // RUN: %empty-directory(%t)
// RUN: %target-clang -fmodules -c -o %t/ErrorBridgedStaticImpl.o %S/Inputs/ErrorBridgedStaticImpl.m
// RUN: %target-build-swift -static-stdlib -o %t/ErrorBridgedStatic %t/ErrorBridgedStaticImpl.o %s -import-objc-header %S/Inputs/ErrorBridgedStaticImpl.h
// RUN: strip %t/ErrorBridgedStatic
// RUN: %target-run %t/ErrorBridgedStatic
// REQUIRES: executable_test
// REQUIRES: objc_interop
// REQUIRES: static_stdlib
// rdar://39473208
// REQUIRES: asserts
import StdlibUnittest
class Bar: Foo {
override func foo(_ x: Int32) throws {
try super.foo(5)
}
}
var ErrorBridgingStaticTests = TestSuite("ErrorBridging with static libs")
ErrorBridgingStaticTests.test("round-trip Swift override of ObjC method") {
do {
try (Bar() as Foo).foo(5)
} catch { }
}
runAllTests()
| 26.354839 | 153 | 0.729498 |
ac61d97f7c826a598eafe556fbcf53c166b9b803 | 1,963 | //
// Comment.swift
// GistLiX
//
// Created by Augusto Reis on 25/12/2017.
// Copyright © 2017 Augusto Reis. All rights reserved.
//
import UIKit
import Bond
import SwiftyJSON
class Comment: Model {
var url = Observable<String?>(nil)
var id = Observable<Int?>(nil)
var user = User()
var author_association = Observable<String?>(nil)
var created_at = Observable<String?>(nil)
var updated_at = Observable<String?>(nil)
var body = Observable<String?>(nil)
public class func modelsFromDictionaryArray(array:NSArray) -> [Comment]
{
var models:[Comment] = []
for item in array
{
models.append(Comment(json: item as! JSON))
}
return models
}
required init(json: JSON) {
super.init(json: json)
url.value = json["url"].string
id.value = json["id"].int
if json["user"].exists() { user = User(json: json["user"] ) }
author_association.value = json["author_association"].string
created_at.value = json["created_at"].string
updated_at.value = json["updated_at"].string
body.value = json["body"].string
}
/**
Returns the dictionary representation for the current instance.
- returns: NSDictionary.
*/
public func dictionaryRepresentation() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary.setValue(self.url, forKey: "url")
dictionary.setValue(self.id, forKey: "id")
dictionary.setValue(self.user.dictionaryRepresentation(), forKey: "user")
dictionary.setValue(self.author_association, forKey: "author_association")
dictionary.setValue(self.created_at, forKey: "created_at")
dictionary.setValue(self.updated_at, forKey: "updated_at")
dictionary.setValue(self.body, forKey: "body")
return dictionary
}
}
| 28.042857 | 82 | 0.615894 |
b998f86b970cc935ab9c246e091c22e183ea42bb | 6,335 | import Capacitor
import GoogleMobileAds
extension CAPBridgeViewController {
@objc dynamic func _admobSwizzled_viewWillLayoutSubviews() {
if self.responds(to: #selector(_admobSwizzled_viewWillLayoutSubviews)) {
_admobSwizzled_viewWillLayoutSubviews()
}
if AMBBanner.mainView.superview != nil {
NSLayoutConstraint.activate(AMBBanner.mainViewConstraints)
}
}
static func admobSwizzle() {
let selector1 = #selector(Self.viewWillLayoutSubviews)
let selector2 = #selector(Self._admobSwizzled_viewWillLayoutSubviews)
if let originalMethod = class_getInstanceMethod(Self.self, selector1),
let swizzleMethod = class_getInstanceMethod(Self.self, selector2) {
method_exchangeImplementations(originalMethod, swizzleMethod)
}
}
}
class AMBBanner: AMBAdBase, GADAdSizeDelegate, GADBannerViewDelegate {
static let stackView = UIStackView(frame: rootView.frame)
static let placeholderView = UIView(frame: stackView.frame)
static let priortyLeast = UILayoutPriority(10)
static let rootView = AMBContext.window
static let mainView = AMBContext.plugin.webView!
static var mainViewConstraints: [NSLayoutConstraint] = []
static let topConstraint = stackView.topAnchor.constraint(
equalTo: rootView.safeAreaLayoutGuide.topAnchor)
static let bottomConstraint = stackView.bottomAnchor.constraint(
equalTo: rootView.safeAreaLayoutGuide.bottomAnchor)
let adSize: GADAdSize!
let position: String!
var bannerView: GADBannerView!
init(id: Int, adUnitId: String, adSize: GADAdSize, position: String) {
self.adSize = adSize
self.position = position
super.init(id: id, adUnitId: adUnitId)
}
convenience init?(_ ctx: AMBContext) {
guard let id = ctx.optId(),
let adUnitId = ctx.optAdUnitID()
else {
return nil
}
let adSize = kGADAdSizeBanner
self.init(id: id,
adUnitId: adUnitId,
adSize: adSize,
position: ctx.optPosition())
}
func load(_ ctx: AMBContext) {
if bannerView == nil {
bannerView = GADBannerView(adSize: self.adSize)
bannerView.adSizeDelegate = self
bannerView.delegate = self
bannerView.rootViewController = AMBContext.rootViewController
}
bannerView.adUnitID = adUnitId
bannerView.load(ctx.optGADRequest())
}
func show(_ ctx: AMBContext) {
load(ctx)
Self.prepareStackView()
switch position {
case "top":
Self.stackView.insertArrangedSubview(bannerView, at: 0)
default:
Self.stackView.addArrangedSubview(bannerView)
}
bannerView.isHidden = false
Self.updateLayout()
ctx.success()
}
func hide(_ ctx: AMBContext) {
if bannerView != nil {
bannerView.isHidden = true
Self.stackView.removeArrangedSubview(bannerView)
Self.updateLayout()
}
ctx.success()
}
func adView(_ bannerView: GADBannerView, willChangeAdSizeTo adSize: GADAdSize) {
self.emit(AMBEvents.bannerSizeChange, adSize)
}
func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
self.emit(AMBEvents.bannerLoad)
}
func bannerView(_ bannerView: GADBannerView,
didFailToReceiveAdWithError error: Error) {
self.emit(AMBEvents.bannerLoadFail, error)
}
func bannerViewDidRecordImpression(_ bannerView: GADBannerView) {
self.emit(AMBEvents.bannerImpression)
}
func bannerViewWillPresentScreen(_ bannerView: GADBannerView) {
self.emit(AMBEvents.bannerOpen)
}
func bannerViewWillDismissScreen(_ bannerView: GADBannerView) {
}
func bannerViewDidDismissScreen(_ bannerView: GADBannerView) {
self.emit(AMBEvents.bannerClose)
}
private static func prepareStackView() {
if stackView.arrangedSubviews.isEmpty {
CAPBridgeViewController.admobSwizzle()
var constraints: [NSLayoutConstraint] = []
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .fill
rootView.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
constraints += [
stackView.leadingAnchor.constraint(equalTo: rootView.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: rootView.trailingAnchor)
]
placeholderView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
stackView.addArrangedSubview(placeholderView)
mainView.translatesAutoresizingMaskIntoConstraints = false
mainViewConstraints += [
mainView.leadingAnchor.constraint(equalTo: placeholderView.leadingAnchor),
mainView.trailingAnchor.constraint(equalTo: placeholderView.trailingAnchor),
mainView.topAnchor.constraint(equalTo: placeholderView.topAnchor),
mainView.bottomAnchor.constraint(equalTo: placeholderView.bottomAnchor)
]
constraints += mainViewConstraints
let constraintTop = stackView.topAnchor.constraint(equalTo: rootView.topAnchor)
let constraintBottom = stackView.bottomAnchor.constraint(equalTo: rootView.bottomAnchor)
constraintTop.priority = priortyLeast
constraintBottom.priority = priortyLeast
constraints += [
constraintBottom,
constraintTop
]
NSLayoutConstraint.activate(constraints)
rootView.sendSubviewToBack(stackView)
}
}
private static func updateLayout() {
if stackView.arrangedSubviews.first is GADBannerView {
AMBContext.plugin.bridge?.statusBarStyle = .lightContent
topConstraint.isActive = true
} else {
topConstraint.isActive = false
}
if stackView.arrangedSubviews.last is GADBannerView {
bottomConstraint.isActive = true
} else {
bottomConstraint.isActive = false
}
}
}
| 33.877005 | 100 | 0.652723 |
d72456d502fa81d4f7d4e3c433d9b65458176075 | 95 | // Copyright © Fleuronic LLC. All rights reserved.
infix operator ?!: NilCoalescingPrecedence
| 23.75 | 50 | 0.778947 |
2379a893d0fed73418176b44158cf727ae8792ce | 537 | import Foundation
enum PageType: CaseIterable, Identifiable, Hashable {
case loading
case error
case empty
case single
case paged
case stream
var id: Self { self }
}
extension PageType: CustomStringConvertible {
var description: String {
switch self {
case .loading: return "Loading"
case .error: return "Error"
case .empty: return "Empty"
case .single: return "Single"
case .paged: return "Paged"
case .stream: return "Stream"
}
}
}
| 20.653846 | 53 | 0.612663 |
9b1df74247da52d0cf1682fffd974ba92a99eb37 | 1,306 | //
// ViewControllerLifeCicleUITests.swift
// ViewControllerLifeCicleUITests
//
// Created by Yevhen Herasymenko on 01/07/2016.
// Copyright © 2016 Yevhen Herasymenko. All rights reserved.
//
import XCTest
class ViewControllerLifeCicleUITests: 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.
}
}
| 35.297297 | 182 | 0.678407 |
e6afb7dd21c3e5d79f6664e2f0e7310c55772e0c | 1,364 | //
// SearchHeaderCollectionReusableView.swift
// OMDb
//
// Created by Daniel Torres on 5/6/20.
// Copyright © 2020 dansTeam. All rights reserved.
//
import UIKit
protocol SearchHeaderCollectionReusableViewProtocol: UICollectionReusableView {
var titleLabel: UILabel! {get set}
var button: UIButton! {get set}
}
protocol SearchHeaderCollectionReusableViewProtocolDelegate {
func buttonAllSelected(sender: AnyObject)
}
class SearchHeaderCollectionReusableView: UICollectionReusableView, SearchHeaderCollectionReusableViewProtocol {
@IBOutlet var titleLabel: UILabel!
@IBOutlet var button: UIButton!
@IBOutlet var contentViewCell: UIView!
var delegate: SearchHeaderCollectionReusableViewProtocolDelegate?
@IBAction
func buttonAllSelectedPressed(){
delegate?.buttonAllSelected(sender: self)
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("SearchHeaderCollectionReusableView", owner: self, options: nil)
addSubview(contentViewCell)
contentViewCell.frame = self.bounds
contentViewCell.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
| 27.28 | 112 | 0.71261 |
161ac157d8e6ea9f0b4401762b33fee206df2882 | 3,381 | //
// MetricsDictionary.swift
// AmazonChimeSDKDemo
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
import AmazonChimeSDK
import UIKit
let userDefaultsKeyBroadcastMetrics = "demoMeetingBroadcastMetrics"
class MetricsModel: NSObject {
let appGroupUserDefaults = UserDefaults(suiteName: AppConfiguration.appGroupId)
var userDefaultsObserver: NSKeyValueObservation?
private var appMetrics = [String: Double]()
private var broadcastMetrics = [String: Double]()
private var combinedMetrics: [String: Double] {
return appMetrics.merging(broadcastMetrics) { (metric, _) in metric }
}
var metricsUpdatedHandler: (() -> Void)?
override init() {
super.init()
// Since Broadcast Extension runs independently from Demo app, Metrics from Broadcasting does not
// automatically flow into the app. So we are saving these metrics from Broadcast Extension into
// shared App Groups User Defaults, observe and retrieve them in MetricsModel to display in demo app.
userDefaultsObserver = appGroupUserDefaults?.observe(\.demoMeetingBroadcastMetrics,
options: [.new, .old]) { [weak self] (_, _) in
if let strongSelf = self,
let userDefaults = strongSelf.appGroupUserDefaults,
let broadcastMetrics = userDefaults.demoMeetingBroadcastMetrics {
strongSelf.broadcastMetrics = broadcastMetrics
} else {
self?.broadcastMetrics = [:]
}
self?.metricsUpdatedHandler?()
}
}
deinit {
userDefaultsObserver?.invalidate()
}
func updateAppMetrics(metrics: [AnyHashable: Any]) {
self.appMetrics = [:]
for key in metrics.keys {
if let key = key as? ObservableMetric {
self.appMetrics[key.description] = metrics[key] as? Double ?? 0
}
}
}
private func getMetricsName(index: Int) -> String {
return Array(combinedMetrics.keys).sorted(by: <)[index]
}
private func getMetricsValue(index: Int) -> String {
let key = getMetricsName(index: index)
return String(combinedMetrics[key] ?? 0)
}
}
// MARK: UITableViewDelegate, UITableViewDataSource
extension MetricsModel: UITableViewDelegate, UITableViewDataSource {
func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return combinedMetrics.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.item >= combinedMetrics.count {
return UITableViewCell()
}
let metricsName = getMetricsName(index: indexPath.item)
let metricsValue = getMetricsValue(index: indexPath.item)
guard let cell = tableView.dequeueReusableCell(withIdentifier: metricsTableCellReuseIdentifier) as? MetricsTableCell else {
return MetricsTableCell(name: metricsName, value: metricsValue)
}
cell.updateCell(name: metricsName, value: metricsValue)
return cell
}
}
extension UserDefaults {
@objc dynamic var demoMeetingBroadcastMetrics: [String: Double]? {
return object(forKey: userDefaultsKeyBroadcastMetrics) as? [String: Double]
}
}
| 35.21875 | 131 | 0.665779 |
fec2c50468f779536fe569234ece0046379e570b | 2,321 | //
// MainTableViewController.swift
// Quartz2DDraw
//
// Created by Oniityann on 2018/9/8.
// Copyright © 2018年 Oniityann. All rights reserved.
//
import UIKit
class MainTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 30.946667 | 136 | 0.664369 |
eb926d315f16f45dc960e634ee433b5cd6ff99b8 | 9,547 | //
// ClientTests.swift
// Example
//
// Created by Luciano Polit on 11/14/17.
// Copyright © 2017 Luciano Polit. All rights reserved.
//
import Foundation
import Alamofire
import XCTest
import OHHTTPStubs
@testable import Leash
#if !COCOAPODS
import OHHTTPStubsSwift
#endif
class ClientTests: BaseTestCase { }
// MARK: - URLRequest
extension ClientTests {
// MARK: - Method
func testMethod() {
let endpoint = Endpoint()
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
XCTAssertEqual(urlRequest.httpMethod, endpoint.method.rawValue)
}
}
// MARK: - URL
func testURLWithoutPortAndPath() {
let endpoint = Endpoint(path: "some/another/123")
manager = Manager.Builder()
.scheme(ClientTests.scheme)
.host(ClientTests.host)
.build()
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
XCTAssertEqual(urlRequest.url?.absoluteString, "\(ClientTests.scheme)://\(ClientTests.host)/\(endpoint.path)")
}
}
func testFullURL() {
let endpoint = Endpoint(path: "some/another/123")
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
XCTAssertEqual(urlRequest.url?.absoluteString, "\(baseURL)\(endpoint.path)")
}
}
// MARK: - Authenticator
func testAuthenticatorWithoutAuthorization() {
let endpoint = Endpoint()
let authenticator = Authenticator()
manager = builder
.authenticator(authenticator)
.build()
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
XCTAssertNil(urlRequest.value(forHTTPHeaderField: Authenticator.header))
}
}
func testAuthenticatorWithAuthorization() {
let endpoint = Endpoint()
let authenticator = Authenticator()
authenticator.authentication = "123"
manager = builder
.authenticator(authenticator)
.build()
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
let header = urlRequest.value(forHTTPHeaderField: Authenticator.header)
XCTAssertNotNil(header)
XCTAssertEqual(header, authenticator.authentication)
}
}
// MARK: - Body
func testEmptyBody() {
let endpoint = Endpoint()
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
XCTAssertNil(urlRequest.httpBody)
}
}
func testBodyWithEncodable() {
let entity = PrimitiveEntity(first: "some", second: 10, third: true)
let endpoint = Endpoint(method: .post, parameters: entity)
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
guard let body = urlRequest.httpBody else { return XCTFail() }
let decoded = try manager.jsonDecoder.decode(PrimitiveEntity.self, from: body)
XCTAssertEqual(decoded, entity)
}
}
func testBodyWithCustomDateFormatterWithEncodable() {
let entity = DatedEntity(date: Date(timeIntervalSince1970: 100))
let endpoint = Endpoint(method: .post, parameters: entity)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S'Z'"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
manager = builder
.jsonDateFormatter(formatter)
.build()
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
guard let body = urlRequest.httpBody else { return XCTFail() }
let decoded = try manager.jsonDecoder.decode(DatedEntity.self, from: body)
let dictionary = try JSONSerialization.jsonObject(with: body) as? [String: Any]
XCTAssertEqual(decoded, entity)
XCTAssertEqual(dictionary?["date"] as? String, "1970-01-01T00:01:40.0Z")
}
}
func testBodyWithDifferentEncoderWithEncodable() {
let entity = DatedEntity(date: Date(timeIntervalSince1970: 100))
let endpoint = Endpoint(method: .post, parameters: entity)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S'Z'"
manager = builder
.jsonEncoder { $0.dateEncodingStrategy = .iso8601 }
.build()
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
guard let body = urlRequest.httpBody else { return XCTFail() }
let dictionary = try JSONSerialization.jsonObject(with: body) as? [String: Any]
XCTAssertEqual(dictionary?["date"] as? String, "1970-01-01T00:01:40Z")
}
}
func testBodyWithDictionary() {
let entity: [String: Any] = PrimitiveEntity(first: "some", second: 10, third: true).toJSON()
let endpoint = Endpoint(method: .post, parameters: entity)
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
guard let body = urlRequest.httpBody else { return XCTFail() }
let decoded = try manager.jsonDecoder.decode(PrimitiveEntity.self, from: body)
XCTAssertTrue(NSDictionary(dictionary: decoded.toJSON()).isEqual(to: entity))
}
}
// MARK: - Content Type
func testContentTypeWithEncodable() {
let entity = PrimitiveEntity(first: "some", second: 10, third: true)
let endpoint = Endpoint(method: .post, parameters: entity)
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/json")
}
}
func testContentTypeWithDictionary() {
let entity = PrimitiveEntity(first: "some", second: 10, third: true).toJSON()
let endpoint = Endpoint(method: .post, parameters: entity)
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/json")
}
}
// MARK: - Query
func testQueryWithQueryEncodable() {
let entity = QueryEntity(first: "some", second: 10, third: true)
let endpoint = Endpoint(method: .get, parameters: entity)
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
XCTAssertEqual(urlRequest.url?.absoluteString, "\(baseURL)?first=some&second=10&third=1")
}
}
func testQueryWithDictionary() {
let entity = QueryEntity(first: "some", second: 10, third: true).toQuery()
let endpoint = Endpoint(method: .get, parameters: entity)
assertNoErrorThrown {
let urlRequest = try client.urlRequest(for: endpoint)
XCTAssertEqual(urlRequest.url?.absoluteString, "\(baseURL)?first=some&second=10&third=1")
}
}
}
// MARK: - DataRequest
extension ClientTests {
func testRequestCallsSessionManager() {
let endpoint = Endpoint()
let session = MockSession()
manager = builder
.session(session)
.build()
assertNoErrorThrown {
let _ = try client.request(for: endpoint)
XCTAssertTrue(session.requestCalled)
}
}
func testExecuteCallsResponse() {
let expectation = self.expectation(description: "Expected to find a success response")
let endpoint = Endpoint(path: "response/123")
let json = ["some": "123"]
stub(condition: isEndpoint(endpoint)) { _ in
return HTTPStubsResponse(jsonObject: json, statusCode: 200, headers: nil)
}
client.execute(endpoint) { (response: Result<[String: String], Swift.Error>) in
guard case .success(let result) = response else {
XCTFail()
return
}
XCTAssertEqual(result, json)
expectation.fulfill()
}
waitForExpectations(timeout: 5)
}
}
// MARK: - Errors
extension ClientTests {
func testEncodingError() {
let expectation = self.expectation(description: "Expected to find a failure response")
let endpoint = Endpoint(method: .post, parameters: Data())
FailureClient(manager: manager).execute(endpoint) { (response: Response<Data>) in
guard case .failure(let error) = response, case Leash.Error.encoding = error else {
XCTFail()
return
}
expectation.fulfill()
}
waitForExpectations(timeout: 5)
}
}
// MARK: - Utils
class MockSession: Session {
var requestCalled = false
var requestParameterURLRequest: URLRequestConvertible?
convenience init() {
self.init(startRequestsImmediately: false)
}
override func request(_ urlRequest: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest {
requestCalled = true
requestParameterURLRequest = urlRequest
return super.request(urlRequest)
}
}
class FailureClient: Client {
override func urlRequest(for endpoint: Leash.Endpoint) throws -> URLRequest {
throw Leash.Error.unknown
}
}
| 34.59058 | 122 | 0.621661 |
9b73ff68d40fa5cae84967cc46dc39669e404956 | 521 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
enum S<h> {
func c) -> {
private class b> == "A> A {
}
class A {
struct X<h : Sequence where h: d where T -> {
let f = c()
| 32.5625 | 79 | 0.704415 |
64b8aca1ae2ae62cee6b712cbff9294967698001 | 10,683 | //
// UIViewController+Ext.swift
// TSwiftHelper
//
// Created by User on 3/22/20.
// Copyright © 2020 ThinhNguyen. All rights reserved.
// Email: [email protected]
//
import Foundation
import UIKit
public extension UIViewController {
// MARK: - Notifications
// MARK: Adds an NotificationCenter with name and Selector
func addNotificationObserver(_ name: String, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: NSNotification.Name(rawValue: name), object: nil)
}
// MARK: Removes an NSNotificationCenter for name
func removeNotificationObserver(_ name: String) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: name), object: nil)
}
// MARK: Removes NotificationCenter'd observer
func removeNotificationObserver() {
NotificationCenter.default.removeObserver(self)
}
#if os(iOS)
// MARK: Adds a NotificationCenter Observer for keyboardWillShowNotification()
///
/// ⚠️ You also need to implement ```keyboardWillShowNotification(_ notification: Notification)```
func addKeyboardWillShowNotification() {
self.addNotificationObserver(UIResponder.keyboardWillShowNotification.rawValue, selector: #selector(UIViewController.keyboardWillShowNotification(_:)))
}
// MARK: Adds a NotificationCenter Observer for keyboardDidShowNotification()
///
/// ⚠️ You also need to implement ```keyboardDidShowNotification(_ notification: Notification)```
func addKeyboardDidShowNotification() {
self.addNotificationObserver(UIResponder.keyboardDidShowNotification.rawValue, selector: #selector(UIViewController.keyboardDidShowNotification(_:)))
}
// MARK: Adds a NotificationCenter Observer for keyboardWillHideNotification()
///
/// ⚠️ You also need to implement ```keyboardWillHideNotification(_ notification: Notification)```
func addKeyboardWillHideNotification() {
self.addNotificationObserver(UIResponder.keyboardWillHideNotification.rawValue, selector: #selector(UIViewController.keyboardWillHideNotification(_:)))
}
// MARK: Adds a NotificationCenter Observer for keyboardDidHideNotification()
///
/// ⚠️ You also need to implement ```keyboardDidHideNotification(_ notification: Notification)```
func addKeyboardDidHideNotification() {
self.addNotificationObserver(UIResponder.keyboardDidHideNotification.rawValue, selector: #selector(UIViewController.keyboardDidHideNotification(_:)))
}
// MARK: Removes keyboardWillShowNotification()'s NotificationCenter Observer
func removeKeyboardWillShowNotification() {
self.removeNotificationObserver(UIResponder.keyboardWillShowNotification.rawValue)
}
// MARK: Removes keyboardDidShowNotification()'s NotificationCenter Observer
func removeKeyboardDidShowNotification() {
self.removeNotificationObserver(UIResponder.keyboardDidShowNotification.rawValue)
}
// MARK: Removes keyboardWillHideNotification()'s NotificationCenter Observer
func removeKeyboardWillHideNotification() {
self.removeNotificationObserver(UIResponder.keyboardWillHideNotification.rawValue)
}
// MARK: Removes keyboardDidHideNotification()'s NotificationCenter Observer
func removeKeyboardDidHideNotification() {
self.removeNotificationObserver(UIResponder.keyboardDidHideNotification.rawValue)
}
@objc func keyboardDidShowNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.cgRectValue
keyboardDidShowWithFrame(frame)
}
}
@objc func keyboardWillShowNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.cgRectValue
keyboardWillShowWithFrame(frame)
}
}
@objc func keyboardWillHideNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.cgRectValue
keyboardWillHideWithFrame(frame)
}
}
@objc func keyboardDidHideNotification(_ notification: Notification) {
if let nInfo = (notification as NSNotification).userInfo, let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let frame = value.cgRectValue
keyboardDidHideWithFrame(frame)
}
}
func keyboardWillShowWithFrame(_ frame: CGRect) {
}
func keyboardDidShowWithFrame(_ frame: CGRect) {
}
func keyboardWillHideWithFrame(_ frame: CGRect) {
}
func keyboardDidHideWithFrame(_ frame: CGRect) {
}
//MARK: : Makes the UIViewController register tap events and hides keyboard when clicked somewhere in the ViewController.
func hideKeyboardWhenTappedAround(cancelTouches: Bool = false) {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = cancelTouches
view.addGestureRecognizer(tap)
}
#endif
//MARK: : Dismisses keyboard
@objc func dismissKeyboard() {
view.endEditing(true)
}
// MARK: - VC Container
// MARK: Returns maximum y of the ViewController
var top: CGFloat {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.top
}
if let nav = self.navigationController {
if nav.isNavigationBarHidden {
return view.top
} else {
return nav.navigationBar.bottom
}
} else {
return view.top
}
}
// MARK: Returns minimum y of the ViewController
var bottom: CGFloat {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.bottom
}
if let tab = tabBarController {
if tab.tabBar.isHidden {
return view.bottom
} else {
return tab.tabBar.top
}
} else {
return view.bottom
}
}
// MARK: Returns Tab Bar's height
var tabBarHeight: CGFloat {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.tabBarHeight
}
if let tab = self.tabBarController {
return tab.tabBar.frame.size.height
}
return 0
}
// MARK: Returns Navigation Bar's height
var navigationBarHeight: CGFloat {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.navigationBarHeight
}
if let nav = self.navigationController {
return nav.navigationBar.h
}
return 0
}
// MARK: Returns Navigation Bar's color
var navigationBarColor: UIColor? {
get {
if let me = self as? UINavigationController, let visibleViewController = me.visibleViewController {
return visibleViewController.navigationBarColor
}
return navigationController?.navigationBar.tintColor
} set(value) {
navigationController?.navigationBar.barTintColor = value
}
}
// MARK: Returns current Navigation Bar
var navBar: UINavigationBar? {
return navigationController?.navigationBar
}
///
var applicationFrame: CGRect {
return CGRect(x: view.x, y: top, width: view.w, height: bottom - top)
}
// MARK: - VC Flow
// MARK: Pushes a view controller onto the receiver’s stack and updates the display.
func pushVC(_ vc: UIViewController) {
navigationController?.pushViewController(vc, animated: true)
}
// MARK: Pops the top view controller from the navigation stack and updates the display.
func popVC() {
_ = navigationController?.popViewController(animated: true)
}
// MARK: Hide or show navigation bar
var isNavBarHidden: Bool {
get {
return (navigationController?.isNavigationBarHidden)!
}
set {
navigationController?.isNavigationBarHidden = newValue
}
}
// MARK: Added extension for popToRootViewController
func popToRootVC() {
_ = navigationController?.popToRootViewController(animated: true)
}
// MARK: Presents a view controller modally.
func presentVC(_ vc: UIViewController) {
present(vc, animated: true, completion: nil)
}
// MARK: Dismisses the view controller that was presented modally by the view controller.
func dismissVC(completion: (() -> Void)? ) {
dismiss(animated: true, completion: completion)
}
// MARK: Adds the specified view controller as a child of the current view controller.
func addAsChildViewController(_ vc: UIViewController, toView: UIView) {
self.addChild(vc)
toView.addSubview(vc.view)
vc.didMove(toParent: self)
}
// MARK: Adds image named: as a UIImageView in the Background
func setBackgroundImage(_ named: String) {
let image = UIImage(named: named)
let imageView = UIImageView(frame: view.frame)
imageView.image = image
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
}
// MARK: Adds UIImage as a UIImageView in the Background
@nonobjc func setBackgroundImage(_ image: UIImage) {
let imageView = UIImageView(frame: view.frame)
imageView.image = image
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
}
#if os(iOS)
@available(*, deprecated)
func hideKeyboardWhenTappedAroundAndCancelsTouchesInView() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
#endif
}
| 36.71134 | 159 | 0.672096 |
9b5e0e32230da0e3a04c8aa9fb450e10eb5375c0 | 488 | //
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import Foundation
extension Cameras.Manufacturers.Olympus {
public struct TG4: CameraModel {
public init() {}
public let name = "Olympus TG-4"
public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Olympus.self
}
}
public typealias OlympusTG4 = Cameras.Manufacturers.Olympus.TG4
| 27.111111 | 97 | 0.72541 |
ffb396a1642889873c4836f7c5526520ac9bf351 | 1,187 | //
// LatestMessagesController.swift
// App
//
// Created by Tommi Kivimäki on 08/12/2018.
//
import Vapor
import Fluent
import Authentication
struct MessagesController: RouteCollection {
func boot(router: Router) throws {
let messagesRoutes = router.grouped("api", "v1", "messages")
let tokenAuthMiddleware = User.tokenAuthMiddleware()
let guardAuthMiddleware = User.guardAuthMiddleware()
let tokenAuthGroup = messagesRoutes.grouped(tokenAuthMiddleware, guardAuthMiddleware)
tokenAuthGroup.get(use: getAllHandler)
tokenAuthGroup.post(MessageCreateData.self, use: createHandler)
}
func getAllHandler(_ req: Request) throws -> Future<[Message]> {
return Message.query(on: req).all()
}
func createHandler(_ req: Request, data: MessageCreateData) throws -> Future<Message> {
let _ = try req.requireAuthenticated(User.self)
// #warning("user.requireID() should be saved to Message.userID, but linking User-Message is still missing")
let message = Message(message: data.message)
return message.save(on: req)
}
}
// Model for creating a Message
struct MessageCreateData: Content {
var message: String
}
| 26.377778 | 111 | 0.722831 |
91c7b8f9ba9ba393a1ddb848320e0a8628a33ea9 | 626 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SWRevealViewController",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "SWRevealViewController",
targets: ["SWRevealViewController"]),
],
targets: [
.binaryTarget(
name: "SWRevealViewController",
path: "Sources/SWRevealViewController.xcframework")
]
)
| 31.3 | 117 | 0.658147 |
8789a1dcad80543b7db0618319f84fb284ffc25f | 2,131 | /// Copyright (c) 2019 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Foundation
final class User: Codable {
var id: UUID?
var name: String
var username: String
init(name: String, username: String) {
self.name = name
self.username = username
}
}
final class CreateUser: Codable {
var id: UUID?
var name: String
var username: String
var password: String?
init(name: String, username: String, password: String) {
self.name = name
self.username = username
self.password = password
}
}
| 39.462963 | 83 | 0.738151 |
33bcd4f1ac70e75f9d004b384ea81c133c76d69e | 950 | // Generated using Sourcery 0.13.1 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
import Foundation
extension ServiceResponse.Authorisation {
init(xml: XMLElement, decoder: XMLDecoderProtocol) throws {
guard let acquirerID: String =
decoder.decodeValue(xml.attributes["OverallResult"])
else { throw XMLParsableError.missingOrInvalidTypeFor("acquirerID", String.self) }
guard let timeStamp: Date =
decoder.decodeValue(xml.attributes["TimeStamp"])
else { throw XMLParsableError.missingOrInvalidTypeFor("timeStamp", Date.self) }
let approvalCode: String? =
decoder.decodeValue(xml.attributes["ApprovalCode"])
let acquirerBatch: String? =
decoder.decodeValue(xml.attributes["AcquirerBatch"])
self.init(acquirerID: acquirerID, timeStamp: timeStamp, approvalCode: approvalCode, acquirerBatch: acquirerBatch)
}
}
| 41.304348 | 121 | 0.697895 |
f5f65ec6d0ee4cd1b132c8f75b0fd9ac001ae744 | 7,282 | import XCTest
#if !os(Linux)
import CoreLocation
#if SWIFT_PACKAGE
import OHHTTPStubsSwift
#endif
import OHHTTPStubs
@testable import MapboxDirections
class AnnotationTests: XCTestCase {
override func tearDown() {
HTTPStubs.removeAllStubs()
super.tearDown()
}
func testAnnotation() {
let expectation = self.expectation(description: "calculating directions should return results")
let queryParams: [String: String?] = [
"alternatives": "false",
"geometries": "polyline",
"overview": "full",
"steps": "false",
"continue_straight": "true",
"access_token": BogusToken,
"annotations": "distance,duration,speed,congestion,maxspeed,congestion_numeric"
]
stub(condition: isHost("api.mapbox.com")
&& containsQueryParams(queryParams)) { _ in
let path = Bundle.module.path(forResource: "annotation", ofType: "json")
return HTTPStubsResponse(fileAtPath: path!, statusCode: 200, headers: ["Content-Type": "application/json"])
}
let options = RouteOptions(coordinates: [
CLLocationCoordinate2D(latitude: 37.780602, longitude: -122.431373),
CLLocationCoordinate2D(latitude: 37.758859, longitude: -122.404058),
], profileIdentifier: .automobileAvoidingTraffic)
options.shapeFormat = .polyline
options.includesSteps = false
options.includesAlternativeRoutes = false
options.routeShapeResolution = .full
options.attributeOptions = [.distance, .expectedTravelTime, .speed, .congestionLevel, .numericCongestionLevel, .maximumSpeedLimit]
var route: Route?
let task = Directions(credentials: BogusCredentials).calculate(options) { (session, disposition) in
switch disposition {
case let .failure(error):
XCTFail("Error! \(error)")
case let .success(response):
XCTAssertNotNil(response.routes)
XCTAssertEqual(response.routes!.count, 1)
route = response.routes!.first!
expectation.fulfill()
}
}
XCTAssertNotNil(task)
waitForExpectations(timeout: 2) { (error) in
XCTAssertNil(error, "Error: \(error!.localizedDescription)")
XCTAssertEqual(task.state, .completed)
}
XCTAssertNotNil(route)
if let route = route {
XCTAssertNotNil(route.shape)
XCTAssertEqual(route.shape?.coordinates.count, 154)
XCTAssertEqual(route.legs.count, 1)
}
if let leg = route?.legs.first {
XCTAssertEqual(leg.segmentDistances?.count, 153)
XCTAssertEqual(leg.segmentSpeeds?.count, 153)
XCTAssertEqual(leg.expectedSegmentTravelTimes?.count, 153)
XCTAssertEqual(leg.segmentCongestionLevels?.count, 153)
XCTAssertEqual(leg.segmentCongestionLevels?.firstIndex(of: .unknown), 2)
XCTAssertEqual(leg.segmentCongestionLevels?.firstIndex(of: .low), 0)
XCTAssertEqual(leg.segmentCongestionLevels?.firstIndex(of: .moderate), 14)
XCTAssertFalse(leg.segmentCongestionLevels?.contains(.heavy) ?? true)
XCTAssertFalse(leg.segmentCongestionLevels?.contains(.severe) ?? true)
XCTAssertEqual(leg.segmentNumericCongestionLevels?.count, 153)
XCTAssertEqual(leg.segmentNumericCongestionLevels?.firstIndex(of: nil), 2)
XCTAssertEqual(leg.segmentNumericCongestionLevels?.firstIndex(of: 12), 91)
XCTAssertEqual(leg.segmentNumericCongestionLevels?.firstIndex(of: 32), 60)
XCTAssertFalse(leg.segmentNumericCongestionLevels?.contains(26) ?? true)
XCTAssertEqual(leg.segmentMaximumSpeedLimits?.count, 153)
XCTAssertEqual(leg.segmentMaximumSpeedLimits?.first, Measurement(value: 48, unit: .kilometersPerHour))
XCTAssertEqual(leg.segmentMaximumSpeedLimits?.firstIndex(of: nil), 2)
XCTAssertFalse(leg.segmentMaximumSpeedLimits?.contains(Measurement(value: .infinity, unit: .kilometersPerHour)) ?? true)
}
}
func testSpeedLimits() {
func assert(_ speedLimitDescriptorJSON: [String: Any], roundTripsWith expectedSpeedLimitDescriptor: SpeedLimitDescriptor) {
let speedLimitDescriptorData = try! JSONSerialization.data(withJSONObject: speedLimitDescriptorJSON, options: [])
var speedLimitDescriptor: SpeedLimitDescriptor?
XCTAssertNoThrow(speedLimitDescriptor = try JSONDecoder().decode(SpeedLimitDescriptor.self, from: speedLimitDescriptorData))
XCTAssertEqual(speedLimitDescriptor, expectedSpeedLimitDescriptor)
speedLimitDescriptor = expectedSpeedLimitDescriptor
let encoder = JSONEncoder()
var encodedData: Data?
XCTAssertNoThrow(encodedData = try encoder.encode(speedLimitDescriptor))
XCTAssertNotNil(encodedData)
if let encodedData = encodedData {
var encodedSpeedLimitDescriptorJSON: [String: Any?]?
XCTAssertNoThrow(encodedSpeedLimitDescriptorJSON = try JSONSerialization.jsonObject(with: encodedData, options: []) as? [String: Any?])
XCTAssertNotNil(encodedSpeedLimitDescriptorJSON)
XCTAssert(JSONSerialization.objectsAreEqual(speedLimitDescriptorJSON, encodedSpeedLimitDescriptorJSON, approximate: true))
}
}
XCTAssertEqual(SpeedLimitDescriptor(speed: Measurement(value: 55, unit: .milesPerHour)),
.some(speed: Measurement(value: 55, unit: .milesPerHour)))
XCTAssertEqual(Measurement<UnitSpeed>(speedLimitDescriptor: .some(speed: Measurement(value: 55, unit: .milesPerHour))),
Measurement(value: 55, unit: .milesPerHour))
assert(["speed": 55.0, "unit": "mph"], roundTripsWith: .some(speed: Measurement(value: 55, unit: .milesPerHour)))
XCTAssertEqual(SpeedLimitDescriptor(speed: Measurement(value: 80, unit: .kilometersPerHour)),
.some(speed: Measurement(value: 80, unit: .kilometersPerHour)))
XCTAssertEqual(Measurement<UnitSpeed>(speedLimitDescriptor: .some(speed: Measurement(value: 80, unit: .kilometersPerHour))),
Measurement(value: 80, unit: .kilometersPerHour))
assert(["speed": 80.0, "unit": "km/h"], roundTripsWith: .some(speed: Measurement(value: 80, unit: .kilometersPerHour)))
XCTAssertEqual(SpeedLimitDescriptor(speed: nil), .unknown)
XCTAssertNil(Measurement<UnitSpeed>(speedLimitDescriptor: .unknown))
assert(["unknown": true], roundTripsWith: .unknown)
XCTAssertEqual(SpeedLimitDescriptor(speed: Measurement(value: .infinity, unit: .kilometersPerHour)), .none)
XCTAssertEqual(Measurement<UnitSpeed>(speedLimitDescriptor: .none),
Measurement(value: .infinity, unit: .kilometersPerHour))
assert(["none": true], roundTripsWith: .none)
}
}
#endif
| 50.923077 | 151 | 0.651607 |
87f11aa4790ac66814f57e8b7bc2b69c2b319c34 | 1,579 | //
// DetailPageViewModel.swift
// Detail
//
// Created by Ayşenur Bakırcı on 2.12.2021.
//
import RestaurantAPI
import RxSwift
//MARK: - TableView Data Sections
enum DetailPageSection {
case restaurantDetail(RestaurantModel)
case mealList([RestaurantMenuModel])
case drinkList([RestaurantMenuModel])
var numberOfSections: Int {
switch self {
case .restaurantDetail(_):
return 1
case .mealList(let mealList):
return mealList.count
case .drinkList(let drinkList):
return drinkList.count
}
}
var sectionTitle: String {
switch self {
case .restaurantDetail(_):
return ""
case .mealList(_):
return "Meal List"
case .drinkList(_):
return "Drink List"
}
}
}
protocol DetailPageViewModelProtocol {
func getData() -> Observable<[DetailPageSection]>
}
final class DetailPageViewModel: DetailPageViewModelProtocol {
//MARK: - Properties
private var restaurantId: Int
//MARK: - Initalization
init(restaurantId: Int) {
self.restaurantId = restaurantId
}
func getData() -> Observable<[DetailPageSection]> {
Observable.just(restaurantId)
.flatMap(DetailAPI.restaurantDetail)
.compactMap { $0 }
.map { model in
return [.restaurantDetail(model),
.mealList(model.restaurantMeals),
.drinkList(model.restaurantDrinks)]
}
}
}
| 23.924242 | 62 | 0.59088 |
6a7957d8897b93614e084cf72a2e605258994aa4 | 12,096 | import DateTimeOnly
import XCTJSONKit
final class DateOnlyTests: XCTestCase {}
extension DateOnlyTests {
func testInit() throws {
try XCTAssertEqual(
DateOnly(year: 10300, month: 07, day: 14),
DateOnly(year: 10300, month: 07, day: 14)
)
try XCTAssertEqual(
DateOnly(year: 2021, month: 07, day: 14),
DateOnly(year: 2021, month: 07, day: 14)
)
try XCTAssertEqual(
DateOnly(year: 2019, month: 12, day: 03),
DateOnly(year: 2019, month: 12, day: 03)
)
try XCTAssertEqual(
DateOnly(year: 103, month: 12, day: 03),
DateOnly(year: 103, month: 12, day: 03)
)
try XCTAssertEqual(
DateOnly(year: 1, month: 12, day: 03),
DateOnly(year: 1, month: 12, day: 03)
)
try XCTAssertEqual(
DateOnly(year: .max, month: .max, day: .max),
DateOnly(year: 0001, month: 01, day: 01)
)
func assertInitThrows(year: Int, month: Int, day: Int, file: StaticString = #file, line: UInt = #line) {
XCTAssertThrowsError(try DateOnly(year: year, month: month, day: day), file: file, line: line) { error in
switch error {
case DateOnlyInitError.invalidDateComponents(let y, let m, let d):
XCTAssertEqual(y, year, file: file, line: line)
XCTAssertEqual(m, month, file: file, line: line)
XCTAssertEqual(d, day, file: file, line: line)
break
default:
XCTFail("Unexpected error received: \(error)")
}
}
}
assertInitThrows(year: 0, month: 12, day: 03)
assertInitThrows(year: -1, month: 12, day: 03)
assertInitThrows(year: -120, month: 12, day: 03)
assertInitThrows(year: -120, month: 13, day: 03)
assertInitThrows(year: .min, month: .min, day: .min)
}
func testInitFromDateAndTimeZone() throws {
let timeZone = try XCTUnwrap(TimeZone(identifier: "Europe/London"))
let sut = DateOnly("2021-10-29T23:00:00Z", in: timeZone)
XCTAssertEqual(sut.year, 2021)
XCTAssertEqual(sut.month, 10)
XCTAssertEqual(sut.day, 30)
}
}
extension DateOnlyTests {
func testDecode() throws {
try XCTAssertJSONDecoding("10300-07-14", DateOnly(year: 10300, month: 07, day: 14))
try XCTAssertJSONDecoding("2021-07-14", DateOnly(year: 2021, month: 07, day: 14))
try XCTAssertJSONDecoding("2019-12-03", DateOnly(year: 2019, month: 12, day: 03))
try XCTAssertJSONDecoding("0103-12-03", DateOnly(year: 103, month: 12, day: 03))
try XCTAssertJSONDecoding("0001-12-03", DateOnly(year: 1, month: 12, day: 03))
try XCTAssertJSONDecoding("0001-12-03", DateOnly(year: 1, month: 12, day: 03))
try XCTAssertJSONDecoding("0002-12-03", DateOnly(year: 2, month: 12, day: 03))
try XCTAssertJSONDecoding(" 0121-12-03 ", DateOnly(year: 121, month: 12, day: 03))
try XCTAssertThrowsError(XCTAssertJSONDecoding("12-03", DateOnly?.none))
try XCTAssertThrowsError(XCTAssertJSONDecoding("-12-03", DateOnly?.none))
try XCTAssertThrowsError(XCTAssertJSONDecoding("-0001-12-03", DateOnly?.none))
try XCTAssertThrowsError(XCTAssertJSONDecoding("-0120-12-03", DateOnly?.none))
}
func testEncode() throws {
try XCTAssertJSONEncoding(DateOnly(year: 10300, month: 07, day: 14), "10300-07-14")
try XCTAssertJSONEncoding(DateOnly(year: 2021, month: 07, day: 14), "2021-07-14")
try XCTAssertJSONEncoding(DateOnly(year: 2019, month: 12, day: 03), "2019-12-03")
try XCTAssertJSONEncoding(DateOnly(year: 103, month: 12, day: 03), "0103-12-03")
try XCTAssertJSONEncoding(DateOnly(year: 1, month: 12, day: 03), "0001-12-03")
#if !os(Linux)
try XCTAssertJSONEncoding(DateOnly(year: .max, month: .max, day: .max), "0001-01-01")
#endif
}
}
extension DateOnlyTests {
func testComparable() throws {
let sut = try [
DateOnly(year: 2019, month: 11, day: 14),
DateOnly(year: 2020, month: 07, day: 03),
DateOnly(year: 2020, month: 07, day: 03),
DateOnly(year: 2021, month: 06, day: 02),
DateOnly(year: 2021, month: 06, day: 03),
DateOnly(year: 2021, month: 07, day: 02),
DateOnly(year: 2021, month: 07, day: 03),
]
XCTAssertEqual(sut, sut.shuffled().sorted())
}
}
extension DateOnlyTests {
func testFormat() throws {
let locale = try XCTUnwrap(Locale(identifier: "en_GB"))
let sut = try DateOnly(year: 2019, month: 11, day: 14)
XCTAssertEqual(sut.formatted(style: .none, locale: locale), "")
XCTAssertEqual(sut.formatted(style: .short, locale: locale), "14/11/2019")
XCTAssertEqual(sut.formatted(style: .medium, locale: locale), "14 Nov 2019")
XCTAssertEqual(sut.formatted(style: .long, locale: locale), "14 November 2019")
XCTAssertEqual(sut.formatted(style: .full, locale: locale), "Thursday, 14 November 2019")
}
func testCustomFormat() throws {
let locale = try XCTUnwrap(Locale(identifier: "en_GB"))
let sut = try DateOnly(year: 2019, month: 11, day: 14)
XCTAssertEqual(sut.formatted(custom: "", locale: locale), "")
XCTAssertEqual(sut.formatted(custom: "EEEE", locale: locale), "Thursday")
#if os(Linux)
XCTAssertEqual(sut.formatted(custom: "EEEE d MMMM", locale: locale), "Thursday, 14 November")
#else
XCTAssertEqual(sut.formatted(custom: "EEEE d MMMM", locale: locale), "Thursday 14 November")
#endif
}
}
extension DateOnlyTests {
func testLosslessStringConvertible() {
try XCTAssertEqual(String(DateOnly(year: 2020, month: 02, day: 29)), "2020-02-29")
}
func testCustomStringConvertible() {
try XCTAssertEqual(String(describing: DateOnly(year: 2020, month: 02, day: 29)), "2020-02-29")
try XCTAssertEqual(DateOnly(year: 2020, month: 02, day: 29).description, "2020-02-29")
try XCTAssertEqual("\(DateOnly(year: 2020, month: 02, day: 29))", "2020-02-29")
}
func testCustomDebugStringConvertible() {
try XCTAssertEqual(
String(reflecting: DateOnly(year: 2020, month: 02, day: 29)),
"DateOnly(year: 2020, month: 2, day: 29)"
)
try XCTAssertEqual(
DateOnly(year: 2020, month: 02, day: 29).debugDescription,
"DateOnly(year: 2020, month: 2, day: 29)"
)
}
}
extension DateOnlyTests {
func testExpressibleByStringLiteral() {
try XCTAssertEqual("10300-07-14", DateOnly(year: 10300, month: 07, day: 14))
try XCTAssertEqual("2021-07-14", DateOnly(year: 2021, month: 07, day: 14))
try XCTAssertEqual("2019-12-03", DateOnly(year: 2019, month: 12, day: 03))
try XCTAssertEqual("0103-12-03", DateOnly(year: 103, month: 12, day: 03))
try XCTAssertEqual("0001-12-03", DateOnly(year: 1, month: 12, day: 03))
try XCTAssertEqual("0001-12-03", DateOnly(year: 1, month: 12, day: 03))
try XCTAssertEqual("0002-12-03", DateOnly(year: 2, month: 12, day: 03))
try XCTAssertEqual(" 0121-12-03 ", DateOnly(year: 121, month: 12, day: 03))
}
}
extension DateOnlyTests {
func testInitFromISO8601() {
XCTAssertEqual(DateOnly(iso8601: "10300-07-14"), try DateOnly(year: 10300, month: 07, day: 14))
XCTAssertEqual(DateOnly(iso8601: "2021-07-14"), try DateOnly(year: 2021, month: 07, day: 14))
XCTAssertEqual(DateOnly(iso8601: "2019-12-03"), try DateOnly(year: 2019, month: 12, day: 03))
XCTAssertEqual(DateOnly(iso8601: "0103-12-03"), try DateOnly(year: 103, month: 12, day: 03))
XCTAssertEqual(DateOnly(iso8601: "0001-12-03"), try DateOnly(year: 1, month: 12, day: 03))
XCTAssertEqual(DateOnly(iso8601: "0001-12-03"), try DateOnly(year: 1, month: 12, day: 03))
XCTAssertEqual(DateOnly(iso8601: "0002-12-03"), try DateOnly(year: 2, month: 12, day: 03))
XCTAssertEqual(DateOnly(iso8601: " 0121-12-03 "), try DateOnly(year: 121, month: 12, day: 03))
XCTAssertEqual(DateOnly(iso8601: "12-03"), DateOnly?.none)
XCTAssertEqual(DateOnly(iso8601: "-12-03"), DateOnly?.none)
XCTAssertEqual(DateOnly(iso8601: "-0001-12-03"), DateOnly?.none)
XCTAssertEqual(DateOnly(iso8601: "-0120-12-03"), DateOnly?.none)
}
func testISO8601Formatting() {
XCTAssertEqual(try DateOnly(year: 10300, month: 07, day: 14).formatted(style: .iso8601), "10300-07-14")
XCTAssertEqual(try DateOnly(year: 2021, month: 07, day: 14).formatted(style: .iso8601), "2021-07-14")
XCTAssertEqual(try DateOnly(year: 2019, month: 12, day: 03).formatted(style: .iso8601), "2019-12-03")
XCTAssertEqual(try DateOnly(year: 103, month: 12, day: 03).formatted(style: .iso8601), "0103-12-03")
XCTAssertEqual(try DateOnly(year: 1, month: 12, day: 03).formatted(style: .iso8601), "0001-12-03")
}
}
extension DateOnlyTests {
func testAdd() throws {
let sut = try DateOnly(year: 2021, month: 10, day: 24)
// BST to BST (DST) — but not really
try XCTAssertEqual(sut + (1, .day), DateOnly(year: 2021, month: 10, day: 25))
try XCTAssertEqual(sut + (3, .month), DateOnly(year: 2022, month: 01, day: 24))
try XCTAssertEqual(sut + (3, .year), DateOnly(year: 2024, month: 10, day: 24))
// BST to GMT (DST) — but not really
try XCTAssertEqual(sut + (1, .weekOfYear), DateOnly(year: 2021, month: 10, day: 31))
try XCTAssertEqual(sut + (2, .weekOfYear), DateOnly(year: 2021, month: 11, day: 07))
try XCTAssertEqual(sut + (1, .month), DateOnly(year: 2021, month: 11, day: 24))
}
func testAdd_toLeapDay() throws {
let sut = try DateOnly(year: 2020, month: 02, day: 29) // leap day
try XCTAssertEqual(sut + (3, .day), DateOnly(year: 2020, month: 03, day: 03))
try XCTAssertEqual(sut + (3, .month), DateOnly(year: 2020, month: 05, day: 29))
try XCTAssertEqual(sut + (3, .year), DateOnly(year: 2023, month: 02, day: 28))
}
func testSubtract() throws {
let sut = try DateOnly(year: 2021, month: 10, day: 24)
// BST to BST (DST) — but not really
try XCTAssertEqual(sut, DateOnly(year: 2021, month: 10, day: 25) - (1, .day))
try XCTAssertEqual(sut, DateOnly(year: 2022, month: 01, day: 24) - (3, .month))
try XCTAssertEqual(sut, DateOnly(year: 2024, month: 10, day: 24) - (3, .year))
// GMT to BST (DST) — but not really
try XCTAssertEqual(sut, DateOnly(year: 2021, month: 10, day: 31) - (1, .weekOfYear))
try XCTAssertEqual(sut, DateOnly(year: 2021, month: 11, day: 07) - (2, .weekOfYear))
try XCTAssertEqual(sut, DateOnly(year: 2021, month: 11, day: 24) - (1, .month))
}
func testSubtract_toLeapDay() throws {
let sut = try DateOnly(year: 2020, month: 02, day: 29) // leap day
try XCTAssertEqual(sut, DateOnly(year: 2020, month: 03, day: 03) - (3, .day))
try XCTAssertEqual(sut, DateOnly(year: 2020, month: 05, day: 29) - (3, .month))
try XCTAssertGreaterThan(sut, DateOnly(year: 2023, month: 02, day: 28) - (3, .year))
try XCTAssertEqual(sut - (1, .day), DateOnly(year: 2023, month: 02, day: 28) - (3, .year))
}
func testDiff() throws {
let sut = try DateOnly(year: 2021, month: 10, day: 24) // leap day
// BST-BST (DST) — but not really
try XCTAssertEqual(sut - (DateOnly(year: 2021, month: 10, day: 24), .day), 0)
try XCTAssertEqual(sut - (DateOnly(year: 2021, month: 10, day: 21), .day), 3)
try XCTAssertEqual(sut - (DateOnly(year: 2011, month: 10, day: 24), .year), 10)
try XCTAssertEqual(sut - (DateOnly(year: 2011, month: 10, day: 24), .month), 120)
try XCTAssertEqual(sut - (DateOnly(year: 2021, month: 10, day: 30), .hour), -144)
}
}
| 49.777778 | 117 | 0.615245 |
695a03591ad52359af11aa22a4ecfbcc846ddf1e | 926 | //
// ViewController.swift
// MZTextField
//
// Created by 曾龙 on 2021/12/18.
//
import UIKit
class ViewController: UIViewController, MZTextFieldDelegate {
lazy var textField1: MZTextField = {
let textField = MZTextField(frame: CGRect(x: 30, y: 100, width: 300, height: 40))
textField.backgroundColor = .lightGray
textField.placeholder = "请输入长度不超过10的字符串"
textField.maxTextLength = 10
return textField
}()
@IBOutlet weak var textField2: MZTextField!
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(textField1)
view.addSubview(textField2)
textField2.maxTextLength = 12
textField2.mzDeleagte = self
}
func textFieldDidDeleteBackword(_ textField: MZTextField, _ originText: String) {
print("originText:\(originText)")
print("currentText:\(textField.text ?? "")")
}
}
| 25.722222 | 89 | 0.649028 |
2602a0e594337c25de27add4c6f297e4030e6a69 | 10,291 | //
// Copyright (c) 2019 muukii
//
// 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
#if !COCOAPODS
import Verge
#endif
protocol EntityModifierType: AnyObject {
var entityName: EntityTableIdentifier { get }
var _insertsOrUpdates: _EntityTableType { get }
var _deletes: Set<AnyEntityIdentifier> { get }
}
/// For performBatchUpdates
public final class EntityModifier<Schema: EntitySchemaType, Entity: EntityType>: EntityModifierType {
public typealias InsertionResult = EntityTable<Schema, Entity>.InsertionResult
var _current: _EntityTableType {
current
}
var _insertsOrUpdates: _EntityTableType {
insertsOrUpdates
}
var _deletes: Set<AnyEntityIdentifier> {
deletes
}
let entityName = Entity.entityName
/// An EntityTable contains entities that stored currently.
public let current: EntityTable<Schema, Entity>
/// An EntityTable contains entities that will be stored after batchUpdates finished.
/// The objects this table contains would be applied, that's why it's mutable property.
private var insertsOrUpdates: EntityTable<Schema, Entity>
/// A set of entity ids that entity will be deleted after batchUpdates finished.
/// The current entities will be deleted with this identifiers.
private var deletes: Set<AnyEntityIdentifier> = .init()
init(current: EntityTable<Schema, Entity>) {
self.current = current
self.insertsOrUpdates = .init()
}
// MARK: - Querying
/// All entities from context and current
///
/// - TODO: Expensive
public func all() -> AnyCollection<Entity> {
AnyCollection(
insertsOrUpdates
.rawTable
.entities
.merging(current.rawTable.entities, uniquingKeysWith: { e, _ in e })
.values
.lazy
.map { $0.base as! Entity }
)
}
/// Find entity from updates and current.
///
/// Firstly, find from updates and then find from current.
/// - Parameter id:
public func find(by id: Entity.EntityID) -> Entity? {
insertsOrUpdates.find(by: id) ?? current.find(by: id)
}
/// Find entities from updates and current.
///
/// Firstly, find from updates and then find from current.
/// - Parameter id:
public func find<S: Sequence>(in ids: S) -> [Entity] where S.Element == Entity.EntityID {
insertsOrUpdates.find(in: ids) + current.find(in: ids)
}
// MARK: - Mutating
/// Set inserts entity
@discardableResult
public func insert(_ entity: Entity) -> InsertionResult {
insertsOrUpdates.insert(entity)
}
/// Set inserts entities
@discardableResult
public func insert<S: Sequence>(_ addingEntities: S) -> [InsertionResult] where S.Element == Entity {
insertsOrUpdates.insert(addingEntities)
}
/// Set deletes entity with entity object
/// - Parameter entity:
public func delete(_ entity: Entity) {
deletes.insert(entity.entityID.any)
}
/// Set deletes entity with identifier
/// - Parameter entityID:
public func delete(_ entityID: Entity.EntityID) {
deletes.insert(entityID.any)
}
/// Set deletes entities with passed entities.
/// - Parameter entities:
public func delete<S: Sequence>(_ entities: S) where S.Element == Entity {
deletes.formUnion(entities.lazy.map { $0.entityID.any })
}
/// Set deletes entities with passed sequence of entity's identifier.
/// - Parameter entityIDs:
public func delete<S: Sequence>(_ entityIDs: S) where S.Element == Entity.EntityID {
deletes.formUnion(entityIDs.map(\.any))
}
/// Set deletes all entities
public func deleteAll() {
deletes.formUnion(current.allIDs().map(\.any))
}
/// Update existing entity. it throws if does not exsist.
@discardableResult
@inline(__always)
public func updateExists(id: Entity.EntityID, update: (inout Entity) throws -> Void) throws -> Entity {
/// Updates from context
if insertsOrUpdates.find(by: id) != nil {
return try insertsOrUpdates.updateExists(id: id, update: update)
}
/// Updates from current
if var target = current.find(by: id) {
try update(&target)
precondition(target.entityID == id, "EntityID was modified")
insertsOrUpdates.insert(target)
return target
}
throw BatchUpdatesError.storedEntityNotFound
}
/// Updates existing entity from insertsOrUpdates or current.
/// It's never been called update closure if the entity was not found.
///
/// - Parameters:
/// - id:
/// - update:
@discardableResult
public func updateIfExists(id: Entity.EntityID, update: (inout Entity) throws -> Void) rethrows -> Entity? {
try? updateExists(id: id, update: update)
}
}
public struct DatabaseEntityUpdatesResult<Schema: EntitySchemaType>: Equatable {
let updated: [EntityTableIdentifier : Set<AnyEntityIdentifier>]
let deleted: [EntityTableIdentifier : Set<AnyEntityIdentifier>]
public func wasUpdated<E: EntityType>(_ id: E.EntityID) -> Bool {
guard let set = updated[E.entityName] else { return false }
return set.contains(id.any)
}
public func wasDeleted<E: EntityType>(_ id: E.EntityID) -> Bool {
guard let set = deleted[E.entityName] else { return false }
return set.contains(id.any)
}
public func containsEntityUpdated<E: EntityType>(_ entityType: E.Type) -> Bool {
updated.keys.contains(E.entityName)
}
public func containsEntityDeleted<E: EntityType>(_ entityType: E.Type) -> Bool {
deleted.keys.contains(E.entityName)
}
}
@dynamicMemberLookup
public class DatabaseEntityBatchUpdatesContext<Schema: EntitySchemaType> {
@dynamicMemberLookup
public struct EntityProxy {
let base: DatabaseEntityBatchUpdatesContext<Schema>
public func table<E: EntityType>(_ entityType: E.Type) -> EntityModifier<Schema, E> {
guard let rawTable = base.editing[E.entityName] else {
let modifier = EntityModifier<Schema, E>(current: base.entityStorage.table(E.self))
base.editing[E.entityName] = modifier
return modifier
}
return rawTable as! EntityModifier<Schema, E>
}
public subscript <U: EntityType>(dynamicMember keyPath: KeyPath<Schema, EntityTableKey<U>>) -> EntityModifier<Schema, U> {
table(U.self)
}
}
private let entityStorage: EntityTablesStorage<Schema>
public var entities: EntityProxy {
return .init(base: self)
}
var editing: [EntityTableIdentifier : EntityModifierType] = [:]
init(current: EntityTablesStorage<Schema>) {
self.entityStorage = current
}
public func abort() throws -> Never {
throw BatchUpdatesError.aborted
}
@available(*, deprecated, message: "Use .entities.table")
public func table<E: EntityType>(_ entityType: E.Type) -> EntityModifier<Schema, E> {
entities.table(entityType)
}
@available(*, deprecated, message: "Use .entities.<YOUR_ENTITY>")
public subscript <U: EntityType>(dynamicMember keyPath: KeyPath<Schema, EntityTableKey<U>>) -> EntityModifier<Schema, U> {
entities.table(U.self)
}
func makeResult() -> DatabaseEntityUpdatesResult<Schema> {
var updated: [EntityTableIdentifier : Set<AnyEntityIdentifier>] = [:]
var deleted: [EntityTableIdentifier : Set<AnyEntityIdentifier>] = [:]
for (entityName, rawEntityData) in editing {
deleted[entityName] = rawEntityData._deletes
updated[entityName] = Set(rawEntityData._insertsOrUpdates.rawTable.entities.keys)
}
return .init(updated: updated, deleted: deleted)
}
}
public final class DatabaseBatchUpdatesContext<Database: DatabaseType>: DatabaseEntityBatchUpdatesContext<Database.Schema> {
public var indexes: IndexesStorage<Database.Schema, Database.Indexes>
init(current: Database) {
self.indexes = current._backingStorage.indexesStorage
super.init(current: current._backingStorage.entityBackingStorage)
}
}
extension DatabaseType {
public func beginBatchUpdates() -> DatabaseBatchUpdatesContext<Self> {
let context = DatabaseBatchUpdatesContext<Self>(current: self)
return context
}
public mutating func commitBatchUpdates(context: DatabaseBatchUpdatesContext<Self>) {
let t = VergeSignpostTransaction("DatabaseType.commit")
defer {
t.end()
}
middlewareAfter: do {
middlewares.forEach {
$0.performAfterUpdates(context: context)
}
}
apply: do {
_backingStorage.entityBackingStorage.apply(edits: context.editing)
context.indexes.apply(edits: context.editing)
_backingStorage.indexesStorage = context.indexes
}
_backingStorage.markUpdated()
_backingStorage.lastUpdatesResult = context.makeResult()
}
/// Performs operations to update entities and indexes
/// If can be run on background thread with locking.
///
/// - Parameter update:
public mutating func performBatchUpdates<Result>(_ update: (DatabaseBatchUpdatesContext<Self>) throws -> Result) rethrows -> Result {
do {
let context = beginBatchUpdates()
let result = try update(context)
commitBatchUpdates(context: context)
return result
} catch {
throw error
}
}
}
| 31.279635 | 150 | 0.696628 |
6acec38e97ec4e2560a202ebf7f1e03d7ef1505f | 2,944 | //
// Copyright 2020 Swiftkube Project
//
// 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.
//
///
/// Generated by Swiftkube:ModelGen
/// Kubernetes v1.20.9
/// core.v1.SecretProjection
///
import Foundation
public extension core.v1 {
///
/// Adapts a secret into a projected volume.
///
/// The contents of the target Secret's Data field will be presented in a projected volume as files using the keys in the Data field as the file names. Note that this is identical to a secret volume source without the default mode.
///
struct SecretProjection: KubernetesResource {
///
/// If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.
///
public var items: [core.v1.KeyToPath]?
///
/// Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
///
public var name: String?
///
/// Specify whether the Secret or its key must be defined
///
public var optional: Bool?
///
/// Default memberwise initializer
///
public init(
items: [core.v1.KeyToPath]? = nil,
name: String? = nil,
optional: Bool? = nil
) {
self.items = items
self.name = name
self.optional = optional
}
}
}
///
/// Codable conformance
///
public extension core.v1.SecretProjection {
private enum CodingKeys: String, CodingKey {
case items = "items"
case name = "name"
case optional = "optional"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.items = try container.decodeIfPresent([core.v1.KeyToPath].self, forKey: .items)
self.name = try container.decodeIfPresent(String.self, forKey: .name)
self.optional = try container.decodeIfPresent(Bool.self, forKey: .optional)
}
func encode(to encoder: Encoder) throws {
var encodingContainer = encoder.container(keyedBy: CodingKeys.self)
try encodingContainer.encode(items, forKey: .items)
try encodingContainer.encode(name, forKey: .name)
try encodingContainer.encode(optional, forKey: .optional)
}
}
| 33.83908 | 482 | 0.723845 |
62b82a240c7fb236dbc80a72f1272bd07772a048 | 564 | //
// ViewController.swift
// MyTwitter
//
// Created by mac on 2/21/17.
// Copyright © 2017 Muhammad Umair Khokhar. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLoginButton(_ sender: Any) {
}
}
| 20.142857 | 80 | 0.664894 |
c17af71079dece8653d5bd91a0f2454cbc5cf7df | 269 | //
// MainViewInput.swift
// OTPTextFieldExample
//
// Created by Krupenko Validislav on 20/03/2020.
// Copyright © 2020 Fixique. All rights reserved.
//
protocol MainViewInput: class {
/// Method for setup initial state of view
func setupInitialState()
}
| 20.692308 | 50 | 0.70632 |
ddbae27c8165dbc41594925788e6f5a9d9095f80 | 27,826 | //
// ArcusThermostatControl.swift
// i2app
//
// Created by Arcus Team on 6/15/17.
/*
* Copyright 2019 Arcus Project
*
* 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.
*/
//
enum ThermostatActiveHandle {
case heatHandle
case coolHandle
}
protocol ArcusThermostatControlDelegate: class {
func modeButtonPressed(_ arcusThermostatControl: ArcusThermostatControl)
func interactionStarted(_ arcusThermostatControl: ArcusThermostatControl)
func interactionEnded(_ arcusThermostatControl: ArcusThermostatControl)
}
@IBDesignable @objc class ArcusThermostatControl: UIControl {
weak var delegate: ArcusThermostatControlDelegate?
var debounceInterval: TimeInterval = 2.0
// MARK: Internal Elements
private var backgroundArcView: ArcusArcView!
private var temperatureArcView: ArcusArcView!
private var rangeArcView: ArcusArcView!
private let circle = CAShapeLayer()
private var coolHandle = UIImageView(image: UIImage(named: "circletarget_icon-small-ios"))
private var coolHandleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 35, height: 18))
private var heatHandle = UIImageView(image: UIImage(named: "circletarget_icon-small-ios"))
private var heatHandleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 35, height: 18))
private var temperatureLockMin = UIImageView(image: UIImage(named: "circletarget_icon-small-ios"))
private var temperatureLockMax = UIImageView(image: UIImage(named: "circletarget_icon-small-ios"))
private var icon = UIImageView(frame: CGRect(x: 0, y: 0, width: 27, height: 25))
private var currentTemperatureBar: UIImageView!
private var currentTemperatureLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 35, height: 21))
private var humidityIcon = UIImageView(image: UIImage(named: "haloHumidity"))
private var humidityLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 65, height: 21))
private var minusButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
private var plusButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
private var modeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 62, height: 42))
private var thermostatTemperatureLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 55))
private var thermostatModeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 24))
// MARK: Properties
private(set) var viewModel = ThermostatControlViewModel()
private(set) var activeHandle = ThermostatActiveHandle.heatHandle
private var changeScheduler = Timer()
private var activeStartAngle: CGFloat = 0
private var isMovingHandle = false
// MARK: View LifeCycle
override init(frame: CGRect) {
super.init(frame: frame)
initLayers()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initLayers()
}
func initLayers() {
backgroundArcView = ArcusArcView(frame: CGRect(x: 0, y: 0, width: 340, height: 255))
backgroundArcView.startAngle = ArcusArcMath.radians(135)
backgroundArcView.endAngle = ArcusArcMath.radians(45)
backgroundArcView.centerPoint = CGPoint(x: 170, y: 150)
backgroundArcView.width = 26
backgroundArcView.radius = 130 - (backgroundArcView.width/2)
backgroundArcView.backgroundColor = UIColor.clear
backgroundArcView.colorsArray = [UIColor.white.withAlphaComponent(0.3)]
rangeArcView = ArcusArcView(frame: backgroundArcView.bounds)
temperatureArcView = ArcusArcView(frame: backgroundArcView.bounds)
modeButton.setImage(UIImage(named: "DeviceThermostatModeButton"), for: .normal)
modeButton.center = CGPoint(x: backgroundArcView.center.x, y: backgroundArcView.centerPoint.y + 170)
modeButton.isUserInteractionEnabled = true
modeButton.addTarget(self, action: #selector(handleModeButton), for: .touchUpInside)
plusButton.setImage(UIImage(named: "deviceThermostatPlusButton"), for: .normal)
plusButton.center = CGPoint(x: modeButton.center.x + 80, y: modeButton.center.y)
plusButton.isUserInteractionEnabled = true
plusButton.addTarget(self, action: #selector(handlePlusButton(button:)), for: .touchUpInside)
minusButton.setImage(UIImage(named: "deviceThermostatMinusButton"), for: .normal)
minusButton.center = CGPoint(x: modeButton.center.x - 80, y: modeButton.center.y)
minusButton.isUserInteractionEnabled = true
minusButton.addTarget(self, action: #selector(handleMinusButton(button:)), for: .touchUpInside)
currentTemperatureBar = UIImageView(image: UIImage(named: "currentbar_icon-small-ios"))
coolHandle.backgroundColor = UIColor.clear
heatHandle.backgroundColor = UIColor.clear
humidityLabel.center = CGPoint(x: center.x + 3, y: backgroundArcView.center.y + 145)
humidityIcon.center = CGPoint(x: center.x - 45, y: backgroundArcView.center.y + 143)
temperatureLockMin.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
temperatureLockMax.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
setUpValueLabels()
addCircle()
icon.center = CGPoint(x: thermostatTemperatureLabel.center.x, y: thermostatTemperatureLabel.center.y + 60)
layer.addSublayer(backgroundArcView.layer)
layer.addSublayer(currentTemperatureLabel.layer)
layer.addSublayer(thermostatTemperatureLabel.layer)
layer.addSublayer(thermostatModeLabel.layer)
layer.addSublayer(coolHandleLabel.layer)
layer.addSublayer(heatHandleLabel.layer)
layer.addSublayer(modeButton.layer)
layer.addSublayer(plusButton.layer)
layer.addSublayer(minusButton.layer)
layer.addSublayer(humidityIcon.layer)
layer.addSublayer(humidityLabel.layer)
layer.addSublayer(rangeArcView.layer)
layer.addSublayer(temperatureArcView.layer)
layer.addSublayer(temperatureLockMin.layer)
layer.addSublayer(temperatureLockMax.layer)
layer.addSublayer(icon.layer)
layer.addSublayer(currentTemperatureBar.layer)
layer.addSublayer(coolHandle.layer)
layer.addSublayer(heatHandle.layer)
}
override func setNeedsDisplay() {
super.setNeedsDisplay()
if backgroundArcView != nil {
backgroundArcView.setNeedsDisplay()
}
if temperatureArcView != nil {
temperatureArcView?.setNeedsDisplay()
}
if rangeArcView != nil {
rangeArcView?.setNeedsDisplay()
}
}
override func layoutSubviews() {
backgroundArcView.frame = bounds
super.layoutSubviews()
}
// MARK: Touch Handling
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
super.beginTracking(touch, with: event)
let touchPoint: CGPoint = touch.location(in: self)
if thermostatTemperatureLabel.frame.contains(touchPoint) && viewModel.mode == .auto {
toggleSelectedSetpoint()
return false
}
delegate?.interactionStarted(self)
if plusButton.frame.contains(touchPoint) {
plusButton.sendActions(for: .touchUpInside)
} else if minusButton.frame.contains(touchPoint) {
minusButton.sendActions(for: .touchUpInside)
} else if modeButton.frame.contains(touchPoint) {
modeButton.sendActions(for: .touchUpInside)
} else if coolHandle.frame.contains(touchPoint) {
isMovingHandle = true
activeHandle = .coolHandle
highlightActiveSetpoint()
} else if heatHandle.frame.contains(touchPoint) {
isMovingHandle = true
activeHandle = .heatHandle
highlightActiveSetpoint()
}
return true
}
override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
super.continueTracking(touch, with: event)
guard isMovingHandle else {
return true
}
let touchPoint: CGPoint = touch.location(in: self)
moveHandle(touchPoint)
return true
}
override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
isMovingHandle = false
delegate?.interactionEnded(self)
}
override func cancelTracking(with event: UIEvent?) {
super.cancelTracking(with: event)
}
// MARK: Event Handling
func handlePlusButton(button: UIButton) {
guard viewModel.mode == .heat || viewModel.mode == .cool || viewModel.mode == .auto else {
return
}
var temperature: Int
if activeHandle == .heatHandle {
temperature = viewModel.heatSetpoint + 1
} else {
temperature = viewModel.coolSetpoint + 1
}
if temperature > viewModel.temperatureLimitHigh {
temperature = viewModel.temperatureLimitHigh
}
updateActiveSetpointToTemperature(temperature)
scheduleChangeEvent()
configureView()
}
func handleMinusButton(button: UIButton) {
guard viewModel.mode == .heat || viewModel.mode == .cool || viewModel.mode == .auto else {
return
}
var temperature: Int
if activeHandle == .heatHandle {
temperature = viewModel.heatSetpoint - 1
} else {
temperature = viewModel.coolSetpoint - 1
}
updateActiveSetpointToTemperature(temperature)
scheduleChangeEvent()
configureView()
}
func handleModeButton(button: UIButton) {
delegate?.modeButtonPressed(self)
}
func emitChangeEvent() {
sendActions(for: UIControlEvents.valueChanged)
}
// MARK: Public Configuration Methods
func updateThermostatControl(_ viewModel: ThermostatControlViewModel) {
self.viewModel = viewModel
self.rangeArcView.isHidden = true
configureView()
}
// MARK: Helpers
private func configureView() {
configureThermostatMode()
configureTemperatureText()
configureHumidity()
configureCurrentTemperatureSetpoint()
configureCoolHandle()
configureHeatHandle()
highlightActiveSetpoint()
configureRangeArc()
configureTemperatureArc()
configureActionButtons()
configureTemperatureLock()
configureThermostatIcon()
setNeedsDisplay()
}
private func configureThermostatIcon() {
if let iconName = viewModel.iconImageName {
icon.isHidden = false
icon.image = UIImage(named: iconName)
} else {
icon.isHidden = true
}
}
private func configureTemperatureLock() {
if let minLock = viewModel.temperatureLockMin {
let degrees = temperatureToDegrees(temperature: minLock)
let angle = ArcusArcMath.radians(degrees)
temperatureLockMin.isHidden = false
temperatureLockMin.center = ArcusArcMath.pointForAngle(angle,
center: backgroundArcView.centerPoint,
radius: backgroundArcView.radius)
} else {
temperatureLockMin.isHidden = true
}
if let maxLock = viewModel.temperatureLockMax {
let degrees = temperatureToDegrees(temperature: maxLock)
let angle = ArcusArcMath.radians(degrees)
temperatureLockMax.isHidden = false
temperatureLockMax.center = ArcusArcMath.pointForAngle(angle,
center: backgroundArcView.centerPoint,
radius: backgroundArcView.radius)
} else {
temperatureLockMax.isHidden = true
}
}
private func configureActionButtons() {
switch viewModel.mode {
case .off, .eco:
plusButton.isHidden = true
minusButton.isHidden = true
default:
plusButton.isHidden = false
minusButton.isHidden = false
}
}
private func configureCoolHandle() {
if viewModel.mode == .cool || viewModel.mode == .auto {
coolHandle.isHidden = false
coolHandleLabel.isHidden = false
} else {
coolHandle.isHidden = true
coolHandleLabel.isHidden = true
return
}
let temperature = viewModel.coolSetpoint
let temperatureLimitHigh = viewModel.temperatureLimitHigh
let temperatureLimitLow = viewModel.temperatureLimitLow
guard temperature >= temperatureLimitLow && temperature <= temperatureLimitHigh else {
return
}
coolHandleLabel.text = "\(temperature)°"
setPosition(forHanldle: coolHandle, toTemperature: temperature)
}
private func configureHeatHandle() {
if viewModel.mode == .heat || viewModel.mode == .auto {
heatHandle.isHidden = false
heatHandleLabel.isHidden = false
} else {
heatHandle.isHidden = true
heatHandleLabel.isHidden = true
return
}
let temperature = viewModel.heatSetpoint
let temperatureLimitHigh = viewModel.temperatureLimitHigh
let temperatureLimitLow = viewModel.temperatureLimitLow
guard temperature >= temperatureLimitLow && temperature <= temperatureLimitHigh else {
return
}
heatHandleLabel.text = "\(temperature)°"
setPosition(forHanldle: heatHandle, toTemperature: temperature)
}
private func configureHumidity() {
guard let humidity = viewModel.humidity else {
humidityIcon.isHidden = true
humidityLabel.text = ""
return
}
humidityIcon.isHidden = false
humidityLabel.text = "\(humidity)%"
}
private func configureCurrentTemperatureSetpoint() {
let temperature = viewModel.currentTemperature
let degrees = temperatureToDegrees(temperature: temperature)
let angle = ArcusArcMath.radians(degrees)
let point = ArcusArcMath.pointForAngle(angle, center: backgroundArcView.centerPoint,
radius: backgroundArcView.radius)
let newAngle = ArcusArcMath.angleForPoint(point, center: backgroundArcView.centerPoint)
let adjustedAngle = (CGFloat.pi/2) - newAngle * -1
let labelRadius = (backgroundArcView.radius) + currentTemperatureLabel.frame.width
currentTemperatureBar.transform = CGAffineTransform(rotationAngle: adjustedAngle)
currentTemperatureBar.center = point
currentTemperatureBar.isHidden = false
currentTemperatureLabel.text = "\(temperature)°"
currentTemperatureLabel.isHidden = false
currentTemperatureLabel.center = ArcusArcMath.pointForAngle(newAngle,
center: backgroundArcView.centerPoint,
radius: labelRadius)
}
private func configureTemperatureText() {
switch viewModel.mode {
case .auto:
thermostatTemperatureLabel.text = "\(viewModel.heatSetpoint)°●\(viewModel.coolSetpoint)°"
case .cool:
thermostatTemperatureLabel.text = "\(viewModel.coolSetpoint)°"
case .heat:
thermostatTemperatureLabel.text = "\(viewModel.heatSetpoint)°"
case .eco:
thermostatTemperatureLabel.text = NSLocalizedString("ECO", comment: "")
case .off:
thermostatTemperatureLabel.text = NSLocalizedString("OFF", comment: "")
}
}
private func configureThermostatMode() {
switch viewModel.mode {
case .auto:
if let text = viewModel.customAutoModeText {
thermostatModeLabel.text = text
} else {
thermostatModeLabel.text = NSLocalizedString("AUTO", comment: "")
}
case .cool:
thermostatModeLabel.text = NSLocalizedString("COOL", comment: "")
activeHandle = .coolHandle
case .heat:
activeHandle = .heatHandle
thermostatModeLabel.text = NSLocalizedString("HEAT", comment: "")
default:
thermostatModeLabel.text = ""
}
}
private func highlightActiveSetpoint() {
guard viewModel.mode == .auto else {
return
}
let first = "\(viewModel.heatSetpoint)°"
let second = "\(viewModel.coolSetpoint)°"
let white = UIColor(red: 255, green: 255, blue: 255, alpha: 0.5)
let attributes: [String: AnyObject] = [ NSForegroundColorAttributeName: white]
let firstComponent: NSMutableAttributedString
let secondComponent: NSMutableAttributedString
if activeHandle == .heatHandle {
firstComponent = NSMutableAttributedString(string: first)
secondComponent = NSMutableAttributedString(string: "●\(second)", attributes: attributes)
} else {
firstComponent = NSMutableAttributedString(string: "\(first)●", attributes: attributes)
secondComponent = NSMutableAttributedString(string: second)
}
firstComponent.append(secondComponent)
thermostatTemperatureLabel.attributedText = firstComponent
}
private func setPosition(forHanldle handle: UIImageView, toTemperature temperature: Int) {
let adjustedTemperature: Int
if temperature == viewModel.currentTemperature + 1 {
adjustedTemperature = viewModel.currentTemperature + 2
} else if temperature == viewModel.currentTemperature - 1 {
adjustedTemperature = viewModel.currentTemperature - 2
} else {
adjustedTemperature = temperature
}
let degrees = temperatureToDegrees(temperature: temperature)
let adjustedDegrees = temperatureToDegrees(temperature: adjustedTemperature)
let angle = ArcusArcMath.radians(degrees)
let adjustedAngle = ArcusArcMath.radians(adjustedDegrees)
let labelPosition = ArcusArcMath.pointForAngle(adjustedAngle,
center: backgroundArcView.centerPoint,
radius: backgroundArcView.radius + 30)
handle.center = ArcusArcMath.pointForAngle(angle,
center: backgroundArcView.centerPoint,
radius: backgroundArcView.radius)
if handle == coolHandle {
coolHandleLabel.isHidden = viewModel.coolSetpoint == viewModel.currentTemperature
coolHandleLabel.center = labelPosition
} else {
heatHandleLabel.isHidden = viewModel.heatSetpoint == viewModel.currentTemperature
heatHandleLabel.center = labelPosition
}
}
private func configureRangeArc() {
guard viewModel.mode == .auto else {
rangeArcView.isHidden = true
return
}
let start = temperatureToDegrees(temperature: viewModel.heatSetpoint)
let end = temperatureToDegrees(temperature: viewModel.coolSetpoint)
let colors = [UIColor.white.withAlphaComponent(0.7)]
rangeArcView.isHidden = false
update(arcView: rangeArcView, withColors: colors, startAngle: start, endAngle: end)
}
private func configureTemperatureArc() {
var start: Double?
var end: Double?
let lightOrange = UIColor(red: 226/255, green: 33/255, blue: 42/255, alpha: 1)
let orange = UIColor(red: 239/255, green: 147/255, blue: 27/255, alpha: 1)
let lightBlue = UIColor(red: 175/255, green: 221/255, blue: 232/255, alpha: 1)
let blue = UIColor(red: 27/255, green: 143/255, blue: 210/255, alpha: 1)
let white = UIColor.white.withAlphaComponent(0.7)
var colors = [UIColor]()
if viewModel.mode == .auto {
if viewModel.coolSetpoint < viewModel.currentTemperature {
end = temperatureToDegrees(temperature: viewModel.currentTemperature)
start = temperatureToDegrees(temperature: viewModel.coolSetpoint)
colors = [blue, lightBlue]
} else if viewModel.heatSetpoint > viewModel.currentTemperature {
start = temperatureToDegrees(temperature: viewModel.currentTemperature)
end = temperatureToDegrees(temperature: viewModel.heatSetpoint)
colors = [lightOrange, orange]
}
} else if viewModel.mode == .cool {
if viewModel.coolSetpoint > viewModel.currentTemperature {
end = temperatureToDegrees(temperature: viewModel.coolSetpoint)
start = temperatureToDegrees(temperature: viewModel.currentTemperature)
colors = [white]
} else if viewModel.coolSetpoint < viewModel.currentTemperature {
start = temperatureToDegrees(temperature: viewModel.coolSetpoint)
end = temperatureToDegrees(temperature: viewModel.currentTemperature)
colors = [blue, lightBlue]
}
} else if viewModel.mode == .heat {
if viewModel.heatSetpoint < viewModel.currentTemperature {
start = temperatureToDegrees(temperature: viewModel.heatSetpoint)
end = temperatureToDegrees(temperature: viewModel.currentTemperature)
colors = [white]
} else if viewModel.heatSetpoint > viewModel.currentTemperature {
end = temperatureToDegrees(temperature: viewModel.heatSetpoint)
start = temperatureToDegrees(temperature: viewModel.currentTemperature)
colors = [orange, lightOrange]
}
}
if start == nil || end == nil {
temperatureArcView.isHidden = true
return
}
temperatureArcView.isHidden = false
update(arcView: temperatureArcView, withColors: colors, startAngle: start!, endAngle: end!)
}
private func update(arcView: ArcusArcView,
withColors colors: [UIColor],
startAngle: Double,
endAngle: Double) {
arcView.squareCap = true
arcView.backgroundColor = UIColor.clear
arcView.arcMode = .colorArray
arcView.colorsArray = colors
arcView.centerPoint = backgroundArcView.centerPoint
arcView.radius = backgroundArcView.radius
arcView.width = backgroundArcView.width
arcView.startAngle = ArcusArcMath.radians(startAngle)
arcView.endAngle = ArcusArcMath.radians(endAngle)
}
private func temperatureToDegrees(temperature: Int) -> Double {
let temperatureLimitHigh: Int = viewModel.temperatureLimitHigh
let temperatureLimitLow: Int = viewModel.temperatureLimitLow
let startDegrees: Double = ArcusArcMath.degrees(backgroundArcView.startAngle)
let endDegrees: Double = ArcusArcMath.degrees(backgroundArcView.endAngle)
var newTemperature: Int = temperature
if temperature > temperatureLimitHigh {
newTemperature = temperatureLimitHigh
}
if temperature < temperatureLimitLow {
newTemperature = temperatureLimitLow
}
let adjustedTemperature = Double((newTemperature - temperatureLimitLow) * 100)
let percentage: Double = adjustedTemperature / Double(temperatureLimitHigh - temperatureLimitLow)
let newDegree: Double = percentage * (360 - abs(startDegrees - endDegrees)) / 100
return newDegree + startDegrees
}
private func degreesToTemperature(degrees: Double) -> Int {
let temperatureLimitLow = viewModel.temperatureLimitLow
let temperatureLimitHigh = viewModel.temperatureLimitHigh
let startDegrees = ArcusArcMath.degrees(backgroundArcView.startAngle)
let endDegrees = ArcusArcMath.degrees(backgroundArcView.endAngle)
var adjustedNewDegree = degrees
if degrees < startDegrees {
adjustedNewDegree = degrees + 360
}
let percentage = (adjustedNewDegree - startDegrees) * 100 / (360 - abs(startDegrees - endDegrees))
let newTemperature = Int(round(percentage * Double(temperatureLimitHigh - temperatureLimitLow) / 100))
return temperatureLimitLow + newTemperature
}
private func addCircle() {
let circleRadius = backgroundArcView.radius - backgroundArcView.width/2 - 5
let circlePath = UIBezierPath(arcCenter: backgroundArcView.centerPoint,
radius: circleRadius,
startAngle: CGFloat(0),
endAngle: CGFloat(Double.pi * 2),
clockwise: true)
circle.path = circlePath.cgPath
circle.fillColor = UIColor.clear.cgColor
circle.strokeColor = UIColor.white.cgColor
circle.lineWidth = 1.0
layer.addSublayer(circle)
}
private func setUpValueLabels() {
setUpLabel(currentTemperatureLabel, withFontSize: 17)
setUpLabel(thermostatModeLabel, withFontSize: 17)
setUpLabel(coolHandleLabel, withFontSize: 17)
setUpLabel(heatHandleLabel, withFontSize: 17)
setUpLabel(thermostatTemperatureLabel, withFontSize: 40)
setUpLabel(thermostatModeLabel, withFontSize: 17)
setUpLabel(humidityLabel, withFontSize: 19)
humidityLabel.textAlignment = .left
thermostatTemperatureLabel.center = backgroundArcView.centerPoint
thermostatModeLabel.center = CGPoint(x: frame.width/2, y: thermostatTemperatureLabel.center.x - 65)
}
private func setUpLabel(_ label: UILabel, withFontSize fontSize: CGFloat) {
label.font = UIFont(name: "AvenirNext-DemiBold", size: fontSize)
label.textAlignment = .center
label.textColor = UIColor.white
}
func moveHandle(_ point: CGPoint) {
let newAngle = ArcusArcMath.angleForPoint(point, center: backgroundArcView.centerPoint)
let newDegree = ((round(ArcusArcMath.degrees(newAngle)) + 360).truncatingRemainder(dividingBy: 360))
let startDegrees = ArcusArcMath.degrees(backgroundArcView.startAngle)
let endDegrees = ArcusArcMath.degrees(backgroundArcView.endAngle)
let center = backgroundArcView.centerPoint
if (newDegree <= endDegrees && point.x > center.x && point.y > center.y) ||
(point.x >= center.x && point.y <= center.y) ||
(point.x < center.x && newDegree >= startDegrees) {
updateActiveSetpointToTemperature(degreesToTemperature(degrees: newDegree))
configureView()
scheduleChangeEvent()
}
}
private func updateActiveSetpointToTemperature(_ temperature: Int) {
let separation = viewModel.setpointSeparation
var temperatureLimitHigh = viewModel.temperatureLimitHigh
var temperatureLimitLow = viewModel.temperatureLimitLow
var newTemperature = temperature
if let newLimit = viewModel.temperatureLockMin {
temperatureLimitLow = newLimit
}
if let newLimit = viewModel.temperatureLockMax {
temperatureLimitHigh = newLimit
}
if viewModel.mode == .auto {
if activeHandle == .heatHandle {
let adjustedHigh = temperatureLimitHigh - separation
if newTemperature < temperatureLimitLow {
newTemperature = temperatureLimitLow
}
if newTemperature > adjustedHigh {
newTemperature = adjustedHigh
}
} else {
let adjustedLow = temperatureLimitLow + separation
if newTemperature < adjustedLow {
newTemperature = adjustedLow
}
if newTemperature > temperatureLimitHigh {
newTemperature = temperatureLimitHigh
}
}
} else {
if newTemperature < temperatureLimitLow {
newTemperature = temperatureLimitLow
}
if newTemperature > temperatureLimitHigh {
newTemperature = temperatureLimitHigh
}
}
if activeHandle == .heatHandle {
viewModel.heatSetpoint = newTemperature
if viewModel.coolSetpoint < viewModel.heatSetpoint + separation {
viewModel.coolSetpoint = viewModel.heatSetpoint + separation
}
} else {
viewModel.coolSetpoint = newTemperature
if viewModel.heatSetpoint > viewModel.coolSetpoint - separation {
viewModel.heatSetpoint = viewModel.coolSetpoint - separation
}
}
}
private func toggleSelectedSetpoint() {
if activeHandle == .heatHandle {
activeHandle = .coolHandle
} else {
activeHandle = .heatHandle
}
configureView()
}
private func scheduleChangeEvent() {
changeScheduler.invalidate()
changeScheduler = Timer.scheduledTimer(timeInterval: debounceInterval,
target: self,
selector: #selector(emitChangeEvent),
userInfo: nil,
repeats: false)
}
}
| 35.720154 | 110 | 0.698052 |
1d2f0cfeca8e8cc688dd2280d8c7f92d8e5dfa07 | 995 | //
// TipsForTheLazyTests.swift
// TipsForTheLazyTests
//
// Created by Student on 12/31/15.
// Copyright © 2015 codepath. All rights reserved.
//
import XCTest
@testable import TipsForTheLazy
class TipsForTheLazyTests: 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.891892 | 111 | 0.643216 |
eb792e8fa15c4a178906c3a67e15564e9b802967 | 441 | //
// PeekTextOverlay.swift
// Peek
//
// Created by Shaps Benkau on 13/03/2018.
//
import UIKit
internal final class PeekTextOverlayView: PeekOverlayView {
private var textView: UITextView?
internal init(textView: UITextView) {
self.textView = textView
super.init()
}
internal required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 18.375 | 59 | 0.643991 |
9051b79549f964ce523672e82bcea460f89a97ad | 2,483 | //
// Simple Feed
// Copyright © 2020 Florian Herzog. All rights reserved.
//
import CoreData
import SimpleFeedCore
import UIKit
extension NewsFeedTVC {
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController<Article>? {
if internalFetchedResultsController != nil,
internalFetchedResultsController?.managedObjectContext == CoreDataService.shared.viewContext {
return internalFetchedResultsController!
}
let context = CoreDataService.shared.viewContext
let request: NSFetchRequest<Article> = Article.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
let aFetchedResultsController = NSFetchedResultsController(
fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil
)
aFetchedResultsController.delegate = self
internalFetchedResultsController = aFetchedResultsController
do {
try aFetchedResultsController.performFetch()
} catch {
print(error)
}
internalFetchedResultsController = aFetchedResultsController
return internalFetchedResultsController!
}
public func controllerWillChangeContent(_: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
public func controller(_: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .automatic)
case .delete:
UIView.animate(withDuration: 0.002) {
self.tableView.deleteRows(at: [indexPath!], with: .fade)
}
case .update:
guard let cell = tableView.cellForRow(at: indexPath!) as? ArticleCell, let article = anObject as? Article else { return }
configureCell(cell, withObject: article)
case .move:
tableView.moveRow(at: indexPath!, to: newIndexPath!)
@unknown default:
fatalError()
}
}
public func controllerDidChangeContent(_: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
setUpReadButton()
refreshHeaderView()
updateUnreadLabel()
}
}
| 35.985507 | 133 | 0.673782 |
3936dbfd967e0e41e3bf3515b609912ba805d674 | 3,552 | //
// HTTPDebugging.swift
// WolfNetwork
//
// Created by Wolf McNally on 6/3/16.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import WolfFoundation
extension URLRequest {
public func printRequest(includeAuxFields: Bool = false, level: Int = 0) {
print("➡️ \(httpMethod†) \(url†)".indented(level))
let level = level + 1
if let headers = allHTTPHeaderFields {
for (key, value) in headers {
print("\(key): \(value)".indented(level))
}
}
if let data = httpBody, data.count > 0 {
print("body:".indented(level))
let level = level + 1
// do {
// try print((data |> JSON.init).prettyString.indented(level))
// } catch {
print("Non-JSON Data: \(data)".indented(level))
// }
}
guard includeAuxFields else { return }
let cachePolicyStrings: [URLRequest.CachePolicy: String] = [
.useProtocolCachePolicy: ".useProtocolCachePolicy",
.reloadIgnoringLocalCacheData: ".reloadIgnoringLocalCacheData",
.returnCacheDataElseLoad: ".returnCacheDataElseLoad",
.returnCacheDataDontLoad: ".returnCacheDataDontLoad"
]
let networkServiceTypes: [URLRequest.NetworkServiceType: String]
if #available(iOS 10.0, *) {
networkServiceTypes = [
.`default`: ".default",
.voip: ".voip",
.video: ".video",
.background: ".background",
.voice: ".voice",
.callSignaling: ".callSignaling"
]
} else {
networkServiceTypes = [
.`default`: ".default",
.voip: ".voip",
.video: ".video",
.background: ".background",
.voice: ".voice"
]
}
print("timeoutInterval: \(timeoutInterval)".indented(level))
print("cachePolicy: \(cachePolicyStrings[cachePolicy]!)".indented(level))
print("allowsCellularAccess: \(allowsCellularAccess)".indented(level))
print("httpShouldHandleCookies: \(httpShouldHandleCookies)".indented(level))
print("httpShouldUsePipelining: \(httpShouldUsePipelining)".indented(level))
print("mainDocumentURL: \(mainDocumentURL†)".indented(level))
print("networkServiceType: \(networkServiceTypes[networkServiceType]!)".indented(level))
}
}
| 40.363636 | 96 | 0.622466 |
ed1d56b2b1e8a03c78553e13e1b0b3ecd7103071 | 226 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
func a {
var d {
init {
var d [ {
class
case ,
| 18.833333 | 87 | 0.721239 |
f5a1dcd64f6ccbb8a95ef28c78f2320c1cf75209 | 314 | //
// Define.swift
// CoreMLDemo
//
// Created by YZF on 2018/4/8.
// Copyright © 2018年 Xiaoye. All rights reserved.
//
import Foundation
import UIKit
let screenHeight = UIScreen.main.bounds.height
let screenWidth = UIScreen.main.bounds.width
let topHeight = UIApplication.shared.statusBarFrame.height + 44
| 19.625 | 63 | 0.745223 |
0ab6a1b6073bf44d8122cd8f595491e8df1e10b9 | 3,867 | //
// ScrollCollectionViewCell.swift
// IKS-0.0.0
//
// Created by Christoph Labacher on 11.05.15.
// Copyright (c) 2015 Made with ♥ in Schwäbisch Gmünd. All rights reserved.
//
import UIKit
class ScrollCollectionViewCell: UICollectionViewCell {
var data : Card!
var cardColor : UIColor = UIColor.grayColor()
let card : UIView!
let imageView: UIImageView!
let borderTop : UIView = UIView()
let borderRight : UIView = UIView()
let borderBottom : UIView = UIView()
let borderLeft : UIView = UIView()
let blurEffectView : UIVisualEffectView!
override init(frame: CGRect) {
card = UIView();
card.backgroundColor = UIColor.whiteColor();
card.layer.cornerRadius = 4;
card.clipsToBounds = true
card.setTranslatesAutoresizingMaskIntoConstraints(false)
card.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
card.alpha = 0.4
imageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
card.addSubview(imageView)
let borderWidth : CGFloat = 3.0
borderTop.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: borderWidth)
borderTop.backgroundColor = appColorBlue
card.addSubview(borderTop)
borderRight.frame = CGRect(x: frame.size.width - borderWidth, y: borderWidth, width: borderWidth, height: frame.size.height - (borderWidth*2))
borderRight.backgroundColor = appColorBlue
card.addSubview(borderRight)
borderBottom.frame = CGRect(x: 0, y: frame.size.height - borderWidth, width: frame.size.width, height: borderWidth)
borderBottom.backgroundColor = appColorBlue
card.addSubview(borderBottom)
borderLeft.frame = CGRect(x: 0, y: borderWidth, width: borderWidth, height: frame.size.height - (borderWidth*2))
borderLeft.backgroundColor = appColorBlue
card.addSubview(borderLeft)
borderTop.backgroundColor = UIColor.clearColor()
borderBottom.backgroundColor = UIColor.clearColor()
borderLeft.backgroundColor = UIColor.clearColor()
borderRight.backgroundColor = UIColor.clearColor()
// Card > BlurEffect
//////////////////////////
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = card.frame
//blurEffectView.alpha = 0
// blurEffectView.setTranslatesAutoresizingMaskIntoConstraints(false)
card.addSubview(blurEffectView)
super.init(frame: frame)
contentView.addSubview(card)
}
func initCard(indexPath : NSIndexPath) {
self.data.scrollCollectionViewIndexPath = indexPath
//println("ItemAt: \(self.data.scrollCollectionViewIndexPath)")
cardColor = colors[data!.type]!
imageView.image = UIImage(named: data!.coverImage)
borderTop.backgroundColor = cardColor
borderLeft.backgroundColor = cardColor
borderRight.backgroundColor = cardColor
borderBottom.backgroundColor = cardColor
}
func isActive() {
self.blurEffectView.alpha = 0
}
func becomeActive() {
UIView.animateWithDuration(0.8, animations: {
self.blurEffectView.alpha = 0
self.data.hasBecomeActive = true
})
}
func wasRead() {
UIView.animateWithDuration(0.8, animations: {
self.borderTop.backgroundColor = UIColor.clearColor()
self.borderLeft.backgroundColor = UIColor.clearColor()
self.borderRight.backgroundColor = UIColor.clearColor()
})
}
func wasSelected() {
UIView.animateWithDuration(0.2, animations: {
self.card.alpha = 1
})
}
func wasDeselected() {
UIView.animateWithDuration(0.2, animations: {
self.card.alpha = 0.3
})
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
self.blurEffectView.alpha = 1
self.card.alpha = 0.3
}
}
| 28.644444 | 144 | 0.732092 |
91bfd210ddd626c59b7dfbf0b074d754d2fd0c7a | 2,933 | //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// THIS FILE IS REGENERATED BY EASY BINDINGS, ONLY MODIFY IT WITHIN USER ZONES
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
import Cocoa
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
//--- START OF USER ZONE 1
//--- END OF USER ZONE 1
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
func transient_PackageRoot_issues (
_ self_packageObjects_issues : [PackageObject_issues],
_ self_packageZones_rect : [PackageZone_rect],
_ self_packageZones_zoneName : [PackageZone_zoneName],
_ self_packageZones_xName : [PackageZone_xName],
_ self_packageZones_yName : [PackageZone_yName],
_ prefs_padZoneFont : NSFont
) -> CanariIssueArray {
//--- START OF USER ZONE 2
var issues = CanariIssueArray ()
//--- collect intersecting zones
var idx = 0
while idx < self_packageZones_rect.count {
var idy = idx + 1
while idy < self_packageZones_rect.count {
let intersection = self_packageZones_rect [idx].rect!.intersection (self_packageZones_rect [idy].rect!)
if !intersection.isEmpty {
issues.appendZoneIntersectionIssueIn (rect: intersection)
}
idy += 1
}
idx += 1
}
//--- Collect name collisions
var nameDictionary = [String : Int] ()
for zone in self_packageZones_zoneName {
if zone.zoneName != "" {
let d = nameDictionary [zone.zoneName] ?? 0
nameDictionary [zone.zoneName] = d + 1
}
}
idx = 0
while idx < self_packageZones_zoneName.count {
let zoneName = self_packageZones_zoneName [idx].zoneName
if let c = nameDictionary [zoneName], c > 1 {
let p = CanariPoint (x: self_packageZones_xName [idx].xName, y: self_packageZones_yName [idx].yName).cocoaPoint
let textAttributes : [NSAttributedString.Key : Any] = [
NSAttributedString.Key.font : prefs_padZoneFont
]
var shape = EBShape ()
shape.add (text: zoneName, p, textAttributes, .center, .center)
issues.appendDuplicatedZoneNameIssueIn (rect: shape.boundingBox)
}
idx += 1
}
//--- Collect issues
for optionalIssueArray in self_packageObjects_issues {
if let issueArray = optionalIssueArray.issues {
issues += issueArray
}
}
//-------------------- Sort issues
// issues.sort (by: CanariIssue.displaySortingCompare)
//---
return issues
//--- END OF USER ZONE 2
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
| 39.106667 | 120 | 0.502898 |
46328d4e759477deabcf575a22ad72f7323a27be | 6,511 | //
// Copyright (c) 2019 Daniel Rinser and contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
/// A `ReturningFunctionMock` allows to record the calls to a retuning function, but in
/// addition to a `FunctionMock` it also allows to statically or dynamically stub the return
/// value of the function.
///
/// The returning function mock is generic over the function's arguments' types and its
/// return value. The generic parameter `Args` is usually a tuple of size n where n is the
/// number of the function's arguments.
///
/// For a function with this signature
///
/// func doSomething(arg1: String, arg2: [Int]) -> Int
///
/// declare the function mock like this:
///
/// let doSomethingFunc = ReturningFunctionMock<(String, [Int]), Int>(name: "doSomething(arg1:arg2:)")
///
public class ReturningFunctionMock<Args, ReturnValue>: FunctionMock<Args> {
private var stubs: [FunctionStub<Args, ReturnValue>] = []
/// A return value that is used as a default.
public var defaultReturnValue: ReturnValue?
/// Reset the mock to its initial state. This will set the call count to 0,
/// remove any recorded arguments and remove any stubs.
public override func reset() {
super.reset()
defaultReturnValue = nil
stubs.removeAll()
}
// MARK: - Call
/// Record a call of the mocked function and return a stubbed return value.
///
/// - parameters:
/// - args: The arguments that the mocked function has been called with.
public func recordCallAndReturn(_ args: Args) -> ReturnValue {
recordCall(args)
// stub return value
guard let stub = stubs.first(where: { $0.shouldHandle(args) }) else {
if let returnValue = defaultReturnValue {
return returnValue
}
preconditionFailure("No return value for \(name ?? "function")")
}
return stub.handle(args)
}
// MARK: - Stubbing
/// Stub a static return value that is used by `recordCallAndReturn(_:)`, with an
/// optional condition closure.
///
/// - parameters:
/// - returnValue: The return value to use.
/// - condition: An optional closure that is used to select whether this return value
/// should be used. If the closure returns `true`, the return value will
/// be used; if it returns `false`, it will be skipped. If the
/// condition closure is `nil`, the return value will always be used.
public func returns(_ returnValue: ReturnValue, when condition: ((Args) -> Bool)? = nil) {
let stub = FunctionStub<Args, ReturnValue>(returnValue: returnValue, condition: condition)
stubs.append(stub)
}
/// Stub a dynamic return value that is used by `recordCallAndReturn(_:)`.
///
/// - parameters:
/// - handler: A closure that returns the value to be used as return value.
/// - args: The arguments of the original call to the mocked function.
public func returns(_ handler: @escaping (_ args: Args) -> ReturnValue) {
returns(handler, when: nil)
}
/// Stub a dynamic return value that is used by `recordCallAndReturn(_:)`, with an
/// optional condition closure.
///
/// - parameters:
/// - handler: A closure that returns the value to be used as return value.
/// - args: The arguments of the original call to the mocked function.
/// - condition: An optional closure that is used to select whether this return value
/// should be used. If the closure returns `true`, the return value will
/// be used; if it returns `false`, it will be skipped. If the
/// condition closure is `nil`, the return value will always be used.
public func returns(_ handler: @escaping (_ args: Args) -> ReturnValue, when condition: ((Args) -> Bool)? = nil) {
let stub = FunctionStub<Args, ReturnValue>(handler: handler, condition: condition)
stubs.append(stub)
}
// MARK: - FunctionStub
/// Used internally to represent a static or dynamic stubbed return
/// value with an optional condition.
private class FunctionStub<Args, ReturnValue> {
private enum Mode {
case staticReturnValue(ReturnValue) // returns(42)
case handler((Args) -> ReturnValue) // returns { return $0 / 2 }
}
private let condition: ((Args) -> Bool)?
private let mode: Mode
init(returnValue: ReturnValue, condition: ((Args) -> Bool)?) {
self.mode = .staticReturnValue(returnValue)
self.condition = condition
}
init(handler: @escaping (Args) -> ReturnValue, condition: ((Args) -> Bool)?) {
self.mode = .handler(handler)
self.condition = condition
}
func shouldHandle(_ args: Args) -> Bool {
guard let condition = self.condition else { return true }
return condition(args)
}
func handle(_ args: Args) -> ReturnValue {
switch self.mode {
case .staticReturnValue(let returnValue):
return returnValue
case .handler(let handler):
return handler(args)
}
}
}
}
| 42.006452 | 118 | 0.631239 |
469655d024fa0eab1b508022740930f4cbfbd497 | 7,254 | //
// ExampleOptionsViewController.swift
// JZCalendarViewExample
//
// Created by Jeff Zhang on 6/4/18.
// Copyright © 2018 Jeff Zhang. All rights reserved.
//
import UIKit
import JZCalendarWeekView
protocol OptionsViewDelegate: class {
func finishUpdate(selectedData: OptionsSelectedData)
}
class ExampleOptionsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var viewModel: OptionsViewModel!
weak var delegate: OptionsViewDelegate?
override func viewDidLoad() {
super.viewDidLoad()
setupBasic()
setupTableView()
}
func setupBasic() {
self.automaticallyAdjustsScrollViewInsets = false
view.backgroundColor = UIColor.white
navigationItem.title = "Options"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(onBtnDoneTapped))
}
func setupTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 60
tableView.tableFooterView = UIView(frame: .zero)
tableView.sectionHeaderHeight = 44
tableView.separatorStyle = .none
tableView.register(UINib(nibName: OptionsTableViewCell.className, bundle: nil), forCellReuseIdentifier: OptionsTableViewCell.className)
tableView.register(UINib(nibName: ExpandableHeaderView.className, bundle: nil), forHeaderFooterViewReuseIdentifier: ExpandableHeaderView.className)
}
@objc func onBtnDoneTapped() {
var optionalScrollType: JZScrollType?
var optionalHourGridDivision: JZHourGridDivision?
var firstDayOfWeek: DayOfWeek?
let dataList = viewModel.optionsData
let scrollableRange: (Date?, Date?)
if dataList[2].selectedValue as? Int == 7 {
firstDayOfWeek = dataList[3].selectedValue as? DayOfWeek
optionalScrollType = dataList[4].selectedValue as? JZScrollType
optionalHourGridDivision = dataList[5].selectedValue as? JZHourGridDivision
scrollableRange = (dataList[6].selectedValue as? Date, dataList[7].selectedValue as? Date)
} else {
optionalScrollType = dataList[3].selectedValue as? JZScrollType
optionalHourGridDivision = dataList[4].selectedValue as? JZHourGridDivision
scrollableRange = (dataList[5].selectedValue as? Date, dataList[6].selectedValue as? Date)
}
guard
let viewType = dataList[0].selectedValue as? ViewType,
let scrollType = optionalScrollType,
let hourGridDivision = optionalHourGridDivision,
let date = dataList[1].selectedValue as? Date,
let numOfDays = dataList[2].selectedValue as? Int else { return }
let selectedData = OptionsSelectedData(viewType: viewType,
date: date,
numOfDays: numOfDays,
scrollType: scrollType,
firstDayOfWeek: firstDayOfWeek,
hourGridDivision: hourGridDivision,
scrollableRange: scrollableRange)
guard viewType == viewModel.perviousSelectedData.viewType else {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc: UIViewController
switch viewType {
case .defaultView:fatalError()
// vc = mainStoryboard.instantiateViewController(withIdentifier: DefaultViewController.className)
// (vc as? DefaultViewController)?.viewModel.currentSelectedData = selectedData
case .customView:fatalError()
// vc = mainStoryboard.instantiateViewController(withIdentifier: CustomViewController.className)
// (vc as? CustomViewController)?.viewModel.currentSelectedData = selectedData
case .longPressView:
vc = mainStoryboard.instantiateViewController(withIdentifier: LongPressViewController.className)
(vc as? LongPressViewController)?.viewModel.currentSelectedData = selectedData
}
(UIApplication.shared.keyWindow?.rootViewController as? UINavigationController)?.viewControllers = [vc]
self.dismiss(animated: true, completion: nil)
return
}
delegate?.finishUpdate(selectedData: selectedData)
self.dismiss(animated: true, completion: nil)
}
}
extension ExampleOptionsViewController: UITableViewDelegate, UITableViewDataSource, ExpandableHeaderViewDelegate, OptionsCellDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.optionsData.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return viewModel.optionsData[indexPath.section].isExpanded ? UITableView.automaticDimension : 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: OptionsTableViewCell.className, for: indexPath) as? OptionsTableViewCell else {
preconditionFailure("OptionsTableViewCell should be casted")
}
cell.updateCell(data: viewModel.optionsData[indexPath.section], section: indexPath.section)
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: ExpandableHeaderView.className) as? ExpandableHeaderView else {
preconditionFailure("ExpandableHeaderView should be casted")
}
headerView.updateHeaderView(section: section, title: viewModel.optionsData[section].subject.rawValue, subTitle: viewModel.getHeaderViewSubtitle(section))
headerView.delegate = self
return headerView
}
func toggleSection(section: Int) {
viewModel.optionsData[section].isExpanded = !viewModel.optionsData[section].isExpanded
tableView.beginUpdates()
tableView.reloadRows(at: [IndexPath(row: 0, section: section)], with: .automatic)
tableView.endUpdates()
}
func selectedValueChanged(section: Int) {
guard let headerView = tableView.headerView(forSection: section) as? ExpandableHeaderView else { return }
headerView.lblSelectedValue.text = viewModel.getHeaderViewSubtitle(section)
if section == 2 {
if viewModel.optionsData[2].selectedIndex == 6 && viewModel.optionsData[3].subject != .firstDayOfWeek {
viewModel.insertDayOfWeekToData(firstDayOfWeek: .Sunday)
tableView.reloadData()
}
if viewModel.optionsData[2].selectedIndex != 6 && viewModel.optionsData[3].subject == .firstDayOfWeek {
viewModel.removeDayOfWeekInData()
tableView.reloadData()
}
}
}
}
| 46.203822 | 161 | 0.672594 |
f46ffcd8e394ea5e59d2d7d6ec26de2cd52360b4 | 23,907 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
@_exported import SotoCore
/// Service object for interacting with AWS OpenSearchService service.
///
/// Amazon OpenSearch Configuration Service Use the Amazon OpenSearch configuration API to create, configure, and manage Amazon OpenSearch Service domains. For sample code that uses the configuration API, see the Amazon OpenSearch Service Developer Guide. The guide also contains sample code for sending signed HTTP requests to the OpenSearch APIs. The endpoint for configuration service requests is region-specific: es.region.amazonaws.com. For example, es.us-east-1.amazonaws.com. For a current list of supported regions and endpoints, see Regions and Endpoints.
public struct OpenSearchService: AWSService {
// MARK: Member variables
/// Client used for communication with AWS
public let client: AWSClient
/// Service configuration
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the OpenSearchService client
/// - parameters:
/// - client: AWSClient used to process requests
/// - region: Region of server you want to communicate with. This will override the partition parameter.
/// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov).
/// - endpoint: Custom endpoint URL to use instead of standard AWS servers
/// - timeout: Timeout value for HTTP requests
public init(
client: AWSClient,
region: SotoCore.Region? = nil,
partition: AWSPartition = .aws,
endpoint: String? = nil,
timeout: TimeAmount? = nil,
byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(),
options: AWSServiceConfig.Options = []
) {
self.client = client
self.config = AWSServiceConfig(
region: region,
partition: region?.partition ?? partition,
service: "es",
serviceProtocol: .restjson,
apiVersion: "2021-01-01",
endpoint: endpoint,
errorType: OpenSearchServiceErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Allows the remote domain owner to accept an inbound cross-cluster connection request.
public func acceptInboundConnection(_ input: AcceptInboundConnectionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AcceptInboundConnectionResponse> {
return self.client.execute(operation: "AcceptInboundConnection", path: "/2021-01-01/opensearch/cc/inboundConnection/{ConnectionId}/accept", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Attaches tags to an existing domain. Tags are a set of case-sensitive key value pairs. An domain can have up to 10 tags. See Tagging Amazon OpenSearch Service domains for more information.
@discardableResult public func addTags(_ input: AddTagsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "AddTags", path: "/2021-01-01/tags", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Associates a package with an Amazon OpenSearch Service domain.
public func associatePackage(_ input: AssociatePackageRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AssociatePackageResponse> {
return self.client.execute(operation: "AssociatePackage", path: "/2021-01-01/packages/associate/{PackageID}/{DomainName}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Cancels a scheduled service software update for an Amazon OpenSearch Service domain. You can only perform this operation before the AutomatedUpdateDate and when the UpdateStatus is in the PENDING_UPDATE state.
public func cancelServiceSoftwareUpdate(_ input: CancelServiceSoftwareUpdateRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CancelServiceSoftwareUpdateResponse> {
return self.client.execute(operation: "CancelServiceSoftwareUpdate", path: "/2021-01-01/opensearch/serviceSoftwareUpdate/cancel", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new Amazon OpenSearch Service domain. For more information, see Creating and managing Amazon OpenSearch Service domains in the Amazon OpenSearch Service Developer Guide.
public func createDomain(_ input: CreateDomainRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateDomainResponse> {
return self.client.execute(operation: "CreateDomain", path: "/2021-01-01/opensearch/domain", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new cross-cluster connection from a local OpenSearch domain to a remote OpenSearch domain.
public func createOutboundConnection(_ input: CreateOutboundConnectionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateOutboundConnectionResponse> {
return self.client.execute(operation: "CreateOutboundConnection", path: "/2021-01-01/opensearch/cc/outboundConnection", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Create a package for use with Amazon OpenSearch Service domains.
public func createPackage(_ input: CreatePackageRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreatePackageResponse> {
return self.client.execute(operation: "CreatePackage", path: "/2021-01-01/packages", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Permanently deletes the specified domain and all of its data. Once a domain is deleted, it cannot be recovered.
public func deleteDomain(_ input: DeleteDomainRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteDomainResponse> {
return self.client.execute(operation: "DeleteDomain", path: "/2021-01-01/opensearch/domain/{DomainName}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Allows the remote domain owner to delete an existing inbound cross-cluster connection.
public func deleteInboundConnection(_ input: DeleteInboundConnectionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteInboundConnectionResponse> {
return self.client.execute(operation: "DeleteInboundConnection", path: "/2021-01-01/opensearch/cc/inboundConnection/{ConnectionId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Allows the local domain owner to delete an existing outbound cross-cluster connection.
public func deleteOutboundConnection(_ input: DeleteOutboundConnectionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteOutboundConnectionResponse> {
return self.client.execute(operation: "DeleteOutboundConnection", path: "/2021-01-01/opensearch/cc/outboundConnection/{ConnectionId}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the package.
public func deletePackage(_ input: DeletePackageRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeletePackageResponse> {
return self.client.execute(operation: "DeletePackage", path: "/2021-01-01/packages/{PackageID}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns domain configuration information about the specified domain, including the domain ID, domain endpoint, and domain ARN.
public func describeDomain(_ input: DescribeDomainRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDomainResponse> {
return self.client.execute(operation: "DescribeDomain", path: "/2021-01-01/opensearch/domain/{DomainName}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Provides scheduled Auto-Tune action details for the domain, such as Auto-Tune action type, description, severity, and scheduled date.
public func describeDomainAutoTunes(_ input: DescribeDomainAutoTunesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDomainAutoTunesResponse> {
return self.client.execute(operation: "DescribeDomainAutoTunes", path: "/2021-01-01/opensearch/domain/{DomainName}/autoTunes", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Provides cluster configuration information about the specified domain, such as the state, creation date, update version, and update date for cluster options.
public func describeDomainConfig(_ input: DescribeDomainConfigRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDomainConfigResponse> {
return self.client.execute(operation: "DescribeDomainConfig", path: "/2021-01-01/opensearch/domain/{DomainName}/config", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns domain configuration information about the specified domains, including the domain ID, domain endpoint, and domain ARN.
public func describeDomains(_ input: DescribeDomainsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeDomainsResponse> {
return self.client.execute(operation: "DescribeDomains", path: "/2021-01-01/opensearch/domain-info", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists all the inbound cross-cluster connections for a remote domain.
public func describeInboundConnections(_ input: DescribeInboundConnectionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeInboundConnectionsResponse> {
return self.client.execute(operation: "DescribeInboundConnections", path: "/2021-01-01/opensearch/cc/inboundConnection/search", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describe the limits for a given instance type and OpenSearch or Elasticsearch version. When modifying an existing domain, specify the DomainName to see which limits you can modify.
public func describeInstanceTypeLimits(_ input: DescribeInstanceTypeLimitsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeInstanceTypeLimitsResponse> {
return self.client.execute(operation: "DescribeInstanceTypeLimits", path: "/2021-01-01/opensearch/instanceTypeLimits/{EngineVersion}/{InstanceType}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists all the outbound cross-cluster connections for a local domain.
public func describeOutboundConnections(_ input: DescribeOutboundConnectionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeOutboundConnectionsResponse> {
return self.client.execute(operation: "DescribeOutboundConnections", path: "/2021-01-01/opensearch/cc/outboundConnection/search", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Describes all packages available to Amazon OpenSearch Service domains. Includes options for filtering, limiting the number of results, and pagination.
public func describePackages(_ input: DescribePackagesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribePackagesResponse> {
return self.client.execute(operation: "DescribePackages", path: "/2021-01-01/packages/describe", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists available reserved OpenSearch instance offerings.
public func describeReservedInstanceOfferings(_ input: DescribeReservedInstanceOfferingsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeReservedInstanceOfferingsResponse> {
return self.client.execute(operation: "DescribeReservedInstanceOfferings", path: "/2021-01-01/opensearch/reservedInstanceOfferings", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns information about reserved OpenSearch instances for this account.
public func describeReservedInstances(_ input: DescribeReservedInstancesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeReservedInstancesResponse> {
return self.client.execute(operation: "DescribeReservedInstances", path: "/2021-01-01/opensearch/reservedInstances", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Dissociates a package from the Amazon OpenSearch Service domain.
public func dissociatePackage(_ input: DissociatePackageRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DissociatePackageResponse> {
return self.client.execute(operation: "DissociatePackage", path: "/2021-01-01/packages/dissociate/{PackageID}/{DomainName}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of upgrade-compatible versions of OpenSearch/Elasticsearch. You can optionally pass a DomainName to get all upgrade-compatible versions of OpenSearch/Elasticsearch for that specific domain.
public func getCompatibleVersions(_ input: GetCompatibleVersionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetCompatibleVersionsResponse> {
return self.client.execute(operation: "GetCompatibleVersions", path: "/2021-01-01/opensearch/compatibleVersions", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of package versions, along with their creation time and commit message.
public func getPackageVersionHistory(_ input: GetPackageVersionHistoryRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetPackageVersionHistoryResponse> {
return self.client.execute(operation: "GetPackageVersionHistory", path: "/2021-01-01/packages/{PackageID}/history", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Retrieves the complete history of the last 10 upgrades performed on the domain.
public func getUpgradeHistory(_ input: GetUpgradeHistoryRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetUpgradeHistoryResponse> {
return self.client.execute(operation: "GetUpgradeHistory", path: "/2021-01-01/opensearch/upgradeDomain/{DomainName}/history", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Retrieves the latest status of the last upgrade or upgrade eligibility check performed on the domain.
public func getUpgradeStatus(_ input: GetUpgradeStatusRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetUpgradeStatusResponse> {
return self.client.execute(operation: "GetUpgradeStatus", path: "/2021-01-01/opensearch/upgradeDomain/{DomainName}/status", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns the names of all domains owned by the current user's account.
public func listDomainNames(_ input: ListDomainNamesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDomainNamesResponse> {
return self.client.execute(operation: "ListDomainNames", path: "/2021-01-01/domain", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists all Amazon OpenSearch Service domains associated with the package.
public func listDomainsForPackage(_ input: ListDomainsForPackageRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListDomainsForPackageResponse> {
return self.client.execute(operation: "ListDomainsForPackage", path: "/2021-01-01/packages/{PackageID}/domains", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
public func listInstanceTypeDetails(_ input: ListInstanceTypeDetailsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListInstanceTypeDetailsResponse> {
return self.client.execute(operation: "ListInstanceTypeDetails", path: "/2021-01-01/opensearch/instanceTypeDetails/{EngineVersion}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists all packages associated with the Amazon OpenSearch Service domain.
public func listPackagesForDomain(_ input: ListPackagesForDomainRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPackagesForDomainResponse> {
return self.client.execute(operation: "ListPackagesForDomain", path: "/2021-01-01/domain/{DomainName}/packages", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns all tags for the given domain.
public func listTags(_ input: ListTagsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsResponse> {
return self.client.execute(operation: "ListTags", path: "/2021-01-01/tags/", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// List all supported versions of OpenSearch and Elasticsearch.
public func listVersions(_ input: ListVersionsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListVersionsResponse> {
return self.client.execute(operation: "ListVersions", path: "/2021-01-01/opensearch/versions", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Allows you to purchase reserved OpenSearch instances.
public func purchaseReservedInstanceOffering(_ input: PurchaseReservedInstanceOfferingRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PurchaseReservedInstanceOfferingResponse> {
return self.client.execute(operation: "PurchaseReservedInstanceOffering", path: "/2021-01-01/opensearch/purchaseReservedInstanceOffering", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Allows the remote domain owner to reject an inbound cross-cluster connection request.
public func rejectInboundConnection(_ input: RejectInboundConnectionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<RejectInboundConnectionResponse> {
return self.client.execute(operation: "RejectInboundConnection", path: "/2021-01-01/opensearch/cc/inboundConnection/{ConnectionId}/reject", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Removes the specified set of tags from the given domain.
@discardableResult public func removeTags(_ input: RemoveTagsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "RemoveTags", path: "/2021-01-01/tags-removal", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Schedules a service software update for an Amazon OpenSearch Service domain.
public func startServiceSoftwareUpdate(_ input: StartServiceSoftwareUpdateRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartServiceSoftwareUpdateResponse> {
return self.client.execute(operation: "StartServiceSoftwareUpdate", path: "/2021-01-01/opensearch/serviceSoftwareUpdate/start", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Modifies the cluster configuration of the specified domain, such as setting the instance type and the number of instances.
public func updateDomainConfig(_ input: UpdateDomainConfigRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateDomainConfigResponse> {
return self.client.execute(operation: "UpdateDomainConfig", path: "/2021-01-01/opensearch/domain/{DomainName}/config", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates a package for use with Amazon OpenSearch Service domains.
public func updatePackage(_ input: UpdatePackageRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdatePackageResponse> {
return self.client.execute(operation: "UpdatePackage", path: "/2021-01-01/packages/update", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Allows you to either upgrade your domain or perform an upgrade eligibility check to a compatible version of OpenSearch or Elasticsearch.
public func upgradeDomain(_ input: UpgradeDomainRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpgradeDomainResponse> {
return self.client.execute(operation: "UpgradeDomain", path: "/2021-01-01/opensearch/upgradeDomain", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension OpenSearchService {
/// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public
/// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead.
public init(from: OpenSearchService, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
| 89.205224 | 567 | 0.755218 |
db190126324715dda1dc20a0d3d97ab008bfa625 | 3,100 | // Copyright (c) 2015 Petr Zvoníček <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE
//
// ActivityIndicator.swift
// ImageSlideshow
//
// Created by Petr Zvoníček on 01.05.17.
//
import UIKit
/// Cusotm Activity Indicator can be used by implementing this protocol
protocol ActivityIndicatorView {
/// View of the activity indicator
var view: UIView { get }
/// Show activity indicator
func show()
/// Hide activity indicator
func hide()
}
/// Factory protocol to create new ActivityIndicatorViews. Meant to be implemented when creating custom activity indicator.
protocol ActivityIndicatorFactory {
func create() -> ActivityIndicatorView
}
/// Default ActivityIndicatorView implementation for UIActivityIndicatorView
extension UIActivityIndicatorView: ActivityIndicatorView {
public var view: UIView {
return self
}
public func show() {
startAnimating()
}
public func hide() {
stopAnimating()
}
}
/// Default activity indicator factory creating UIActivityIndicatorView instances
@objcMembers
class DefaultActivityIndicator: ActivityIndicatorFactory {
/// activity indicator style
open var style: UIActivityIndicatorViewStyle
/// activity indicator color
open var color: UIColor?
/// Create a new ActivityIndicator for UIActivityIndicatorView
///
/// - style: activity indicator style
/// - color: activity indicator color
public init(style: UIActivityIndicatorViewStyle = .gray, color: UIColor? = nil) {
self.style = style
self.color = color
}
/// create ActivityIndicatorView instance
open func create() -> ActivityIndicatorView {
#if swift(>=4.2)
let activityIndicator = UIActivityIndicatorView(style: style)
#else
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: style)
#endif
activityIndicator.color = color
activityIndicator.hidesWhenStopped = true
return activityIndicator
}
}
| 33.333333 | 123 | 0.720968 |
5b78fe2b8c66fb777abad5dd12a96ae0ba11588e | 1,402 | //
// RingLinkedList.swift
// LinkedList
//
// Created by ggl on 2019/3/28.
// Copyright © 2019年 ggl. All rights reserved.
// 带环的链表
import Foundation
class RingLinkedList {
/// 头结点
var head: Node?
/// 环的位置
var ringPos: UInt
init(count: UInt, ringPos: UInt) {
self.ringPos = ringPos
if count == 0 {
return
}
head = Node(data: 1, next: nil)
var p = head
var ringNode = head
var tail = head
for i in 1..<Int(count) {
let node = Node(data: i+1, next: nil)
p?.next = node
p = node
if i == Int(ringPos) {
ringNode = node
} else if i == Int(count) - 1 {
tail = node
}
}
tail?.next = ringNode
}
/// 打印带有环的链表
func print() {
var p: Node? = head
var ringNode = head
var count = 0
for i in 0..<Int.max {
if count == 1 && p == ringNode {
break
}
if i == self.ringPos {
ringNode = p
count = 1
Swift.print("[\(p!.data)]", terminator: " -> ")
} else {
Swift.print(p!.data, terminator: " -> ")
}
p = p?.next
}
Swift.print("")
}
}
| 21.90625 | 63 | 0.407275 |
bbecd1b61f3e5f5bd6a9377ae8515b8b290b1abb | 962 | import Foundation
import UIKit
import ALLKit
struct GalleryItem {
let name: String
let images: [URL]
}
final class MultiGalleriesViewController: ListViewController<UICollectionView, UICollectionViewCell> {
override func viewDidLoad() {
super.viewDidLoad()
let listItems = DemoContent.NATO.map { name -> ListItem<DemoContext> in
let images = (0..<100).map { _ in URL(string: "https://picsum.photos/200/150?random&q=\(Int.random(in: 1..<1000))")! }
let listItem = ListItem<DemoContext>(
id: name,
layoutSpec: GalleryItemLayoutSpec(model: GalleryItem(name: name, images: images))
)
return listItem
}
adapter.set(items: listItems)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
adapter.set(boundingDimensions: CGSize(width: view.bounds.width, height: .nan).layoutDimensions)
}
}
| 28.294118 | 130 | 0.64657 |
50063965b6bc0da979dc71d187f24826f632106c | 1,403 | //
// MockRendererCommand.swift
// ProtonTests
//
// Created by Rajdeep Kwatra on 9/4/20.
// Copyright © 2020 Rajdeep Kwatra. 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
import UIKit
import Proton
class MockRendererCommand: RendererCommand {
var onCanExecute: (RendererView) -> Bool
var onExecute: (RendererView) -> Void
let name: CommandName
init(name: String = "_MockRendererCommand", onCanExecute: @escaping ((RendererView) -> Bool) = { _ in true },
onExecute: @escaping ((RendererView) -> Void)) {
self.name = CommandName(name)
self.onCanExecute = onCanExecute
self.onExecute = onExecute
}
func canExecute(on renderer: RendererView) -> Bool {
return onCanExecute(renderer)
}
func execute(on renderer: RendererView) {
onExecute(renderer)
}
}
| 30.5 | 113 | 0.695652 |
33eefb42f425f82d123bb17e51b27b606ca007e6 | 3,799 | //
// Swipe.swift
// Eureka
//
// Created by Marco Betschart on 14.06.17.
// Copyright © 2017 Xmartlabs. All rights reserved.
//
import Foundation
public typealias SwipeActionHandler = (SwipeAction, BaseRow, ((Bool) -> Void)?) -> Void
public class SwipeAction: ContextualAction {
let handler: SwipeActionHandler
let style: Style
public var backgroundColor: UIColor?
public var image: UIImage?
public var title: String?
public init(style: Style, title: String?, handler: @escaping SwipeActionHandler){
self.style = style
self.title = title
self.handler = handler
}
func contextualAction(forRow: BaseRow) -> ContextualAction {
var action: ContextualAction
if #available(iOS 11, *){
action = UIContextualAction(style: style.contextualStyle as! UIContextualAction.Style, title: title){ [weak self] action, view, completion -> Void in
guard let strongSelf = self else{ return }
strongSelf.handler(strongSelf, forRow, completion)
}
} else {
action = UITableViewRowAction(style: style.contextualStyle as! UITableViewRowActionStyle,title: title){ [weak self] (action, indexPath) -> Void in
guard let strongSelf = self else{ return }
strongSelf.handler(strongSelf, forRow) { _ in
DispatchQueue.main.async {
guard action.style == .destructive else {
forRow.baseCell?.formViewController()?.tableView?.setEditing(false, animated: true)
return
}
forRow.section?.remove(at: indexPath.row)
}
}
}
}
if let color = self.backgroundColor {
action.backgroundColor = color
}
if let image = self.image {
action.image = image
}
return action
}
public enum Style{
case normal
case destructive
var contextualStyle: ContextualStyle {
if #available(iOS 11, *){
switch self{
case .normal:
return UIContextualAction.Style.normal
case .destructive:
return UIContextualAction.Style.destructive
}
} else {
switch self{
case .normal:
return UITableViewRowActionStyle.normal
case .destructive:
return UITableViewRowActionStyle.destructive
}
}
}
}
}
public struct SwipeConfiguration {
unowned var row: BaseRow
init(_ row: BaseRow){
self.row = row
}
public var performsFirstActionWithFullSwipe = false
public var actions: [SwipeAction] = []
}
extension SwipeConfiguration {
@available(iOS 11.0, *)
var contextualConfiguration: UISwipeActionsConfiguration? {
let contextualConfiguration = UISwipeActionsConfiguration(actions: self.contextualActions as! [UIContextualAction])
contextualConfiguration.performsFirstActionWithFullSwipe = self.performsFirstActionWithFullSwipe
return contextualConfiguration
}
var contextualActions: [ContextualAction]{
return self.actions.map { $0.contextualAction(forRow: self.row) }
}
}
protocol ContextualAction {
var backgroundColor: UIColor? { get set }
var image: UIImage? { get set }
var title: String? { get set }
}
extension UITableViewRowAction: ContextualAction {
public var image: UIImage? {
get { return nil }
set { return }
}
}
@available(iOS 11.0, *)
extension UIContextualAction: ContextualAction {}
public protocol ContextualStyle{}
extension UITableViewRowActionStyle: ContextualStyle {}
@available(iOS 11.0, *)
extension UIContextualAction.Style: ContextualStyle {}
| 29.913386 | 161 | 0.633851 |
21b952cc34f5d87d7c3384edb069dc033adb7803 | 14,969 | import XCTest
import Cuckoo
@testable import AccountSDKIOSWeb
final class MigratingKeychainCompatStorageTests: XCTestCase {
func testStoreOnlyWritesToNewStorage() {
let userSession = UserSession(clientId: "client1", userTokens: Fixtures.userTokens, updatedAt: Date())
let legacyStorage = MockLegacyKeychainSessionStorage()
let newStorage = MockKeychainSessionStorage(service: "test")
stub(newStorage) { mock in
when(mock.store(equal(to: userSession), accessGroup: any(), completion: anyClosure())).then { _, _, completion in
completion(.success())
}
}
let migratingStorage = MigratingKeychainCompatStorage(from: legacyStorage,
to: newStorage,
legacyClient: Client(configuration: Fixtures.clientConfig),
legacyClientSecret: "",
makeTokenRequest: { _, _, _ in })
migratingStorage.store(userSession, accessGroup: nil) { _ in }
verify(newStorage).store(equal(to: userSession), accessGroup: any(), completion: anyClosure())
verifyNoMoreInteractions(legacyStorage)
}
func testGetAllOnlyReadsNewStorage() {
let userSession = UserSession(clientId: "client1", userTokens: Fixtures.userTokens, updatedAt: Date())
let legacyStorage = MockLegacyKeychainSessionStorage()
let newStorage = MockKeychainSessionStorage(service: "test")
stub(newStorage) { mock in
when(mock.getAll()).thenReturn([userSession])
}
let migratingStorage = MigratingKeychainCompatStorage(from: legacyStorage,
to: newStorage,
legacyClient: Client(configuration: Fixtures.clientConfig),
legacyClientSecret: "",
makeTokenRequest: { _, _, _ in })
_ = migratingStorage.getAll()
verify(newStorage).getAll()
verifyNoMoreInteractions(legacyStorage)
}
func testRemoveFromBothStorages() {
let clientId = "client1"
let legacyStorage = MockLegacyKeychainSessionStorage()
let newStorage = MockKeychainSessionStorage(service: "test")
stub(newStorage) { mock in
when(mock.remove(forClientId: equal(to: clientId))).thenDoNothing()
}
stub(legacyStorage) { mock in
when(mock.remove()).thenDoNothing()
}
let migratingStorage = MigratingKeychainCompatStorage(from: legacyStorage, to: newStorage,
legacyClient: Client(configuration: Fixtures.clientConfig),
legacyClientSecret: "",
makeTokenRequest: { _, _, _ in })
migratingStorage.remove(forClientId: clientId)
verify(newStorage).remove(forClientId: equal(to: clientId))
verify(legacyStorage).remove()
verifyNoMoreInteractions(legacyStorage)
}
func testGetPrefersNewStorage() {
let clientId = "client1"
let userSession = UserSession(clientId: clientId, userTokens: Fixtures.userTokens, updatedAt: Date())
let legacyStorage = MockLegacyKeychainSessionStorage()
let newStorage = MockKeychainSessionStorage(service: "test")
stub(newStorage) { mock in
when(mock.get(forClientId: clientId, completion: anyClosure()))
.then{ clientId, completion in
completion(userSession)
}
}
let migratingStorage = MigratingKeychainCompatStorage(from: legacyStorage, to: newStorage,
legacyClient: Client(configuration: Fixtures.clientConfig),
legacyClientSecret: "",
makeTokenRequest: { _, _, _ in })
migratingStorage.get(forClientId: clientId) { retrievedUserSession in
XCTAssertEqual(retrievedUserSession, userSession)
}
verify(newStorage).get(forClientId: clientId, completion: anyClosure())
verifyNoMoreInteractions(legacyStorage)
}
func testGetMigratesExistingLegacySession() {
let clientId = "client1"
let legacyUserSession = LegacyUserSession(clientId: clientId, accessToken: "access-token", refreshToken: "refresh-token", updatedAt: Date())
let legacyStorage = MockLegacyKeychainSessionStorage()
stub(legacyStorage) { mock in
when(mock.get(forClientId: equal(to: clientId))).thenReturn(legacyUserSession)
when(mock.remove()).thenDoNothing()
}
let newStorage = MockKeychainSessionStorage(service: "test")
stub(newStorage) { mock in
when(mock.get(forClientId: equal(to: clientId), completion: anyClosure()))
.then{ _, completion in
completion(nil)
}
when(mock.store(any(), accessGroup: "", completion: anyClosure())).thenDoNothing()
}
let migratingStorage = MigratingKeychainCompatStorage(from: legacyStorage, to: newStorage,
legacyClient: Client(configuration: Fixtures.clientConfig),
legacyClientSecret: "",
makeTokenRequest: { _, _, _ in })
migratingStorage.get(forClientId: clientId) { retrievedUserSession in
XCTAssertEqual(retrievedUserSession, nil)
}
// TODO: Fixup on untangling User and Client
// verify(newStorage).get(forClientId: equal(to: clientId), completion: anyClosure())
// verify(legacyStorage).get(forClientId: equal(to: clientId))
// verify(newStorage).store(equal(to: legacyUserSession))
// verify(legacyStorage).remove()
}
func testGetReturnsNilIfNoSessionExists() {
let clientId = "client1"
let legacyStorage = MockLegacyKeychainSessionStorage()
stub(legacyStorage) { mock in
when(mock.get(forClientId: equal(to: clientId))).thenReturn(nil)
}
let newStorage = MockKeychainSessionStorage(service: "test")
stub(newStorage) { mock in
when(mock.get(forClientId: clientId, completion: anyClosure()))
.then{ _, completion in completion(nil) }
}
let migratingStorage = MigratingKeychainCompatStorage(from: legacyStorage, to: newStorage,
legacyClient: Client(configuration: Fixtures.clientConfig),
legacyClientSecret: "",
makeTokenRequest: { _, _, _ in })
migratingStorage.get(forClientId: clientId) { retrievedUserSession in
XCTAssertNil(retrievedUserSession)
}
verify(newStorage).get(forClientId: equal(to: clientId), completion: anyClosure())
verify(legacyStorage).get(forClientId: clientId)
}
}
final class OldSDKClientTests: XCTestCase {
func testOneTimeCodeWithRefreshOnCodeExchangeFailure401() throws {
let expectedCode = "A code string"
let expectedResponse = SchibstedAccountAPIResponse(data: CodeExchangeResponse(code: expectedCode))
let mockHTTPClient = MockHTTPClient()
stub(mockHTTPClient) {mock in
when(mock.execute(request: any(), withRetryPolicy: any(), completion: anyClosure()))
.then { _, _, completion in
completion(.success(expectedResponse))
}
}
let expectedTokenRefreshResponse = TokenResponse(access_token: Fixtures.userTokens.accessToken,
refresh_token: nil,
id_token: nil,
scope: nil,
expires_in: 1337)
let mockApi = MockSchibstedAccountAPI(baseURL: Fixtures.clientConfig.serverURL, sessionServiceURL: Fixtures.clientConfig.sessionServiceURL)
var codeExchangeCallCount = 0
stub(mockApi) { mock in
when(mock.oldSDKCodeExchange(with: any(), clientId: any(), oldSDKAccessToken: any(), completion: anyClosure()))
.then{ _, _, _, completion in
codeExchangeCallCount += 1
completion(.failure(HTTPError.errorResponse(code: 401, body: nil)))
}
when(mock.oldSDKRefresh(with: any(), refreshToken: any(), clientId: any(), clientSecret: any(), completion: anyClosure()))
.then { _, _, _, _, completion in
completion(.success(expectedTokenRefreshResponse))
}
}
let sut = OldSDKClient(clientId: "", clientSecret: "", api: mockApi, legacyAccessToken: "foo", legacyRefreshToken: "bar", httpClient: mockHTTPClient)
Await.until { done in
sut.oneTimeCodeWithOldSDKRefresh(newSDKClientId: "") { result in
switch result {
case .failure(.errorResponse(let errorCode, _)):
XCTAssertEqual(codeExchangeCallCount, 2, "Code Exchange should only be called 2 times on 401 failure.")
XCTAssertEqual(401, errorCode)
default:
XCTFail("Unexpected result \(result)")
}
done()
}
}
}
func testOneTimeCodeWithRefreshOnCodeExchangeSuccess() throws {
let expectedCode = "A code string"
let expectedResponse = SchibstedAccountAPIResponse(data: CodeExchangeResponse(code: expectedCode))
let mockHTTPClient = MockHTTPClient()
stub(mockHTTPClient) {mock in
when(mock.execute(request: any(), withRetryPolicy: any(), completion: anyClosure()))
.then { _, _, completion in
completion(.success(expectedResponse))
}
}
let expectedTokenRefreshResponse = TokenResponse(access_token: Fixtures.userTokens.accessToken,
refresh_token: nil,
id_token: nil,
scope: nil,
expires_in: 1337)
let mockApi = MockSchibstedAccountAPI(baseURL: Fixtures.clientConfig.serverURL, sessionServiceURL: Fixtures.clientConfig.sessionServiceURL)
var codeExchangeCallCount = 0
stub(mockApi) { mock in
when(mock.oldSDKCodeExchange(with: any(), clientId: any(), oldSDKAccessToken: any(), completion: anyClosure()))
.then{ _, _, _, completion in
codeExchangeCallCount += 1
completion(.success(expectedResponse))
}
when(mock.oldSDKRefresh(with: any(), refreshToken: any(), clientId: any(), clientSecret: any(), completion: anyClosure()))
.then { _, _, _, _, completion in
completion(.success(expectedTokenRefreshResponse))
}
}
let sut = OldSDKClient(clientId: "", clientSecret: "", api: mockApi, legacyAccessToken: "foo", legacyRefreshToken: "bar", httpClient: mockHTTPClient)
Await.until { done in
sut.oneTimeCodeWithOldSDKRefresh(newSDKClientId: "") { result in
switch result {
case .success(let code):
XCTAssertEqual(codeExchangeCallCount, 1, "Code Exchange should only be called once.")
XCTAssertEqual(expectedCode, code)
default:
XCTFail("Unexpected result \(result)")
}
done()
}
}
}
func testOLDSDKRefresh() throws {
let expectedResponse = TokenResponse(access_token: Fixtures.userTokens.accessToken,
refresh_token: nil,
id_token: nil,
scope: nil,
expires_in: 1337)
let mockHTTPClient = MockHTTPClient()
stub(mockHTTPClient) {mock in
when(mock.execute(request: any(), withRetryPolicy: any(), completion: anyClosure()))
.then { _, _, completion in
completion(.success(expectedResponse))
}
}
let api = Fixtures.schibstedAccountAPI
let sut = OldSDKClient(clientId: "", clientSecret: "", api: api, legacyAccessToken: "accessToken", legacyRefreshToken: "foo", httpClient: mockHTTPClient)
Await.until { done in
sut.oldSDKRefresh(refreshToken: "") { result in
switch result {
case .success(let refreshedToken):
XCTAssertEqual(refreshedToken, "accessToken")
default:
XCTFail("Unexpected result \(result)")
}
done()
}
}
}
func testOneTimeCode() throws {
let expectedCode = "A code string"
let expectedResponse = SchibstedAccountAPIResponse(data: CodeExchangeResponse(code: expectedCode))
let mockHTTPClient = MockHTTPClient()
stub(mockHTTPClient) {mock in
when(mock.execute(request: any(), withRetryPolicy: any(), completion: anyClosure()))
.then { _, _, completion in
completion(.success(expectedResponse))
}
}
let api = Fixtures.schibstedAccountAPI
let sut = OldSDKClient(clientId: "", clientSecret: "", api: api, legacyAccessToken: "access-token", legacyRefreshToken: "refresh-token", httpClient: mockHTTPClient)
Await.until { done in
sut.oneTimeCode(newSDKClientId: "", oldSDKAccessToken: "") { result in
switch result {
case .success(let code):
XCTAssertEqual(code, expectedCode)
default:
XCTFail("Unexpected result \(result)")
}
done()
}
}
}
}
| 47.671975 | 172 | 0.552609 |
db0d36f0d8daabe0e96ba2dd475c3a459b7777e3 | 3,661 | //
// CoreDataStorageContext+Extension.swift
// StorageAbstraction
//
// Created by Samvel on 9/12/19.
// Copyright © 2019 Samo. All rights reserved.
//
import Foundation
import CoreData
extension CoreDataStorageContext {
func create<T>(_ model: T.Type, completion: @escaping ((Any) -> Void)) throws where T : Storable {
let managedContext = self.persistentContainer.viewContext
let object = NSEntityDescription.insertNewObject(forEntityName: String(describing: model),
into:self.persistentContainer.viewContext)
managedContext.insert(object)
completion(object)
}
func save(object: Storable) throws {
let managedContext = self.persistentContainer.viewContext
managedContext.insert(object as! NSManagedObject)
try? managedContext.save()
}
func save(object: [Storable]) throws {
let managedContext = self.persistentContainer.viewContext
for obj in object {
managedContext.insert(obj as! NSManagedObject)
}
try? managedContext.save()
}
func update(block: @escaping () -> ()) throws {
// Nothing to do
}
}
extension CoreDataStorageContext {
func delete(object: Storable) throws {
let managedContext = self.persistentContainer.viewContext
managedContext.delete(object as! NSManagedObject)
try managedContext.save()
}
func delete(object: [Storable]) throws {
let managedContext = self.persistentContainer.viewContext
for obj in object {
managedContext.delete(obj as! NSManagedObject)
}
try managedContext.save()
}
func deleteAll<T>(_ model: T.Type) throws where T : Storable {
let managedContext = self.persistentContainer.viewContext
managedContext.delete(model as! T as! NSManagedObject)
try managedContext.save()
}
func reset() throws {
let managedContext = self.persistentContainer.viewContext
managedContext.reset()
try managedContext.save()
}
}
extension CoreDataStorageContext {
func fetch<T: Storable>(_ model: T.Type, predicate: NSPredicate? = nil, sorted: [Sorted]? = nil, completion: (([T]) -> ())) {
let objects = getObjects(model, predicate: predicate, sorted: sorted)
var accumulate: [T] = [T]()
for object in objects {
accumulate.append(object as! T)
}
completion(accumulate)
}
func fetch<T: Storable>(_ model: T.Type, predicate: NSPredicate? = nil, sorted: [Sorted]? = nil) -> [T] {
let objects = getObjects(model, predicate: predicate, sorted: sorted)
var accumulate: [T] = [T]()
for object in objects {
accumulate.append(object as! T)
}
return accumulate
}
fileprivate func getObjects<T: Storable>(_ model: T.Type, predicate: NSPredicate? = nil, sorted: [Sorted]? = nil) -> [NSManagedObject] {
let managedContext = self.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: model))
request.predicate = predicate
request.sortDescriptors = sorted?.map({NSSortDescriptor(key: $0.key, ascending: $0.asc)})
var result:[Any] = []
do {
result = try managedContext.fetch(request)
} catch {
return []
}
return result.map({$0 as! NSManagedObject})
}
}
extension NSManagedObject: Storable {
}
| 31.290598 | 140 | 0.618137 |
e8ab640aa827cfb5a6acb0d7ae2f90d2cf780d83 | 28,107 | // RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
func sideEffect1() -> Int { return 1 }
func sideEffect2() -> Int { return 2 }
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>) {}
func takesConstPointer(_ x: UnsafePointer<Int>) {}
func takesOptConstPointer(_ x: UnsafePointer<Int>?, and: Int) {}
func takesOptOptConstPointer(_ x: UnsafePointer<Int>??, and: Int) {}
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>, and: Int) {}
func takesConstPointer(_ x: UnsafePointer<Int>, and: Int) {}
func takesMutableVoidPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstVoidPointer(_ x: UnsafeRawPointer) {}
func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstRawPointer(_ x: UnsafeRawPointer) {}
func takesOptConstRawPointer(_ x: UnsafeRawPointer?, and: Int) {}
func takesOptOptConstRawPointer(_ x: UnsafeRawPointer??, and: Int) {}
// CHECK-LABEL: sil hidden @_T018pointer_conversion0A9ToPointerySpySiG_SPySiGSvtF
// CHECK: bb0([[MP:%.*]] : $UnsafeMutablePointer<Int>, [[CP:%.*]] : $UnsafePointer<Int>, [[MRP:%.*]] : $UnsafeMutableRawPointer):
func pointerToPointer(_ mp: UnsafeMutablePointer<Int>,
_ cp: UnsafePointer<Int>, _ mrp: UnsafeMutableRawPointer) {
// There should be no conversion here
takesMutablePointer(mp)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[MP]])
takesMutableVoidPointer(mp)
// CHECK: [[TAKES_MUTABLE_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion23takesMutableVoidPointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: apply [[TAKES_MUTABLE_VOID_POINTER]]
takesMutableRawPointer(mp)
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointerySvF :
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]
takesConstPointer(mp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<Int>>
// CHECK: apply [[TAKES_CONST_POINTER]]
takesConstVoidPointer(mp)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySVF
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(mp)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF :
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstPointer(cp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]([[CP]])
takesConstVoidPointer(cp)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySVF
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(cp)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstRawPointer(mrp)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion14arrayToPointeryyF
func arrayToPointer() {
var ints = [1,2,3]
takesMutablePointer(&ints)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @_T0s37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutablePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutablePointer<Int> on [[OWNER]]
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstPointer(ints)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: apply [[TAKES_CONST_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesMutableRawPointer(&ints)
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointerySvF :
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @_T0s37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutableRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutableRawPointer on [[OWNER]]
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(ints)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF :
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstPointer(ints, and: sideEffect1())
// CHECK: [[TAKES_OPT_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesOptConstPointerySPySiGSg_Si3andtF :
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEPENDENT]]
// CHECK: apply [[TAKES_OPT_CONST_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion15stringToPointerySSF
func stringToPointer(_ s: String) {
takesConstVoidPointer(s)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySV{{[_0-9a-zA-Z]*}}F
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(s)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySV{{[_0-9a-zA-Z]*}}F
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstRawPointer(s, and: sideEffect1())
// CHECK: [[TAKES_OPT_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion23takesOptConstRawPointerySVSg_Si3andtF :
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEPENDENT]]
// CHECK: apply [[TAKES_OPT_CONST_RAW_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion14inoutToPointeryyF
func inoutToPointer() {
var int = 0
// CHECK: [[INT:%.*]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[INT]]
takesMutablePointer(&int)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_MUTABLE]]
var logicalInt: Int {
get { return 0 }
set { }
}
takesMutablePointer(&logicalInt)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[GETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
takesMutableRawPointer(&int)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_MUTABLE]]
takesMutableRawPointer(&logicalInt)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[GETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
}
class C {}
func takesPlusOnePointer(_ x: UnsafeMutablePointer<C>) {}
func takesPlusZeroPointer(_ x: AutoreleasingUnsafeMutablePointer<C>) {}
func takesPlusZeroOptionalPointer(_ x: AutoreleasingUnsafeMutablePointer<C?>) {}
// CHECK-LABEL: sil hidden @_T018pointer_conversion19classInoutToPointeryyF
func classInoutToPointer() {
var c = C()
// CHECK: [[VAR:%.*]] = alloc_box ${ var C }
// CHECK: [[PB:%.*]] = project_box [[VAR]]
takesPlusOnePointer(&c)
// CHECK: [[TAKES_PLUS_ONE:%.*]] = function_ref @_T018pointer_conversion19takesPlusOnePointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_PLUS_ONE]]
takesPlusZeroPointer(&c)
// CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @_T018pointer_conversion20takesPlusZeroPointerys026AutoreleasingUnsafeMutableF0VyAA1CCGF
// CHECK: [[WRITEBACK:%.*]] = alloc_stack $@sil_unmanaged C
// CHECK: [[OWNED:%.*]] = load_borrow [[PB]]
// CHECK: [[UNOWNED:%.*]] = ref_to_unmanaged [[OWNED]]
// CHECK: store [[UNOWNED]] to [trivial] [[WRITEBACK]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITEBACK]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<AutoreleasingUnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_PLUS_ZERO]]
// CHECK: [[UNOWNED_OUT:%.*]] = load [trivial] [[WRITEBACK]]
// CHECK: [[OWNED_OUT:%.*]] = unmanaged_to_ref [[UNOWNED_OUT]]
// CHECK: [[OWNED_OUT_COPY:%.*]] = copy_value [[OWNED_OUT]]
// CHECK: assign [[OWNED_OUT_COPY]] to [[PB]]
var cq: C? = C()
takesPlusZeroOptionalPointer(&cq)
}
// Check that pointer types don't bridge anymore.
@objc class ObjCMethodBridging : NSObject {
// CHECK-LABEL: sil hidden [thunk] @_T018pointer_conversion18ObjCMethodBridgingC0A4Args{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (UnsafeMutablePointer<Int>, UnsafePointer<Int>, AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>, ObjCMethodBridging)
@objc func pointerArgs(_ x: UnsafeMutablePointer<Int>,
y: UnsafePointer<Int>,
z: AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>) {}
}
// rdar://problem/21505805
// CHECK-LABEL: sil hidden @_T018pointer_conversion22functionInoutToPointeryyF
func functionInoutToPointer() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_owned () -> () }
var f: () -> () = {}
// CHECK: [[REABSTRACT_BUF:%.*]] = alloc_stack $@callee_owned (@in ()) -> @out ()
// CHECK: address_to_pointer [[REABSTRACT_BUF]]
takesMutableVoidPointer(&f)
}
// rdar://problem/31781386
// CHECK-LABEL: sil hidden @_T018pointer_conversion20inoutPointerOrderingyyF
func inoutPointerOrdering() {
// CHECK: [[ARRAY_BOX:%.*]] = alloc_box ${ var Array<Int> }
// CHECK: [[ARRAY:%.*]] = project_box [[ARRAY_BOX]] :
// CHECK: store {{.*}} to [init] [[ARRAY]]
var array = [Int]()
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointerySpySiG_Si3andtF
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @_T018pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: apply [[TAKES_MUTABLE]]({{.*}}, [[RESULT2]])
// CHECK: strong_unpin
// CHECK: end_access [[ACCESS]]
takesMutablePointer(&array[sideEffect1()], and: sideEffect2())
// CHECK: [[TAKES_CONST:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiG_Si3andtF
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @_T018pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: apply [[TAKES_CONST]]({{.*}}, [[RESULT2]])
// CHECK: end_access [[ACCESS]]
takesConstPointer(&array[sideEffect1()], and: sideEffect2())
}
// rdar://problem/31542269
// CHECK-LABEL: sil hidden @_T018pointer_conversion20optArrayToOptPointerySaySiGSg5array_tF
func optArrayToOptPointer(array: [Int]?) {
// CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion20takesOptConstPointerySPySiGSg_Si3andtF
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgumentyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion013optOptArrayTodD7PointerySaySiGSgSg5array_tF
func optOptArrayToOptOptPointer(array: [Int]??) {
// CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion08takesOptD12ConstPointerySPySiGSgSg_Si3andtF
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[T0:%.*]] = select_enum [[SOME_VALUE]]
// CHECK: cond_br [[T0]], [[SOME_SOME_BB:bb[0-9]+]], [[SOME_NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_NONE_BB]]:
// CHECK: destroy_value [[SOME_VALUE]]
// CHECK: br [[SOME_NONE_BB2:bb[0-9]+]]
// CHECK: [[SOME_SOME_BB]]:
// CHECK: [[SOME_SOME_VALUE:%.*]] = unchecked_enum_data [[SOME_VALUE]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgumentyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.some!enumelt.1, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>> on [[OWNER]]
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[SOME_NONE_BB2]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafePointer<Int>>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion21optStringToOptPointerySSSg6string_tF
func optStringToOptPointer(string: String?) {
// CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion23takesOptConstRawPointerySVSg_Si3andtF
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgumentyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstRawPointer(string, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion014optOptStringTodD7PointerySSSgSg6string_tF
func optOptStringToOptOptPointer(string: String??) {
// CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion08takesOptD15ConstRawPointerySVSgSg_Si3andtF
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// FIXME: this should really go somewhere that will make nil, not some(nil)
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[T0:%.*]] = select_enum [[SOME_VALUE]]
// CHECK: cond_br [[T0]], [[SOME_SOME_BB:bb[0-9]+]], [[SOME_NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_NONE_BB]]:
// CHECK: destroy_value [[SOME_VALUE]]
// CHECK: br [[SOME_NONE_BB2:bb[0-9]+]]
// CHECK: [[SOME_SOME_BB]]:
// CHECK: [[SOME_SOME_VALUE:%.*]] = unchecked_enum_data [[SOME_VALUE]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgumentyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.some!enumelt.1, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>> on [[OWNER]]
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[SOME_NONE_BB2]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafeRawPointer>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstRawPointer(string, and: sideEffect1())
}
| 60.575431 | 260 | 0.669975 |
1684aa577bf8ba98c1746a8392ed31e40d20cb29 | 297 | //
// String+trimend.swift
// pinfo
//
// Created by Mikael Konradsson on 2021-03-13.
//
import Foundation
extension String {
var trimEnd: String {
var newString = self
while newString.last?.isWhitespace == true {
newString = String(newString.dropLast())
}
return newString
}
}
| 14.85 | 47 | 0.680135 |
8a3f209aacd26046ab36d7a772b03c7344252d14 | 5,352 | import Flutter
import UIKit
public class SwiftScreenBrightnessIosPlugin: NSObject, FlutterPlugin, FlutterApplicationLifeCycleDelegate {
var methodChannel: FlutterMethodChannel?
var currentBrightnessChangeEventChannel: FlutterEventChannel?
let currentBrightnessChangeStreamHandler: CurrentBrightnessChangeStreamHandler = CurrentBrightnessChangeStreamHandler()
var systemBrightness: CGFloat?
var changedBrightness: CGFloat?
public static func register(with registrar: FlutterPluginRegistrar) {
let instance = SwiftScreenBrightnessIosPlugin()
instance.methodChannel = FlutterMethodChannel(name: "github.com/aaassseee/screen_brightness", binaryMessenger: registrar.messenger())
registrar.addMethodCallDelegate(instance, channel: instance.methodChannel!)
instance.currentBrightnessChangeEventChannel = FlutterEventChannel(name: "github.com/aaassseee/screen_brightness/change", binaryMessenger: registrar.messenger())
instance.currentBrightnessChangeEventChannel!.setStreamHandler(instance.currentBrightnessChangeStreamHandler)
registrar.addApplicationDelegate(instance)
}
override init() {
super.init()
systemBrightness = UIScreen.main.brightness
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getSystemScreenBrightness":
handleGetSystemBrightnessMethodCall(result: result)
break;
case "getScreenBrightness":
handleGetScreenBrightnessMethodCall(result: result)
break;
case "setScreenBrightness":
handleSetScreenBrightnessMethodCall(call: call, result: result)
break;
case "resetScreenBrightness":
handleResetScreenBrightnessMethodCall(result: result)
break;
default:
result(FlutterMethodNotImplemented)
break;
}
}
func handleGetSystemBrightnessMethodCall(result: FlutterResult) {
result(systemBrightness)
}
func handleGetScreenBrightnessMethodCall(result: FlutterResult) {
result(UIScreen.main.brightness)
}
func handleSetScreenBrightnessMethodCall(call: FlutterMethodCall, result: FlutterResult) {
guard let parameters = call.arguments as? Dictionary<String, Any>, let brightness = parameters["brightness"] as? NSNumber else {
result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil))
return
}
let _changedBrightness = CGFloat(brightness.doubleValue)
UIScreen.main.brightness = _changedBrightness
changedBrightness = _changedBrightness
handleCurrentBrightnessChanged(_changedBrightness)
result(nil)
}
func handleResetScreenBrightnessMethodCall(result: FlutterResult) {
guard let initialBrightness = systemBrightness else {
result(FlutterError.init(code: "-2", message: "Unexpected error on null brightness", details: nil))
return
}
UIScreen.main.brightness = initialBrightness
changedBrightness = nil
handleCurrentBrightnessChanged(initialBrightness)
result(nil)
}
public func handleCurrentBrightnessChanged(_ currentBrightness: CGFloat) {
currentBrightnessChangeStreamHandler.addCurrentBrightnessToEventSink(currentBrightness)
}
@objc private func onSystemBrightnessChanged(notification: Notification) {
guard let screenObject = notification.object, let brightness = (screenObject as AnyObject).brightness else {
return
}
systemBrightness = brightness
if (changedBrightness == nil) {
handleCurrentBrightnessChanged(brightness)
}
}
func onApplicationPause() {
guard let initialBrightness = systemBrightness else {
return
}
UIScreen.main.brightness = initialBrightness
}
func onApplicationResume() {
guard let changedBrightness = changedBrightness else {
return
}
UIScreen.main.brightness = changedBrightness
}
public func applicationWillResignActive(_ application: UIApplication) {
onApplicationPause()
NotificationCenter.default.addObserver(self, selector: #selector(onSystemBrightnessChanged), name: UIScreen.brightnessDidChangeNotification, object: nil)
}
public func applicationDidBecomeActive(_ application: UIApplication) {
NotificationCenter.default.removeObserver(self, name: UIScreen.brightnessDidChangeNotification, object: nil)
onApplicationResume()
}
public func applicationDidEnterBackground(_ application: UIApplication) {
onApplicationPause()
}
public func applicationWillEnterForeground(_ application: UIApplication) {
onApplicationResume()
}
public func applicationWillTerminate(_ application: UIApplication) {
onApplicationPause()
NotificationCenter.default.removeObserver(self)
}
public func detachFromEngine(for registrar: FlutterPluginRegistrar) {
NotificationCenter.default.removeObserver(self)
methodChannel?.setMethodCallHandler(nil)
currentBrightnessChangeEventChannel?.setStreamHandler(nil)
}
}
| 35.919463 | 169 | 0.716928 |
1d481f181a37935e5f8eb1c27d0f6500deb3c02a | 2,367 | //
// AppFlowController+CoreTests+CurrentPage.swift
// AppFlowController
//
// Created by Paweł Sporysz on 26.06.2017.
// Copyright © 2017 Paweł Sporysz. All rights reserved.
//
import XCTest
@testable import AppFlowController
extension AppFlowController_CoreTests {
func testCurrentPage_missingPrepareMethodInvokation() {
XCTAssertNil(flowController.currentPathComponent)
}
func testCurrentPage_rootNavigationControllerIsEmpty() {
prepareFlowController()
XCTAssertNil(flowController.currentPathComponent)
}
func testCurrentPage_thereIsNoShownPage() {
prepareFlowController()
let pages = newPage("1") => newPage("2")
do {
try flowController.register(pathComponents: pages)
XCTAssertNil(flowController.currentPathComponent)
} catch _ {
XCTFail()
}
}
func testCurrentPage_visibleViewControllerIsNotRegistered() {
prepareFlowController()
let pages = newPage("1") => newPage("2")
do {
try flowController.register(pathComponents: pages)
flowController.rootNavigationController?.viewControllers = [UIViewController()]
XCTAssertNil(flowController.currentPathComponent)
} catch _ {
XCTFail()
}
}
func testCurrentPage_withoutVariant() {
prepareFlowController()
let pages = newPage("1") => newPage("2")
do {
try flowController.register(pathComponents: pages)
try flowController.show(pages[1])
XCTAssertEqual(flowController.currentPathComponent, pages[1])
} catch _ {
XCTFail()
}
}
func testCurrentPage_withVariant() {
prepareFlowController()
let pages = newPage("1") =>> [
newPage("2") => newPage("4", supportVariants: true),
newPage("3") => newPage("4", supportVariants: true)
]
do {
try flowController.register(pathComponents: pages)
try flowController.show(pages[0][2], variant: pages[0][1], animated: false)
var expectedPage = pages[0][2]
expectedPage.variantName = "2"
XCTAssertEqual(flowController.currentPathComponent, expectedPage)
} catch _ {
XCTFail()
}
}
}
| 31.144737 | 91 | 0.618927 |
286ab9f63c90ae915ec7726f09995a7f1773cfdb | 119,351 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
import Foundation
import SotoCore
extension LookoutEquipment {
// MARK: Enums
public enum DataUploadFrequency: String, CustomStringConvertible, Codable, _SotoSendable {
case pt10m = "PT10M"
case pt15m = "PT15M"
case pt1h = "PT1H"
case pt30m = "PT30M"
case pt5m = "PT5M"
public var description: String { return self.rawValue }
}
public enum DatasetStatus: String, CustomStringConvertible, Codable, _SotoSendable {
case active = "ACTIVE"
case created = "CREATED"
case ingestionInProgress = "INGESTION_IN_PROGRESS"
public var description: String { return self.rawValue }
}
public enum InferenceExecutionStatus: String, CustomStringConvertible, Codable, _SotoSendable {
case failed = "FAILED"
case inProgress = "IN_PROGRESS"
case success = "SUCCESS"
public var description: String { return self.rawValue }
}
public enum InferenceSchedulerStatus: String, CustomStringConvertible, Codable, _SotoSendable {
case pending = "PENDING"
case running = "RUNNING"
case stopped = "STOPPED"
case stopping = "STOPPING"
public var description: String { return self.rawValue }
}
public enum IngestionJobStatus: String, CustomStringConvertible, Codable, _SotoSendable {
case failed = "FAILED"
case inProgress = "IN_PROGRESS"
case success = "SUCCESS"
public var description: String { return self.rawValue }
}
public enum ModelStatus: String, CustomStringConvertible, Codable, _SotoSendable {
case failed = "FAILED"
case inProgress = "IN_PROGRESS"
case success = "SUCCESS"
public var description: String { return self.rawValue }
}
public enum Monotonicity: String, CustomStringConvertible, Codable, _SotoSendable {
case decreasing = "DECREASING"
case increasing = "INCREASING"
case `static` = "STATIC"
public var description: String { return self.rawValue }
}
public enum StatisticalIssueStatus: String, CustomStringConvertible, Codable, _SotoSendable {
case noIssueDetected = "NO_ISSUE_DETECTED"
case potentialIssueDetected = "POTENTIAL_ISSUE_DETECTED"
public var description: String { return self.rawValue }
}
public enum TargetSamplingRate: String, CustomStringConvertible, Codable, _SotoSendable {
case pt10m = "PT10M"
case pt10s = "PT10S"
case pt15m = "PT15M"
case pt15s = "PT15S"
case pt1h = "PT1H"
case pt1m = "PT1M"
case pt1s = "PT1S"
case pt30m = "PT30M"
case pt30s = "PT30S"
case pt5m = "PT5M"
case pt5s = "PT5S"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct CategoricalValues: AWSDecodableShape {
/// Indicates the number of categories in the data.
public let numberOfCategory: Int?
/// Indicates whether there is a potential data issue related to categorical values.
public let status: StatisticalIssueStatus
public init(numberOfCategory: Int? = nil, status: StatisticalIssueStatus) {
self.numberOfCategory = numberOfCategory
self.status = status
}
private enum CodingKeys: String, CodingKey {
case numberOfCategory = "NumberOfCategory"
case status = "Status"
}
}
public struct CountPercent: AWSDecodableShape {
/// Indicates the count of occurences of the given statistic.
public let count: Int
/// Indicates the percentage of occurances of the given statistic.
public let percentage: Float
public init(count: Int, percentage: Float) {
self.count = count
self.percentage = percentage
}
private enum CodingKeys: String, CodingKey {
case count = "Count"
case percentage = "Percentage"
}
}
public struct CreateDatasetRequest: AWSEncodableShape {
/// A unique identifier for the request. If you do not set the client request token, Amazon Lookout for Equipment generates one.
public let clientToken: String
/// The name of the dataset being created.
public let datasetName: String
/// A JSON description of the data that is in each time series dataset, including names, column names, and data types.
public let datasetSchema: DatasetSchema?
/// Provides the identifier of the KMS key used to encrypt dataset data by Amazon Lookout for Equipment.
public let serverSideKmsKeyId: String?
/// Any tags associated with the ingested data described in the dataset.
public let tags: [Tag]?
public init(clientToken: String = CreateDatasetRequest.idempotencyToken(), datasetName: String, datasetSchema: DatasetSchema? = nil, serverSideKmsKeyId: String? = nil, tags: [Tag]? = nil) {
self.clientToken = clientToken
self.datasetName = datasetName
self.datasetSchema = datasetSchema
self.serverSideKmsKeyId = serverSideKmsKeyId
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "^\\p{ASCII}{1,256}$")
try self.validate(self.datasetName, name: "datasetName", parent: name, max: 200)
try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1)
try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.datasetSchema?.validate(name: "\(name).datasetSchema")
try self.validate(self.serverSideKmsKeyId, name: "serverSideKmsKeyId", parent: name, max: 2048)
try self.validate(self.serverSideKmsKeyId, name: "serverSideKmsKeyId", parent: name, min: 1)
try self.validate(self.serverSideKmsKeyId, name: "serverSideKmsKeyId", parent: name, pattern: "^[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,2048}$")
try self.tags?.forEach {
try $0.validate(name: "\(name).tags[]")
}
try self.validate(self.tags, name: "tags", parent: name, max: 200)
}
private enum CodingKeys: String, CodingKey {
case clientToken = "ClientToken"
case datasetName = "DatasetName"
case datasetSchema = "DatasetSchema"
case serverSideKmsKeyId = "ServerSideKmsKeyId"
case tags = "Tags"
}
}
public struct CreateDatasetResponse: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the dataset being created.
public let datasetArn: String?
/// The name of the dataset being created.
public let datasetName: String?
/// Indicates the status of the CreateDataset operation.
public let status: DatasetStatus?
public init(datasetArn: String? = nil, datasetName: String? = nil, status: DatasetStatus? = nil) {
self.datasetArn = datasetArn
self.datasetName = datasetName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case datasetArn = "DatasetArn"
case datasetName = "DatasetName"
case status = "Status"
}
}
public struct CreateInferenceSchedulerRequest: AWSEncodableShape {
/// A unique identifier for the request. If you do not set the client request token, Amazon Lookout for Equipment generates one.
public let clientToken: String
/// A period of time (in minutes) by which inference on the data is delayed after the data starts. For instance, if you select an offset delay time of five minutes, inference will not begin on the data until the first data measurement after the five minute mark. For example, if five minutes is selected, the inference scheduler will wake up at the configured frequency with the additional five minute delay time to check the customer S3 bucket. The customer can upload data at the same frequency and they don't need to stop and restart the scheduler when uploading new data.
public let dataDelayOffsetInMinutes: Int64?
/// Specifies configuration information for the input data for the inference scheduler, including delimiter, format, and dataset location.
public let dataInputConfiguration: InferenceInputConfiguration
/// Specifies configuration information for the output results for the inference scheduler, including the S3 location for the output.
public let dataOutputConfiguration: InferenceOutputConfiguration
/// How often data is uploaded to the source S3 bucket for the input data. The value chosen is the length of time between data uploads. For instance, if you select 5 minutes, Amazon Lookout for Equipment will upload the real-time data to the source bucket once every 5 minutes. This frequency also determines how often Amazon Lookout for Equipment starts a scheduled inference on your data. In this example, it starts once every 5 minutes.
public let dataUploadFrequency: DataUploadFrequency
/// The name of the inference scheduler being created.
public let inferenceSchedulerName: String
/// The name of the previously trained ML model being used to create the inference scheduler.
public let modelName: String
/// The Amazon Resource Name (ARN) of a role with permission to access the data source being used for the inference.
public let roleArn: String
/// Provides the identifier of the KMS key used to encrypt inference scheduler data by Amazon Lookout for Equipment.
public let serverSideKmsKeyId: String?
/// Any tags associated with the inference scheduler.
public let tags: [Tag]?
public init(clientToken: String = CreateInferenceSchedulerRequest.idempotencyToken(), dataDelayOffsetInMinutes: Int64? = nil, dataInputConfiguration: InferenceInputConfiguration, dataOutputConfiguration: InferenceOutputConfiguration, dataUploadFrequency: DataUploadFrequency, inferenceSchedulerName: String, modelName: String, roleArn: String, serverSideKmsKeyId: String? = nil, tags: [Tag]? = nil) {
self.clientToken = clientToken
self.dataDelayOffsetInMinutes = dataDelayOffsetInMinutes
self.dataInputConfiguration = dataInputConfiguration
self.dataOutputConfiguration = dataOutputConfiguration
self.dataUploadFrequency = dataUploadFrequency
self.inferenceSchedulerName = inferenceSchedulerName
self.modelName = modelName
self.roleArn = roleArn
self.serverSideKmsKeyId = serverSideKmsKeyId
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "^\\p{ASCII}{1,256}$")
try self.validate(self.dataDelayOffsetInMinutes, name: "dataDelayOffsetInMinutes", parent: name, max: 60)
try self.validate(self.dataDelayOffsetInMinutes, name: "dataDelayOffsetInMinutes", parent: name, min: 0)
try self.dataInputConfiguration.validate(name: "\(name).dataInputConfiguration")
try self.dataOutputConfiguration.validate(name: "\(name).dataOutputConfiguration")
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, max: 200)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, min: 1)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.modelName, name: "modelName", parent: name, max: 200)
try self.validate(self.modelName, name: "modelName", parent: name, min: 1)
try self.validate(self.modelName, name: "modelName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048)
try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20)
try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:aws(-[^:]+)?:iam::[0-9]{12}:role/.+$")
try self.validate(self.serverSideKmsKeyId, name: "serverSideKmsKeyId", parent: name, max: 2048)
try self.validate(self.serverSideKmsKeyId, name: "serverSideKmsKeyId", parent: name, min: 1)
try self.validate(self.serverSideKmsKeyId, name: "serverSideKmsKeyId", parent: name, pattern: "^[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,2048}$")
try self.tags?.forEach {
try $0.validate(name: "\(name).tags[]")
}
try self.validate(self.tags, name: "tags", parent: name, max: 200)
}
private enum CodingKeys: String, CodingKey {
case clientToken = "ClientToken"
case dataDelayOffsetInMinutes = "DataDelayOffsetInMinutes"
case dataInputConfiguration = "DataInputConfiguration"
case dataOutputConfiguration = "DataOutputConfiguration"
case dataUploadFrequency = "DataUploadFrequency"
case inferenceSchedulerName = "InferenceSchedulerName"
case modelName = "ModelName"
case roleArn = "RoleArn"
case serverSideKmsKeyId = "ServerSideKmsKeyId"
case tags = "Tags"
}
}
public struct CreateInferenceSchedulerResponse: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the inference scheduler being created.
public let inferenceSchedulerArn: String?
/// The name of inference scheduler being created.
public let inferenceSchedulerName: String?
/// Indicates the status of the CreateInferenceScheduler operation.
public let status: InferenceSchedulerStatus?
public init(inferenceSchedulerArn: String? = nil, inferenceSchedulerName: String? = nil, status: InferenceSchedulerStatus? = nil) {
self.inferenceSchedulerArn = inferenceSchedulerArn
self.inferenceSchedulerName = inferenceSchedulerName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case inferenceSchedulerArn = "InferenceSchedulerArn"
case inferenceSchedulerName = "InferenceSchedulerName"
case status = "Status"
}
}
public struct CreateModelRequest: AWSEncodableShape {
/// A unique identifier for the request. If you do not set the client request token, Amazon Lookout for Equipment generates one.
public let clientToken: String
/// The configuration is the TargetSamplingRate, which is the sampling rate of the data after post processing by Amazon Lookout for Equipment. For example, if you provide data that has been collected at a 1 second level and you want the system to resample the data at a 1 minute rate before training, the TargetSamplingRate is 1 minute. When providing a value for the TargetSamplingRate, you must attach the prefix "PT" to the rate you want. The value for a 1 second rate is therefore PT1S, the value for a 15 minute rate is PT15M, and the value for a 1 hour rate is PT1H
public let dataPreProcessingConfiguration: DataPreProcessingConfiguration?
/// The name of the dataset for the ML model being created.
public let datasetName: String
/// The data schema for the ML model being created.
public let datasetSchema: DatasetSchema?
/// Indicates the time reference in the dataset that should be used to end the subset of evaluation data for the ML model.
public let evaluationDataEndTime: Date?
/// Indicates the time reference in the dataset that should be used to begin the subset of evaluation data for the ML model.
public let evaluationDataStartTime: Date?
/// The input configuration for the labels being used for the ML model that's being created.
public let labelsInputConfiguration: LabelsInputConfiguration?
/// The name for the ML model to be created.
public let modelName: String
/// Indicates that the asset associated with this sensor has been shut off. As long as this condition is met, Lookout for Equipment will not use data from this asset for training, evaluation, or inference.
public let offCondition: String?
/// The Amazon Resource Name (ARN) of a role with permission to access the data source being used to create the ML model.
public let roleArn: String?
/// Provides the identifier of the KMS key used to encrypt model data by Amazon Lookout for Equipment.
public let serverSideKmsKeyId: String?
/// Any tags associated with the ML model being created.
public let tags: [Tag]?
/// Indicates the time reference in the dataset that should be used to end the subset of training data for the ML model.
public let trainingDataEndTime: Date?
/// Indicates the time reference in the dataset that should be used to begin the subset of training data for the ML model.
public let trainingDataStartTime: Date?
public init(clientToken: String = CreateModelRequest.idempotencyToken(), dataPreProcessingConfiguration: DataPreProcessingConfiguration? = nil, datasetName: String, datasetSchema: DatasetSchema? = nil, evaluationDataEndTime: Date? = nil, evaluationDataStartTime: Date? = nil, labelsInputConfiguration: LabelsInputConfiguration? = nil, modelName: String, offCondition: String? = nil, roleArn: String? = nil, serverSideKmsKeyId: String? = nil, tags: [Tag]? = nil, trainingDataEndTime: Date? = nil, trainingDataStartTime: Date? = nil) {
self.clientToken = clientToken
self.dataPreProcessingConfiguration = dataPreProcessingConfiguration
self.datasetName = datasetName
self.datasetSchema = datasetSchema
self.evaluationDataEndTime = evaluationDataEndTime
self.evaluationDataStartTime = evaluationDataStartTime
self.labelsInputConfiguration = labelsInputConfiguration
self.modelName = modelName
self.offCondition = offCondition
self.roleArn = roleArn
self.serverSideKmsKeyId = serverSideKmsKeyId
self.tags = tags
self.trainingDataEndTime = trainingDataEndTime
self.trainingDataStartTime = trainingDataStartTime
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "^\\p{ASCII}{1,256}$")
try self.validate(self.datasetName, name: "datasetName", parent: name, max: 200)
try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1)
try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.datasetSchema?.validate(name: "\(name).datasetSchema")
try self.labelsInputConfiguration?.validate(name: "\(name).labelsInputConfiguration")
try self.validate(self.modelName, name: "modelName", parent: name, max: 200)
try self.validate(self.modelName, name: "modelName", parent: name, min: 1)
try self.validate(self.modelName, name: "modelName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.offCondition, name: "offCondition", parent: name, max: 2048)
try self.validate(self.offCondition, name: "offCondition", parent: name, min: 1)
try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048)
try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20)
try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:aws(-[^:]+)?:iam::[0-9]{12}:role/.+$")
try self.validate(self.serverSideKmsKeyId, name: "serverSideKmsKeyId", parent: name, max: 2048)
try self.validate(self.serverSideKmsKeyId, name: "serverSideKmsKeyId", parent: name, min: 1)
try self.validate(self.serverSideKmsKeyId, name: "serverSideKmsKeyId", parent: name, pattern: "^[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,2048}$")
try self.tags?.forEach {
try $0.validate(name: "\(name).tags[]")
}
try self.validate(self.tags, name: "tags", parent: name, max: 200)
}
private enum CodingKeys: String, CodingKey {
case clientToken = "ClientToken"
case dataPreProcessingConfiguration = "DataPreProcessingConfiguration"
case datasetName = "DatasetName"
case datasetSchema = "DatasetSchema"
case evaluationDataEndTime = "EvaluationDataEndTime"
case evaluationDataStartTime = "EvaluationDataStartTime"
case labelsInputConfiguration = "LabelsInputConfiguration"
case modelName = "ModelName"
case offCondition = "OffCondition"
case roleArn = "RoleArn"
case serverSideKmsKeyId = "ServerSideKmsKeyId"
case tags = "Tags"
case trainingDataEndTime = "TrainingDataEndTime"
case trainingDataStartTime = "TrainingDataStartTime"
}
}
public struct CreateModelResponse: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the model being created.
public let modelArn: String?
/// Indicates the status of the CreateModel operation.
public let status: ModelStatus?
public init(modelArn: String? = nil, status: ModelStatus? = nil) {
self.modelArn = modelArn
self.status = status
}
private enum CodingKeys: String, CodingKey {
case modelArn = "ModelArn"
case status = "Status"
}
}
public struct DataIngestionJobSummary: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the dataset used in the data ingestion job.
public let datasetArn: String?
/// The name of the dataset used for the data ingestion job.
public let datasetName: String?
/// Specifies information for the input data for the data inference job, including data Amazon S3 location parameters.
public let ingestionInputConfiguration: IngestionInputConfiguration?
/// Indicates the job ID of the data ingestion job.
public let jobId: String?
/// Indicates the status of the data ingestion job.
public let status: IngestionJobStatus?
public init(datasetArn: String? = nil, datasetName: String? = nil, ingestionInputConfiguration: IngestionInputConfiguration? = nil, jobId: String? = nil, status: IngestionJobStatus? = nil) {
self.datasetArn = datasetArn
self.datasetName = datasetName
self.ingestionInputConfiguration = ingestionInputConfiguration
self.jobId = jobId
self.status = status
}
private enum CodingKeys: String, CodingKey {
case datasetArn = "DatasetArn"
case datasetName = "DatasetName"
case ingestionInputConfiguration = "IngestionInputConfiguration"
case jobId = "JobId"
case status = "Status"
}
}
public struct DataPreProcessingConfiguration: AWSEncodableShape & AWSDecodableShape {
/// The sampling rate of the data after post processing by Amazon Lookout for Equipment. For example, if you provide data that has been collected at a 1 second level and you want the system to resample the data at a 1 minute rate before training, the TargetSamplingRate is 1 minute. When providing a value for the TargetSamplingRate, you must attach the prefix "PT" to the rate you want. The value for a 1 second rate is therefore PT1S, the value for a 15 minute rate is PT15M, and the value for a 1 hour rate is PT1H
public let targetSamplingRate: TargetSamplingRate?
public init(targetSamplingRate: TargetSamplingRate? = nil) {
self.targetSamplingRate = targetSamplingRate
}
private enum CodingKeys: String, CodingKey {
case targetSamplingRate = "TargetSamplingRate"
}
}
public struct DataQualitySummary: AWSDecodableShape {
/// Parameter that gives information about duplicate timestamps in the input data.
public let duplicateTimestamps: DuplicateTimestamps
/// Parameter that gives information about insufficient data for sensors in the dataset. This includes information about those sensors that have complete data missing and those with a short date range.
public let insufficientSensorData: InsufficientSensorData
/// Parameter that gives information about data that is invalid over all the sensors in the input data.
public let invalidSensorData: InvalidSensorData
/// Parameter that gives information about data that is missing over all the sensors in the input data.
public let missingSensorData: MissingSensorData
/// Parameter that gives information about unsupported timestamps in the input data.
public let unsupportedTimestamps: UnsupportedTimestamps
public init(duplicateTimestamps: DuplicateTimestamps, insufficientSensorData: InsufficientSensorData, invalidSensorData: InvalidSensorData, missingSensorData: MissingSensorData, unsupportedTimestamps: UnsupportedTimestamps) {
self.duplicateTimestamps = duplicateTimestamps
self.insufficientSensorData = insufficientSensorData
self.invalidSensorData = invalidSensorData
self.missingSensorData = missingSensorData
self.unsupportedTimestamps = unsupportedTimestamps
}
private enum CodingKeys: String, CodingKey {
case duplicateTimestamps = "DuplicateTimestamps"
case insufficientSensorData = "InsufficientSensorData"
case invalidSensorData = "InvalidSensorData"
case missingSensorData = "MissingSensorData"
case unsupportedTimestamps = "UnsupportedTimestamps"
}
}
public struct DatasetSchema: AWSEncodableShape {
///
public let inlineDataSchema: String?
public init(inlineDataSchema: String? = nil) {
self.inlineDataSchema = inlineDataSchema
}
public func validate(name: String) throws {
try self.validate(self.inlineDataSchema, name: "inlineDataSchema", parent: name, max: 1_000_000)
try self.validate(self.inlineDataSchema, name: "inlineDataSchema", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case inlineDataSchema = "InlineDataSchema"
}
}
public struct DatasetSummary: AWSDecodableShape {
/// The time at which the dataset was created in Amazon Lookout for Equipment.
public let createdAt: Date?
/// The Amazon Resource Name (ARN) of the specified dataset.
public let datasetArn: String?
/// The name of the dataset.
public let datasetName: String?
/// Indicates the status of the dataset.
public let status: DatasetStatus?
public init(createdAt: Date? = nil, datasetArn: String? = nil, datasetName: String? = nil, status: DatasetStatus? = nil) {
self.createdAt = createdAt
self.datasetArn = datasetArn
self.datasetName = datasetName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case createdAt = "CreatedAt"
case datasetArn = "DatasetArn"
case datasetName = "DatasetName"
case status = "Status"
}
}
public struct DeleteDatasetRequest: AWSEncodableShape {
/// The name of the dataset to be deleted.
public let datasetName: String
public init(datasetName: String) {
self.datasetName = datasetName
}
public func validate(name: String) throws {
try self.validate(self.datasetName, name: "datasetName", parent: name, max: 200)
try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1)
try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
}
private enum CodingKeys: String, CodingKey {
case datasetName = "DatasetName"
}
}
public struct DeleteInferenceSchedulerRequest: AWSEncodableShape {
/// The name of the inference scheduler to be deleted.
public let inferenceSchedulerName: String
public init(inferenceSchedulerName: String) {
self.inferenceSchedulerName = inferenceSchedulerName
}
public func validate(name: String) throws {
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, max: 200)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, min: 1)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
}
private enum CodingKeys: String, CodingKey {
case inferenceSchedulerName = "InferenceSchedulerName"
}
}
public struct DeleteModelRequest: AWSEncodableShape {
/// The name of the ML model to be deleted.
public let modelName: String
public init(modelName: String) {
self.modelName = modelName
}
public func validate(name: String) throws {
try self.validate(self.modelName, name: "modelName", parent: name, max: 200)
try self.validate(self.modelName, name: "modelName", parent: name, min: 1)
try self.validate(self.modelName, name: "modelName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
}
private enum CodingKeys: String, CodingKey {
case modelName = "ModelName"
}
}
public struct DescribeDataIngestionJobRequest: AWSEncodableShape {
/// The job ID of the data ingestion job.
public let jobId: String
public init(jobId: String) {
self.jobId = jobId
}
public func validate(name: String) throws {
try self.validate(self.jobId, name: "jobId", parent: name, max: 32)
try self.validate(self.jobId, name: "jobId", parent: name, pattern: "^[A-Fa-f0-9]{0,32}$")
}
private enum CodingKeys: String, CodingKey {
case jobId = "JobId"
}
}
public struct DescribeDataIngestionJobResponse: AWSDecodableShape {
/// The time at which the data ingestion job was created.
public let createdAt: Date?
/// Indicates the latest timestamp corresponding to data that was successfully ingested during this specific ingestion job.
public let dataEndTime: Date?
/// Gives statistics about a completed ingestion job. These statistics primarily relate to quantifying incorrect data such as MissingCompleteSensorData, MissingSensorData, UnsupportedDateFormats, InsufficientSensorData, and DuplicateTimeStamps.
public let dataQualitySummary: DataQualitySummary?
/// The Amazon Resource Name (ARN) of the dataset being used in the data ingestion job.
public let datasetArn: String?
/// Indicates the earliest timestamp corresponding to data that was successfully ingested during this specific ingestion job.
public let dataStartTime: Date?
/// Specifies the reason for failure when a data ingestion job has failed.
public let failedReason: String?
/// Indicates the size of the ingested dataset.
public let ingestedDataSize: Int64?
public let ingestedFilesSummary: IngestedFilesSummary?
/// Specifies the S3 location configuration for the data input for the data ingestion job.
public let ingestionInputConfiguration: IngestionInputConfiguration?
/// Indicates the job ID of the data ingestion job.
public let jobId: String?
/// The Amazon Resource Name (ARN) of an IAM role with permission to access the data source being ingested.
public let roleArn: String?
/// Indicates the status of the DataIngestionJob operation.
public let status: IngestionJobStatus?
/// Provides details about status of the ingestion job that is currently in progress.
public let statusDetail: String?
public init(createdAt: Date? = nil, dataEndTime: Date? = nil, dataQualitySummary: DataQualitySummary? = nil, datasetArn: String? = nil, dataStartTime: Date? = nil, failedReason: String? = nil, ingestedDataSize: Int64? = nil, ingestedFilesSummary: IngestedFilesSummary? = nil, ingestionInputConfiguration: IngestionInputConfiguration? = nil, jobId: String? = nil, roleArn: String? = nil, status: IngestionJobStatus? = nil, statusDetail: String? = nil) {
self.createdAt = createdAt
self.dataEndTime = dataEndTime
self.dataQualitySummary = dataQualitySummary
self.datasetArn = datasetArn
self.dataStartTime = dataStartTime
self.failedReason = failedReason
self.ingestedDataSize = ingestedDataSize
self.ingestedFilesSummary = ingestedFilesSummary
self.ingestionInputConfiguration = ingestionInputConfiguration
self.jobId = jobId
self.roleArn = roleArn
self.status = status
self.statusDetail = statusDetail
}
private enum CodingKeys: String, CodingKey {
case createdAt = "CreatedAt"
case dataEndTime = "DataEndTime"
case dataQualitySummary = "DataQualitySummary"
case datasetArn = "DatasetArn"
case dataStartTime = "DataStartTime"
case failedReason = "FailedReason"
case ingestedDataSize = "IngestedDataSize"
case ingestedFilesSummary = "IngestedFilesSummary"
case ingestionInputConfiguration = "IngestionInputConfiguration"
case jobId = "JobId"
case roleArn = "RoleArn"
case status = "Status"
case statusDetail = "StatusDetail"
}
}
public struct DescribeDatasetRequest: AWSEncodableShape {
/// The name of the dataset to be described.
public let datasetName: String
public init(datasetName: String) {
self.datasetName = datasetName
}
public func validate(name: String) throws {
try self.validate(self.datasetName, name: "datasetName", parent: name, max: 200)
try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1)
try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
}
private enum CodingKeys: String, CodingKey {
case datasetName = "DatasetName"
}
}
public struct DescribeDatasetResponse: AWSDecodableShape {
/// Specifies the time the dataset was created in Amazon Lookout for Equipment.
public let createdAt: Date?
/// Indicates the latest timestamp corresponding to data that was successfully ingested during the most recent ingestion of this particular dataset.
public let dataEndTime: Date?
/// Gives statistics associated with the given dataset for the latest successful associated ingestion job id. These statistics primarily relate to quantifying incorrect data such as MissingCompleteSensorData, MissingSensorData, UnsupportedDateFormats, InsufficientSensorData, and DuplicateTimeStamps.
public let dataQualitySummary: DataQualitySummary?
/// The Amazon Resource Name (ARN) of the dataset being described.
public let datasetArn: String?
/// The name of the dataset being described.
public let datasetName: String?
/// Indicates the earliest timestamp corresponding to data that was successfully ingested during the most recent ingestion of this particular dataset.
public let dataStartTime: Date?
/// IngestedFilesSummary associated with the given dataset for the latest successful associated ingestion job id.
public let ingestedFilesSummary: IngestedFilesSummary?
/// Specifies the S3 location configuration for the data input for the data ingestion job.
public let ingestionInputConfiguration: IngestionInputConfiguration?
/// Specifies the time the dataset was last updated, if it was.
public let lastUpdatedAt: Date?
/// The Amazon Resource Name (ARN) of the IAM role that you are using for this the data ingestion job.
public let roleArn: String?
/// A JSON description of the data that is in each time series dataset, including names, column names, and data types.
public let schema: String?
/// Provides the identifier of the KMS key used to encrypt dataset data by Amazon Lookout for Equipment.
public let serverSideKmsKeyId: String?
/// Indicates the status of the dataset.
public let status: DatasetStatus?
public init(createdAt: Date? = nil, dataEndTime: Date? = nil, dataQualitySummary: DataQualitySummary? = nil, datasetArn: String? = nil, datasetName: String? = nil, dataStartTime: Date? = nil, ingestedFilesSummary: IngestedFilesSummary? = nil, ingestionInputConfiguration: IngestionInputConfiguration? = nil, lastUpdatedAt: Date? = nil, roleArn: String? = nil, schema: String? = nil, serverSideKmsKeyId: String? = nil, status: DatasetStatus? = nil) {
self.createdAt = createdAt
self.dataEndTime = dataEndTime
self.dataQualitySummary = dataQualitySummary
self.datasetArn = datasetArn
self.datasetName = datasetName
self.dataStartTime = dataStartTime
self.ingestedFilesSummary = ingestedFilesSummary
self.ingestionInputConfiguration = ingestionInputConfiguration
self.lastUpdatedAt = lastUpdatedAt
self.roleArn = roleArn
self.schema = schema
self.serverSideKmsKeyId = serverSideKmsKeyId
self.status = status
}
private enum CodingKeys: String, CodingKey {
case createdAt = "CreatedAt"
case dataEndTime = "DataEndTime"
case dataQualitySummary = "DataQualitySummary"
case datasetArn = "DatasetArn"
case datasetName = "DatasetName"
case dataStartTime = "DataStartTime"
case ingestedFilesSummary = "IngestedFilesSummary"
case ingestionInputConfiguration = "IngestionInputConfiguration"
case lastUpdatedAt = "LastUpdatedAt"
case roleArn = "RoleArn"
case schema = "Schema"
case serverSideKmsKeyId = "ServerSideKmsKeyId"
case status = "Status"
}
}
public struct DescribeInferenceSchedulerRequest: AWSEncodableShape {
/// The name of the inference scheduler being described.
public let inferenceSchedulerName: String
public init(inferenceSchedulerName: String) {
self.inferenceSchedulerName = inferenceSchedulerName
}
public func validate(name: String) throws {
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, max: 200)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, min: 1)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
}
private enum CodingKeys: String, CodingKey {
case inferenceSchedulerName = "InferenceSchedulerName"
}
}
public struct DescribeInferenceSchedulerResponse: AWSDecodableShape {
/// Specifies the time at which the inference scheduler was created.
public let createdAt: Date?
/// A period of time (in minutes) by which inference on the data is delayed after the data starts. For instance, if you select an offset delay time of five minutes, inference will not begin on the data until the first data measurement after the five minute mark. For example, if five minutes is selected, the inference scheduler will wake up at the configured frequency with the additional five minute delay time to check the customer S3 bucket. The customer can upload data at the same frequency and they don't need to stop and restart the scheduler when uploading new data.
public let dataDelayOffsetInMinutes: Int64?
/// Specifies configuration information for the input data for the inference scheduler, including delimiter, format, and dataset location.
public let dataInputConfiguration: InferenceInputConfiguration?
/// Specifies information for the output results for the inference scheduler, including the output S3 location.
public let dataOutputConfiguration: InferenceOutputConfiguration?
/// Specifies how often data is uploaded to the source S3 bucket for the input data. This value is the length of time between data uploads. For instance, if you select 5 minutes, Amazon Lookout for Equipment will upload the real-time data to the source bucket once every 5 minutes. This frequency also determines how often Amazon Lookout for Equipment starts a scheduled inference on your data. In this example, it starts once every 5 minutes.
public let dataUploadFrequency: DataUploadFrequency?
/// The Amazon Resource Name (ARN) of the inference scheduler being described.
public let inferenceSchedulerArn: String?
/// The name of the inference scheduler being described.
public let inferenceSchedulerName: String?
/// The Amazon Resource Name (ARN) of the ML model of the inference scheduler being described.
public let modelArn: String?
/// The name of the ML model of the inference scheduler being described.
public let modelName: String?
/// The Amazon Resource Name (ARN) of a role with permission to access the data source for the inference scheduler being described.
public let roleArn: String?
/// Provides the identifier of the KMS key used to encrypt inference scheduler data by Amazon Lookout for Equipment.
public let serverSideKmsKeyId: String?
/// Indicates the status of the inference scheduler.
public let status: InferenceSchedulerStatus?
/// Specifies the time at which the inference scheduler was last updated, if it was.
public let updatedAt: Date?
public init(createdAt: Date? = nil, dataDelayOffsetInMinutes: Int64? = nil, dataInputConfiguration: InferenceInputConfiguration? = nil, dataOutputConfiguration: InferenceOutputConfiguration? = nil, dataUploadFrequency: DataUploadFrequency? = nil, inferenceSchedulerArn: String? = nil, inferenceSchedulerName: String? = nil, modelArn: String? = nil, modelName: String? = nil, roleArn: String? = nil, serverSideKmsKeyId: String? = nil, status: InferenceSchedulerStatus? = nil, updatedAt: Date? = nil) {
self.createdAt = createdAt
self.dataDelayOffsetInMinutes = dataDelayOffsetInMinutes
self.dataInputConfiguration = dataInputConfiguration
self.dataOutputConfiguration = dataOutputConfiguration
self.dataUploadFrequency = dataUploadFrequency
self.inferenceSchedulerArn = inferenceSchedulerArn
self.inferenceSchedulerName = inferenceSchedulerName
self.modelArn = modelArn
self.modelName = modelName
self.roleArn = roleArn
self.serverSideKmsKeyId = serverSideKmsKeyId
self.status = status
self.updatedAt = updatedAt
}
private enum CodingKeys: String, CodingKey {
case createdAt = "CreatedAt"
case dataDelayOffsetInMinutes = "DataDelayOffsetInMinutes"
case dataInputConfiguration = "DataInputConfiguration"
case dataOutputConfiguration = "DataOutputConfiguration"
case dataUploadFrequency = "DataUploadFrequency"
case inferenceSchedulerArn = "InferenceSchedulerArn"
case inferenceSchedulerName = "InferenceSchedulerName"
case modelArn = "ModelArn"
case modelName = "ModelName"
case roleArn = "RoleArn"
case serverSideKmsKeyId = "ServerSideKmsKeyId"
case status = "Status"
case updatedAt = "UpdatedAt"
}
}
public struct DescribeModelRequest: AWSEncodableShape {
/// The name of the ML model to be described.
public let modelName: String
public init(modelName: String) {
self.modelName = modelName
}
public func validate(name: String) throws {
try self.validate(self.modelName, name: "modelName", parent: name, max: 200)
try self.validate(self.modelName, name: "modelName", parent: name, min: 1)
try self.validate(self.modelName, name: "modelName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
}
private enum CodingKeys: String, CodingKey {
case modelName = "ModelName"
}
}
public struct DescribeModelResponse: AWSDecodableShape {
/// Indicates the time and date at which the ML model was created.
public let createdAt: Date?
/// The configuration is the TargetSamplingRate, which is the sampling rate of the data after post processing by Amazon Lookout for Equipment. For example, if you provide data that has been collected at a 1 second level and you want the system to resample the data at a 1 minute rate before training, the TargetSamplingRate is 1 minute. When providing a value for the TargetSamplingRate, you must attach the prefix "PT" to the rate you want. The value for a 1 second rate is therefore PT1S, the value for a 15 minute rate is PT15M, and the value for a 1 hour rate is PT1H
public let dataPreProcessingConfiguration: DataPreProcessingConfiguration?
/// The Amazon Resouce Name (ARN) of the dataset used to create the ML model being described.
public let datasetArn: String?
/// The name of the dataset being used by the ML being described.
public let datasetName: String?
/// Indicates the time reference in the dataset that was used to end the subset of evaluation data for the ML model.
public let evaluationDataEndTime: Date?
/// Indicates the time reference in the dataset that was used to begin the subset of evaluation data for the ML model.
public let evaluationDataStartTime: Date?
/// If the training of the ML model failed, this indicates the reason for that failure.
public let failedReason: String?
/// Specifies configuration information about the labels input, including its S3 location.
public let labelsInputConfiguration: LabelsInputConfiguration?
/// Indicates the last time the ML model was updated. The type of update is not specified.
public let lastUpdatedTime: Date?
/// The Amazon Resource Name (ARN) of the ML model being described.
public let modelArn: String?
/// The Model Metrics show an aggregated summary of the model's performance within the evaluation time range. This is the JSON content of the metrics created when evaluating the model.
public let modelMetrics: String?
/// The name of the ML model being described.
public let modelName: String?
/// Indicates that the asset associated with this sensor has been shut off. As long as this condition is met, Lookout for Equipment will not use data from this asset for training, evaluation, or inference.
public let offCondition: String?
/// The Amazon Resource Name (ARN) of a role with permission to access the data source for the ML model being described.
public let roleArn: String?
/// A JSON description of the data that is in each time series dataset, including names, column names, and data types.
public let schema: String?
/// Provides the identifier of the KMS key used to encrypt model data by Amazon Lookout for Equipment.
public let serverSideKmsKeyId: String?
/// Specifies the current status of the model being described. Status describes the status of the most recent action of the model.
public let status: ModelStatus?
/// Indicates the time reference in the dataset that was used to end the subset of training data for the ML model.
public let trainingDataEndTime: Date?
/// Indicates the time reference in the dataset that was used to begin the subset of training data for the ML model.
public let trainingDataStartTime: Date?
/// Indicates the time at which the training of the ML model was completed.
public let trainingExecutionEndTime: Date?
/// Indicates the time at which the training of the ML model began.
public let trainingExecutionStartTime: Date?
public init(createdAt: Date? = nil, dataPreProcessingConfiguration: DataPreProcessingConfiguration? = nil, datasetArn: String? = nil, datasetName: String? = nil, evaluationDataEndTime: Date? = nil, evaluationDataStartTime: Date? = nil, failedReason: String? = nil, labelsInputConfiguration: LabelsInputConfiguration? = nil, lastUpdatedTime: Date? = nil, modelArn: String? = nil, modelMetrics: String? = nil, modelName: String? = nil, offCondition: String? = nil, roleArn: String? = nil, schema: String? = nil, serverSideKmsKeyId: String? = nil, status: ModelStatus? = nil, trainingDataEndTime: Date? = nil, trainingDataStartTime: Date? = nil, trainingExecutionEndTime: Date? = nil, trainingExecutionStartTime: Date? = nil) {
self.createdAt = createdAt
self.dataPreProcessingConfiguration = dataPreProcessingConfiguration
self.datasetArn = datasetArn
self.datasetName = datasetName
self.evaluationDataEndTime = evaluationDataEndTime
self.evaluationDataStartTime = evaluationDataStartTime
self.failedReason = failedReason
self.labelsInputConfiguration = labelsInputConfiguration
self.lastUpdatedTime = lastUpdatedTime
self.modelArn = modelArn
self.modelMetrics = modelMetrics
self.modelName = modelName
self.offCondition = offCondition
self.roleArn = roleArn
self.schema = schema
self.serverSideKmsKeyId = serverSideKmsKeyId
self.status = status
self.trainingDataEndTime = trainingDataEndTime
self.trainingDataStartTime = trainingDataStartTime
self.trainingExecutionEndTime = trainingExecutionEndTime
self.trainingExecutionStartTime = trainingExecutionStartTime
}
private enum CodingKeys: String, CodingKey {
case createdAt = "CreatedAt"
case dataPreProcessingConfiguration = "DataPreProcessingConfiguration"
case datasetArn = "DatasetArn"
case datasetName = "DatasetName"
case evaluationDataEndTime = "EvaluationDataEndTime"
case evaluationDataStartTime = "EvaluationDataStartTime"
case failedReason = "FailedReason"
case labelsInputConfiguration = "LabelsInputConfiguration"
case lastUpdatedTime = "LastUpdatedTime"
case modelArn = "ModelArn"
case modelMetrics = "ModelMetrics"
case modelName = "ModelName"
case offCondition = "OffCondition"
case roleArn = "RoleArn"
case schema = "Schema"
case serverSideKmsKeyId = "ServerSideKmsKeyId"
case status = "Status"
case trainingDataEndTime = "TrainingDataEndTime"
case trainingDataStartTime = "TrainingDataStartTime"
case trainingExecutionEndTime = "TrainingExecutionEndTime"
case trainingExecutionStartTime = "TrainingExecutionStartTime"
}
}
public struct DuplicateTimestamps: AWSDecodableShape {
/// Indicates the total number of duplicate timestamps.
public let totalNumberOfDuplicateTimestamps: Int
public init(totalNumberOfDuplicateTimestamps: Int) {
self.totalNumberOfDuplicateTimestamps = totalNumberOfDuplicateTimestamps
}
private enum CodingKeys: String, CodingKey {
case totalNumberOfDuplicateTimestamps = "TotalNumberOfDuplicateTimestamps"
}
}
public struct InferenceExecutionSummary: AWSDecodableShape {
///
public let customerResultObject: S3Object?
/// Indicates the time reference in the dataset at which the inference execution stopped.
public let dataEndTime: Date?
/// Specifies configuration information for the input data for the inference scheduler, including delimiter, format, and dataset location.
public let dataInputConfiguration: InferenceInputConfiguration?
/// Specifies configuration information for the output results from for the inference execution, including the output Amazon S3 location.
public let dataOutputConfiguration: InferenceOutputConfiguration?
/// Indicates the time reference in the dataset at which the inference execution began.
public let dataStartTime: Date?
/// Specifies the reason for failure when an inference execution has failed.
public let failedReason: String?
/// The Amazon Resource Name (ARN) of the inference scheduler being used for the inference execution.
public let inferenceSchedulerArn: String?
/// The name of the inference scheduler being used for the inference execution.
public let inferenceSchedulerName: String?
/// The Amazon Resource Name (ARN) of the ML model used for the inference execution.
public let modelArn: String?
/// The name of the ML model being used for the inference execution.
public let modelName: String?
/// Indicates the start time at which the inference scheduler began the specific inference execution.
public let scheduledStartTime: Date?
/// Indicates the status of the inference execution.
public let status: InferenceExecutionStatus?
public init(customerResultObject: S3Object? = nil, dataEndTime: Date? = nil, dataInputConfiguration: InferenceInputConfiguration? = nil, dataOutputConfiguration: InferenceOutputConfiguration? = nil, dataStartTime: Date? = nil, failedReason: String? = nil, inferenceSchedulerArn: String? = nil, inferenceSchedulerName: String? = nil, modelArn: String? = nil, modelName: String? = nil, scheduledStartTime: Date? = nil, status: InferenceExecutionStatus? = nil) {
self.customerResultObject = customerResultObject
self.dataEndTime = dataEndTime
self.dataInputConfiguration = dataInputConfiguration
self.dataOutputConfiguration = dataOutputConfiguration
self.dataStartTime = dataStartTime
self.failedReason = failedReason
self.inferenceSchedulerArn = inferenceSchedulerArn
self.inferenceSchedulerName = inferenceSchedulerName
self.modelArn = modelArn
self.modelName = modelName
self.scheduledStartTime = scheduledStartTime
self.status = status
}
private enum CodingKeys: String, CodingKey {
case customerResultObject = "CustomerResultObject"
case dataEndTime = "DataEndTime"
case dataInputConfiguration = "DataInputConfiguration"
case dataOutputConfiguration = "DataOutputConfiguration"
case dataStartTime = "DataStartTime"
case failedReason = "FailedReason"
case inferenceSchedulerArn = "InferenceSchedulerArn"
case inferenceSchedulerName = "InferenceSchedulerName"
case modelArn = "ModelArn"
case modelName = "ModelName"
case scheduledStartTime = "ScheduledStartTime"
case status = "Status"
}
}
public struct InferenceInputConfiguration: AWSEncodableShape & AWSDecodableShape {
/// Specifies configuration information for the input data for the inference, including timestamp format and delimiter.
public let inferenceInputNameConfiguration: InferenceInputNameConfiguration?
/// Indicates the difference between your time zone and Coordinated Universal Time (UTC).
public let inputTimeZoneOffset: String?
/// Specifies configuration information for the input data for the inference, including Amazon S3 location of input data.
public let s3InputConfiguration: InferenceS3InputConfiguration?
public init(inferenceInputNameConfiguration: InferenceInputNameConfiguration? = nil, inputTimeZoneOffset: String? = nil, s3InputConfiguration: InferenceS3InputConfiguration? = nil) {
self.inferenceInputNameConfiguration = inferenceInputNameConfiguration
self.inputTimeZoneOffset = inputTimeZoneOffset
self.s3InputConfiguration = s3InputConfiguration
}
public func validate(name: String) throws {
try self.inferenceInputNameConfiguration?.validate(name: "\(name).inferenceInputNameConfiguration")
try self.validate(self.inputTimeZoneOffset, name: "inputTimeZoneOffset", parent: name, pattern: "^(\\+|\\-)[0-9]{2}\\:[0-9]{2}$")
try self.s3InputConfiguration?.validate(name: "\(name).s3InputConfiguration")
}
private enum CodingKeys: String, CodingKey {
case inferenceInputNameConfiguration = "InferenceInputNameConfiguration"
case inputTimeZoneOffset = "InputTimeZoneOffset"
case s3InputConfiguration = "S3InputConfiguration"
}
}
public struct InferenceInputNameConfiguration: AWSEncodableShape & AWSDecodableShape {
/// Indicates the delimiter character used between items in the data.
public let componentTimestampDelimiter: String?
/// The format of the timestamp, whether Epoch time, or standard, with or without hyphens (-).
public let timestampFormat: String?
public init(componentTimestampDelimiter: String? = nil, timestampFormat: String? = nil) {
self.componentTimestampDelimiter = componentTimestampDelimiter
self.timestampFormat = timestampFormat
}
public func validate(name: String) throws {
try self.validate(self.componentTimestampDelimiter, name: "componentTimestampDelimiter", parent: name, max: 1)
try self.validate(self.componentTimestampDelimiter, name: "componentTimestampDelimiter", parent: name, pattern: "^(\\-|\\_|\\s)?$")
try self.validate(self.timestampFormat, name: "timestampFormat", parent: name, pattern: "^EPOCH|yyyy-MM-dd-HH-mm-ss|yyyyMMddHHmmss$")
}
private enum CodingKeys: String, CodingKey {
case componentTimestampDelimiter = "ComponentTimestampDelimiter"
case timestampFormat = "TimestampFormat"
}
}
public struct InferenceOutputConfiguration: AWSEncodableShape & AWSDecodableShape {
/// The ID number for the AWS KMS key used to encrypt the inference output.
public let kmsKeyId: String?
/// Specifies configuration information for the output results from for the inference, output S3 location.
public let s3OutputConfiguration: InferenceS3OutputConfiguration
public init(kmsKeyId: String? = nil, s3OutputConfiguration: InferenceS3OutputConfiguration) {
self.kmsKeyId = kmsKeyId
self.s3OutputConfiguration = s3OutputConfiguration
}
public func validate(name: String) throws {
try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, max: 2048)
try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, min: 1)
try self.validate(self.kmsKeyId, name: "kmsKeyId", parent: name, pattern: "^[A-Za-z0-9][A-Za-z0-9:_/+=,@.-]{0,2048}$")
try self.s3OutputConfiguration.validate(name: "\(name).s3OutputConfiguration")
}
private enum CodingKeys: String, CodingKey {
case kmsKeyId = "KmsKeyId"
case s3OutputConfiguration = "S3OutputConfiguration"
}
}
public struct InferenceS3InputConfiguration: AWSEncodableShape & AWSDecodableShape {
/// The bucket containing the input dataset for the inference.
public let bucket: String
/// The prefix for the S3 bucket used for the input data for the inference.
public let prefix: String?
public init(bucket: String, prefix: String? = nil) {
self.bucket = bucket
self.prefix = prefix
}
public func validate(name: String) throws {
try self.validate(self.bucket, name: "bucket", parent: name, max: 63)
try self.validate(self.bucket, name: "bucket", parent: name, min: 3)
try self.validate(self.bucket, name: "bucket", parent: name, pattern: "^[a-z0-9][\\.\\-a-z0-9]{1,61}[a-z0-9]$")
try self.validate(self.prefix, name: "prefix", parent: name, max: 1024)
try self.validate(self.prefix, name: "prefix", parent: name, pattern: "^(^$)|([\\P{M}\\p{M}]{1,1023}/$)$")
}
private enum CodingKeys: String, CodingKey {
case bucket = "Bucket"
case prefix = "Prefix"
}
}
public struct InferenceS3OutputConfiguration: AWSEncodableShape & AWSDecodableShape {
/// The bucket containing the output results from the inference
public let bucket: String
/// The prefix for the S3 bucket used for the output results from the inference.
public let prefix: String?
public init(bucket: String, prefix: String? = nil) {
self.bucket = bucket
self.prefix = prefix
}
public func validate(name: String) throws {
try self.validate(self.bucket, name: "bucket", parent: name, max: 63)
try self.validate(self.bucket, name: "bucket", parent: name, min: 3)
try self.validate(self.bucket, name: "bucket", parent: name, pattern: "^[a-z0-9][\\.\\-a-z0-9]{1,61}[a-z0-9]$")
try self.validate(self.prefix, name: "prefix", parent: name, max: 1024)
try self.validate(self.prefix, name: "prefix", parent: name, pattern: "^(^$)|([\\P{M}\\p{M}]{1,1023}/$)$")
}
private enum CodingKeys: String, CodingKey {
case bucket = "Bucket"
case prefix = "Prefix"
}
}
public struct InferenceSchedulerSummary: AWSDecodableShape {
/// A period of time (in minutes) by which inference on the data is delayed after the data starts. For instance, if an offset delay time of five minutes was selected, inference will not begin on the data until the first data measurement after the five minute mark. For example, if five minutes is selected, the inference scheduler will wake up at the configured frequency with the additional five minute delay time to check the customer S3 bucket. The customer can upload data at the same frequency and they don't need to stop and restart the scheduler when uploading new data.
public let dataDelayOffsetInMinutes: Int64?
/// How often data is uploaded to the source S3 bucket for the input data. This value is the length of time between data uploads. For instance, if you select 5 minutes, Amazon Lookout for Equipment will upload the real-time data to the source bucket once every 5 minutes. This frequency also determines how often Amazon Lookout for Equipment starts a scheduled inference on your data. In this example, it starts once every 5 minutes.
public let dataUploadFrequency: DataUploadFrequency?
/// The Amazon Resource Name (ARN) of the inference scheduler.
public let inferenceSchedulerArn: String?
/// The name of the inference scheduler.
public let inferenceSchedulerName: String?
/// The Amazon Resource Name (ARN) of the ML model used by the inference scheduler.
public let modelArn: String?
/// The name of the ML model used for the inference scheduler.
public let modelName: String?
/// Indicates the status of the inference scheduler.
public let status: InferenceSchedulerStatus?
public init(dataDelayOffsetInMinutes: Int64? = nil, dataUploadFrequency: DataUploadFrequency? = nil, inferenceSchedulerArn: String? = nil, inferenceSchedulerName: String? = nil, modelArn: String? = nil, modelName: String? = nil, status: InferenceSchedulerStatus? = nil) {
self.dataDelayOffsetInMinutes = dataDelayOffsetInMinutes
self.dataUploadFrequency = dataUploadFrequency
self.inferenceSchedulerArn = inferenceSchedulerArn
self.inferenceSchedulerName = inferenceSchedulerName
self.modelArn = modelArn
self.modelName = modelName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case dataDelayOffsetInMinutes = "DataDelayOffsetInMinutes"
case dataUploadFrequency = "DataUploadFrequency"
case inferenceSchedulerArn = "InferenceSchedulerArn"
case inferenceSchedulerName = "InferenceSchedulerName"
case modelArn = "ModelArn"
case modelName = "ModelName"
case status = "Status"
}
}
public struct IngestedFilesSummary: AWSDecodableShape {
/// Indicates the number of files that were discarded. A file could be discarded because its format is invalid (for example, a jpg or pdf) or not readable.
public let discardedFiles: [S3Object]?
/// Indicates the number of files that were successfully ingested.
public let ingestedNumberOfFiles: Int
/// Indicates the total number of files that were submitted for ingestion.
public let totalNumberOfFiles: Int
public init(discardedFiles: [S3Object]? = nil, ingestedNumberOfFiles: Int, totalNumberOfFiles: Int) {
self.discardedFiles = discardedFiles
self.ingestedNumberOfFiles = ingestedNumberOfFiles
self.totalNumberOfFiles = totalNumberOfFiles
}
private enum CodingKeys: String, CodingKey {
case discardedFiles = "DiscardedFiles"
case ingestedNumberOfFiles = "IngestedNumberOfFiles"
case totalNumberOfFiles = "TotalNumberOfFiles"
}
}
public struct IngestionInputConfiguration: AWSEncodableShape & AWSDecodableShape {
/// The location information for the S3 bucket used for input data for the data ingestion.
public let s3InputConfiguration: IngestionS3InputConfiguration
public init(s3InputConfiguration: IngestionS3InputConfiguration) {
self.s3InputConfiguration = s3InputConfiguration
}
public func validate(name: String) throws {
try self.s3InputConfiguration.validate(name: "\(name).s3InputConfiguration")
}
private enum CodingKeys: String, CodingKey {
case s3InputConfiguration = "S3InputConfiguration"
}
}
public struct IngestionS3InputConfiguration: AWSEncodableShape & AWSDecodableShape {
/// The name of the S3 bucket used for the input data for the data ingestion.
public let bucket: String
/// Pattern for matching the Amazon S3 files which will be used for ingestion.
/// If no KeyPattern is provided, we will use the default hierarchy file structure, which is same as KeyPattern {prefix}/{component_name}/*
public let keyPattern: String?
/// The prefix for the S3 location being used for the input data for the data ingestion.
public let prefix: String?
public init(bucket: String, keyPattern: String? = nil, prefix: String? = nil) {
self.bucket = bucket
self.keyPattern = keyPattern
self.prefix = prefix
}
public func validate(name: String) throws {
try self.validate(self.bucket, name: "bucket", parent: name, max: 63)
try self.validate(self.bucket, name: "bucket", parent: name, min: 3)
try self.validate(self.bucket, name: "bucket", parent: name, pattern: "^[a-z0-9][\\.\\-a-z0-9]{1,61}[a-z0-9]$")
try self.validate(self.keyPattern, name: "keyPattern", parent: name, max: 2048)
try self.validate(self.keyPattern, name: "keyPattern", parent: name, min: 1)
try self.validate(self.prefix, name: "prefix", parent: name, max: 1024)
try self.validate(self.prefix, name: "prefix", parent: name, pattern: "^(^$)|([\\P{M}\\p{M}]{1,1023}/$)$")
}
private enum CodingKeys: String, CodingKey {
case bucket = "Bucket"
case keyPattern = "KeyPattern"
case prefix = "Prefix"
}
}
public struct InsufficientSensorData: AWSDecodableShape {
/// Parameter that describes the total number of sensors that have data completely missing for it.
public let missingCompleteSensorData: MissingCompleteSensorData
/// Parameter that describes the total number of sensors that have a short date range of less than 90 days of data overall.
public let sensorsWithShortDateRange: SensorsWithShortDateRange
public init(missingCompleteSensorData: MissingCompleteSensorData, sensorsWithShortDateRange: SensorsWithShortDateRange) {
self.missingCompleteSensorData = missingCompleteSensorData
self.sensorsWithShortDateRange = sensorsWithShortDateRange
}
private enum CodingKeys: String, CodingKey {
case missingCompleteSensorData = "MissingCompleteSensorData"
case sensorsWithShortDateRange = "SensorsWithShortDateRange"
}
}
public struct InvalidSensorData: AWSDecodableShape {
/// Indicates the number of sensors that have at least some invalid values.
public let affectedSensorCount: Int
/// Indicates the total number of invalid values across all the sensors.
public let totalNumberOfInvalidValues: Int
public init(affectedSensorCount: Int, totalNumberOfInvalidValues: Int) {
self.affectedSensorCount = affectedSensorCount
self.totalNumberOfInvalidValues = totalNumberOfInvalidValues
}
private enum CodingKeys: String, CodingKey {
case affectedSensorCount = "AffectedSensorCount"
case totalNumberOfInvalidValues = "TotalNumberOfInvalidValues"
}
}
public struct LabelsInputConfiguration: AWSEncodableShape & AWSDecodableShape {
/// Contains location information for the S3 location being used for label data.
public let s3InputConfiguration: LabelsS3InputConfiguration
public init(s3InputConfiguration: LabelsS3InputConfiguration) {
self.s3InputConfiguration = s3InputConfiguration
}
public func validate(name: String) throws {
try self.s3InputConfiguration.validate(name: "\(name).s3InputConfiguration")
}
private enum CodingKeys: String, CodingKey {
case s3InputConfiguration = "S3InputConfiguration"
}
}
public struct LabelsS3InputConfiguration: AWSEncodableShape & AWSDecodableShape {
/// The name of the S3 bucket holding the label data.
public let bucket: String
/// The prefix for the S3 bucket used for the label data.
public let prefix: String?
public init(bucket: String, prefix: String? = nil) {
self.bucket = bucket
self.prefix = prefix
}
public func validate(name: String) throws {
try self.validate(self.bucket, name: "bucket", parent: name, max: 63)
try self.validate(self.bucket, name: "bucket", parent: name, min: 3)
try self.validate(self.bucket, name: "bucket", parent: name, pattern: "^[a-z0-9][\\.\\-a-z0-9]{1,61}[a-z0-9]$")
try self.validate(self.prefix, name: "prefix", parent: name, max: 1024)
try self.validate(self.prefix, name: "prefix", parent: name, pattern: "^(^$)|([\\P{M}\\p{M}]{1,1023}/$)$")
}
private enum CodingKeys: String, CodingKey {
case bucket = "Bucket"
case prefix = "Prefix"
}
}
public struct LargeTimestampGaps: AWSDecodableShape {
/// Indicates the size of the largest timestamp gap, in days.
public let maxTimestampGapInDays: Int?
/// Indicates the number of large timestamp gaps, if there are any.
public let numberOfLargeTimestampGaps: Int?
/// Indicates whether there is a potential data issue related to large gaps in timestamps.
public let status: StatisticalIssueStatus
public init(maxTimestampGapInDays: Int? = nil, numberOfLargeTimestampGaps: Int? = nil, status: StatisticalIssueStatus) {
self.maxTimestampGapInDays = maxTimestampGapInDays
self.numberOfLargeTimestampGaps = numberOfLargeTimestampGaps
self.status = status
}
private enum CodingKeys: String, CodingKey {
case maxTimestampGapInDays = "MaxTimestampGapInDays"
case numberOfLargeTimestampGaps = "NumberOfLargeTimestampGaps"
case status = "Status"
}
}
public struct ListDataIngestionJobsRequest: AWSEncodableShape {
/// The name of the dataset being used for the data ingestion job.
public let datasetName: String?
/// Specifies the maximum number of data ingestion jobs to list.
public let maxResults: Int?
/// An opaque pagination token indicating where to continue the listing of data ingestion jobs.
public let nextToken: String?
/// Indicates the status of the data ingestion job.
public let status: IngestionJobStatus?
public init(datasetName: String? = nil, maxResults: Int? = nil, nextToken: String? = nil, status: IngestionJobStatus? = nil) {
self.datasetName = datasetName
self.maxResults = maxResults
self.nextToken = nextToken
self.status = status
}
public func validate(name: String) throws {
try self.validate(self.datasetName, name: "datasetName", parent: name, max: 200)
try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1)
try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 500)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 8192)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^\\p{ASCII}{0,8192}$")
}
private enum CodingKeys: String, CodingKey {
case datasetName = "DatasetName"
case maxResults = "MaxResults"
case nextToken = "NextToken"
case status = "Status"
}
}
public struct ListDataIngestionJobsResponse: AWSDecodableShape {
/// Specifies information about the specific data ingestion job, including dataset name and status.
public let dataIngestionJobSummaries: [DataIngestionJobSummary]?
/// An opaque pagination token indicating where to continue the listing of data ingestion jobs.
public let nextToken: String?
public init(dataIngestionJobSummaries: [DataIngestionJobSummary]? = nil, nextToken: String? = nil) {
self.dataIngestionJobSummaries = dataIngestionJobSummaries
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case dataIngestionJobSummaries = "DataIngestionJobSummaries"
case nextToken = "NextToken"
}
}
public struct ListDatasetsRequest: AWSEncodableShape {
/// The beginning of the name of the datasets to be listed.
public let datasetNameBeginsWith: String?
/// Specifies the maximum number of datasets to list.
public let maxResults: Int?
/// An opaque pagination token indicating where to continue the listing of datasets.
public let nextToken: String?
public init(datasetNameBeginsWith: String? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.datasetNameBeginsWith = datasetNameBeginsWith
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.datasetNameBeginsWith, name: "datasetNameBeginsWith", parent: name, max: 200)
try self.validate(self.datasetNameBeginsWith, name: "datasetNameBeginsWith", parent: name, min: 1)
try self.validate(self.datasetNameBeginsWith, name: "datasetNameBeginsWith", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 500)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 8192)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^\\p{ASCII}{0,8192}$")
}
private enum CodingKeys: String, CodingKey {
case datasetNameBeginsWith = "DatasetNameBeginsWith"
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListDatasetsResponse: AWSDecodableShape {
/// Provides information about the specified dataset, including creation time, dataset ARN, and status.
public let datasetSummaries: [DatasetSummary]?
/// An opaque pagination token indicating where to continue the listing of datasets.
public let nextToken: String?
public init(datasetSummaries: [DatasetSummary]? = nil, nextToken: String? = nil) {
self.datasetSummaries = datasetSummaries
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case datasetSummaries = "DatasetSummaries"
case nextToken = "NextToken"
}
}
public struct ListInferenceExecutionsRequest: AWSEncodableShape {
/// The time reference in the inferenced dataset before which Amazon Lookout for Equipment stopped the inference execution.
public let dataEndTimeBefore: Date?
/// The time reference in the inferenced dataset after which Amazon Lookout for Equipment started the inference execution.
public let dataStartTimeAfter: Date?
/// The name of the inference scheduler for the inference execution listed.
public let inferenceSchedulerName: String
/// Specifies the maximum number of inference executions to list.
public let maxResults: Int?
/// An opaque pagination token indicating where to continue the listing of inference executions.
public let nextToken: String?
/// The status of the inference execution.
public let status: InferenceExecutionStatus?
public init(dataEndTimeBefore: Date? = nil, dataStartTimeAfter: Date? = nil, inferenceSchedulerName: String, maxResults: Int? = nil, nextToken: String? = nil, status: InferenceExecutionStatus? = nil) {
self.dataEndTimeBefore = dataEndTimeBefore
self.dataStartTimeAfter = dataStartTimeAfter
self.inferenceSchedulerName = inferenceSchedulerName
self.maxResults = maxResults
self.nextToken = nextToken
self.status = status
}
public func validate(name: String) throws {
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, max: 200)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, min: 1)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 500)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 8192)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^\\p{ASCII}{0,8192}$")
}
private enum CodingKeys: String, CodingKey {
case dataEndTimeBefore = "DataEndTimeBefore"
case dataStartTimeAfter = "DataStartTimeAfter"
case inferenceSchedulerName = "InferenceSchedulerName"
case maxResults = "MaxResults"
case nextToken = "NextToken"
case status = "Status"
}
}
public struct ListInferenceExecutionsResponse: AWSDecodableShape {
/// Provides an array of information about the individual inference executions returned from the ListInferenceExecutions operation, including model used, inference scheduler, data configuration, and so on.
public let inferenceExecutionSummaries: [InferenceExecutionSummary]?
/// An opaque pagination token indicating where to continue the listing of inference executions.
public let nextToken: String?
public init(inferenceExecutionSummaries: [InferenceExecutionSummary]? = nil, nextToken: String? = nil) {
self.inferenceExecutionSummaries = inferenceExecutionSummaries
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case inferenceExecutionSummaries = "InferenceExecutionSummaries"
case nextToken = "NextToken"
}
}
public struct ListInferenceSchedulersRequest: AWSEncodableShape {
/// The beginning of the name of the inference schedulers to be listed.
public let inferenceSchedulerNameBeginsWith: String?
/// Specifies the maximum number of inference schedulers to list.
public let maxResults: Int?
/// The name of the ML model used by the inference scheduler to be listed.
public let modelName: String?
/// An opaque pagination token indicating where to continue the listing of inference schedulers.
public let nextToken: String?
public init(inferenceSchedulerNameBeginsWith: String? = nil, maxResults: Int? = nil, modelName: String? = nil, nextToken: String? = nil) {
self.inferenceSchedulerNameBeginsWith = inferenceSchedulerNameBeginsWith
self.maxResults = maxResults
self.modelName = modelName
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.inferenceSchedulerNameBeginsWith, name: "inferenceSchedulerNameBeginsWith", parent: name, max: 200)
try self.validate(self.inferenceSchedulerNameBeginsWith, name: "inferenceSchedulerNameBeginsWith", parent: name, min: 1)
try self.validate(self.inferenceSchedulerNameBeginsWith, name: "inferenceSchedulerNameBeginsWith", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 500)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.modelName, name: "modelName", parent: name, max: 200)
try self.validate(self.modelName, name: "modelName", parent: name, min: 1)
try self.validate(self.modelName, name: "modelName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 8192)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^\\p{ASCII}{0,8192}$")
}
private enum CodingKeys: String, CodingKey {
case inferenceSchedulerNameBeginsWith = "InferenceSchedulerNameBeginsWith"
case maxResults = "MaxResults"
case modelName = "ModelName"
case nextToken = "NextToken"
}
}
public struct ListInferenceSchedulersResponse: AWSDecodableShape {
/// Provides information about the specified inference scheduler, including data upload frequency, model name and ARN, and status.
public let inferenceSchedulerSummaries: [InferenceSchedulerSummary]?
/// An opaque pagination token indicating where to continue the listing of inference schedulers.
public let nextToken: String?
public init(inferenceSchedulerSummaries: [InferenceSchedulerSummary]? = nil, nextToken: String? = nil) {
self.inferenceSchedulerSummaries = inferenceSchedulerSummaries
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case inferenceSchedulerSummaries = "InferenceSchedulerSummaries"
case nextToken = "NextToken"
}
}
public struct ListModelsRequest: AWSEncodableShape {
/// The beginning of the name of the dataset of the ML models to be listed.
public let datasetNameBeginsWith: String?
/// Specifies the maximum number of ML models to list.
public let maxResults: Int?
/// The beginning of the name of the ML models being listed.
public let modelNameBeginsWith: String?
/// An opaque pagination token indicating where to continue the listing of ML models.
public let nextToken: String?
/// The status of the ML model.
public let status: ModelStatus?
public init(datasetNameBeginsWith: String? = nil, maxResults: Int? = nil, modelNameBeginsWith: String? = nil, nextToken: String? = nil, status: ModelStatus? = nil) {
self.datasetNameBeginsWith = datasetNameBeginsWith
self.maxResults = maxResults
self.modelNameBeginsWith = modelNameBeginsWith
self.nextToken = nextToken
self.status = status
}
public func validate(name: String) throws {
try self.validate(self.datasetNameBeginsWith, name: "datasetNameBeginsWith", parent: name, max: 200)
try self.validate(self.datasetNameBeginsWith, name: "datasetNameBeginsWith", parent: name, min: 1)
try self.validate(self.datasetNameBeginsWith, name: "datasetNameBeginsWith", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 500)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.modelNameBeginsWith, name: "modelNameBeginsWith", parent: name, max: 200)
try self.validate(self.modelNameBeginsWith, name: "modelNameBeginsWith", parent: name, min: 1)
try self.validate(self.modelNameBeginsWith, name: "modelNameBeginsWith", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 8192)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^\\p{ASCII}{0,8192}$")
}
private enum CodingKeys: String, CodingKey {
case datasetNameBeginsWith = "DatasetNameBeginsWith"
case maxResults = "MaxResults"
case modelNameBeginsWith = "ModelNameBeginsWith"
case nextToken = "NextToken"
case status = "Status"
}
}
public struct ListModelsResponse: AWSDecodableShape {
/// Provides information on the specified model, including created time, model and dataset ARNs, and status.
public let modelSummaries: [ModelSummary]?
/// An opaque pagination token indicating where to continue the listing of ML models.
public let nextToken: String?
public init(modelSummaries: [ModelSummary]? = nil, nextToken: String? = nil) {
self.modelSummaries = modelSummaries
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case modelSummaries = "ModelSummaries"
case nextToken = "NextToken"
}
}
public struct ListSensorStatisticsRequest: AWSEncodableShape {
/// The name of the dataset associated with the list of Sensor Statistics.
public let datasetName: String
/// The ingestion job id associated with the list of Sensor Statistics. To get sensor statistics for a particular ingestion job id, both dataset name and ingestion job id must be submitted as inputs.
public let ingestionJobId: String?
/// Specifies the maximum number of sensors for which to retrieve statistics.
public let maxResults: Int?
/// An opaque pagination token indicating where to continue the listing of sensor statistics.
public let nextToken: String?
public init(datasetName: String, ingestionJobId: String? = nil, maxResults: Int? = nil, nextToken: String? = nil) {
self.datasetName = datasetName
self.ingestionJobId = ingestionJobId
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.datasetName, name: "datasetName", parent: name, max: 200)
try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1)
try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.ingestionJobId, name: "ingestionJobId", parent: name, max: 32)
try self.validate(self.ingestionJobId, name: "ingestionJobId", parent: name, pattern: "^[A-Fa-f0-9]{0,32}$")
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 500)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
try self.validate(self.nextToken, name: "nextToken", parent: name, max: 8192)
try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^\\p{ASCII}{0,8192}$")
}
private enum CodingKeys: String, CodingKey {
case datasetName = "DatasetName"
case ingestionJobId = "IngestionJobId"
case maxResults = "MaxResults"
case nextToken = "NextToken"
}
}
public struct ListSensorStatisticsResponse: AWSDecodableShape {
/// An opaque pagination token indicating where to continue the listing of sensor statistics.
public let nextToken: String?
/// Provides ingestion-based statistics regarding the specified sensor with respect to various validation types, such as whether data exists, the number and percentage of missing values, and the number and percentage of duplicate timestamps.
public let sensorStatisticsSummaries: [SensorStatisticsSummary]?
public init(nextToken: String? = nil, sensorStatisticsSummaries: [SensorStatisticsSummary]? = nil) {
self.nextToken = nextToken
self.sensorStatisticsSummaries = sensorStatisticsSummaries
}
private enum CodingKeys: String, CodingKey {
case nextToken = "NextToken"
case sensorStatisticsSummaries = "SensorStatisticsSummaries"
}
}
public struct ListTagsForResourceRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the resource (such as the dataset or model) that is the focus of the ListTagsForResource operation.
public let resourceArn: String
public init(resourceArn: String) {
self.resourceArn = resourceArn
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 1011)
try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case resourceArn = "ResourceArn"
}
}
public struct ListTagsForResourceResponse: AWSDecodableShape {
/// Any tags associated with the resource.
public let tags: [Tag]?
public init(tags: [Tag]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags = "Tags"
}
}
public struct MissingCompleteSensorData: AWSDecodableShape {
/// Indicates the number of sensors that have data missing completely.
public let affectedSensorCount: Int
public init(affectedSensorCount: Int) {
self.affectedSensorCount = affectedSensorCount
}
private enum CodingKeys: String, CodingKey {
case affectedSensorCount = "AffectedSensorCount"
}
}
public struct MissingSensorData: AWSDecodableShape {
/// Indicates the number of sensors that have atleast some data missing.
public let affectedSensorCount: Int
/// Indicates the total number of missing values across all the sensors.
public let totalNumberOfMissingValues: Int
public init(affectedSensorCount: Int, totalNumberOfMissingValues: Int) {
self.affectedSensorCount = affectedSensorCount
self.totalNumberOfMissingValues = totalNumberOfMissingValues
}
private enum CodingKeys: String, CodingKey {
case affectedSensorCount = "AffectedSensorCount"
case totalNumberOfMissingValues = "TotalNumberOfMissingValues"
}
}
public struct ModelSummary: AWSDecodableShape {
/// The time at which the specific model was created.
public let createdAt: Date?
/// The Amazon Resource Name (ARN) of the dataset used to create the model.
public let datasetArn: String?
/// The name of the dataset being used for the ML model.
public let datasetName: String?
/// The Amazon Resource Name (ARN) of the ML model.
public let modelArn: String?
/// The name of the ML model.
public let modelName: String?
/// Indicates the status of the ML model.
public let status: ModelStatus?
public init(createdAt: Date? = nil, datasetArn: String? = nil, datasetName: String? = nil, modelArn: String? = nil, modelName: String? = nil, status: ModelStatus? = nil) {
self.createdAt = createdAt
self.datasetArn = datasetArn
self.datasetName = datasetName
self.modelArn = modelArn
self.modelName = modelName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case createdAt = "CreatedAt"
case datasetArn = "DatasetArn"
case datasetName = "DatasetName"
case modelArn = "ModelArn"
case modelName = "ModelName"
case status = "Status"
}
}
public struct MonotonicValues: AWSDecodableShape {
/// Indicates the monotonicity of values. Can be INCREASING, DECREASING, or STATIC.
public let monotonicity: Monotonicity?
/// Indicates whether there is a potential data issue related to having monotonic values.
public let status: StatisticalIssueStatus
public init(monotonicity: Monotonicity? = nil, status: StatisticalIssueStatus) {
self.monotonicity = monotonicity
self.status = status
}
private enum CodingKeys: String, CodingKey {
case monotonicity = "Monotonicity"
case status = "Status"
}
}
public struct MultipleOperatingModes: AWSDecodableShape {
/// Indicates whether there is a potential data issue related to having multiple operating modes.
public let status: StatisticalIssueStatus
public init(status: StatisticalIssueStatus) {
self.status = status
}
private enum CodingKeys: String, CodingKey {
case status = "Status"
}
}
public struct S3Object: AWSDecodableShape {
/// The name of the specific S3 bucket.
public let bucket: String
/// The AWS Key Management Service (AWS KMS) key being used to encrypt the S3 object. Without this key, data in the bucket is not accessible.
public let key: String
public init(bucket: String, key: String) {
self.bucket = bucket
self.key = key
}
private enum CodingKeys: String, CodingKey {
case bucket = "Bucket"
case key = "Key"
}
}
public struct SensorStatisticsSummary: AWSDecodableShape {
/// Parameter that describes potential risk about whether data associated with the sensor is categorical.
public let categoricalValues: CategoricalValues?
/// Name of the component to which the particular sensor belongs for which the statistics belong to.
public let componentName: String?
/// Indicates the time reference to indicate the end of valid data associated with the sensor that the statistics belong to.
public let dataEndTime: Date?
/// Parameter that indicates whether data exists for the sensor that the statistics belong to.
public let dataExists: Bool?
/// Indicates the time reference to indicate the beginning of valid data associated with the sensor that the statistics belong to.
public let dataStartTime: Date?
/// Parameter that describes the total number of duplicate timestamp records associated with the sensor that the statistics belong to.
public let duplicateTimestamps: CountPercent?
/// Parameter that describes the total number of invalid date entries associated with the sensor that the statistics belong to.
public let invalidDateEntries: CountPercent?
/// Parameter that describes the total number of, and percentage of, values that are invalid for the sensor that the statistics belong to.
public let invalidValues: CountPercent?
/// Parameter that describes potential risk about whether data associated with the sensor contains one or more large gaps between consecutive timestamps.
public let largeTimestampGaps: LargeTimestampGaps?
/// Parameter that describes the total number of, and percentage of, values that are missing for the sensor that the statistics belong to.
public let missingValues: CountPercent?
/// Parameter that describes potential risk about whether data associated with the sensor is mostly monotonic.
public let monotonicValues: MonotonicValues?
/// Parameter that describes potential risk about whether data associated with the sensor has more than one operating mode.
public let multipleOperatingModes: MultipleOperatingModes?
/// Name of the sensor that the statistics belong to.
public let sensorName: String?
public init(categoricalValues: CategoricalValues? = nil, componentName: String? = nil, dataEndTime: Date? = nil, dataExists: Bool? = nil, dataStartTime: Date? = nil, duplicateTimestamps: CountPercent? = nil, invalidDateEntries: CountPercent? = nil, invalidValues: CountPercent? = nil, largeTimestampGaps: LargeTimestampGaps? = nil, missingValues: CountPercent? = nil, monotonicValues: MonotonicValues? = nil, multipleOperatingModes: MultipleOperatingModes? = nil, sensorName: String? = nil) {
self.categoricalValues = categoricalValues
self.componentName = componentName
self.dataEndTime = dataEndTime
self.dataExists = dataExists
self.dataStartTime = dataStartTime
self.duplicateTimestamps = duplicateTimestamps
self.invalidDateEntries = invalidDateEntries
self.invalidValues = invalidValues
self.largeTimestampGaps = largeTimestampGaps
self.missingValues = missingValues
self.monotonicValues = monotonicValues
self.multipleOperatingModes = multipleOperatingModes
self.sensorName = sensorName
}
private enum CodingKeys: String, CodingKey {
case categoricalValues = "CategoricalValues"
case componentName = "ComponentName"
case dataEndTime = "DataEndTime"
case dataExists = "DataExists"
case dataStartTime = "DataStartTime"
case duplicateTimestamps = "DuplicateTimestamps"
case invalidDateEntries = "InvalidDateEntries"
case invalidValues = "InvalidValues"
case largeTimestampGaps = "LargeTimestampGaps"
case missingValues = "MissingValues"
case monotonicValues = "MonotonicValues"
case multipleOperatingModes = "MultipleOperatingModes"
case sensorName = "SensorName"
}
}
public struct SensorsWithShortDateRange: AWSDecodableShape {
/// Indicates the number of sensors that have less than 90 days of data.
public let affectedSensorCount: Int
public init(affectedSensorCount: Int) {
self.affectedSensorCount = affectedSensorCount
}
private enum CodingKeys: String, CodingKey {
case affectedSensorCount = "AffectedSensorCount"
}
}
public struct StartDataIngestionJobRequest: AWSEncodableShape {
/// A unique identifier for the request. If you do not set the client request token, Amazon Lookout for Equipment generates one.
public let clientToken: String
/// The name of the dataset being used by the data ingestion job.
public let datasetName: String
/// Specifies information for the input data for the data ingestion job, including dataset S3 location.
public let ingestionInputConfiguration: IngestionInputConfiguration
/// The Amazon Resource Name (ARN) of a role with permission to access the data source for the data ingestion job.
public let roleArn: String
public init(clientToken: String = StartDataIngestionJobRequest.idempotencyToken(), datasetName: String, ingestionInputConfiguration: IngestionInputConfiguration, roleArn: String) {
self.clientToken = clientToken
self.datasetName = datasetName
self.ingestionInputConfiguration = ingestionInputConfiguration
self.roleArn = roleArn
}
public func validate(name: String) throws {
try self.validate(self.clientToken, name: "clientToken", parent: name, max: 256)
try self.validate(self.clientToken, name: "clientToken", parent: name, min: 1)
try self.validate(self.clientToken, name: "clientToken", parent: name, pattern: "^\\p{ASCII}{1,256}$")
try self.validate(self.datasetName, name: "datasetName", parent: name, max: 200)
try self.validate(self.datasetName, name: "datasetName", parent: name, min: 1)
try self.validate(self.datasetName, name: "datasetName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.ingestionInputConfiguration.validate(name: "\(name).ingestionInputConfiguration")
try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048)
try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20)
try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:aws(-[^:]+)?:iam::[0-9]{12}:role/.+$")
}
private enum CodingKeys: String, CodingKey {
case clientToken = "ClientToken"
case datasetName = "DatasetName"
case ingestionInputConfiguration = "IngestionInputConfiguration"
case roleArn = "RoleArn"
}
}
public struct StartDataIngestionJobResponse: AWSDecodableShape {
/// Indicates the job ID of the data ingestion job.
public let jobId: String?
/// Indicates the status of the StartDataIngestionJob operation.
public let status: IngestionJobStatus?
public init(jobId: String? = nil, status: IngestionJobStatus? = nil) {
self.jobId = jobId
self.status = status
}
private enum CodingKeys: String, CodingKey {
case jobId = "JobId"
case status = "Status"
}
}
public struct StartInferenceSchedulerRequest: AWSEncodableShape {
/// The name of the inference scheduler to be started.
public let inferenceSchedulerName: String
public init(inferenceSchedulerName: String) {
self.inferenceSchedulerName = inferenceSchedulerName
}
public func validate(name: String) throws {
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, max: 200)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, min: 1)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
}
private enum CodingKeys: String, CodingKey {
case inferenceSchedulerName = "InferenceSchedulerName"
}
}
public struct StartInferenceSchedulerResponse: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the inference scheduler being started.
public let inferenceSchedulerArn: String?
/// The name of the inference scheduler being started.
public let inferenceSchedulerName: String?
/// The Amazon Resource Name (ARN) of the ML model being used by the inference scheduler.
public let modelArn: String?
/// The name of the ML model being used by the inference scheduler.
public let modelName: String?
/// Indicates the status of the inference scheduler.
public let status: InferenceSchedulerStatus?
public init(inferenceSchedulerArn: String? = nil, inferenceSchedulerName: String? = nil, modelArn: String? = nil, modelName: String? = nil, status: InferenceSchedulerStatus? = nil) {
self.inferenceSchedulerArn = inferenceSchedulerArn
self.inferenceSchedulerName = inferenceSchedulerName
self.modelArn = modelArn
self.modelName = modelName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case inferenceSchedulerArn = "InferenceSchedulerArn"
case inferenceSchedulerName = "InferenceSchedulerName"
case modelArn = "ModelArn"
case modelName = "ModelName"
case status = "Status"
}
}
public struct StopInferenceSchedulerRequest: AWSEncodableShape {
/// The name of the inference scheduler to be stopped.
public let inferenceSchedulerName: String
public init(inferenceSchedulerName: String) {
self.inferenceSchedulerName = inferenceSchedulerName
}
public func validate(name: String) throws {
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, max: 200)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, min: 1)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
}
private enum CodingKeys: String, CodingKey {
case inferenceSchedulerName = "InferenceSchedulerName"
}
}
public struct StopInferenceSchedulerResponse: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the inference schedule being stopped.
public let inferenceSchedulerArn: String?
/// The name of the inference scheduler being stopped.
public let inferenceSchedulerName: String?
/// The Amazon Resource Name (ARN) of the ML model used by the inference scheduler being stopped.
public let modelArn: String?
/// The name of the ML model used by the inference scheduler being stopped.
public let modelName: String?
/// Indicates the status of the inference scheduler.
public let status: InferenceSchedulerStatus?
public init(inferenceSchedulerArn: String? = nil, inferenceSchedulerName: String? = nil, modelArn: String? = nil, modelName: String? = nil, status: InferenceSchedulerStatus? = nil) {
self.inferenceSchedulerArn = inferenceSchedulerArn
self.inferenceSchedulerName = inferenceSchedulerName
self.modelArn = modelArn
self.modelName = modelName
self.status = status
}
private enum CodingKeys: String, CodingKey {
case inferenceSchedulerArn = "InferenceSchedulerArn"
case inferenceSchedulerName = "InferenceSchedulerName"
case modelArn = "ModelArn"
case modelName = "ModelName"
case status = "Status"
}
}
public struct Tag: AWSEncodableShape & AWSDecodableShape {
/// The key for the specified tag.
public let key: String
/// The value for the specified tag.
public let value: String
public init(key: String, value: String) {
self.key = key
self.value = value
}
public func validate(name: String) throws {
try self.validate(self.key, name: "key", parent: name, max: 128)
try self.validate(self.key, name: "key", parent: name, min: 1)
try self.validate(self.key, name: "key", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$")
try self.validate(self.value, name: "value", parent: name, max: 256)
try self.validate(self.value, name: "value", parent: name, pattern: "^[\\s\\w+-=\\.:/@]*$")
}
private enum CodingKeys: String, CodingKey {
case key = "Key"
case value = "Value"
}
}
public struct TagResourceRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the specific resource to which the tag should be associated.
public let resourceArn: String
/// The tag or tags to be associated with a specific resource. Both the tag key and value are specified.
public let tags: [Tag]
public init(resourceArn: String, tags: [Tag]) {
self.resourceArn = resourceArn
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 1011)
try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 1)
try self.tags.forEach {
try $0.validate(name: "\(name).tags[]")
}
try self.validate(self.tags, name: "tags", parent: name, max: 200)
}
private enum CodingKeys: String, CodingKey {
case resourceArn = "ResourceArn"
case tags = "Tags"
}
}
public struct TagResourceResponse: AWSDecodableShape {
public init() {}
}
public struct UnsupportedTimestamps: AWSDecodableShape {
/// Indicates the total number of unsupported timestamps across the ingested data.
public let totalNumberOfUnsupportedTimestamps: Int
public init(totalNumberOfUnsupportedTimestamps: Int) {
self.totalNumberOfUnsupportedTimestamps = totalNumberOfUnsupportedTimestamps
}
private enum CodingKeys: String, CodingKey {
case totalNumberOfUnsupportedTimestamps = "TotalNumberOfUnsupportedTimestamps"
}
}
public struct UntagResourceRequest: AWSEncodableShape {
/// The Amazon Resource Name (ARN) of the resource to which the tag is currently associated.
public let resourceArn: String
/// Specifies the key of the tag to be removed from a specified resource.
public let tagKeys: [String]
public init(resourceArn: String, tagKeys: [String]) {
self.resourceArn = resourceArn
self.tagKeys = tagKeys
}
public func validate(name: String) throws {
try self.validate(self.resourceArn, name: "resourceArn", parent: name, max: 1011)
try self.validate(self.resourceArn, name: "resourceArn", parent: name, min: 1)
try self.tagKeys.forEach {
try validate($0, name: "tagKeys[]", parent: name, max: 128)
try validate($0, name: "tagKeys[]", parent: name, min: 1)
try validate($0, name: "tagKeys[]", parent: name, pattern: "^(?!aws:)[a-zA-Z+-=._:/]+$")
}
try self.validate(self.tagKeys, name: "tagKeys", parent: name, max: 200)
}
private enum CodingKeys: String, CodingKey {
case resourceArn = "ResourceArn"
case tagKeys = "TagKeys"
}
}
public struct UntagResourceResponse: AWSDecodableShape {
public init() {}
}
public struct UpdateInferenceSchedulerRequest: AWSEncodableShape {
/// A period of time (in minutes) by which inference on the data is delayed after the data starts. For instance, if you select an offset delay time of five minutes, inference will not begin on the data until the first data measurement after the five minute mark. For example, if five minutes is selected, the inference scheduler will wake up at the configured frequency with the additional five minute delay time to check the customer S3 bucket. The customer can upload data at the same frequency and they don't need to stop and restart the scheduler when uploading new data.
public let dataDelayOffsetInMinutes: Int64?
/// Specifies information for the input data for the inference scheduler, including delimiter, format, and dataset location.
public let dataInputConfiguration: InferenceInputConfiguration?
/// Specifies information for the output results from the inference scheduler, including the output S3 location.
public let dataOutputConfiguration: InferenceOutputConfiguration?
/// How often data is uploaded to the source S3 bucket for the input data. The value chosen is the length of time between data uploads. For instance, if you select 5 minutes, Amazon Lookout for Equipment will upload the real-time data to the source bucket once every 5 minutes. This frequency also determines how often Amazon Lookout for Equipment starts a scheduled inference on your data. In this example, it starts once every 5 minutes.
public let dataUploadFrequency: DataUploadFrequency?
/// The name of the inference scheduler to be updated.
public let inferenceSchedulerName: String
/// The Amazon Resource Name (ARN) of a role with permission to access the data source for the inference scheduler.
public let roleArn: String?
public init(dataDelayOffsetInMinutes: Int64? = nil, dataInputConfiguration: InferenceInputConfiguration? = nil, dataOutputConfiguration: InferenceOutputConfiguration? = nil, dataUploadFrequency: DataUploadFrequency? = nil, inferenceSchedulerName: String, roleArn: String? = nil) {
self.dataDelayOffsetInMinutes = dataDelayOffsetInMinutes
self.dataInputConfiguration = dataInputConfiguration
self.dataOutputConfiguration = dataOutputConfiguration
self.dataUploadFrequency = dataUploadFrequency
self.inferenceSchedulerName = inferenceSchedulerName
self.roleArn = roleArn
}
public func validate(name: String) throws {
try self.validate(self.dataDelayOffsetInMinutes, name: "dataDelayOffsetInMinutes", parent: name, max: 60)
try self.validate(self.dataDelayOffsetInMinutes, name: "dataDelayOffsetInMinutes", parent: name, min: 0)
try self.dataInputConfiguration?.validate(name: "\(name).dataInputConfiguration")
try self.dataOutputConfiguration?.validate(name: "\(name).dataOutputConfiguration")
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, max: 200)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, min: 1)
try self.validate(self.inferenceSchedulerName, name: "inferenceSchedulerName", parent: name, pattern: "^[0-9a-zA-Z_-]{1,200}$")
try self.validate(self.roleArn, name: "roleArn", parent: name, max: 2048)
try self.validate(self.roleArn, name: "roleArn", parent: name, min: 20)
try self.validate(self.roleArn, name: "roleArn", parent: name, pattern: "^arn:aws(-[^:]+)?:iam::[0-9]{12}:role/.+$")
}
private enum CodingKeys: String, CodingKey {
case dataDelayOffsetInMinutes = "DataDelayOffsetInMinutes"
case dataInputConfiguration = "DataInputConfiguration"
case dataOutputConfiguration = "DataOutputConfiguration"
case dataUploadFrequency = "DataUploadFrequency"
case inferenceSchedulerName = "InferenceSchedulerName"
case roleArn = "RoleArn"
}
}
}
| 55.178456 | 732 | 0.674607 |
bf8f056d8a86cbaad19fac7e436da6d6614d1345 | 5,418 | /**
* MetaModel.swift
*
* Copyright 2015 Tony Stone
*
* 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.
*
* Created by Tony Stone on 12/10/15.
*/
import Foundation
import CoreData
internal class MetaModel: NSManagedObjectModel {
override init() {
super.init()
self.entities = [self.metaLogEntry(), self.refreshStatus()]
self.versionIdentifiers = [1]
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
fileprivate func metaLogEntry() -> NSEntityDescription {
var attributes = [NSAttributeDescription]()
let sequenceNumber = NSAttributeDescription()
sequenceNumber.name = "sequenceNumber"
sequenceNumber.isOptional = false
sequenceNumber.attributeType = NSAttributeType.integer32AttributeType
attributes.append(sequenceNumber)
let previousSequenceNumber = NSAttributeDescription()
previousSequenceNumber.name = "previousSequenceNumber"
previousSequenceNumber.isOptional = false
previousSequenceNumber.attributeType = NSAttributeType.integer32AttributeType
attributes.append(previousSequenceNumber)
let transactionID = NSAttributeDescription()
transactionID.name = "transactionID"
transactionID.isOptional = false
transactionID.attributeType = NSAttributeType.stringAttributeType
attributes.append(transactionID)
let timestamp = NSAttributeDescription()
timestamp.name = "timestamp"
timestamp.isOptional = false
timestamp.attributeType = NSAttributeType.dateAttributeType
attributes.append(timestamp)
let type = NSAttributeDescription()
type.name = "type"
type.isOptional = false
type.attributeType = NSAttributeType.integer32AttributeType
attributes.append(type)
let updateEntityName = NSAttributeDescription()
updateEntityName.name = "updateEntityName"
updateEntityName.isOptional = true
updateEntityName.attributeType = NSAttributeType.stringAttributeType
attributes.append(updateEntityName)
let updateObjectID = NSAttributeDescription()
updateObjectID.name = "updateObjectID"
updateObjectID.isOptional = true
updateObjectID.attributeType = NSAttributeType.stringAttributeType
attributes.append(updateObjectID)
let updateUniqueID = NSAttributeDescription()
updateUniqueID.name = "updateUniqueID"
updateUniqueID.isOptional = true
updateUniqueID.attributeType = NSAttributeType.stringAttributeType
attributes.append(updateUniqueID)
let updateData = NSAttributeDescription()
updateData.name = "updateData"
updateData.isOptional = true
updateData.attributeType = NSAttributeType.transformableAttributeType
attributes.append(updateData)
let entity = NSEntityDescription()
entity.name = "MetaLogEntry"
entity.managedObjectClassName = "MetaLogEntry"
entity.properties = attributes
return entity;
}
fileprivate func refreshStatus() -> NSEntityDescription {
var attributes = [NSAttributeDescription]()
let name = NSAttributeDescription()
name.name = "name"
name.isOptional = false
name.attributeType = NSAttributeType.stringAttributeType
attributes.append(name)
let type = NSAttributeDescription()
type.name = "type"
type.isOptional = false
type.attributeType = NSAttributeType.stringAttributeType
// type.defaultValue = kDefaultRefreshType
attributes.append(type)
let scope = NSAttributeDescription()
scope.name = "scope"
scope.isOptional = true
scope.attributeType = NSAttributeType.stringAttributeType
scope.isIndexed = true
attributes.append(scope)
let lastSyncError = NSAttributeDescription()
lastSyncError.name = "lastSyncError"
lastSyncError.isOptional = true
lastSyncError.attributeType = NSAttributeType.transformableAttributeType
attributes.append(lastSyncError)
let lastSyncStatus = NSAttributeDescription()
lastSyncStatus.name = "lastSyncStatus"
lastSyncStatus.isOptional = true
lastSyncStatus.attributeType = NSAttributeType.integer32AttributeType
attributes.append(lastSyncStatus)
let lastSyncTime = NSAttributeDescription()
lastSyncTime.name = "lastSyncTime"
lastSyncTime.isOptional = true
lastSyncTime.attributeType = NSAttributeType.dateAttributeType
attributes.append(lastSyncTime)
let entity = NSEntityDescription()
entity.name = "RefreshStatus"
entity.managedObjectClassName = "RefreshStatus"
entity.properties = attributes
return entity;
}
}
| 34.954839 | 85 | 0.700258 |
295ff528c8995b332e5c7b4ffd6c3ab9664ac6a5 | 2,411 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import NIO
import NIOHTTP1
class HTTPServerProtocolErrorHandlerTest: XCTestCase {
func testHandlesBasicErrors() throws {
let channel = EmbeddedChannel()
XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).wait())
var buffer = channel.allocator.buffer(capacity: 1024)
buffer.write(staticString: "GET / HTTP/1.1\r\nContent-Length: -4\r\n\r\n")
do {
try channel.writeInbound(buffer)
} catch HTTPParserError.invalidContentLength {
// This error is expected
}
(channel.eventLoop as! EmbeddedEventLoop).run()
// The channel should be closed at this stage.
XCTAssertNoThrow(try channel.closeFuture.wait())
// We expect exactly one ByteBuffer in the output.
guard case .some(.byteBuffer(var written)) = channel.readOutbound() else {
XCTFail("No writes")
return
}
XCTAssertNil(channel.readOutbound())
// Check the response.
assertResponseIs(response: written.readString(length: written.readableBytes)!,
expectedResponseLine: "HTTP/1.1 400 Bad Request",
expectedResponseHeaders: ["Connection: close", "Content-Length: 0"])
}
func testIgnoresNonParserErrors() throws {
enum DummyError: Error {
case error
}
let channel = EmbeddedChannel()
XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withErrorHandling: true).wait())
channel.pipeline.fireErrorCaught(DummyError.error)
do {
try channel.throwIfErrorCaught()
XCTFail("No error caught")
} catch DummyError.error {
// ok
} catch {
XCTFail("Unexpected error: \(error)")
}
XCTAssertNoThrow(try channel.finish())
}
}
| 34.442857 | 106 | 0.60141 |
b927f93fbed24ee8c351ecc17ebc5baf31fadd3f | 636 | // Copyright (c) 2014 segfault.jp. All rights reserved.
public enum Either<L, R> {
case Left(L), Right(R)
public func fold<V>(@noescape lhs: L -> V, @noescape _ rhs: R -> V) -> V {
switch self {
case .Left (let e): return lhs(e)
case .Right(let e): return rhs(e)
}
}
public var right: R? { return fold(null, {$0}) }
public var left: L? { return fold({$0}, null) }
}
func null<A, B>(_: A) -> B? { return nil }
public func == <L: Equatable, R: Equatable>(lhs: Either<L, R>, rhs: Either<L, R>) -> Bool {
return lhs.fold({$0 == rhs.left}, {$0 == rhs.right})
}
| 26.5 | 91 | 0.533019 |
1d1995b926bdf6cff8efd0349f57925d592b9d0c | 123 | import XCTest
import DisruptorTests
var tests = [XCTestCaseEntry]()
tests += DisruptorTests.__allTests()
XCTMain(tests)
| 13.666667 | 36 | 0.780488 |
e53391a8aafeb5aa40d5f470d9c71913cd155227 | 972 | //
// Pixabay4MLTests.swift
// Pixabay4MLTests
//
// Created by qd-hxt on 2017/12/7.
// Copyright © 2017年 qding. All rights reserved.
//
import XCTest
@testable import Pixabay4ML
class Pixabay4MLTests: 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.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.27027 | 111 | 0.633745 |
ef0f8c9221776a3d3678e5615343774ad2d738e9 | 1,078 | //
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
import UIKit
public extension UIDevice {
class var isPad: Bool {
return current.userInterfaceIdiom == .pad
}
class var isPhone: Bool {
return current.userInterfaceIdiom == .phone
}
class var isPhone5or5s: Bool {
return isPhone && (UIScreen.main.bounds.size.height == 568 || UIScreen.main.bounds.size.width == 568)
}
class var isPhone6orLarger: Bool {
return isPhone && (UIScreen.main.bounds.size.height >= 667 || UIScreen.main.bounds.size.width >= 667)
}
class var isPhonePlus: Bool {
return isPhone && (UIScreen.main.bounds.size.height == 736 || UIScreen.main.bounds.size.width == 736)
}
class var isPhoneX: Bool {
return isPhone && (UIScreen.main.bounds.size.height == 812 || UIScreen.main.bounds.size.width == 812)
}
class var isPadProLarge: Bool {
return isPad && (UIScreen.main.bounds.size.height == 1366 || UIScreen.main.bounds.size.width == 1366)
}
}
| 32.666667 | 109 | 0.652134 |
bf11a1b6260c661f828a4fe34f97c258f57d4c73 | 6,356 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* 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 CosmicMind 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 COPYRIGHT HOLDER 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 UIKit
open class CollectionViewLayout: UICollectionViewLayout {
/// Used to calculate the dimensions of the cells.
open var offset = CGPoint.zero
/// The size of items.
open var itemSize = CGSize.zero
/// A preset wrapper around contentEdgeInsets.
open var contentEdgeInsetsPreset = EdgeInsetsPreset.none {
didSet {
contentEdgeInsets = EdgeInsetsPresetToValue(preset: contentEdgeInsetsPreset)
}
}
/// A wrapper around grid.contentEdgeInsets.
open var contentEdgeInsets = EdgeInsets.zero
/// Size of the content.
open fileprivate(set) var contentSize = CGSize.zero
/// Layout attribute items.
open fileprivate(set) lazy var layoutItems = [(UICollectionViewLayoutAttributes, NSIndexPath)]()
/// Cell data source items.
open fileprivate(set) var dataSourceItems: [DataSourceItem]?
/// Scroll direction.
open var scrollDirection = UICollectionViewScrollDirection.vertical
/// A preset wrapper around interimSpace.
open var interimSpacePreset = InterimSpacePreset.none {
didSet {
interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset)
}
}
/// Spacing between items.
open var interimSpace: InterimSpace = 0
open override var collectionViewContentSize: CGSize {
return contentSize
}
/**
Retrieves the index paths for the items within the passed in CGRect.
- Parameter rect: A CGRect that acts as the bounds to find the items within.
- Returns: An Array of NSIndexPath objects.
*/
open func indexPathsOfItemsInRect(rect: CGRect) -> [NSIndexPath] {
var paths = [NSIndexPath]()
for (attribute, indexPath) in layoutItems {
if rect.intersects(attribute.frame) {
paths.append(indexPath)
}
}
return paths
}
open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
let item = dataSourceItems![indexPath.item]
if 0 < itemSize.width && 0 < itemSize.height {
attributes.frame = CGRect(x: offset.x, y: offset.y, width: itemSize.width - contentEdgeInsets.left - contentEdgeInsets.right, height: itemSize.height - contentEdgeInsets.top - contentEdgeInsets.bottom)
} else if .vertical == scrollDirection {
attributes.frame = CGRect(x: contentEdgeInsets.left, y: offset.y, width: collectionView!.bounds.width - contentEdgeInsets.left - contentEdgeInsets.right, height: item.height ?? collectionView!.bounds.height)
} else {
attributes.frame = CGRect(x: offset.x, y: contentEdgeInsets.top, width: item.width ?? collectionView!.bounds.width, height: collectionView!.bounds.height - contentEdgeInsets.top - contentEdgeInsets.bottom)
}
return attributes
}
open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for (attribute, _) in layoutItems {
if rect.intersects(attribute.frame) {
layoutAttributes.append(attribute)
}
}
return layoutAttributes
}
open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return .vertical == scrollDirection ? newBounds.width != collectionView!.bounds.width : newBounds.height != collectionView!.bounds.height
}
open override func prepare() {
guard let dataSource = collectionView?.dataSource as? CollectionViewDataSource else {
return
}
prepareLayoutForItems(dataSourceItems: dataSource.dataSourceItems)
}
open override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return proposedContentOffset
}
fileprivate func prepareLayoutForItems(dataSourceItems: [DataSourceItem]) {
self.dataSourceItems = dataSourceItems
layoutItems.removeAll()
offset.x = contentEdgeInsets.left
offset.y = contentEdgeInsets.top
for i in 0..<dataSourceItems.count {
let item = dataSourceItems[i]
let indexPath = IndexPath(item: i, section: 0)
layoutItems.append((layoutAttributesForItem(at: indexPath)!, indexPath as NSIndexPath))
offset.x += interimSpace
offset.x += item.width ?? itemSize.width
offset.y += interimSpace
offset.y += item.height ?? itemSize.height
}
offset.x += contentEdgeInsets.right - interimSpace
offset.y += contentEdgeInsets.bottom - interimSpace
if 0 < itemSize.width && 0 < itemSize.height {
contentSize = CGSize(width: offset.x, height: offset.y)
} else if .vertical == scrollDirection {
contentSize = CGSize(width: collectionView!.bounds.width, height: offset.y)
} else {
contentSize = CGSize(width: offset.x, height: collectionView!.bounds.height)
}
}
}
| 38.993865 | 219 | 0.743392 |
33f51f45173a8da0e4cb72932d5b855be08fc229 | 1,341 | //
// Copyright (c) 2018 KxCoding <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//: [Previous](@previous)
import Foundation
/*:
# Bitwise OR Operator
````
a | b
````

*/
let a:UInt8 = 0b00100011
let b:UInt8 = 0b00011010
a | b
//: [Next](@next)
| 30.477273 | 81 | 0.722595 |
e5570b8e90f6eb5886760158e9680ca8405719ca | 2,280 | // swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
/**
* Copyright IBM Corporation 2016-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 PackageDescription
var dependencies: [Package.Dependency] = [
.package(url: "https://github.com/IBM-Swift/LoggerAPI.git", from: "1.7.3"),
.package(url: "https://github.com/IBM-Swift/BlueSocket.git", from: "1.0.0"),
.package(url: "https://github.com/IBM-Swift/BlueSSLService.git", from: "1.0.0")
]
var kituraNetDependencies: [Target.Dependency] = [
.byName(name: "CHTTPParser"),
.byName(name: "LoggerAPI"),
.byName(name: "Socket"),
.target(name: "CCurl"),
.byName(name: "SSLService")
]
#if os(Linux)
dependencies.append(contentsOf: [
.package(url: "https://github.com/IBM-Swift/BlueSignals.git", from: "1.0.0")
])
kituraNetDependencies.append(contentsOf: [
.target(name: "CEpoll"),
.byName(name: "Signals")
])
#endif
var targets: [Target] = [
.target(
name: "CHTTPParser"
),
.systemLibrary(
name: "CCurl"
),
.target(
name: "KituraNet",
dependencies: kituraNetDependencies
),
.testTarget(
name: "KituraNetTests",
dependencies: ["KituraNet"]
)
]
#if os(Linux)
targets.append(
.systemLibrary(name: "CEpoll")
)
#endif
let package = Package(
name: "Kitura-net",
platforms: [
.macOS(.v10_13),
],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "KituraNet",
targets: ["KituraNet"]
)
],
dependencies: dependencies,
targets: targets
)
| 26.823529 | 120 | 0.652632 |
3814a61b37c89b51bdd4bed117354154533e84f7 | 1,486 | import Vapor
// MultipleResponseCodesApiDelegate.swift
//
// Generated by vapor-server-codegen
// https://github.com/thecheatah/SwiftVapor-swagger-codegen
// Template Input: /APIs.MultipleResponseCodes
public enum multipleResponseCodesResponse: ResponseEncodable {
case http200
case http201(SimpleObject)
case http401
case http500
public func encodeResponse(for request: Request) -> EventLoopFuture<Response> {
switch self {
case .http200:
let response = Response()
response.status = HTTPStatus(statusCode: 200)
return request.eventLoop.makeSucceededFuture(response)
case .http201(let content):
return content.encodeResponse(for: request).map { (response: Response) -> (Response) in
response.status = HTTPStatus(statusCode: 201)
return response
}
case .http401:
let response = Response()
response.status = HTTPStatus(statusCode: 401)
return request.eventLoop.makeSucceededFuture(response)
case .http500:
let response = Response()
response.status = HTTPStatus(statusCode: 500)
return request.eventLoop.makeSucceededFuture(response)
}
}
}
public protocol MultipleResponseCodesApiDelegate {
associatedtype AuthType
/**
POST /multiple/response/codes
Test ability to support multiple response codes in a single call */
func multipleResponseCodes(with req: Request, body: MultipleResponseCodeRequest) throws -> EventLoopFuture<multipleResponseCodesResponse>
}
| 33.022222 | 139 | 0.741588 |
e468f261cc26d69239900ad69e9a6bb3b30f8956 | 7,420 | //
// EntryImageView.swift
// Clipper
//
// Created by Ashwin Chugh on 1/11/22.
//
import SwiftUI
struct EntryImageView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(sortDescriptors: []) var categories : FetchedResults<Category>
@ObservedObject var PB : PasteboardHistory
@ObservedObject var data : PasteboardData
@State private var alertMessage = "Error"
@State private var selectedCategory = ""
@State private var showCategoryAssigner = false
@State private var isSaved = false
@State private var showingAlert = false
@State private var showCategories = false
@State private var disableCategoryInfo = true
let image : NSImage
let imageName : String
init(PB : PasteboardHistory, data : PasteboardData) {
self.PB = PB
self.data = data
if let dict = data.data as? [String : Any] {
image = dict["File"] as? NSImage ?? NSImage(systemSymbolName: "exclamationmark.circle", accessibilityDescription: "Error Image Placeholder")!
imageName = dict["Name"] as? String ?? "Image Name Error"
} else {
image = NSImage(systemSymbolName: "exclamationmark.circle", accessibilityDescription: "Error Image Placeholder")!
imageName = "Image Error"
}
}
var body: some View {
ZStack(alignment: .top) {
VStack(alignment: .center) {
Image(nsImage: image)
.resizable()
.scaledToFit()
.frame(maxWidth: 350, maxHeight: 350)
.padding(.top)
Text(imageName)
.multilineTextAlignment(.center)
.font(.title.bold())
Text("Copied Image")
.font(.headline)
.multilineTextAlignment(.center)
Text(data.date, style: .date)
EntryOptionView(data: self.data, PB: self.PB)
.environment(\.managedObjectContext, self.moc)
if (showCategories) {
ScrollView(.horizontal) {
HStack {
ForEach(self.data.categories.sorted(), id: \.self) { category in
CategoryView(category)
.onTapGesture(count: 3) {
withAnimation(.easeOut) {
self.data.categories.remove(category)
self.disableCategoryInfo = self.data.categories.isEmpty
if self.disableCategoryInfo {
self.showCategories.toggle()
}
}
if self.data.saved {
self.data.deleteSaved(self.moc)
self.data.saveItem(self.moc)
if moc.hasChanges {
try? moc.save()
}
}
}
}
}
}
.padding(.bottom, 5)
}
if (showCategoryAssigner) {
CategoryAssignerView(selectedCategory: self.$selectedCategory, categories: self.categories, data: self.data) {
if self.selectedCategory.isEmpty {
self.alertMessage = "Invalid category selected;"
self.showingAlert = true
return
}
guard let targetCategory = self.categories.first(where: { value in
value.wrappedName == self.selectedCategory
}) else {print("Error in finding category"); return}
self.data.categories.insert(targetCategory)
self.disableCategoryInfo = self.data.categories.isEmpty
if (self.data.saved) {
self.data.deleteSaved(self.moc)
self.data.saveItem(self.moc)
}
withAnimation(.easeOut) {
showCategoryAssigner.toggle()
}
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.bAlert("Error", isPresented: $showingAlert) {
Button("Ok") {}
} message: {
Text(self.alertMessage)
}
HStack {
Button {
if self.showCategories {
withAnimation(.easeIn) {
self.showCategories.toggle()
}
}
if self.showCategoryAssigner {
withAnimation(.easeOut) {
self.showCategoryAssigner.toggle()
}
} else {
withAnimation(.easeIn) {
self.showCategoryAssigner.toggle()
}
}
} label: {
Image(systemName: "plus")
.imageScale(.large)
}
.buttonStyle(.plain)
.offset(x: 2, y: 3)
.disabled(self.categories.isEmpty)
Spacer()
CategoryButton(data: self.data) {
if (self.showCategoryAssigner) {
withAnimation(.easeIn) {
self.showCategoryAssigner.toggle()
}
}
if (self.showCategories) {
withAnimation(.easeOut) {
self.showCategories.toggle()
}
} else {
withAnimation(.easeIn) {
self.showCategories.toggle()
}
}
}
.disabled(self.disableCategoryInfo)
}
}.onAppear {
self.disableCategoryInfo = self.data.categories.isEmpty
}
.onChange(of: self.data.categories) {_ in
self.disableCategoryInfo = self.data.categories.isEmpty
}
}
}
struct EntryImageView_Previews: PreviewProvider {
static var dict : [String : Any] = [
"Name" : "App.png",
"File" : NSImage(systemSymbolName: "app", accessibilityDescription: "app image")!
]
static var previews: some View {
EntryImageView(PB: PasteboardHistory(), data: PasteboardData(saved: false, name: "Sample Data", type: .file, data: dict, rawData: NSData(data: (NSImage(systemSymbolName: "app", accessibilityDescription: "app image")?.tiffRepresentation)!) as Data))
}
}
| 41.452514 | 256 | 0.440162 |
010e990434a40bd5b927292834747ada956060f8 | 1,747 | //
// IAmGenderTableViewController.swift
// Mirchi
//
// Created by Raj Kadiyala on 16/10/2017.
// Copyright © 2019 Raj Kadiyala. All rights reserved.
//
import UIKit
import DropletIF
class IAmGenderTableViewController: UITableViewController {
@IBOutlet weak var manCell: UITableViewCell!
@IBOutlet weak var womanCell: UITableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
updateSelection()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateSelection(){
if AuthService.shared.currentUser?.gender == Genders.male.rawValue{
manCell.accessoryType = .checkmark
womanCell.accessoryType = .none
}else if AuthService.shared.currentUser?.gender == Genders.female.rawValue{
manCell.accessoryType = .none
womanCell.accessoryType = .checkmark
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 0{
if AuthService.shared.currentUser?.gender == Genders.male.rawValue{
return
}
AuthService.shared.currentUser?.gender = Genders.male.rawValue
UserService.shared.resetUsers()
}else if indexPath.row == 1{
if AuthService.shared.currentUser?.gender == Genders.female.rawValue{
return
}
AuthService.shared.currentUser?.gender = Genders.female.rawValue
UserService.shared.resetUsers()
}
updateSelection()
}
}
| 30.12069 | 92 | 0.640527 |
72213fe03e9363fa5d862c8357feb73d7454c6c2 | 2,449 | //
// RightAlignedIconButton.swift
// Commun
//
// Created by Chung Tran on 11/9/19.
// Copyright © 2019 Commun Limited. All rights reserved.
//
import Foundation
class RightAlignedIconButton: UIButton {
var textToImageSpace: CGFloat
init(
imageName: String,
label: String? = nil,
labelFont: UIFont? = nil,
backgroundColor: UIColor? = nil,
textColor: UIColor? = nil,
cornerRadius: CGFloat? = nil,
contentInsets: UIEdgeInsets? = nil,
textToImageSpace: CGFloat = 10
) {
self.textToImageSpace = textToImageSpace
super.init(frame: .zero)
configureForAutoLayout()
setImage(UIImage(named: imageName), for: .normal)
setTitle(label, for: .normal)
if let font = labelFont {
titleLabel?.font = font
}
if let backgroundColor = backgroundColor {
self.backgroundColor = backgroundColor
}
if let textColor = textColor {
setTitleColor(textColor, for: .normal)
}
if let cornerRadius = cornerRadius {
self.cornerRadius = cornerRadius
}
if let contentInsets = contentInsets {
self.contentEdgeInsets = contentInsets
}
semanticContentAttribute = .forceRightToLeft
contentHorizontalAlignment = .right
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let availableSpace = bounds.inset(by: contentEdgeInsets)
let availableWidth = availableSpace.width - imageEdgeInsets.left - imageEdgeInsets.right - (imageView?.frame.width ?? 0) - (titleLabel?.frame.width ?? 0)
titleEdgeInsets = UIEdgeInsets(top: 0, left: -textToImageSpace * 2, bottom: 0, right: availableWidth / 2 + textToImageSpace)
}
}
class LeftAlignedIconButton: UIButton {
var textToImageSpace: CGFloat = 4
override func layoutSubviews() {
super.layoutSubviews()
contentHorizontalAlignment = .left
let availableSpace = bounds.inset(by: contentEdgeInsets)
let availableWidth = availableSpace.width - imageEdgeInsets.right - (imageView?.frame.width ?? 0) - (titleLabel?.frame.width ?? 0)
titleEdgeInsets = UIEdgeInsets(top: 0, left: availableWidth / 2 + textToImageSpace, bottom: 0, right: -textToImageSpace)
}
}
| 34.985714 | 161 | 0.643936 |
f944877884cb0fe7a744e40bf6901576c5aeb471 | 2,336 | import Foundation
import UIKit
public enum DeviceModel: Equatable {
case iPhone1G
case iPhone3G
case iPhone3GS
case iPhone4
case iPhone4S
case iPhone5
case iPhone5C
case iPhone5S
case iPhone6
case iPhone6Plus
case iPhone6S
case iPhone6SPlus
case iPhoneSE
case iPhone7
case iPhone7Plus
case iPhone8
case iPhone8Plus
case iPhoneX
case iPhoneXR
case iPhoneXS
case iPhoneXSMax
case iPodTouch1G
case iPodTouch2G
case iPodTouch3G
case iPodTouch4G
case iPodTouch5G
case iPodTouch6G
case iPodTouch7G
case iPad1G
case iPad2G
case iPad3G
case iPad4G
case iPadMini1
case iPadMini2
case iPadMini3
case iPadMini4
case iPadAir1G
case iPadAir2G
case iPadPro9d7inch1G
case iPadPro10d5inch1G
case iPadPro12d9inch1G
case iPadPro12d9inch2G
case iPadPro12d9inch3G
case iPadPro11inch1G
case iPad5G
case iPad6G
case appleTV4G
case appleTV4K
case iPadSimulator
case iPhoneSimulator
case appleTVSimulator
case iPhoneUnknown(model: String)
case iPadUnknown(model: String)
case iPodUnknown(model: String)
case unknown(model: String)
internal init(_ identifier: DeviceIdentifier) {
guard let model = identifier.model else {
if identifier.rawValue == "i386" || identifier.rawValue == "x86_64" {
#if os(iOS)
let smallerScreen = UIScreen.main.bounds.size.width < 768
self = smallerScreen ? .iPhoneSimulator : .iPadSimulator
#elseif os(tvOS)
self = .appleTVSimulator
#endif
} else if identifier.rawValue.hasPrefix("iPhone") {
self = .iPhoneUnknown(model: identifier.rawValue)
} else if identifier.rawValue.hasPrefix("iPod") {
self = .iPodUnknown(model: identifier.rawValue)
} else if identifier.rawValue.hasPrefix("iPad") {
self = .iPadUnknown(model: identifier.rawValue)
} else {
self = .unknown(model: identifier.rawValue)
}
return
}
self = model
}
}
public func == (lhs: DeviceModel, rhs: DeviceModel) -> Bool {
return lhs.name == rhs.name
}
| 24.589474 | 81 | 0.628425 |
3a8db0651f0aa2f99c8b0f0b89fc0f9c947e30a6 | 880 | //
// UserController.swift
// Created by David Okun on 7/19/20.
//
import Foundation
import Vapor
import afterparty_models_swift
extension User: Content { }
struct UserController: RouteCollection {
func boot(router: Router) throws {
let mockUserRoutes = router.grouped("mock", "users")
mockUserRoutes.get(use: getAllMockHandler)
mockUserRoutes.get("random", use: getRandomMockHandler)
mockUserRoutes.get("sorted", use: getSortedMockHandler)
}
func getAllMockHandler(_ req: Request) throws -> [User] {
MockData.participants
}
func getRandomMockHandler(_ req: Request) throws -> User {
guard let randomUser = MockData.participants.random else {
throw Abort(.badRequest)
}
return randomUser
}
func getSortedMockHandler(_ req: Request) throws -> [User] {
MockData.participants.sorted { $0.email < $1.email }
}
}
| 25.142857 | 62 | 0.707955 |
e91445766ee52804f46bb16cfa6ed6ce03cacbac | 7,291 | //
// LocationSelectViewController.swift
// Shakawekom
//
// Created by AhmeDroid on 4/11/17.
// Copyright © 2017 Imagine Technologies. All rights reserved.
//
import UIKit
import GoogleMaps
import MaterialComponents
import CoreLocation
protocol LocationSelectViewControllerDelegate {
func locationSelectDidReceiveAddress(_ address:String, atCoordinates coordinates:CLLocationCoordinate2D ) -> Void
}
class LocationSelectViewController: UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate {
static func launch( delegate:LocationSelectViewControllerDelegate? ) -> Void {
if let viewC = UIApplication.topViewController(),
let locationVC = viewC.storyboard?.instantiateViewController(withIdentifier: "locationSelectVC") as? LocationSelectViewController {
locationVC.delegate = delegate
viewC.present(locationVC, animated: true, completion: {_ in})
} else {
print("Can't launch date picker on non-UIViewController objects")
}
}
let geocoder = GMSGeocoder()
var delegate:LocationSelectViewControllerDelegate?
@IBOutlet weak var selectionButton: UIButton!
@IBAction func selectAddress(_ sender: Any) {
let alert = UIAlertController(title: "location-select-title".local,
message: String(format: "location-select-confirm".local, self.selectedAddress),
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "no".local, style: .cancel, handler: {_ in})
let okayAction = UIAlertAction(title: "yes".local, style: .default) { (action) in
self.dismiss(animated: true) {
self.delegate?.locationSelectDidReceiveAddress(self.selectedAddress, atCoordinates: self.selectedLocation)
}
}
alert.addAction(okayAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: {_ in})
}
@IBAction func showUserLocation(_ sender: Any) {
self.lookForUserLocation()
}
private var indicator:MDCActivityIndicator!
private var indicatorContainer:UIView!
override func viewDidLoad() {
super.viewDidLoad()
let w = self.view.frame.width
let view = UIView(frame: CGRect(x: (w - 36) * 0.5, y: 25, width: 40, height: 40))
view.layer.masksToBounds = true
view.layer.cornerRadius = 20
view.backgroundColor = UIColor.white
indicator = MDCActivityIndicator(frame: CGRect(x: 4, y: 4, width: 32, height: 32))
view.addSubview(indicator)
indicatorContainer = view
selectionButton.isHidden = true
}
func showLoadingIndicator() -> Void {
self.view.addSubview(indicatorContainer)
indicator.startAnimating()
}
func hideLoadingIndicator() -> Void {
indicatorContainer.removeFromSuperview()
indicator.stopAnimating()
}
private var selectedAddress:String!
private var selectedLocation:CLLocationCoordinate2D!
func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
self.mapView.selectedMarker = nil
}
func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
self.mainMarker.position = position.target
}
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
self.mainMarker.map = nil
self.mainMarker.position = position.target
self.mainMarker.map = mapView
self.lookupForAddress(atCoordinate: position.target)
}
func lookupForAddress(atCoordinate coordinate:CLLocationCoordinate2D) -> Void {
self.showLoadingIndicator()
geocoder.reverseGeocodeCoordinate(coordinate) { (response, error) in
self.hideLoadingIndicator()
if error != nil {
print("Error while reverse geocoding: \(error!.localizedDescription)")
self.mainMarker.title = "Unknown"
return
}
if let result = response?.firstResult() {
self.selectedLocation = coordinate
var fullAddress = "Unknown"
if let lines = result.lines {
fullAddress = lines.joined(separator: ", ");
}
self.selectedAddress = fullAddress
self.selectionButton.isHidden = false
print("location reverse geocoded ...")
self.mainMarker.title = result.lines?[0]
self.mainMarker.snippet = result.lines?[1]
self.mapView.selectedMarker = self.mainMarker
}
}
}
@IBAction func closeView(_ sender: Any) {
self.dismiss(animated: true, completion: {_ in})
}
private var locationManager = CLLocationManager()
private var mapView:GMSMapView!
override func loadView() {
super.loadView()
let location = CLLocationCoordinate2D(latitude: 31.9499895, longitude: 35.9394769)
let camera = GMSCameraPosition.camera(
withLatitude: location.latitude,
longitude: location.longitude,
zoom: 16.0)
self.mapView = GMSMapView.map(withFrame: self.view.frame, camera: camera)
self.mapView.isMyLocationEnabled = true
self.mapView.isIndoorEnabled = true
self.mapView.delegate = self
self.mapView.setMinZoom(4, maxZoom: 18)
self.view.insertSubview(self.mapView, at: 0)
let marker = GMSMarker()
marker.position = location
marker.title = "Loading ..."
marker.map = self.mapView
marker.isDraggable = false
marker.isTappable = false
self.mainMarker = marker
self.lookForUserLocation()
}
var mainMarker:GMSMarker!
func lookForUserLocation() -> Void {
self.locationManager.delegate = self
self.locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
let camera = GMSCameraPosition.camera(
withLatitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
zoom: 16)
self.mapView.animate(to: camera)
self.lookupForAddress(atCoordinate: location.coordinate)
}
self.locationManager.stopUpdatingLocation()
}
@IBAction func zoomInMap(_ sender: Any) {
let pzoom = self.mapView.camera.zoom
let zoom = min(18, pzoom + 2)
self.mapView.animate(toZoom: zoom)
}
@IBAction func zoomOutMap(_ sender: Any) {
let pzoom = self.mapView.camera.zoom
let zoom = max(4, pzoom - 2)
self.mapView.animate(toZoom: zoom)
}
}
| 33.599078 | 143 | 0.60513 |
f53206334a9521cf76cb47cfff26a5c0bf894e3a | 6,558 | // Copyright 2022 Pera Wallet, LDA
// 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.
// CollectibleDetailDataSource.swift
import Foundation
import MacaroonUIKit
import UIKit
final class CollectibleDetailDataSource: UICollectionViewDiffableDataSource<CollectibleDetailSection, CollectibleDetailItem> {
init(
collectionView: UICollectionView,
mediaPreviewController: CollectibleMediaPreviewViewController
) {
super.init(collectionView: collectionView) {
collectionView, indexPath, itemIdentifier in
switch itemIdentifier {
case .loading:
return collectionView.dequeue(
CollectibleDetailLoadingCell.self,
at: indexPath
)
case .error(let viewModel):
let cell = collectionView.dequeue(
CollectibleMediaErrorCell.self,
at: indexPath
)
cell.bindData(viewModel)
return cell
case .media:
let cell = collectionView.dequeue(
CollectibleMediaPreviewCell.self,
at: indexPath
)
cell.contextView = mediaPreviewController.view
return cell
case .action(let viewModel):
let cell = collectionView.dequeue(
CollectibleDetailActionCell.self,
at: indexPath
)
cell.bindData(viewModel)
return cell
case .collectibleCreatorAccountAction(let viewModel):
let cell = collectionView.dequeue(
CollectibleDetailCreatorAccountActionCell.self,
at: indexPath
)
cell.bindData(viewModel)
return cell
case .watchAccountAction(let viewModel):
let cell = collectionView.dequeue(
CollectibleDetailWatchAccountActionCell.self,
at: indexPath
)
cell.bindData(viewModel)
return cell
case .optedInAction(let viewModel):
let cell = collectionView.dequeue(
CollectibleDetailOptedInActionCell.self,
at: indexPath
)
cell.bindData(viewModel)
return cell
case .description(let viewModel):
let cell = collectionView.dequeue(
CollectibleDescriptionCell.self,
at: indexPath
)
cell.bindData(viewModel)
return cell
case .information(let info):
let cell = collectionView.dequeue(
CollectibleDetailInformationCell.self,
at: indexPath
)
let viewModel = CollectibleTransactionInfoViewModel(info)
cell.bindData(viewModel)
return cell
case .properties(let viewModel):
let cell = collectionView.dequeue(
CollectiblePropertyCell.self,
at: indexPath
)
cell.bindData(viewModel)
return cell
case .external(let viewModel):
let cell = collectionView.dequeue(
CollectibleExternalSourceCell.self,
at: indexPath
)
cell.bindData(viewModel)
return cell
}
}
supplementaryViewProvider = { collectionView, kind, indexPath in
guard let section = CollectibleDetailSection(rawValue: indexPath.section),
kind == UICollectionView.elementKindSectionHeader else {
return nil
}
let header = collectionView.dequeueHeader(
TitleSupplementaryHeader.self,
at: indexPath
)
switch section {
case .media,
.action,
.loading:
return header
case .description:
header.bindData(
CollectibleDetailHeaderViewModel(
SingleLineIconTitleItem(
icon: nil,
title: "collectible-detail-description".localized
)
)
)
return header
case .properties:
header.bindData(
CollectibleDetailHeaderViewModel(
SingleLineIconTitleItem(
icon: nil,
title: "collectible-detail-properties".localized
)
)
)
return header
case .external:
header.bindData(
CollectibleDetailHeaderViewModel(
SingleLineIconTitleItem(
icon: nil,
title: "collectible-detail-view-transaction".localized
)
)
)
return header
}
}
[
CollectibleDetailLoadingCell.self,
CollectibleMediaErrorCell.self,
CollectibleDetailActionCell.self,
CollectibleDetailOptedInActionCell.self,
CollectibleDetailWatchAccountActionCell.self,
CollectibleDetailCreatorAccountActionCell.self,
CollectibleDescriptionCell.self,
CollectibleExternalSourceCell.self,
CollectibleDetailInformationCell.self,
CollectibleMediaPreviewCell.self,
CollectiblePropertyCell.self
].forEach {
collectionView.register($0)
}
collectionView.register(header: TitleSupplementaryHeader.self)
}
}
| 37.050847 | 126 | 0.52943 |
e00413f2118103e4b7bad3f702ab7b06725b1ad8 | 612 | //
// UITableView+ReusableCell.swift
// ____PROJECTNAME____
//
// Created by Dani Manuel Céspedes Lara on 1/25/18.
// Copyright © 2018 Dani Manuel Céspedes Lara. All rights reserved.
//
import UIKit
extension UITableView {
func dequeueReusableCell<T>(ofType cellType: T.Type = T.self, at indexPath: IndexPath) -> T where T: UITableViewCell {
guard let cell = dequeueReusableCell(withIdentifier: cellType.reuseIdentifier,
for: indexPath) as? T else {
fatalError()
}
return cell
}
}
| 30.6 | 122 | 0.596405 |
203f251eb9dcc7b3cc78a6f8254bea86eb90ccfc | 395 | //
// LikeNotificationGroup.swift
// gabbie-ios
//
// Created by Tomoya Hirano on 2018/10/18.
// Copyright © 2018 Tomoya Hirano. All rights reserved.
//
import GabKit
protocol NotificationContentable {
var notificationType: NotificationType { get }
var title: NSAttributedString { get }
var body: NSAttributedString? { get }
var notifications: [GabKit.Notification] { get set }
}
| 21.944444 | 56 | 0.724051 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.