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
|
---|---|---|---|---|---|
384e812d91f5c3708fcea5f2e9bdc1bb1d931ceb | 4,452 | //
// List.swift
// TPPDF
//
// Created by Philip Niedertscheider on 13/06/2017.
//
#if os(iOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
/**
TODO: Documentation
*/
public class PDFList: PDFDocumentObject {
/**
TODO: Documentation
*/
internal var items: [PDFListItem] = []
/**
TODO: Documentation
*/
internal var levelIndentations: [(pre: CGFloat, past: CGFloat)] = []
/**
TODO: Documentation
*/
public init(indentations: [(pre: CGFloat, past: CGFloat)]) {
self.levelIndentations = indentations
}
/**
TODO: Documentation
*/
@discardableResult public func addItem(_ item: PDFListItem) -> PDFList {
self.items.append(item)
return self
}
/**
TODO: Documentation
*/
@discardableResult public func addItems(_ items: [PDFListItem]) -> PDFList {
self.items += items
return self
}
/**
TODO: Documentation
*/
public var count: Int {
items.count
}
/**
TODO: Documentation
*/
public func flatted() -> [(level: Int, text: String, symbol: PDFListItemSymbol)] {
var result: [(level: Int, text: String, symbol: PDFListItemSymbol)] = []
for (idx, item) in self.items.enumerated() {
result += flatItem(item: item, level: 0, index: idx)
}
return result
}
/**
TODO: Documentation
*/
private func flatItem(item: PDFListItem, level: Int, index: Int) -> [(level: Int, text: String, symbol: PDFListItemSymbol)] {
var result: [(level: Int, text: String, symbol: PDFListItemSymbol)] = []
if let content = item.content {
var symbol: PDFListItemSymbol = .inherit
if item.symbol == .inherit {
if let parent = item.parent {
if parent.symbol == .numbered(value: nil) {
symbol = .numbered(value: "\(index + 1)")
} else {
symbol = parent.symbol
}
}
} else {
symbol = item.symbol
}
result = [(level: level, text: content, symbol: symbol)]
}
if let children = item.children {
for (idx, child) in children.enumerated() {
result += flatItem(item: child, level: level + (item.content == nil ? 0 : 1), index: idx)
}
}
return result
}
internal func clear() {
self.items = []
}
/**
TODO: Documentation
*/
internal var copy: PDFList {
let list = PDFList(indentations: self.levelIndentations)
list.items = items.map(\.copy)
return list
}
// MARK: - Equatable
/// Compares two instances of `PDFList` for equality
///
/// - Parameters:
/// - lhs: One instance of `PDFList`
/// - rhs: Another instance of `PDFList`
/// - Returns: `true`, if `levelIndentations` and `items` equal; otherwise `false`
override public func isEqual(to other: PDFDocumentObject) -> Bool {
guard super.isEqual(to: other) else {
return false
}
guard let otherList = other as? PDFList else {
return false
}
guard self.levelIndentations.count == otherList.levelIndentations.count else {
return false
}
for (idx, indentation) in self.levelIndentations.enumerated() where otherList.levelIndentations[idx] != indentation {
return false
}
guard self.items.count == otherList.items.count else {
return false
}
for (idx, item) in self.items.enumerated() where otherList.items[idx] != item {
return false
}
return true
}
// MARK: - Hashable
override public func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
for (pre, post) in levelIndentations {
hasher.combine(pre)
hasher.combine(post)
}
hasher.combine(items)
}
}
extension PDFList: CustomDebugStringConvertible {
public var debugDescription: String {
"PDFList(levels: \(levelIndentations.debugDescription), items: \(items.debugDescription))"
}
}
extension PDFList: CustomStringConvertible {
public var description: String {
"PDFList(levels: \(levelIndentations), items: \(items))"
}
}
| 26.5 | 129 | 0.560198 |
bb2e93ae916c4c73f774fabcd73c7a76c74666c8 | 2,756 | //
// SceneDelegate.swift
// Herrera5
//
// Created by Carlyn Maw on 9/16/20.
// Copyright © 2020 carlynorama. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
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).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
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 neccessarily 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.
}
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.
}
}
| 42.4 | 147 | 0.705733 |
e548ba54e4685f85973238b8ee212a622eea2ff8 | 8,323 | // Generated using Sourcery 0.15.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
//
// UILayoutKit
//
// Created by Brian Strobach on 1/22/19.
// Copyright © 2019 Brian Strobach. All rights reserved.
//
// MARK: XYAxesAnchorPair <=> XYAxesAnchorPair.LayoutCoefficientTuple
// MARK: - Equal
@discardableResult
public func .= (lhs: XYAxesAnchorPair, rhs: XYAxesAnchorPair.LayoutCoefficientTuple) -> XYAxesAnchorPair.Solution {
return lhs.equal(to: rhs)
}
@discardableResult
public func .= (lhs: XYAxesAnchorPair, rhs: [XYAxesAnchorPair.LayoutCoefficientTuple]) -> [XYAxesAnchorPair.Solution] {
return lhs.equal(to: rhs)
}
// MARK: - LessThanOrEqual
@discardableResult
public func ≤ (lhs: XYAxesAnchorPair, rhs: XYAxesAnchorPair.LayoutCoefficientTuple) -> XYAxesAnchorPair.Solution {
return lhs.lessThanOrEqual(to: rhs)
}
@discardableResult
public func ≤ (lhs: XYAxesAnchorPair, rhs: [XYAxesAnchorPair.LayoutCoefficientTuple]) -> [XYAxesAnchorPair.Solution] {
return lhs.lessThanOrEqual(to: rhs)
}
// MARK: - GreaterThanOrEqual
@discardableResult
public func ≥ (lhs: XYAxesAnchorPair, rhs: XYAxesAnchorPair.LayoutCoefficientTuple) -> XYAxesAnchorPair.Solution {
return lhs.greaterThanOrEqual(to: rhs)
}
@discardableResult
public func ≥ (lhs: XYAxesAnchorPair, rhs: [XYAxesAnchorPair.LayoutCoefficientTuple]) -> [XYAxesAnchorPair.Solution] {
return lhs.greaterThanOrEqual(to: rhs)
}
// MARK: XYAxesAnchorPair Array <=> XYAxesAnchorPair.LayoutCoefficientTuple
// MARK: - Equal
// MARK: Collection == Expression
@discardableResult
public func .= (lhs: [XYAxesAnchorPair], rhs: XYAxesAnchorPair.LayoutCoefficientTuple) -> [XYAxesAnchorPair.Solution] {
return lhs.map { $0.equal(to: rhs) }
}
// MARK: Collection == Expression Array
@discardableResult
public func .= (lhs: [XYAxesAnchorPair], rhs: [XYAxesAnchorPair.LayoutCoefficientTuple]) -> [[XYAxesAnchorPair.Solution]] {
return lhs.map { $0.equal(to: rhs) }
}
// MARK: - LessThanOrEqual
// MARK: Collection <= Expression
@discardableResult
public func ≤ (lhs: [XYAxesAnchorPair], rhs: XYAxesAnchorPair.LayoutCoefficientTuple) -> [XYAxesAnchorPair.Solution] {
return lhs.map { $0.lessThanOrEqual(to: rhs) }
}
// MARK: Collection <= Expression Array
@discardableResult
public func ≤ (lhs: [XYAxesAnchorPair], rhs: [XYAxesAnchorPair.LayoutCoefficientTuple]) -> [[XYAxesAnchorPair.Solution]] {
return lhs.map { $0.lessThanOrEqual(to: rhs) }
}
// MARK: - GreaterThanOrEqual
// MARK: Collection >= Expression
@discardableResult
public func ≥ (lhs: [XYAxesAnchorPair], rhs: XYAxesAnchorPair.LayoutCoefficientTuple) -> [XYAxesAnchorPair.Solution] {
return lhs.map { $0.greaterThanOrEqual(to: rhs) }
}
// MARK: Collection >= Expression Array
@discardableResult
public func ≥ (lhs: [XYAxesAnchorPair], rhs: [XYAxesAnchorPair.LayoutCoefficientTuple]) -> [[XYAxesAnchorPair.Solution]] {
return lhs.map { $0.greaterThanOrEqual(to: rhs) }
}
// MARK: XYAxesAnchorPair <=> XYAxesAnchorPair.LayoutConstantTuple
// MARK: - Equal
@discardableResult
public func .= (lhs: XYAxesAnchorPair, rhs: XYAxesAnchorPair.LayoutConstantTuple) -> XYAxesAnchorPair.Solution {
return lhs.equal(to: rhs)
}
@discardableResult
public func .= (lhs: XYAxesAnchorPair, rhs: [XYAxesAnchorPair.LayoutConstantTuple]) -> [XYAxesAnchorPair.Solution] {
return lhs.equal(to: rhs)
}
// MARK: - LessThanOrEqual
@discardableResult
public func ≤ (lhs: XYAxesAnchorPair, rhs: XYAxesAnchorPair.LayoutConstantTuple) -> XYAxesAnchorPair.Solution {
return lhs.lessThanOrEqual(to: rhs)
}
@discardableResult
public func ≤ (lhs: XYAxesAnchorPair, rhs: [XYAxesAnchorPair.LayoutConstantTuple]) -> [XYAxesAnchorPair.Solution] {
return lhs.lessThanOrEqual(to: rhs)
}
// MARK: - GreaterThanOrEqual
@discardableResult
public func ≥ (lhs: XYAxesAnchorPair, rhs: XYAxesAnchorPair.LayoutConstantTuple) -> XYAxesAnchorPair.Solution {
return lhs.greaterThanOrEqual(to: rhs)
}
@discardableResult
public func ≥ (lhs: XYAxesAnchorPair, rhs: [XYAxesAnchorPair.LayoutConstantTuple]) -> [XYAxesAnchorPair.Solution] {
return lhs.greaterThanOrEqual(to: rhs)
}
// MARK: XYAxesAnchorPair Array <=> XYAxesAnchorPair.LayoutConstantTuple
// MARK: - Equal
// MARK: Collection == Expression
@discardableResult
public func .= (lhs: [XYAxesAnchorPair], rhs: XYAxesAnchorPair.LayoutConstantTuple) -> [XYAxesAnchorPair.Solution] {
return lhs.map { $0.equal(to: rhs) }
}
// MARK: Collection == Expression Array
@discardableResult
public func .= (lhs: [XYAxesAnchorPair], rhs: [XYAxesAnchorPair.LayoutConstantTuple]) -> [[XYAxesAnchorPair.Solution]] {
return lhs.map { $0.equal(to: rhs) }
}
// MARK: - LessThanOrEqual
// MARK: Collection <= Expression
@discardableResult
public func ≤ (lhs: [XYAxesAnchorPair], rhs: XYAxesAnchorPair.LayoutConstantTuple) -> [XYAxesAnchorPair.Solution] {
return lhs.map { $0.lessThanOrEqual(to: rhs) }
}
// MARK: Collection <= Expression Array
@discardableResult
public func ≤ (lhs: [XYAxesAnchorPair], rhs: [XYAxesAnchorPair.LayoutConstantTuple]) -> [[XYAxesAnchorPair.Solution]] {
return lhs.map { $0.lessThanOrEqual(to: rhs) }
}
// MARK: - GreaterThanOrEqual
// MARK: Collection >= Expression
@discardableResult
public func ≥ (lhs: [XYAxesAnchorPair], rhs: XYAxesAnchorPair.LayoutConstantTuple) -> [XYAxesAnchorPair.Solution] {
return lhs.map { $0.greaterThanOrEqual(to: rhs) }
}
// MARK: Collection >= Expression Array
@discardableResult
public func ≥ (lhs: [XYAxesAnchorPair], rhs: [XYAxesAnchorPair.LayoutConstantTuple]) -> [[XYAxesAnchorPair.Solution]] {
return lhs.map { $0.greaterThanOrEqual(to: rhs) }
}
// MARK: XYAxesAnchorPair <=> XYAxesAnchorPair.LayoutCoefficient
// MARK: - Equal
@discardableResult
public func .= (lhs: XYAxesAnchorPair, rhs: XYAxesAnchorPair.LayoutCoefficient) -> XYAxesAnchorPair.Solution {
return lhs.equal(to: rhs)
}
@discardableResult
public func .= (lhs: XYAxesAnchorPair, rhs: [XYAxesAnchorPair.LayoutCoefficient]) -> [XYAxesAnchorPair.Solution] {
return lhs.equal(to: rhs)
}
// MARK: - LessThanOrEqual
@discardableResult
public func ≤ (lhs: XYAxesAnchorPair, rhs: XYAxesAnchorPair.LayoutCoefficient) -> XYAxesAnchorPair.Solution {
return lhs.lessThanOrEqual(to: rhs)
}
@discardableResult
public func ≤ (lhs: XYAxesAnchorPair, rhs: [XYAxesAnchorPair.LayoutCoefficient]) -> [XYAxesAnchorPair.Solution] {
return lhs.lessThanOrEqual(to: rhs)
}
// MARK: - GreaterThanOrEqual
@discardableResult
public func ≥ (lhs: XYAxesAnchorPair, rhs: XYAxesAnchorPair.LayoutCoefficient) -> XYAxesAnchorPair.Solution {
return lhs.greaterThanOrEqual(to: rhs)
}
@discardableResult
public func ≥ (lhs: XYAxesAnchorPair, rhs: [XYAxesAnchorPair.LayoutCoefficient]) -> [XYAxesAnchorPair.Solution] {
return lhs.greaterThanOrEqual(to: rhs)
}
// MARK: XYAxesAnchorPair Array <=> XYAxesAnchorPair.LayoutCoefficient
// MARK: - Equal
// MARK: Collection == Expression
@discardableResult
public func .= (lhs: [XYAxesAnchorPair], rhs: XYAxesAnchorPair.LayoutCoefficient) -> [XYAxesAnchorPair.Solution] {
return lhs.map { $0.equal(to: rhs) }
}
// MARK: Collection == Expression Array
@discardableResult
public func .= (lhs: [XYAxesAnchorPair], rhs: [XYAxesAnchorPair.LayoutCoefficient]) -> [[XYAxesAnchorPair.Solution]] {
return lhs.map { $0.equal(to: rhs) }
}
// MARK: - LessThanOrEqual
// MARK: Collection <= Expression
@discardableResult
public func ≤ (lhs: [XYAxesAnchorPair], rhs: XYAxesAnchorPair.LayoutCoefficient) -> [XYAxesAnchorPair.Solution] {
return lhs.map { $0.lessThanOrEqual(to: rhs) }
}
// MARK: Collection <= Expression Array
@discardableResult
public func ≤ (lhs: [XYAxesAnchorPair], rhs: [XYAxesAnchorPair.LayoutCoefficient]) -> [[XYAxesAnchorPair.Solution]] {
return lhs.map { $0.lessThanOrEqual(to: rhs) }
}
// MARK: - GreaterThanOrEqual
// MARK: Collection >= Expression
@discardableResult
public func ≥ (lhs: [XYAxesAnchorPair], rhs: XYAxesAnchorPair.LayoutCoefficient) -> [XYAxesAnchorPair.Solution] {
return lhs.map { $0.greaterThanOrEqual(to: rhs) }
}
// MARK: Collection >= Expression Array
@discardableResult
public func ≥ (lhs: [XYAxesAnchorPair], rhs: [XYAxesAnchorPair.LayoutCoefficient]) -> [[XYAxesAnchorPair.Solution]] {
return lhs.map { $0.greaterThanOrEqual(to: rhs) }
}
| 32.897233 | 123 | 0.746486 |
7a6124885aae9ff47f8d30fa40e794ab84cc2339 | 1,153 | //
// EVTTextFieldCell.swift
// EventsUI
//
// Created by Guilherme Rambo on 9/5/16.
// Copyright © 2016 Guilherme Rambo. All rights reserved.
//
import Cocoa
open class EVTTextFieldCell: NSTextFieldCell {
override open var backgroundColor: NSColor? {
get {
// we need to make sure `backgroundColor` is fully transparent to clear the canvas before drawing our label's text
return NSColor.clear
}
set {}
}
override open var drawsBackground: Bool {
get {
// if `drawsBackground` is false and the color is `labelColor`, there's a drawing glitch
return true
}
set {}
}
override open func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
guard let ctx = NSGraphicsContext.current?.cgContext else { return }
ctx.setBlendMode(CGBlendMode.overlay)
ctx.setAlpha(0.5)
super.draw(withFrame: cellFrame, in: controlView)
ctx.setBlendMode(CGBlendMode.plusLighter)
ctx.setAlpha(1.0)
super.draw(withFrame: cellFrame, in: controlView)
}
}
| 27.452381 | 126 | 0.620121 |
38c9d99bfab0b03dab1bcf6722811ec70801dc10 | 5,192 | //
// AKSequencerTrack.swift
// AudioKit
//
// Created by Jeff Cooper on 1/25/19.
// Copyright © 2019 AudioKit. All rights reserved.
//
import Foundation
/// Audio player that loads a sample into memory
open class AKSequencerTrack: AKNode, AKComponent {
public typealias AKAudioUnitType = AKSequencerEngine
/// Four letter unique description of the node
public static let ComponentDescription = AudioComponentDescription(instrument: "sqcr")
// MARK: - Properties
private var internalAU: AKAudioUnitType?
public var targetNode: AKNode?
/// Ramp Duration represents the speed at which parameters are allowed to change
@objc open dynamic var rampDuration: Double = AKSettings.rampDuration {
willSet { internalAU?.rampDuration = newValue }
}
/// Length of the track in beats
public var length: Double {
get { return internalAU?.length ?? 0 }
set { internalAU?.length = newValue }
}
/// Speed of the track in beats per minute
public var tempo: BPM {
get { return internalAU?.tempo ?? 0 }
set { internalAU?.tempo = newValue }
}
/// Maximum number of times to play, ie. loop the track
public var maximumPlayCount: Double {
get { return internalAU?.maximumPlayCount ?? 0 }
set { internalAU?.maximumPlayCount = newValue }
}
public var seqEnabled: Bool {
set { internalAU?.seqEnabled = newValue }
get { return internalAU?.seqEnabled ?? false }
}
/// Is looping enabled?
public var loopEnabled: Bool {
set { internalAU?.loopEnabled = newValue }
get { return internalAU?.loopEnabled ?? false }
}
/// Is the track currently playing?
public var isPlaying: Bool {
return internalAU?.isPlaying ?? false
}
/// Current position of the track
public var currentPosition: Double {
return internalAU?.currentPosition ?? 0
}
// MARK: - Initialization
/// Initialize the track
@objc public override init() {
_Self.register()
super.init()
AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in
guard let strongSelf = self else {
AKLog("Error: self is nil")
return
}
strongSelf.avAudioUnit = avAudioUnit
strongSelf.avAudioNode = avAudioUnit
strongSelf.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType
}
AKManager.internalConnections.append(self)
}
/// Initialize the track with a target node
@objc public convenience init(targetNode: AKNode) {
self.init()
setTarget(node: targetNode)
}
/// Set the target node
public func setTarget(node: AKNode) {
targetNode = node
internalAU?.setTarget(targetNode?.avAudioUnit?.audioUnit)
}
/// Start the track
public func play() {
internalAU?.start()
}
/// Start the track from the beginning
public func playFromStart() {
seek(to: 0)
internalAU?.start()
}
/// Start the track after a certain delay in beats
public func playAfterDelay(beats: Double) {
seek(to: -1 * beats)
internalAU?.start()
}
/// Stop playback
public func stop() {
internalAU?.stop()
}
/// Set the current position to the start ofthe track
public func rewind() {
internalAU?.rewind()
}
/// Move to a position in the track
public func seek(to position: Double) {
internalAU?.seek(to: position)
}
/// Add a MIDI note to the track
open func add(noteNumber: MIDINoteNumber,
velocity: MIDIVelocity = 127,
channel: MIDIChannel = 0,
position: Double,
duration: Double) {
var noteOffPosition: Double = (position + duration)
while noteOffPosition >= length && length != 0 {
noteOffPosition -= length
}
internalAU?.addMIDINote(noteNumber,
velocity: velocity,
beat: position,
duration: duration)
}
/// Add MIDI data to the track as an event
open func add(status: AKMIDIStatus, data1: UInt8, data2: UInt8, position: Double) {
internalAU?.addMIDIEvent(status.byte, data1: data1, data2: data2, beat: position)
}
/// Add a MIDI event to the track at a specific position
open func add(event: AKMIDIEvent, position: Double) {
if let status = event.status, event.data.count > 2 {
add(status: status, data1: event.data[1], data2: event.data[2], position: position)
}
}
open func removeEvent(at position: Double) {
internalAU?.removeEvent(position)
}
open func removeNote(at position: Double) {
internalAU?.removeNote(position)
}
/// Remove the notes in the track
open func clear() {
internalAU?.clear()
}
/// Stop playing all the notes current in the "now playing" array.
open func stopPlayingNotes() {
internalAU?.stopPlayingNotes()
}
}
| 29.005587 | 95 | 0.61171 |
b96d215d9b626e7ac0e17a81312b13f40a0ff0e9 | 351 | // RUN: %empty-directory(%t)
// RUN: %{python} %utils/split_file.py -o %t %s
// RUN: %target-swift-frontend -dump-interface-hash -primary-file %t/a.swift 2> %t/a.hash
// RUN: %target-swift-frontend -dump-interface-hash -primary-file %t/b.swift 2> %t/b.hash
// RUN: not cmp %t/a.hash %t/b.hash
// BEGIN a.swift
var x: Int
// BEGIN b.swift
var y: Int
| 29.25 | 89 | 0.660969 |
713c3a8202fff4fe661bf1457fc288b48f263c2a | 947 | //
// RequestHandlerResponsable.swift
// thanos menu
//
// Created by Lucas Moreton on 22/07/20.
// Copyright © 2020 Lucas Moreton. All rights reserved.
//
import Foundation
protocol RequestHandleResponsable: TreatDataResponse {
func handleResponse<T: Decodable>(
data: Data?,
response: HTTPURLResponse?,
error: Error?,
result: ResultHandler<T>
)
}
extension RequestHandleResponsable {
func handleResponse<T: Decodable>(
data: Data?, response: HTTPURLResponse?,
error: Error?,
result: ResultHandler<T>
) {
if let error = error {
return result(.failure(NetworkError(description: error.localizedDescription)))
}
guard let response = response, let data = data else {
return result(.failure(.noJSONData))
}
treatDataResponse(data: data, response: response, result: result)
}
}
| 24.921053 | 90 | 0.62302 |
14737eb1192581d00e73523adc08df8b338f6007 | 1,150 | // https://github.com/Quick/Quick
import Quick
import Nimble
import DXWSDK
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| 22.54902 | 60 | 0.355652 |
561c9ac9af591b9bb5e50fd9c570a3cf453471ac | 2,942 | //
// TouchIDAuthentication.swift
// IBBreakpoint
//
// Created by Israel Berezin on 11/22/18.
// Copyright © 2018 Israel Berezin. All rights reserved.
//
import UIKit
import SwiftUI
import LocalAuthentication
enum BiometricType {
case none
case touchID
case faceID
}
class BiometricIDAuth{
let context = LAContext()
var loginReason = "Logging in with Touch ID"
func canEvaluatePolicy() -> Bool {
return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
}
func biometricType() -> BiometricType {
let _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
switch context.biometryType {
case .none:
return .none
case .touchID:
return .touchID
case .faceID:
return .faceID
@unknown default:
return .none
}
}
func biometricImage() -> UIImage{
switch self.biometricType() {
case .faceID:
return UIImage(named: "fd")!
default:
return UIImage(named: "Touch-icon-lg")!
}
}
func biometricUIImage() -> Image{
switch self.biometricType() {
case .faceID:
return Image("fd")
default:
return Image("Touch-icon-lg")
}
}
func authenticateUser(completion: @escaping (String?) -> Void) {
guard canEvaluatePolicy() else {
completion("Touch ID not available")
return
}
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: loginReason) { (success, evaluateError) in
if success {
DispatchQueue.main.async {
// User authenticated successfully, take appropriate action
completion(nil)
}
} else {
let message: String
switch evaluateError {
case LAError.authenticationFailed?:
message = "There was a problem verifying your identity."
case LAError.userCancel?:
message = "You pressed cancel."
case LAError.userFallback?:
message = "You pressed password."
case LAError.biometryNotAvailable?:
message = "Face ID/Touch ID is not available."
case LAError.biometryNotEnrolled?:
message = "Face ID/Touch ID is not set up."
case LAError.biometryLockout?:
message = "Face ID/Touch ID is locked."
default:
message = "Face ID/Touch ID may not be configured"
}
DispatchQueue.main.async {
completion(message)
}
}
}
}
}
| 29.128713 | 132 | 0.541468 |
56314fb18cff1d91d7339724e4f2bc5c273dec28 | 250 | //
// UIView+TestHelpers.swift
// EssentialAppTests
//
// Created by Bogdan Poplauschi on 14/03/2021.
//
import UIKit
extension UIView {
func enforceLayoutCycle() {
layoutIfNeeded()
RunLoop.current.run(until: Date())
}
}
| 15.625 | 47 | 0.648 |
2952a3f3fcded0e817f0bb8af8cf4fefb5e8e3bd | 762 | import RxSwift
import UIKit
/*
protocol A_Protocol {// public
var one: String { get }
var two: String { get }
}
struct A { // internal
let one: Bool = true
let two: Bool = true
let yobenai: Bool = true
}
extension A: A_Protocol {}
// 此処から先の世界は A_Protocol の情報だけで良い世界
func something(_ a: A_Protocol) {
}
*/
// something をテストする
// A を one, two, yobenai がそれぞれど色んなパターンについてテストが必要 2^3
// A_Protocol だと 2^2 のパターンが必要
protocol A_ModelProtocol {}
protocol B_ModelProtocol {}
protocol C_ModelProtocol {}
class A_Model: A_ModelProtocol {}
class B_Model: B_ModelProtocol {}
class C_Model: C_ModelProtocol {}
struct Models {
let a: A_ModelProtocol
let b: B_ModelProtocol
let c: C_ModelProtocol
}
// ## 次回
//// ↑ Model層
/// ↓ ViewModel 層
| 15.55102 | 52 | 0.691601 |
fb289395a7085e83a10a26c60202d0f2ccbc455d | 164 | //import PackageDescription
//
//let package = Package(
// name: "BookZvookSite",
// dependencies: [
// .Package(url: "../WebAPI", Version(1, 0, 0))
// ]
//)
| 18.222222 | 50 | 0.585366 |
bfc1987ab1b23e01757dc8166201bdc286d68b35 | 4,200 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2019 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Foundation
import Basic
import SPMUtility
import func POSIX.exit
import SPMPackageEditor
import class PackageModel.Manifest
enum ToolError: Error {
case error(String)
case noManifest
}
enum Mode: String {
case addPackageDependency = "add-package"
case addTarget = "add-target"
case help
}
struct Options {
struct AddPackageDependency {
let url: String
}
struct AddTarget {
let name: String
}
var dataPath: AbsolutePath = AbsolutePath("/tmp")
var addPackageDependency: AddPackageDependency?
var addTarget: AddTarget?
var mode = Mode.help
}
/// Finds the Package.swift manifest file in the current working directory.
func findPackageManifest() -> AbsolutePath? {
guard let cwd = localFileSystem.currentWorkingDirectory else {
return nil
}
let manifestPath = cwd.appending(component: Manifest.filename)
return localFileSystem.isFile(manifestPath) ? manifestPath : nil
}
final class PackageIndex {
struct Entry: Codable {
let name: String
let url: String
}
// Name -> URL
private(set) var index: [String: String]
init() throws {
index = [:]
let indexFile = localFileSystem.homeDirectory.appending(components: ".swiftpm", "package-mapping.json")
guard localFileSystem.isFile(indexFile) else {
return
}
let bytes = try localFileSystem.readFileContents(indexFile).contents
let entries = try JSONDecoder().decode(Array<Entry>.self, from: Data(bytes: bytes, count: bytes.count))
index = Dictionary(uniqueKeysWithValues: entries.map{($0.name, $0.url)})
}
}
do {
let binder = ArgumentBinder<Options>()
let parser = ArgumentParser(
usage: "subcommand",
overview: "Tool for editing the Package.swift manifest file")
// Add package dependency.
let packageDependencyParser = parser.add(subparser: Mode.addPackageDependency.rawValue, overview: "Add a new package dependency")
binder.bind(
positional: packageDependencyParser.add(positional: "package-url", kind: String.self, usage: "Dependency URL"),
to: { $0.addPackageDependency = Options.AddPackageDependency(url: $1) })
// Add Target.
let addTargetParser = parser.add(subparser: Mode.addTarget.rawValue, overview: "Add a new target")
binder.bind(
positional: addTargetParser.add(positional: "target-name", kind: String.self, usage: "Target name"),
to: { $0.addTarget = Options.AddTarget(name: $1) })
// Bind the mode.
binder.bind(
parser: parser,
to: { $0.mode = Mode(rawValue: $1)! })
// Parse the options.
var options = Options()
let result = try parser.parse(Array(CommandLine.arguments.dropFirst()))
try binder.fill(parseResult: result, into: &options)
// Find the Package.swift file in cwd.
guard let manifest = findPackageManifest() else {
throw ToolError.noManifest
}
options.dataPath = (localFileSystem.currentWorkingDirectory ?? AbsolutePath("/tmp")).appending(component: ".build")
switch options.mode {
case .addPackageDependency:
var url = options.addPackageDependency!.url
url = try PackageIndex().index[url] ?? url
let editor = try PackageEditor(buildDir: options.dataPath)
try editor.addPackageDependency(options: .init(manifestPath: manifest, url: url, requirement: nil))
case .addTarget:
let targetOptions = options.addTarget!
let editor = try PackageEditor(buildDir: options.dataPath)
try editor.addTarget(options: .init(manifestPath: manifest, targetName: targetOptions.name, targetType: .regular))
case .help:
parser.printUsage(on: stdoutStream)
}
} catch {
stderrStream <<< String(describing: error) <<< "\n"
stderrStream.flush()
POSIX.exit(1)
}
| 30.882353 | 133 | 0.685952 |
e5f4d176b74c381f6d3da61b4a3d3d48e34521a6 | 2,183 | import Foundation
/**
An abstract class that makes subclassing ConcurrentOperation easier. Updates KVO props `isReady`/`isExecuting`/`isFinished` automatically.
### Usage
1. Subclass `ConcurrentBlockOperation`.
2. Override `execute()` with custom execution.
3. Invoke `finish()` when concurrent execution completes.
- Note: If customize `cancel()` in subclass, should call `super.cancel()` instead of `super.finish()`.
*/
@objc
open class ConcurrentBlockOperation: BlockOperation {
private let semaphore = DispatchSemaphore(value: 0)
@ThreadSafe
public var props = [String: Any]()
private typealias ExecutionBlock = () -> Void
private var executionBlock: ExecutionBlock!
@ThreadSafe
private var isBlockFinished = false
public init(block: @escaping () -> Void) {
fatalError("Must call designated intialize init().")
}
public override init() {
super.init()
executionBlock = { [weak self] in
guard let `self` = self else { return }
self.execute()
// Wait for `semaphore` to finish the block execution - operation will be `isFinished`.
if !self.isBlockFinished {
self.semaphore.wait()
}
}
addExecutionBlock(executionBlock)
}
// MARK: - Override methods
public final override func start() {
guard !isBlockFinished && !self.isExecuting else {
return
}
// Invoke super.start() to execute `self.executionBlock`.
super.start()
}
private func execute() {
guard !isCancelled else {
dbgPrintWithFunc(self, "Skip execute() because the operation has been cancelled!")
return
}
_execute()
}
open func _execute() {
fatalError("\(#function) must be overriden in subclass.")
}
open func finish() {
guard !isBlockFinished else {
// assertionFailure("Shouldn't call finish() twice.")
return
}
isBlockFinished = true
signalFinished()
}
open override func cancel() {
super.cancel()
signalFinished()
dbgPrint("executeBlock cancelled. Class = \(type(of: self)); props = \(props); self = \(self)")
}
private func signalFinished() {
semaphore.signal()
}
}
| 25.682353 | 139 | 0.658727 |
1d95c02959d35523ad31df0bb3308cab2890ac32 | 2,724 | //
// util.swift
//
// Created by Darren Ford on 17/08/21
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#if os(macOS)
import AppKit
internal final class FlippedClipView: NSClipView {
override var isFlipped: Bool {
return true
}
}
internal extension NSView {
// Pin 'self' within 'other' view
func pinEdges(to other: NSView, offset: CGFloat = 0, animate: Bool = false) {
let target = animate ? animator() : self
target.leadingAnchor.constraint(equalTo: other.leadingAnchor, constant: offset).isActive = true
target.trailingAnchor.constraint(equalTo: other.trailingAnchor, constant: -offset).isActive = true
target.topAnchor.constraint(equalTo: other.topAnchor, constant: offset).isActive = true
target.bottomAnchor.constraint(equalTo: other.bottomAnchor, constant: -offset).isActive = true
}
}
internal extension NSView {
func padded(_ edgeInsets: NSEdgeInsets) -> NSView {
let v = NSView()
v.translatesAutoresizingMaskIntoConstraints = false
v.addSubview(self)
self.leadingAnchor.constraint(equalTo: v.leadingAnchor, constant: edgeInsets.left).isActive = true
self.trailingAnchor.constraint(equalTo: v.trailingAnchor, constant: -edgeInsets.right).isActive = true
self.topAnchor.constraint(equalTo: v.topAnchor, constant: edgeInsets.top).isActive = true
self.bottomAnchor.constraint(equalTo: v.bottomAnchor, constant: -edgeInsets.bottom).isActive = true
return v
}
}
internal extension Array {
/// Returns the item at the specified index, or nil if the index is out of range
@inlinable func at(_ index: Int) -> Element? {
if index >= 0 && index < self.count {
return self[index]
}
return nil
}
}
#endif
| 37.833333 | 104 | 0.747797 |
f5fbb511002eeca1aaa52fad3aea53788bb09d4b | 3,740 | //
// MIT License
//
// Copyright (c) 2018-2019 Radix DLT ( https://radixdlt.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import SwiftUI
enum All {
static let gestures = all(of: Gestures.self)
private static func all<CI>(of _: CI.Type) -> CI.AllCases where CI: CaseIterable {
return CI.allCases
}
}
enum Gestures: Hashable, CaseIterable {
case tap, longPress, drag, magnification, rotation
}
protocol ValueGesture: Gesture where Value: Equatable {
func onChanged(_ action: @escaping (Value) -> Void) -> _ChangedGesture<Self>
}
extension LongPressGesture: ValueGesture {}
extension DragGesture: ValueGesture {}
extension MagnificationGesture: ValueGesture {}
extension RotationGesture: ValueGesture {}
extension Gestures {
@discardableResult
func apply<V>(to view: V, perform voidAction: @escaping () -> Void) -> AnyView where V: View {
func highPrio<G>(
gesture: G
) -> AnyView where G: ValueGesture {
view.highPriorityGesture(
gesture.onChanged { value in
_ = value
voidAction()
}
).eraseToAny()
}
switch self {
case .tap:
// not `highPriorityGesture` since tapping is a common gesture, e.g. wanna allow users
// to easily tap on a TextField in another cell in the case of a list of TextFields / Form
return view.gesture(TapGesture().onEnded(voidAction)).eraseToAny()
case .longPress: return highPrio(gesture: LongPressGesture())
case .drag: return highPrio(gesture: DragGesture())
case .magnification: return highPrio(gesture: MagnificationGesture())
case .rotation: return highPrio(gesture: RotationGesture())
}
}
}
struct DismissingKeyboard: ViewModifier {
var gestures: [Gestures] = Gestures.allCases
dynamic func body(content: Content) -> some View {
let action = {
let forcing = true
let keyWindow = UIApplication.shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first
keyWindow?.endEditing(forcing)
}
return gestures.reduce(content.eraseToAny()) { $1.apply(to: $0, perform: action) }
}
}
extension View {
dynamic func dismissKeyboard(on gestures: [Gestures] = Gestures.allCases) -> some View {
return ModifiedContent(content: self, modifier: DismissingKeyboard(gestures: gestures))
}
}
| 37.029703 | 102 | 0.659358 |
abb892bc81e27ed192021eae9e459b0fa0bf72b5 | 4,175 | //
// PlaceDetailView.swift
// SwiftUIStarterKitApp
//
// Created by Osama Naeem on 11/08/2019.
// Copyright © 2019 NexThings. All rights reserved.
//
import SwiftUI
import Combine
class SelectedPoint: ObservableObject {
@Published var selectedIndex: Int = 0
}
struct PlaceDetailView : View {
@Binding var isShowing: Bool
@Binding var placeItem: ActivitiesPlaces?
let defaultPoint = ActivitiesFamousPoints(id: 0, pointName: "Default", pointImage: "Default PlaceHolder", pointDescription: "Default Description PlaceHolder")
@ObservedObject var selectedPoint = SelectedPoint()
var body: some View {
GeometryReader { g in
ZStack {
Image(self.placeItem?.famousPointsArray[self.selectedPoint.selectedIndex].pointImage ?? "")
.resizable()
.frame(width: g.size.width, height: g.size.height)
.aspectRatio(contentMode: .fit)
.opacity(0.3)
.background(Color.black)
.onDisappear {
self.isShowing = false
}
VStack(alignment: .leading) {
Text(self.placeItem?.activityPlace ?? "")
.foregroundColor(Color.white)
.font(.system(size: 30, weight: .bold, design: .default))
.padding(.top, 34)
.padding(.leading, 30)
HStack{
Spacer()
}
Spacer()
PlacesDetail(placeItems: self.placeItem?.famousPointsArray[self.selectedPoint.selectedIndex] ?? self.defaultPoint)
.padding(.bottom, 50)
ZStack {
BlurView(style: .light)
.frame(width: g.size.width, height: 130)
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(self.placeItem?.famousPointsArray ?? [], id: \.id) { item in
PlacesCircleView(placeItems: item, selectedPoint: self.selectedPoint)
}
}.frame(width: g.size.width, height: 130)
}
}.padding(.bottom, 50)
}
}
}
.edgesIgnoringSafeArea(.bottom)
}
}
struct PlacesCircleView: View {
var placeItems: ActivitiesFamousPoints
@ObservedObject var selectedPoint: SelectedPoint
var body: some View {
GeometryReader { g in
Button(action: {
self.selectedPoint.selectedIndex = self.placeItems.id
}) {
ZStack {
Image(self.placeItems.pointImage).renderingMode(.original)
.resizable()
.frame(width: 110, height: 110)
.background(Color.red)
.clipShape(Circle())
if (self.selectedPoint.selectedIndex == self.placeItems.id) {
Text("✓")
.font(.system(size: 30, weight: .bold, design: Font.Design.default))
.foregroundColor(Color.white)
}
}
}
}
}
}
struct PlacesDetail: View {
var placeItems: ActivitiesFamousPoints
var body: some View {
VStack(alignment: .leading) {
Text(placeItems.pointName)
.foregroundColor(Color.white)
.font(.system(size: 24, weight: .bold, design: .default))
.padding(.leading, 30)
Text(placeItems.pointDescription)
.foregroundColor(Color.white)
.font(.system(size: 16, weight: .regular, design: .default))
.padding(.leading, 30)
.padding(.trailing, 30)
}
}
}
| 36.304348 | 162 | 0.482156 |
d6dc356d9d73c0e933f25df972a03b89c04ab3f3 | 610 | //
// Notifications+Names.swift
// Spotify-iOS-Swift-Future
//
// Created by Kevin Johnson on 8/10/18.
// Copyright © 2018 FFR. All rights reserved.
//
import Foundation
extension Notification.Name {
static let trackChanged = NSNotification.Name("TrackChanged")
static let trackIsPlayingChanged = NSNotification.Name("TrackIsPlayingChanged")
static let trackIsShufflingChanged = NSNotification.Name("TrackIsShufflingChanged")
static let trackPositionUpdate = NSNotification.Name("TrackPositionUpdate")
static let spotifySessionUpdated = NSNotification.Name("SpotifySessionUpdated")
}
| 33.888889 | 87 | 0.77541 |
1d0154d8e47e8554bc12db1765c3b0af7cd4d0bd | 629 | import Foundation
import web
import web_swift_server
var port: Int = 8080
if let p = ProcessInfo.processInfo.environment["SERVER_PORT"], let i = Int(p) { port = i }
let indexRoutes : [[Any]] = [
["/"],
]
let log = WebLoggerExtension()
let router = WebRouter()
router.addStaticFiles(root: "public")
for path in indexRoutes {
if path.count == 1, let path = path.first as? String {
router.route(path, file: "public/index.html")
} else {
router.route(path, file: "public/index.html")
}
}
let server = WebServer(adapter: WebSwiftServerAdapter(), responder: router, extensions: [log], port: port)
try server.run()
| 24.192308 | 106 | 0.691574 |
fcdc0a05d77dcb6f41466100bf61df2b9dbe46b8 | 19,458 | //===----------------------------------------------------------------------===//
//
// 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.
@_exported import SotoCore
/// Service object for interacting with AWS Mgn service.
///
/// The Application Migration Service service.
public struct Mgn: AWSService {
// MARK: Member variables
/// Client used for communication with AWS
public let client: AWSClient
/// Service configuration
public let config: AWSServiceConfig
// MARK: Initialization
/// Initialize the Mgn 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: "mgn",
serviceProtocol: .restjson,
apiVersion: "2020-02-26",
endpoint: endpoint,
errorType: MgnErrorType.self,
timeout: timeout,
byteBufferAllocator: byteBufferAllocator,
options: options
)
}
// MARK: API Calls
/// Allows the user to set the SourceServer.LifeCycle.state property for specific Source Server IDs to one of the following: READY_FOR_TEST or READY_FOR_CUTOVER. This command only works if the Source Server is already launchable (dataReplicationInfo.lagDuration is not null.)
public func changeServerLifeCycleState(_ input: ChangeServerLifeCycleStateRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<SourceServer> {
return self.client.execute(operation: "ChangeServerLifeCycleState", path: "/ChangeServerLifeCycleState", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Creates a new ReplicationConfigurationTemplate.
public func createReplicationConfigurationTemplate(_ input: CreateReplicationConfigurationTemplateRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ReplicationConfigurationTemplate> {
return self.client.execute(operation: "CreateReplicationConfigurationTemplate", path: "/CreateReplicationConfigurationTemplate", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a single Job by ID.
public func deleteJob(_ input: DeleteJobRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteJobResponse> {
return self.client.execute(operation: "DeleteJob", path: "/DeleteJob", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a single Replication Configuration Template by ID
public func deleteReplicationConfigurationTemplate(_ input: DeleteReplicationConfigurationTemplateRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteReplicationConfigurationTemplateResponse> {
return self.client.execute(operation: "DeleteReplicationConfigurationTemplate", path: "/DeleteReplicationConfigurationTemplate", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a single source server by ID.
public func deleteSourceServer(_ input: DeleteSourceServerRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteSourceServerResponse> {
return self.client.execute(operation: "DeleteSourceServer", path: "/DeleteSourceServer", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes a single vCenter client by ID.
@discardableResult public func deleteVcenterClient(_ input: DeleteVcenterClientRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "DeleteVcenterClient", path: "/DeleteVcenterClient", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Retrieves detailed Job log with paging.
public func describeJobLogItems(_ input: DescribeJobLogItemsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeJobLogItemsResponse> {
return self.client.execute(operation: "DescribeJobLogItems", path: "/DescribeJobLogItems", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Returns a list of Jobs. Use the JobsID and fromDate and toData filters to limit which jobs are returned. The response is sorted by creationDataTime - latest date first. Jobs are normaly created by the StartTest, StartCutover, and TerminateTargetInstances APIs. Jobs are also created by DiagnosticLaunch and TerminateDiagnosticInstances, which are APIs available only to *Support* and only used in response to relevant support tickets.
public func describeJobs(_ input: DescribeJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeJobsResponse> {
return self.client.execute(operation: "DescribeJobs", path: "/DescribeJobs", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists all ReplicationConfigurationTemplates, filtered by Source Server IDs.
public func describeReplicationConfigurationTemplates(_ input: DescribeReplicationConfigurationTemplatesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeReplicationConfigurationTemplatesResponse> {
return self.client.execute(operation: "DescribeReplicationConfigurationTemplates", path: "/DescribeReplicationConfigurationTemplates", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Retrieves all SourceServers or multiple SourceServers by ID.
public func describeSourceServers(_ input: DescribeSourceServersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeSourceServersResponse> {
return self.client.execute(operation: "DescribeSourceServers", path: "/DescribeSourceServers", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists all vCenter clients.
public func describeVcenterClients(_ input: DescribeVcenterClientsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeVcenterClientsResponse> {
return self.client.execute(operation: "DescribeVcenterClients", path: "/DescribeVcenterClients", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Disconnects specific Source Servers from Application Migration Service. Data replication is stopped immediately. All AWS resources created by Application Migration Service for enabling the replication of these source servers will be terminated / deleted within 90 minutes. Launched Test or Cutover instances will NOT be terminated. If the agent on the source server has not been prevented from communciating with the Application Migration Service service, then it will receive a command to uninstall itself (within approximately 10 minutes). The following properties of the SourceServer will be changed immediately: dataReplicationInfo.dataReplicationState will be set to DISCONNECTED; The totalStorageBytes property for each of dataReplicationInfo.replicatedDisks will be set to zero; dataReplicationInfo.lagDuration and dataReplicationInfo.lagDurationwill be nullified.
public func disconnectFromService(_ input: DisconnectFromServiceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<SourceServer> {
return self.client.execute(operation: "DisconnectFromService", path: "/DisconnectFromService", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Finalizes the cutover immediately for specific Source Servers. All AWS resources created by Application Migration Service for enabling the replication of these source servers will be terminated / deleted within 90 minutes. Launched Test or Cutover instances will NOT be terminated. The AWS Replication Agent will receive a command to uninstall itself (within 10 minutes). The following properties of the SourceServer will be changed immediately: dataReplicationInfo.dataReplicationState will be to DISCONNECTED; The SourceServer.lifeCycle.state will be changed to CUTOVER; The totalStorageBytes property fo each of dataReplicationInfo.replicatedDisks will be set to zero; dataReplicationInfo.lagDuration and dataReplicationInfo.lagDurationwill be nullified.
public func finalizeCutover(_ input: FinalizeCutoverRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<SourceServer> {
return self.client.execute(operation: "FinalizeCutover", path: "/FinalizeCutover", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists all LaunchConfigurations available, filtered by Source Server IDs.
public func getLaunchConfiguration(_ input: GetLaunchConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<LaunchConfiguration> {
return self.client.execute(operation: "GetLaunchConfiguration", path: "/GetLaunchConfiguration", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lists all ReplicationConfigurations, filtered by Source Server ID.
public func getReplicationConfiguration(_ input: GetReplicationConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ReplicationConfiguration> {
return self.client.execute(operation: "GetReplicationConfiguration", path: "/GetReplicationConfiguration", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Initialize Application Migration Service.
public func initializeService(_ input: InitializeServiceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<InitializeServiceResponse> {
return self.client.execute(operation: "InitializeService", path: "/InitializeService", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// List all tags for your Application Migration Service resources.
public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsForResourceResponse> {
return self.client.execute(operation: "ListTagsForResource", path: "/tags/{resourceArn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Archives specific Source Servers by setting the SourceServer.isArchived property to true for specified SourceServers by ID. This command only works for SourceServers with a lifecycle.state which equals DISCONNECTED or CUTOVER.
public func markAsArchived(_ input: MarkAsArchivedRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<SourceServer> {
return self.client.execute(operation: "MarkAsArchived", path: "/MarkAsArchived", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Causes the data replication initiation sequence to begin immediately upon next Handshake for specified SourceServer IDs, regardless of when the previous initiation started. This command will not work if the SourceServer is not stalled or is in a DISCONNECTED or STOPPED state.
public func retryDataReplication(_ input: RetryDataReplicationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<SourceServer> {
return self.client.execute(operation: "RetryDataReplication", path: "/RetryDataReplication", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Launches a Cutover Instance for specific Source Servers. This command starts a LAUNCH job whose initiatedBy property is StartCutover and changes the SourceServer.lifeCycle.state property to CUTTING_OVER.
public func startCutover(_ input: StartCutoverRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartCutoverResponse> {
return self.client.execute(operation: "StartCutover", path: "/StartCutover", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Starts replication on source server by ID.
public func startReplication(_ input: StartReplicationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<SourceServer> {
return self.client.execute(operation: "StartReplication", path: "/StartReplication", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Lauches a Test Instance for specific Source Servers. This command starts a LAUNCH job whose initiatedBy property is StartTest and changes the SourceServer.lifeCycle.state property to TESTING.
public func startTest(_ input: StartTestRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<StartTestResponse> {
return self.client.execute(operation: "StartTest", path: "/StartTest", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Adds or overwrites only the specified tags for the specified Application Migration Service resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value.
@discardableResult public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "TagResource", path: "/tags/{resourceArn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Starts a job that terminates specific launched EC2 Test and Cutover instances. This command will not work for any Source Server with a lifecycle.state of TESTING, CUTTING_OVER, or CUTOVER.
public func terminateTargetInstances(_ input: TerminateTargetInstancesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<TerminateTargetInstancesResponse> {
return self.client.execute(operation: "TerminateTargetInstances", path: "/TerminateTargetInstances", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Deletes the specified set of tags from the specified set of Application Migration Service resources.
@discardableResult public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> {
return self.client.execute(operation: "UntagResource", path: "/tags/{resourceArn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates multiple LaunchConfigurations by Source Server ID.
public func updateLaunchConfiguration(_ input: UpdateLaunchConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<LaunchConfiguration> {
return self.client.execute(operation: "UpdateLaunchConfiguration", path: "/UpdateLaunchConfiguration", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Allows you to update multiple ReplicationConfigurations by Source Server ID.
public func updateReplicationConfiguration(_ input: UpdateReplicationConfigurationRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ReplicationConfiguration> {
return self.client.execute(operation: "UpdateReplicationConfiguration", path: "/UpdateReplicationConfiguration", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates multiple ReplicationConfigurationTemplates by ID.
public func updateReplicationConfigurationTemplate(_ input: UpdateReplicationConfigurationTemplateRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ReplicationConfigurationTemplate> {
return self.client.execute(operation: "UpdateReplicationConfigurationTemplate", path: "/UpdateReplicationConfigurationTemplate", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
/// Updates source server Replication Type by ID.
public func updateSourceServerReplicationType(_ input: UpdateSourceServerReplicationTypeRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<SourceServer> {
return self.client.execute(operation: "UpdateSourceServerReplicationType", path: "/UpdateSourceServerReplicationType", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop)
}
}
extension Mgn {
/// 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: Mgn, patch: AWSServiceConfig.Patch) {
self.client = from.client
self.config = from.config.with(patch: patch)
}
}
| 88.445455 | 879 | 0.760613 |
0943fdcaae971394afb57505a440be9a19821d11 | 628 | //
// AuthError.swift
// Radishing
//
// Created by Nathaniel Dillinger on 4/22/18.
// Copyright © 2018 Nathaniel Dillinger. All rights reserved.
//
import Foundation
enum AuthError: Error {
case phoneLoginUnsuccessful
case emailLoginUnsuccessful
case signOutUnsuccessful
case createPhoneAuthUnsuccessful
case createEmailAuthUnsuccessful
case checkIfEmailIsTakenSearchError
case emailAlreadyInUse
case displayNameCreationError
case emailIsNotRegistered
case emailIsNotProperlyFormatted
case unknownError
case couldNotDeleteFailedUserCreation
case noInternetConnection
}
| 24.153846 | 62 | 0.780255 |
d621ab8d3241df704ed40520f2553b96d88c954a | 5,736 | //
// SearchViewController.swift
// Traffic_sys_Swift
//
// Created by 易无解 on 16/10/2017.
// Copyright © 2017 易无解. All rights reserved.
//
import UIKit
class SearchViewController: UIViewController {
// MARK: - 自定义属性
lazy var carInfoSearchBtn: UIButton = UIButton(type: .custom)
lazy var carOwnerInfoSearchBtn: UIButton = UIButton(type: .custom)
lazy var lawBreakerInfoSearchByICBtn: UIButton = UIButton(type: .custom)
lazy var lawBreakerInfoSearchByCarIdBtn: UIButton = UIButton(type: .custom)
lazy var lawBreakerInfoSearchByCarOwnerNameBtn: UIButton = UIButton(type: .custom)
// MARK: - 系统回调函数
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.backgroundColor = UIColor.colorWithHex(hex: kBackGroundColor, alpha: 1.0)
setupNavigationItem()
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
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.
}
*/
}
// MARK: - 设置UI界面
extension SearchViewController {
func setupNavigationItem() {
// 1.设置标题
navigationItem.title = "查询"
// 2.设置navigationBar颜色
navigationController?.navigationBar.setColor(color: UIColor.clear)
// 3.设置返回按钮
navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: nil)
}
func setupView() {
// 1.添加子控件
view.addSubview(carInfoSearchBtn)
view.addSubview(carOwnerInfoSearchBtn)
view.addSubview(lawBreakerInfoSearchByICBtn)
view.addSubview(lawBreakerInfoSearchByCarIdBtn)
view.addSubview(lawBreakerInfoSearchByCarOwnerNameBtn)
// 2.设置frame
carOwnerInfoSearchBtn.snp.makeConstraints { (make) in
make.top.equalTo(224)
make.left.equalTo(62)
make.right.equalTo(-62)
make.height.equalTo(40)
}
carInfoSearchBtn.snp.makeConstraints { (make) in
make.top.equalTo(269)
make.left.equalTo(62)
make.right.equalTo(-62)
make.height.equalTo(40)
}
lawBreakerInfoSearchByICBtn.snp.makeConstraints { (make) in
make.top.equalTo(314)
make.left.equalTo(62)
make.right.equalTo(-62)
make.height.equalTo(40)
}
lawBreakerInfoSearchByCarIdBtn.snp.makeConstraints { (make) in
make.top.equalTo(359)
make.left.equalTo(62)
make.right.equalTo(-62)
make.height.equalTo(40)
}
lawBreakerInfoSearchByCarOwnerNameBtn.snp.makeConstraints { (make) in
make.top.equalTo(404)
make.left.equalTo(62)
make.right.equalTo(-62)
make.height.equalTo(40)
}
// 3.设置属性
carOwnerInfoSearchBtn.setupBtnProperty(viewController: self, action: #selector(carOwnerInfoSearchBtnClicked(_:)), bgColor: UIColor.colorWithHex(hex: kButtonHighlightBackgroundColor, alpha: 1.0), title: "车主信息查询")
carInfoSearchBtn.setupBtnProperty(viewController: self, action: #selector(carInfoSearchBtnClicked(_:)), bgColor: UIColor.colorWithHex(hex: kButtonHighlightBackgroundColor, alpha: 1.0), title: "车辆信息查询")
lawBreakerInfoSearchByICBtn.setupBtnProperty(viewController: self, action: #selector(lawBreakerInfoSearchByICBtnClicked(_:)), bgColor: UIColor.colorWithHex(hex: kLawBreakerBtnBackGroundColor, alpha: 1.0), title: "按身份证号码查询违规信息")
lawBreakerInfoSearchByCarIdBtn.setupBtnProperty(viewController: self, action: #selector(lawBreakerInfoSearchByCarIdBtnClicked(_:)), bgColor: UIColor.colorWithHex(hex: kLawBreakerBtnBackGroundColor, alpha: 1.0), title: "按车牌号查询违规信息")
lawBreakerInfoSearchByCarOwnerNameBtn.setupBtnProperty(viewController: self, action: #selector(lawBreakerInfoSearchByCarOwnerNameBtnClicked(_:)), bgColor: UIColor.colorWithHex(hex: kLawBreakerBtnBackGroundColor, alpha: 1.0), title: "按车主名查询违规信息")
}
}
// MARK: - 事件监听函数
extension SearchViewController {
@objc func carInfoSearchBtnClicked(_ sender: Any) {
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(CarInfoSearchViewController(), animated: true)
}
@objc func carOwnerInfoSearchBtnClicked(_ sender: Any) {
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(CarOwnerInfoSearchViewController(), animated: true)
}
@objc func lawBreakerInfoSearchByICBtnClicked(_ sender: Any) {
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(LawBreakerInfoSearchByICViewController(), animated: true)
}
@objc func lawBreakerInfoSearchByCarIdBtnClicked(_ sender: Any) {
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(LawBreakerInfoSearchByCarIdViewController(), animated: true)
}
@objc func lawBreakerInfoSearchByCarOwnerNameBtnClicked(_ sender: Any) {
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(LawBreakerInfoSearchByCarOwnerNameViewController(), animated: true)
}
}
| 38.496644 | 253 | 0.68288 |
f8c5a08b407ec19a8541566bb97010d994714809 | 482 | //
// WeakContainer.swift
// Pageboy iOS
//
// Created by Merrick Sapsford on 02/03/2019.
// Copyright © 2019 UI At Six. All rights reserved.
//
import Foundation
internal final class WeakWrapper<T: AnyObject> {
private(set) weak var object: T?
init(_ object: T) {
self.object = object
}
}
extension WeakWrapper: Equatable {
static func == (lhs: WeakWrapper, rhs: WeakWrapper) -> Bool {
return lhs.object === rhs.object
}
}
| 18.538462 | 65 | 0.624481 |
282294f44bd1eb6728cc7921c5a57eb3ac9ab857 | 498 | // 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
let g=1
class b{
protocol c{
{
}
struct A{
let a{
init{
class B{
var _=a({
if b{
class
case c,
case
| 21.652174 | 79 | 0.730924 |
485482f0be93fb28bb2c97447b819bd4e9830d22 | 980 | //
// UBD_VC.swift
// UBDCalculator
//
// Created by Dain Kim on 26/07/2019.
// Copyright © 2019 Dain Kim. All rights reserved.
//
import UIKit
import WebKit
class UBD_VC: UIViewController {
var web_view:WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib. webView = WKWebView()
web_view = WKWebView()
self.view = web_view
let url = "https://bit.ly/2Yr3TV1"
let open_url = URL(string: url)
let req = URLRequest(url: open_url!)
web_view.load(req)
}
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 25.128205 | 106 | 0.638776 |
6ac723ad49b0f01f30332ee8ea8c011393b416a2 | 102 | //
// Dummy.swift
// thingerio
//
// Created by Carlos Cepeda on 10/06/2020.
//
import Foundation
| 11.333333 | 43 | 0.647059 |
5b88a5c2c75129a8e0731b3a8f6874b686e4362d | 936 | //
// SwiftIBDesignableTests.swift
// SwiftIBDesignableTests
//
// Created by Christoffer on 13.03.15.
// Copyright (c) 2015 Christoffer Tews. All rights reserved.
//
import UIKit
import XCTest
class SwiftIBDesignableTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| 25.297297 | 111 | 0.629274 |
7577e1c5529c0a6d7b2b9221d7fbf9343794e9a1 | 5,683 | //
// SINCallKitProvider.swift
// Q8ForSale
//
// Created by Basim Alamuddin on 7/12/18.
// Copyright © 2018 Nahla Mortada. All rights reserved.
//
import CallKit
import Sinch
@available(iOS 10.0, *)
public class SINCallKitProvider : NSObject {
fileprivate var client: SINClient
private var provider: CXProvider
fileprivate var calls: [UUID: SINCall]
private var muted: Bool
public static var instance: SINCallKitProvider!
public static func make(with client: SINClient) {
instance = SINCallKitProvider(with: client)
}
private init(with client: SINClient) {
self.client = client
calls = [UUID: SINCall]()
muted = false
let config = CXProviderConfiguration(localizedName: "4sale") // the text appears on the CallKit screen
config.maximumCallGroups = 1
config.maximumCallsPerCallGroup = 1
config.supportedHandleTypes = [.phoneNumber, .generic]
config.supportsVideo = true
if #available(iOS 11.0, *) {
config.includesCallsInRecents = true
}
provider = CXProvider(configuration: config)
super.init()
provider.setDelegate(self, queue: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.callDidEstablish(_:)), name: NSNotification.Name.SINCallDidEstablish, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.callDidEnd), name: NSNotification.Name.SINCallDidEnd, object: nil)
}
public func reportNewIncomingCall(call: SINCall) {
let update = CXCallUpdate()
update.remoteHandle = CXHandle(type: .generic, value: call.remoteUserId)
provider.reportNewIncomingCall(with: UUID(uuidString: call.callId)!, update: update, completion: {(_ error: Error?) -> Void in
if error == nil {
self.addNewCall(call)
}
})
}
public func callExists(callId: String) -> Bool {
if calls.count == 0 {
return false
}
for callKitCall in calls.values {
if (callKitCall.callId == callId) {
return true
}
}
return false
}
public func currentEstablishedCall() -> SINCall? {
let calls = activeCalls()
if calls.count == 1 && calls[0].state == .established {
return calls[0]
} else {
return nil
}
}
private func addNewCall(_ call: SINCall) {
calls[UUID(uuidString: call.callId)!] = call
}
@objc private func callDidEstablish(_ notification: Notification) {
// let call = notification.userInfo?[SINCallKey] as? SINCall
// if let call = call {
//
// }
}
// Handle cancel/bye event initiated by either caller or callee
@objc private func callDidEnd(_ notification: Notification) {
let call = notification.userInfo?[SINCallKey] as? SINCall
if let call = call {
let callUDID = UUID(uuidString: call.callId)!
provider.reportCall(with: callUDID, endedAt: call.details.endedTime, reason: getCallEndedReason(cause: call.details.endCause))
if callExists(callId: call.callId) {
calls.removeValue(forKey: callUDID)
}
} else {
print("Sinch WARNING: No Call was reported as ended on SINCallDidEndNotification")
}
}
private func activeCalls() -> [SINCall] {
return []
}
private func getCallEndedReason(cause: SINCallEndCause) -> CXCallEndedReason {
switch cause {
case .error:
return .failed
case .denied:
return .remoteEnded
case .hungUp:
// This mapping is not really correct, as .hungUp is the end case also when the local peer ended the call.
return .remoteEnded
case .timeout:
return .unanswered
case .canceled:
return .unanswered
case .noAnswer:
return .unanswered
case .otherDeviceAnswered:
return .unanswered
default:
return .failed
}
}
}
@available(iOS 10.0, *)
extension SINCallKitProvider : CXProviderDelegate {
public func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {
client.call().provider(provider, didActivate: audioSession)
}
private func call(for action: CXCallAction) -> SINCall? {
let call = calls[action.callUUID]
if call == nil {
print("Sinch WARNING: No call found for (\(action.callUUID))")
}
return call
}
public func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
call(for: action)?.answer()
action.fulfill()
}
public func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
call(for: action)?.hangup()
action.fulfill()
}
public func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {
print("Sinch [CXProviderDelegate performSetMutedCallAction:]")
action.fulfill()
}
public func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
print("Sinch -[CXProviderDelegate didDeactivateAudioSession:]");
}
public func providerDidReset(_ provider: CXProvider) {
print("Sinch -[CXProviderDelegate providerDidReset:]");
}
}
| 31.054645 | 160 | 0.603203 |
08697eadffd113a7cd3437666e6d86485896d7b5 | 112 | import UIKit
internal struct MovieWithImage {
internal let movie: Movie
internal let image: UIImage?
}
| 16 | 32 | 0.741071 |
d5d9de1f01c6326a3aa1cffa9328bbd089e11116 | 989 | import CleanReversi
import CleanReversiApp
import Foundation
public final class GameSaver: GameControllerSaveDelegate {
private weak var delegate: GameSaverDelegate?
public init(delegate: GameSaverDelegate) {
self.delegate = delegate
}
public func saveGame(_ state: GameController.SavedState) throws {
try delegate?.writeData(state.data())
}
public func loadGame() throws -> GameController.SavedState {
guard let delegate = self.delegate else { throw IOError() }
do {
return try GameController.SavedState(data: try delegate.readData())
} catch let error {
throw IOError(cause: error)
}
}
public struct IOError: Error {
public let cause: Error?
public init(cause: Error? = nil) {
self.cause = cause
}
}
}
public protocol GameSaverDelegate: AnyObject {
func writeData(_: Data) throws
func readData() throws -> Data
}
| 26.72973 | 79 | 0.641052 |
336e4b0fc4c2cd1bffdab046e0474787ae7372ff | 2,344 | //
// Copyright 2020 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import Reusable
protocol ChooseAvatarTableViewCellDelegate: AnyObject {
func chooseAvatarTableViewCellDidTapChooseAvatar(_ cell: ChooseAvatarTableViewCell, sourceView: UIView)
func chooseAvatarTableViewCellDidTapRemoveAvatar(_ cell: ChooseAvatarTableViewCell)
}
class ChooseAvatarTableViewCell: UITableViewCell {
@IBOutlet private weak var avatarImageView: UIImageView! {
didSet {
avatarImageView.layer.cornerRadius = avatarImageView.frame.width/2
}
}
@IBOutlet private weak var chooseAvatarButton: UIButton!
@IBOutlet private weak var removeAvatarButton: UIButton! {
didSet {
removeAvatarButton.imageView?.contentMode = .scaleAspectFit
}
}
weak var delegate: ChooseAvatarTableViewCellDelegate?
@IBAction private func chooseAvatarButtonTapped(_ sender: UIButton) {
delegate?.chooseAvatarTableViewCellDidTapChooseAvatar(self, sourceView: sender)
}
@IBAction private func removeAvatarButtonTapped(_ sender: UIButton) {
delegate?.chooseAvatarTableViewCellDidTapRemoveAvatar(self)
}
func configure(withViewModel viewModel: ChooseAvatarTableViewCellVM) {
if let image = viewModel.avatarImage {
avatarImageView.image = image
removeAvatarButton.isHidden = false
} else {
avatarImageView.image = Asset.Images.captureAvatar.image
removeAvatarButton.isHidden = true
}
}
}
extension ChooseAvatarTableViewCell: NibReusable {}
extension ChooseAvatarTableViewCell: Themable {
func update(theme: Theme) {
backgroundView = UIView()
backgroundView?.backgroundColor = theme.backgroundColor
}
}
| 33.014085 | 107 | 0.722696 |
aca299ba610e19a5e92f98a2003f7d336d555ed5 | 1,543 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Supplementary view for bading an item
*/
import UIKit
class BadgeSupplementaryView: UICollectionReusableView {
static let reuseIdentifier = "badge-reuse-identifier"
let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
override var frame: CGRect {
didSet {
configureBorder()
}
}
override var bounds: CGRect {
didSet {
configureBorder()
}
}
required init?(coder: NSCoder) {
fatalError("Not implemented")
}
}
extension BadgeSupplementaryView {
func configure() {
label.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 10.0, *) {
label.adjustsFontForContentSizeCategory = true
} else {
// Fallback on earlier versions
}
addSubview(label)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: centerXAnchor),
label.centerYAnchor.constraint(equalTo: centerYAnchor)
])
label.font = UIFont.preferredFont(forTextStyle: .body)
label.textAlignment = .center
label.textColor = .black
backgroundColor = .green
configureBorder()
}
func configureBorder() {
let radius = bounds.width / 2.0
layer.cornerRadius = radius
layer.borderColor = UIColor.black.cgColor
layer.borderWidth = 1.0
}
}
| 24.887097 | 67 | 0.619572 |
ff0c6678a13f98d29e23cb2d16d992cad605e76b | 1,184 | import Foundation
import UIKit
extension UIView {
func pinToSuperview(margin: UIEdgeInsets = .zero, safeArea: Bool = false) -> [NSLayoutConstraint] {
guard let superview = self.superview else {
assertionFailure("Add \(self) as subview")
return []
}
let anchors: Anchors = (safeArea ? superview.safeAreaLayoutGuide : superview)
return [
leadingAnchor.constraint(equalTo: anchors.leadingAnchor, constant: margin.left),
topAnchor.constraint(equalTo: anchors.topAnchor, constant: margin.top),
trailingAnchor.constraint(equalTo: anchors.trailingAnchor, constant: -margin.right),
bottomAnchor.constraint(equalTo: anchors.bottomAnchor, constant: -margin.bottom)
]
}
}
protocol Anchors: class {
var leadingAnchor: NSLayoutXAxisAnchor { get }
var trailingAnchor: NSLayoutXAxisAnchor { get }
var leftAnchor: NSLayoutXAxisAnchor { get }
var rightAnchor: NSLayoutXAxisAnchor { get }
var topAnchor: NSLayoutYAxisAnchor { get }
var bottomAnchor: NSLayoutYAxisAnchor { get }
}
extension UIView: Anchors {}
extension UILayoutGuide: Anchors {}
| 35.878788 | 103 | 0.686655 |
03c8b6a6d8cc38411f1e1782ac1dcf29e94239d3 | 930 | //
// HeadphoneView.swift
// headphone
//
// Created by 藤治仁 on 2021/12/03.
//
import SwiftUI
struct HeadphoneView: View {
@ObservedObject var viewModel = HeadphoneViewModel()
var body: some View {
VStack {
if viewModel.isHeadphone {
Image(systemName: "headphones")
.font(.system(size: 100))
} else if viewModel.isSpeaker {
Image(systemName: "speaker.wave.2.fill")
.font(.system(size: 100))
} else if viewModel.isExternalAudio {
Image(systemName: "hifispeaker.fill")
.font(.system(size: 100))
} else {
Image(systemName: "questionmark")
.font(.system(size: 100))
}
}
}
}
struct HeadphoneView_Previews: PreviewProvider {
static var previews: some View {
HeadphoneView()
}
}
| 25.135135 | 56 | 0.529032 |
bb5059c4ff6f916deeeb4da6a010c5453c52a691 | 217 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class d{deinit{
class A<T where a:A
protocol A:A | 31 | 87 | 0.769585 |
e2b07dd856fb1c3929c227b0dde9ef10927d225b | 6,675 | //
// ContentView.swift
// Example
//
// Created by PowerMobileWeb on 2019/6/7.
// Copyright © 2019 PowerMobileWeb. All rights reserved.
//
import SwiftUI
struct ContentView : View {
var body: some View {
NavigationView {
List {
Section(header: Text("Animation")) {
NavigationLink(destination: LotteryView()) {
PageRow(title: "LotteryView", subTitle: "Rotation Lottery")
}
}
Section(header: Text("特殊视图")) {
NavigationLink(destination: WebViewPage()) {
PageRow(title: "WebView", subTitle: "用于展示一个打开的网页")
}
NavigationLink(destination: ControllerPage<UIKitController>()) {
PageRow(title: "UIViewController", subTitle: "打开 UIViewController")
}
}
Section(header: Text("基础控件")) {
NavigationLink(destination: TextPage()) {
PageRow(title: "Text",subTitle: "显示一行或多行只读文本")
}
NavigationLink(destination: TextFieldPage()) {
PageRow(title: "TextField", subTitle: "显示可编辑文本界面的输入控件")
}
NavigationLink(destination: TextFieldPage()) {
PageRow(title: "SecureField", subTitle: "安全输入私密文本的输入控件")
}
NavigationLink(destination: ImagePage()) {
PageRow(title: "Image",subTitle: "用以展示本地图片")
}
NavigationLink(destination: WebImagePage()) {
PageRow(title: "WebImage",subTitle: "下载网络图片并展示")
}
}
Section(header: Text("按钮")) {
NavigationLink(destination: ButtonPage()) {
PageRow(title: "Button",subTitle: "触发时执行操作的按钮")
}
NavigationLink(destination: NavigationButtonPage()) {
PageRow(title: "NavigationButton",subTitle: "按下时触发导航跳转的按钮")
}
NavigationLink(destination: Text("I'm Text")) {
PageRow(title: "PresentationButton",subTitle: "触发时显示内容的按钮控件")
}
NavigationLink(destination: EditButtonPage()) {
PageRow(title: "EditButton",subTitle: "用于切换当前编辑模式的按钮")
}
}
Section(header: Text("选择器")) {
NavigationLink(destination: PickerPage()) {
PageRow(title: "Picker",subTitle: "可自定义数据源的 Picker 选择器")
}
NavigationLink(destination: DatePickerPage()) {
PageRow(title: "DatePicker",subTitle: "日期展示与选择")
}
NavigationLink(destination: TogglePage()) {
PageRow(title: "Toggle",subTitle: "开关状态切换")
}
NavigationLink(destination: SliderPage()) {
PageRow(title: "Slider",subTitle: "用以设置指定范围内的值")
}
NavigationLink(destination: StepperPage()) {
PageRow(title: "Stepper",subTitle: "用以增加或减少数值")
}
}
Section(header: Text("布局")) {
NavigationLink(destination: HStackPage()) {
PageRow(title: "HStack",subTitle: "将子视图排列在水平线上的视图")
}
NavigationLink(destination: VStackPage()) {
PageRow(title: "VStack",subTitle: "将子视图排列在垂直线上的视图")
}
NavigationLink(destination: ZStackPage()) {
PageRow(title: "ZStack",subTitle: "覆盖子视图,在两轴上对齐")
}
NavigationLink(destination: ListPage()) {
PageRow(title: "List",subTitle: "列表容器,用以显示一列数据")
}
NavigationLink(destination: ScrollViewPage()) {
PageRow(title: "ScrollView",subTitle: "滚动视图")
}
NavigationLink(destination: ForEachPage()) {
PageRow(title: "ForEach",subTitle: "用于根据已有数据的集合展示视图")
}
NavigationLink(destination: GroupPage()) {
PageRow(title: "Group",subTitle: "用于集合多个视图,对 Group 设置的属性,将作用于每个子视图")
}.frame(height: 80)
NavigationLink(destination: SectionPage()) {
PageRow(title: "Section",subTitle: "用于创建带头/尾部的视图内容,一般结合 `List` 组件使用")
}.frame(height: 80)
NavigationLink(destination: FormPage(firstName: "", lastName: "")) {
PageRow(title: "Form",subTitle: "表单视图")
}
}
Section(header: Text("导航视图")) {
NavigationLink(destination: NavigationViewPage()) {
PageRow(title: "NavigationView",subTitle: "用于创建包含顶部导航栏的视图容器")
}
NavigationLink(destination: TableViewPage()) {
PageRow(title: "TabBar",subTitle: "用于创建包含底部 TabBar 的视图容器")
}
}
Section(header: Text("Alert 弹框视图")) {
NavigationLink(destination: AlertPage()) {
PageRow(title: "Alert",subTitle: "展示一个弹框提醒")
}
NavigationLink(destination: ActionSheetPage()) {
PageRow(title: "ActionSheet",subTitle: "弹出一个选择框")
}
NavigationLink(destination: ModalPage()) {
PageRow(title: "Modal",subTitle: "Modal 弹出一个视图")
}
NavigationLink(destination: PopoverPage()) {
PageRow(title: "Popover",subTitle: "Pop 弹出一个视图")
}
}
}
.listStyle(GroupedListStyle())
.navigationBarTitle(Text("Example"), displayMode: .large)
.navigationBarItems(trailing: Button(action: {
print("Tap")
}, label: {
Text("Right").foregroundColor(.orange)
}))
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView().colorScheme(.dark)
}
}
#endif
| 43.344156 | 93 | 0.465768 |
e53a7008010011d446ece7188314634e0c241f23 | 1,238 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows an example of implementing the OperacjaCondition protocol.
*/
import Foundation
/**
A condition that specifies that every dependency must have succeeded.
If any dependency was cancelled, the target operation will be cancelled as
well.
*/
public struct NoCancelledDependencies : OperacjaCondition {
public enum ErrorType : Error {
case dependenciesWereCancelled([Operation])
}
public init() { }
public func dependency(for operation: Operacja) -> Operation? {
return nil
}
public func evaluate(for operation: Operacja, completion: @escaping (OperacjaConditionResult) -> Void) {
// Verify that all of the dependencies executed.
let cancelledDependencies = operation.dependencies.filter({ $0.isCancelled })
if !cancelledDependencies.isEmpty {
// At least one dependency was cancelled; the condition was not satisfied.
completion(.failed(with: ErrorType.dependenciesWereCancelled(cancelledDependencies)))
}
else {
completion(.satisfied)
}
}
}
| 30.195122 | 108 | 0.688207 |
bf2c00019610b3ed3469c9e459964cf9c86ccb30 | 9,046 | //
// NotchKitWindow.swift
// NotchKit
//
// Created by Harshil Shah on 16/09/17.
// Copyright © 2017 Harshil Shah. All rights reserved.
//
import UIKit
@available(iOS 11, *)
open class NotchKitWindow: UIWindow {
// MARK:- Types
public enum CornerRadius {
case standard
case custom(CGFloat)
}
// MARK:- Public variables
/// The edges of the screen to be masked
///
/// Each of the edges works as follows:
/// - `.top`: Shows a bar underneath the status bar on all iPhones and iPads.
/// This is the only property applicable to all devices; the remaining
/// 3 apply only to iPhone X
/// - `.left`: Shows a bar along the left edge of the screen when in
/// landscape orientation. Only applicable for iPhone X
/// - `.right`: Shows a bar along the right edge of the screen when in
/// landscape orientation. Only applicable for iPhone X
/// - `.bottom`: Shows a bar underneath the home indicator regardless of
/// orientation. Only applicable for iPhone X
///
/// The default value of this property is `.all`
@objc open var maskedEdges: UIRectEdge = .all {
didSet { updateSafeAreaInsets(animated: true) }
}
/// The corner radius for the rounded view. It can be set to a custom value,
/// or to use the standard value which sets the corner radius appropriately
/// for the screen size
open var cornerRadius: CornerRadius = .standard {
didSet { updateCornerRadii() }
}
/// A Bool indicating whether bars are shown only on the iPhone X.
///
/// When this property's value is true, black bars to cover the notch and
/// the home indicator are shown only on the iPhone X.
///
/// When this property's value is false, black bars and curved corners are
/// shown on all devices
///
/// The default value of this property is `false`
@objc open var shouldShowBarsOnlyOniPhoneX = false {
didSet { layoutSubviews() }
}
open override var rootViewController: UIViewController? {
didSet {
updateRootViewController(from: oldValue, to: rootViewController)
}
}
// MARK:- Private variables
private let safeAreaInsetsKeyPath = "safeAreaInsets"
private var isiPhoneX: Bool {
return screen.nativeBounds.size == CGSize(width: 1125, height: 2436)
}
// MARK:- View hierarchy
private let safeView = UIView()
private let topBarView = UIView()
private let leftBarView = UIView()
private let rightBarView = UIView()
private let bottomBarView = UIView()
private let topLeftCorner = CornerView()
private let topRightCorner = CornerView()
private let bottomLeftCorner = CornerView()
private let bottomRightCorner = CornerView()
private var barViews: [UIView] {
return [topBarView, leftBarView, rightBarView, bottomBarView]
}
private var cornerViews: [CornerView] {
return [topLeftCorner, topRightCorner, bottomLeftCorner, bottomRightCorner]
}
// MARK:- Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
open override func awakeFromNib() {
super.awakeFromNib()
setup()
}
@available(iOS 13, *)
public override init(windowScene: UIWindowScene) {
super.init(windowScene: windowScene)
setup()
}
private func setup() {
safeView.isUserInteractionEnabled = false
addSubview(safeView)
barViews.forEach { bar in
bar.backgroundColor = .black
bar.translatesAutoresizingMaskIntoConstraints = false
safeView.addSubview(bar)
}
NSLayoutConstraint.activate([
topBarView.topAnchor.constraint(equalTo: topAnchor),
topBarView.bottomAnchor.constraint(equalTo: safeView.topAnchor),
topBarView.leftAnchor.constraint(equalTo: leftAnchor),
topBarView.rightAnchor.constraint(equalTo: rightAnchor),
leftBarView.topAnchor.constraint(equalTo: topAnchor),
leftBarView.bottomAnchor.constraint(equalTo: bottomAnchor),
leftBarView.leftAnchor.constraint(equalTo: leftAnchor),
leftBarView.rightAnchor.constraint(equalTo: safeView.leftAnchor),
rightBarView.topAnchor.constraint(equalTo: topAnchor),
rightBarView.bottomAnchor.constraint(equalTo: bottomAnchor),
rightBarView.leftAnchor.constraint(equalTo: safeView.rightAnchor),
rightBarView.rightAnchor.constraint(equalTo: rightAnchor),
bottomBarView.topAnchor.constraint(equalTo: safeView.bottomAnchor),
bottomBarView.bottomAnchor.constraint(equalTo: bottomAnchor),
bottomBarView.leftAnchor.constraint(equalTo: leftAnchor),
bottomBarView.rightAnchor.constraint(equalTo: rightAnchor)
])
topLeftCorner.corner = .topLeft
topRightCorner.corner = .topRight
bottomLeftCorner.corner = .bottomLeft
bottomRightCorner.corner = .bottomRight
cornerViews.forEach { corner in
corner.cornerRadius = 44
corner.translatesAutoresizingMaskIntoConstraints = false
safeView.addSubview(corner)
}
NSLayoutConstraint.activate([
topLeftCorner.topAnchor.constraint(equalTo: safeView.topAnchor),
topLeftCorner.leftAnchor.constraint(equalTo: safeView.leftAnchor),
topRightCorner.topAnchor.constraint(equalTo: safeView.topAnchor),
topRightCorner.rightAnchor.constraint(equalTo: safeView.rightAnchor),
bottomLeftCorner.bottomAnchor.constraint(equalTo: safeView.bottomAnchor),
bottomLeftCorner.leftAnchor.constraint(equalTo: safeView.leftAnchor),
bottomRightCorner.bottomAnchor.constraint(equalTo: safeView.bottomAnchor),
bottomRightCorner.rightAnchor.constraint(equalTo: safeView.rightAnchor)
])
}
deinit {
updateRootViewController(from: rootViewController, to: nil)
}
// MARK:- UIView methods
open override func layoutSubviews() {
super.layoutSubviews()
bringSubview(toFront: safeView)
updateCornerRadii()
updateSafeAreaInsets()
}
// MARK:- Key value observation
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard keyPath == safeAreaInsetsKeyPath,
let view = object as? UIView,
view.isEqual(rootViewController?.view)
else {
return
}
updateSafeAreaInsets()
}
// MARK:- Private methods
private func updateCornerRadii() {
let newCornerRadius: CGFloat = {
if shouldShowBarsOnlyOniPhoneX && !isiPhoneX {
return 0
}
switch cornerRadius {
case .standard:
if isiPhoneX {
return 22
} else {
return 8
}
case .custom(let customValue):
return customValue
}
}()
cornerViews.forEach {
$0.cornerRadius = newCornerRadius
}
}
private func updateSafeAreaInsets(animated: Bool = false) {
guard let insets = rootViewController?.view.safeAreaInsets else {
return
}
let finalInsets = UIEdgeInsets(
top: maskedEdges.contains(.top) ? insets.top : 0,
left: maskedEdges.contains(.left) ? insets.left : 0,
bottom: maskedEdges.contains(.bottom) ? insets.bottom : 0,
right: maskedEdges.contains(.right) ? insets.right : 0)
let safeViewFrame: CGRect = {
if shouldShowBarsOnlyOniPhoneX && !isiPhoneX {
return bounds
} else {
return bounds.insetBy(insets: finalInsets)
}
}()
let duration = animated ? 0.3 : 0
UIView.animate(withDuration: duration) { [unowned self] in
self.safeView.frame = safeViewFrame
self.safeView.layoutIfNeeded()
}
}
private func updateRootViewController(from oldValue: UIViewController?, to newValue: UIViewController?) {
oldValue?.view.removeObserver(self, forKeyPath: safeAreaInsetsKeyPath)
newValue?.view.addObserver(self, forKeyPath: safeAreaInsetsKeyPath, options: [.initial], context: nil)
}
}
| 34.007519 | 156 | 0.614305 |
23eb38e3baa584caf0b23afc4592c5b90f8ac7ef | 13,788 | //
// HomeScreenViewController.swift
// ravenwallet
//
// Created by Adrian Corscadden on 2017-11-27.
// Copyright © 2018 Ravenwallet Team. All rights reserved.
//
import UIKit
import Core
class HomeScreenViewController : UIViewController, Subscriber {
var walletManager: WalletManager? {
didSet {
setInitialData()
setupSubscriptions()
currencyList.reload()
if(!UserDefaults.hasDismissedPrompt){
attemptShowPrompt()
}
}
}
private let currencyList = AssetListTableView()
private let subHeaderView = UIView()
private var logo: UIImageView = {
let image = UIImageView(image: #imageLiteral(resourceName: "newLogo"))
image.contentMode = .scaleAspectFit
return image
}()
private let total = UILabel(font: .customBold(size: 30.0), color: .darkGray)
private let totalHeader = UILabel(font: .customMedium(size: 18.0), color: .mediumGray)
private let prompt = UIView()
private var promptHiddenConstraint: NSLayoutConstraint!
var didSelectCurrency : ((CurrencyDef) -> Void)?
var didSelectAsset : ((Asset) -> Void)?
var didSelectShowMoreAsset: (() -> Void)?
var didTapSecurity: (() -> Void)?
var didTapSupport: (() -> Void)?
var didTapSettings: (() -> Void)?
var didTapAddressBook: ((CurrencyDef) -> Void)?
var didTapCreateAsset: (() -> Void)?
var didTapTutorial: (() -> Void)?
// MARK: -
init(walletManager: WalletManager?) {
self.walletManager = walletManager
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
currencyList.didSelectCurrency = didSelectCurrency
currencyList.didSelectAsset = didSelectAsset //BMEX
currencyList.didSelectShowMoreAsset = didSelectShowMoreAsset
currencyList.didTapSecurity = didTapSecurity
currencyList.didTapSupport = didTapSupport
currencyList.didTapSettings = didTapSettings
currencyList.didTapAddressBook = didTapAddressBook
currencyList.didTapCreateAsset = didTapCreateAsset
currencyList.didTapTutorial = didTapTutorial
addSubviews()
addConstraints()
addActions()
setInitialData()
setupSubscriptions()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.main.asyncAfter(deadline: .now() + promptDelay) { [weak self] in
if(!UserDefaults.hasDismissedPrompt){
self?.attemptShowPrompt()
}
}
}
// MARK: Setup
private func addSubviews() {
view.addSubview(subHeaderView)
subHeaderView.addSubview(logo)
subHeaderView.addSubview(totalHeader)
subHeaderView.addSubview(total)
view.addSubview(prompt)
}
private func addConstraints() {
let height: CGFloat = 60.0//Height with total label = 136.0
if #available(iOS 11.0, *) {
subHeaderView.constrain([
subHeaderView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
subHeaderView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0),
subHeaderView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
subHeaderView.heightAnchor.constraint(equalToConstant: height) ])
} else {
subHeaderView.constrain([
subHeaderView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
subHeaderView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0.0),
subHeaderView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
subHeaderView.heightAnchor.constraint(equalToConstant: height) ])
}
let yConstraint = NSLayoutConstraint(item: logo, attribute: .centerY, relatedBy: .equal, toItem: subHeaderView, attribute: .centerY, multiplier: 0.5, constant: 0.0)
logo.constrain([
logo.constraint(.centerX, toView: subHeaderView, constant: nil),
logo.trailingAnchor.constraint(equalTo: subHeaderView.trailingAnchor, constant: -C.padding[2]),
logo.leadingAnchor.constraint(equalTo: subHeaderView.leadingAnchor, constant: C.padding[2]),
yConstraint])
if E.isIPad {
logo.addConstraint(logo.widthAnchor.constraint(equalTo: logo.heightAnchor, multiplier: 10.15))
}
totalHeader.constrain([
totalHeader.trailingAnchor.constraint(equalTo: total.trailingAnchor),
totalHeader.bottomAnchor.constraint(equalTo: total.topAnchor, constant: 0.0),
totalHeader.topAnchor.constraint(equalTo: logo.bottomAnchor, constant: C.padding[2]),
totalHeader.heightAnchor.constraint(equalToConstant: 0)//BMEX to show totalHeader just remove this line
])
total.constrain([
total.trailingAnchor.constraint(equalTo: subHeaderView.trailingAnchor, constant: -C.padding[2]),
total.topAnchor.constraint(equalTo: totalHeader.bottomAnchor),
total.heightAnchor.constraint(equalToConstant: 0)//BMEX to show total just remove this line
])
promptHiddenConstraint = prompt.heightAnchor.constraint(equalToConstant: 0.0)
prompt.constrain([
prompt.leadingAnchor.constraint(equalTo: view.leadingAnchor),
prompt.trailingAnchor.constraint(equalTo: view.trailingAnchor),
prompt.topAnchor.constraint(equalTo: subHeaderView.bottomAnchor),
promptHiddenConstraint
])
addChild(currencyList, layout: {
currencyList.view.constrain([
currencyList.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
currencyList.view.topAnchor.constraint(equalTo: prompt.bottomAnchor),
currencyList.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
currencyList.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)])
})
}
private func addActions() {
let gr = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
logo.addGestureRecognizer(gr)
logo.isUserInteractionEnabled = true
}
private func setInitialData() {
view.backgroundColor = .whiteBackground
subHeaderView.backgroundColor = .whiteBackground
subHeaderView.clipsToBounds = false
logo.contentMode = .scaleToFill
navigationItem.titleView = UIView()
navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.shadowImage = #imageLiteral(resourceName: "TransparentPixel")
navigationController?.navigationBar.setBackgroundImage(#imageLiteral(resourceName: "TransparentPixel"), for: .default)
totalHeader.text = S.HomeScreen.totalAssets
totalHeader.textAlignment = .left
total.textAlignment = .left
total.text = "0"
title = ""
updateTotalAssets()
//Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(refreshPeerManagerConnect), userInfo: nil, repeats: true)
}
@objc func refreshPeerManagerConnect() {
if walletManager!.peerManager?.connectionStatus != BRPeerStatusConnected {
DispatchQueue.walletQueue.async { [weak self] in
self?.walletManager!.peerManager?.disconnect()
self?.walletManager!.peerManager?.connect()
}
}
}
@objc private func longPressed(sender:UILongPressGestureRecognizer) {
if (sender.state == .began) {
Store.trigger(name: .playGif("logoGif"))
}
}
private func updateTotalAssets() {
let fiatTotal = Store.state.currencies.map {
let balance = Store.state[$0].balance ?? 0
let rate = Store.state[$0].currentRate?.rate ?? 0
return Double(balance)/$0.baseUnit * rate * 0.001
}.reduce(0.0, +)
let format = NumberFormatter()
format.isLenient = true
format.numberStyle = .currency
format.generatesDecimalNumbers = true
format.negativeFormat = format.positiveFormat.replacingCharacters(in: format.positiveFormat.range(of: "#")!, with: "-#")
format.currencySymbol = Store.state[Currencies.rvn].currentRate?.currencySymbol ?? ""
self.total.text = format.string(from: NSNumber(value: fiatTotal))
}
private func setupSubscriptions() {
Store.unsubscribe(self)
Store.subscribe(self, selector: {
var result = false
let oldState = $0
let newState = $1
$0.currencies.forEach { currency in
if oldState[currency].balance != newState[currency].balance {
result = true
}
if oldState[currency].currentRate?.rate != newState[currency].currentRate?.rate {
result = true
}
}
return result
},
callback: { _ in
self.updateTotalAssets()
})
// prompts
Store.subscribe(self, name: .didUpgradePin, callback: { _ in
if self.currentPrompt?.type == .upgradePin {
self.currentPrompt = nil
}
})
Store.subscribe(self, name: .didEnableShareData, callback: { _ in
if self.currentPrompt?.type == .shareData {
self.currentPrompt = nil
}
})
Store.subscribe(self, name: .didWritePaperKey, callback: { _ in
if self.currentPrompt?.type == .paperKey {
self.currentPrompt = nil
}
})
Store.subscribe(self, name: .didRescanBlockChain, callback: { _ in
if self.currentPrompt?.type == .rescanBlockChain {
self.currentPrompt = nil
}
})
Store.subscribe(self, name: .playGif(""), callback: { [weak self] in
guard let trigger = $0 else { return }
if case .playGif(let gifName) = trigger {
let logoGif = UIImage.gifImageWithName(name: gifName)
let imageView = UIImageView(image: logoGif)
imageView.backgroundColor = UIColor.black
imageView.frame = CGRect(x: 0, y: 0, width: self!.view.frame.size.width, height: self!.view.frame.size.height)
imageView.contentMode = UIView.ContentMode.scaleAspectFit
imageView.alpha = 0.0
self!.view.addSubview(imageView)
imageView.fadeIn(0.5, delay: 0.0, completion: { _ in
imageView.fadeOut(0.5, delay: 6.1, completion: { _ in
imageView.removeFromSuperview()
})
})
}
})
}
// MARK: - Prompt
private let promptDelay: TimeInterval = 0.6
private var currentPrompt: Prompt? {
didSet {
if currentPrompt != oldValue {
var afterFadeOut: TimeInterval = 0.0
if let oldPrompt = oldValue {
afterFadeOut = 0.15
UIView.animate(withDuration: 0.2, animations: {
oldValue?.alpha = 0.0
}, completion: { _ in
oldPrompt.removeFromSuperview()
})
}
if let newPrompt = currentPrompt {
newPrompt.alpha = 0.0
prompt.addSubview(newPrompt)
newPrompt.constrain(toSuperviewEdges: .zero)
prompt.layoutIfNeeded()
promptHiddenConstraint.isActive = false
// fade-in after fade-out and layout
UIView.animate(withDuration: 0.2, delay: afterFadeOut + 0.15, options: .curveEaseInOut, animations: {
newPrompt.alpha = 1.0
})
} else {
promptHiddenConstraint.isActive = true
}
// layout after fade-out
UIView.animate(withDuration: 0.2, delay: afterFadeOut, options: .curveEaseInOut, animations: {
self.view.layoutIfNeeded()
})
}
}
}
private func attemptShowPrompt() {
guard let walletManager = walletManager else {
currentPrompt = nil
return
}
if let type = PromptType.nextPrompt(walletManager: walletManager) {
currentPrompt = Prompt(type: type)
currentPrompt!.dismissButton.tap = { [unowned self] in
self.currentPrompt = nil
UserDefaults.hasDismissedPrompt = true
}
currentPrompt!.continueButton.tap = { [unowned self] in
if let trigger = type.trigger(currency: Currencies.rvn) {
Store.trigger(name: trigger)
}
self.currentPrompt = nil
}
if type == .biometrics {
UserDefaults.hasPromptedBiometrics = true
}
if type == .shareData {
UserDefaults.hasPromptedShareData = true
}
} else {
currentPrompt = nil
}
}
// MARK: -
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 40.672566 | 172 | 0.593124 |
5b13033cbaff935b6a758daa09628d73b032ed90 | 1,460 | //
// XcodeTemplateUtilUITests.swift
// XcodeTemplateUtilUITests
//
// Created by Дмитрий Поляков on 30.08.2021.
//
import XCTest
class XcodeTemplateUtilUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.953488 | 182 | 0.663699 |
f82dc8e8bb2171132f5d4380c0c080fcec7ec052 | 708 | //
// InsertTextFormat.swift
// LanguageServerProtocol
//
// Created by Ryan Lovelett on 5/28/18.
//
/// Defines whether the insert text in a completion item should be interpreted as plain text or a snippet.
public enum InsertTextFormat: Int {
/// The primary text to be inserted is treated as a plain string.
case plainText = 1
/// The primary text to be inserted is treated as a snippet.
///
/// A snippet can define tab stops and placeholders with `$1`, `$2` and `${3:foo}`. `$0` defines the final tab stop,
/// it defaults to the end of the snippet. Placeholders with equal identifiers are linked, that is typing in one
/// will update others too.
case snippet = 2
}
| 35.4 | 120 | 0.687853 |
8784b2ebc2eea305229e5e1dde03a91fa440da06 | 1,297 | //
// UIWebViewController.swift
// JunxinSecurity
//
// Created by mc on 2019/6/6.
// Copyright © 2019 张玉飞. All rights reserved.
//
import UIKit
class UIWebViewController: TSViewController {
let webView = UIWebView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addSubviews(webView)
webView.snp.makeConstraints {
$0.top.equalTo(nav.snp.bottom)
$0.left.bottom.right.equalToSuperview()
}
webView.backgroundColor = UIColor.clear
webView.isOpaque = false
rightItem.title = "关闭"
}
override func pop() {
if webView.canGoBack {
webView.goBack()
} else {
super.pop()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if webView.isLoading {
webView.stopLoading()
}
}
func loadWeb(path: String) {
if let url = URL(string: path) {
let request = URLRequest(url: url)
webView.loadRequest(request)
}
}
override func rightItemAction(sender: UIButton) {
ts.global.nav.popViewController(animated: true)
}
}
| 22.754386 | 58 | 0.575173 |
395918b6354219bf960e84dee0ceb1296668f6fa | 3,093 | //
// Created by Frederick Pietschmann on 07.05.19.
// Copyright © 2019 Flinesoft. All rights reserved.
//
import Foundation
extension Comparable {
// MARK: - Clamp: Returning Variants
/// Returns `self` clamped to the given limits.
///
/// - Parameter limits: The closed range determining minimum & maxmimum value.
/// - Returns:
/// - `self`, if it is inside the given limits.
/// - `lowerBound` of the given limits, if `self` is smaller than it.
/// - `upperBound` of the given limits, if `self` is greater than it.
public func clamped(to limits: ClosedRange<Self>) -> Self {
if limits.lowerBound > self {
return limits.lowerBound
} else if limits.upperBound < self {
return limits.upperBound
} else {
return self
}
}
/// Returns `self` clamped to the given limits.
///
/// - Parameter limits: The partial range (from) determining the minimum value.
/// - Returns:
/// - `self`, if it is inside the given limits.
/// - `lowerBound` of the given limits, if `self` is smaller than it.
public func clamped(to limits: PartialRangeFrom<Self>) -> Self {
if limits.lowerBound > self {
return limits.lowerBound
} else {
return self
}
}
/// Returns `self` clamped to the given limits.
///
/// - Parameter limits: The partial range (through) determining the maximum value.
/// - Returns:
/// - `self`, if it is inside the given limits.
/// - `upperBound` of the given limits, if `self` is greater than it.
public func clamped(to limits: PartialRangeThrough<Self>) -> Self {
if limits.upperBound < self {
return limits.upperBound
} else {
return self
}
}
// MARK: Mutating Variants
/// Clamps `self` to the given limits.
///
/// - `self`, if it is inside the given limits.
/// - `lowerBound` of the given limits, if `self` is smaller than it.
/// - `upperBound` of the given limits, if `self` is greater than it.
///
/// - Parameter limits: The closed range determining minimum & maxmimum value.
public mutating func clamp(to limits: ClosedRange<Self>) {
self = clamped(to: limits)
}
/// Clamps `self` to the given limits.
///
/// - `self`, if it is inside the given limits.
/// - `lowerBound` of the given limits, if `self` is smaller than it.
///
/// - Parameter limits: The partial range (from) determining the minimum value.
public mutating func clamp(to limits: PartialRangeFrom<Self>) {
self = clamped(to: limits)
}
/// Clamps `self` to the given limits.
///
/// - `self`, if it is inside the given limits.
/// - `upperBound` of the given limits, if `self` is greater than it.
///
/// - Parameter limits: The partial range (through) determining the maximum value.
public mutating func clamp(to limits: PartialRangeThrough<Self>) {
self = clamped(to: limits)
}
}
| 35.551724 | 86 | 0.599741 |
48abf4224c725fd23db83fc264da1575fedef9dc | 5,063 | //
// GeometryExtensions.swift
// SwiftGraphics
//
// Created by Jonathan Wight on 2/3/15.
// Copyright (c) 2015 schwa.io. All rights reserved.
//
import CoreGraphics
import SwiftUtilities
// MARK: -
public protocol CGPathable {
var cgpath:CGPath { get }
}
// TODO: Rename to Intersectionable? ICK
public protocol HitTestable {
func contains(point:CGPoint) -> Bool
func intersects(rect:CGRect) -> Bool
func intersects(path:CGPath) -> Bool
}
// MARK: -
extension Rectangle: CGPathable {
public var cgpath:CGPath {
return CGPathCreateWithRect(frame, nil)
}
}
extension Circle: CGPathable {
public var cgpath:CGPath {
return CGPathCreateWithEllipseInRect(frame, nil)
}
}
extension Ellipse: CGPathable {
public var cgpath:CGPath {
let path = CGPathCreateMutable()
let (b1, b2, b3, b4) = self.toBezierCurves
path.move(b1.start!)
path.addCurve(BezierCurve(controls: b1.controls, end: b1.end))
path.addCurve(BezierCurve(controls: b2.controls, end: b2.end))
path.addCurve(BezierCurve(controls: b3.controls, end: b3.end))
path.addCurve(BezierCurve(controls: b4.controls, end: b4.end))
path.close()
return path
}
}
extension Triangle: CGPathable {
public var cgpath:CGPath {
let path = CGPathCreateMutable()
path.move(points.0)
path.addLine(points.1)
path.addLine(points.2)
path.close()
return path
}
}
extension SwiftGraphics.Polygon: CGPathable {
public var cgpath:CGPath {
let path = CGPathCreateMutable()
path.move(points[0])
for point in points[1..<points.count] {
path.addLine(point)
}
path.close()
return path
}
}
// MARK: -
extension Rectangle: HitTestable {
public func contains(point:CGPoint) -> Bool {
return frame.contains(point)
}
public func intersects(rect:CGRect) -> Bool {
return frame.intersects(rect)
}
public func intersects(path:CGPath) -> Bool {
return path.intersects(frame)
}
}
extension Circle: HitTestable {
public func contains(point:CGPoint) -> Bool {
if self.frame.contains(point) {
return (center - point).magnitudeSquared < radius ** 2
}
else {
return false
}
}
public func intersects(rect:CGRect) -> Bool {
// TODO: BROKEN!?
// http://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection
let circleDistance_x = abs(center.x - rect.origin.x);
let circleDistance_y = abs(center.y - rect.origin.y);
let half_width = rect.size.width / 2
let half_height = rect.size.height / 2
if circleDistance_x > half_width + radius {
return false
}
if circleDistance_y > half_height + radius {
return false
}
if circleDistance_x <= half_width {
return true
}
if circleDistance_y <= half_height {
return true
}
let cornerDistance_sq = ((circleDistance_x - half_width) ** 2) + ((circleDistance_y - half_height) ** 2)
return cornerDistance_sq <= (radius ** 2)
}
public func intersects(path:CGPath) -> Bool {
return cgpath.intersects(path)
}
public func intersects(lineSegment:LineSegment) -> Bool {
let Ax = lineSegment.start.x
let Ay = lineSegment.start.y
let Bx = lineSegment.end.x
let By = lineSegment.end.y
let Cx = center.x
let Cy = center.y
// compute the triangle area times 2 (area = area2/2)
let area2 = (Bx-Ax) * (Cy-Ay) - (Cx-Ax) * (By-Ay)
let abs_area2 = abs(area2)
// compute the AB segment length
let LAB = sqrt((Bx-Ax) ** 2 + (By-Ay) ** 2)
// compute the triangle height
let h = abs_area2 / LAB
let R = radius
return h < R
}
}
extension Triangle: HitTestable {
public func contains(point:CGPoint) -> Bool {
// http://totologic.blogspot.fr/2014/01/accurate-point-in-triangle-test.html
// Compute vectors
let v0 = points.2 - points.0
let v1 = points.1 - points.0
let v2 = point - points.0
// Compute dot products
let dot00 = dotProduct(v0, v0)
let dot01 = dotProduct(v0, v1)
let dot02 = dotProduct(v0, v2)
let dot11 = dotProduct(v1, v1)
let dot12 = dotProduct(v1, v2)
// Compute barycentric coordinates
let invDenom = 1 / (dot00 * dot11 - dot01 * dot01)
let u = (dot11 * dot02 - dot01 * dot12) * invDenom
let v = (dot00 * dot12 - dot01 * dot02) * invDenom
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1)
}
public func intersects(rect:CGRect) -> Bool {
return self.cgpath.intersects(rect)
}
public func intersects(path:CGPath) -> Bool {
return cgpath.intersects(path)
}
}
| 26.097938 | 112 | 0.597867 |
e97cfe469431b06622c628d0e0c6ce9a844e2f4f | 2,171 | //
// AppDelegate.swift
// cARd
//
// Created by Artem Novichkov on 03/08/2017.
// Copyright © 2017 Rosberry. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.191489 | 285 | 0.755412 |
e0d23e717d6f3a35301e882527d577789e298bfd | 25,642 | //
// SidebarTableView.swift
// FSNotes iOS
//
// Created by Oleksandr Glushchenko on 5/5/18.
// Copyright © 2018 Oleksandr Glushchenko. All rights reserved.
//
import Foundation
import UIKit
import NightNight
import AudioToolbox
@IBDesignable
class SidebarTableView: UITableView,
UITableViewDelegate,
UITableViewDataSource,
UITableViewDropDelegate {
@IBInspectable var startColor: UIColor = .black { didSet { updateColors() }}
@IBInspectable var endColor: UIColor = .white { didSet { updateColors() }}
@IBInspectable var startLocation: Double = 0.05 { didSet { updateLocations() }}
@IBInspectable var endLocation: Double = 0.95 { didSet { updateLocations() }}
@IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }}
@IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }}
var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer }
private var sidebar: Sidebar = Sidebar()
private var busyTrashReloading = false
public var viewController: ViewController?
override class var layerClass: AnyClass { return CAGradientLayer.self }
override func layoutSubviews() {
super.layoutSubviews()
updatePoints()
updateLocations()
updateColors()
}
func numberOfSections(in tableView: UITableView) -> Int {
return sidebar.items.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sidebar.items[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "sidebarCell", for: indexPath) as! SidebarTableCellView
guard sidebar.items.indices.contains(indexPath.section), sidebar.items[indexPath.section].indices.contains(indexPath.row) else { return cell }
let sidebarItem = sidebar.items[indexPath.section][indexPath.row]
cell.configure(sidebarItem: sidebarItem)
cell.contentView.setNeedsLayout()
cell.contentView.layoutIfNeeded()
return cell
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return ""
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
if let view = view as? UITableViewHeaderFooterView {
let custom = UIView()
view.backgroundView = custom
var font: UIFont = UIFont.systemFont(ofSize: 15)
if #available(iOS 11.0, *) {
let fontMetrics = UIFontMetrics(forTextStyle: .caption1)
font = fontMetrics.scaledFont(for: font)
}
view.textLabel?.font = font.bold()
view.textLabel?.mixedTextColor = MixedColor(normal: 0xffffff, night: 0xffffff)
}
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let view = view as? UITableViewHeaderFooterView {
let custom = UIView()
view.backgroundView = custom
var font: UIFont = UIFont.systemFont(ofSize: 15)
if #available(iOS 11.0, *) {
let fontMetrics = UIFontMetrics(forTextStyle: .caption1)
font = fontMetrics.scaledFont(for: font)
}
view.textLabel?.font = font.bold()
view.textLabel?.mixedTextColor = MixedColor(normal: 0xffffff, night: 0xffffff)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 37
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
selectRow(at: indexPath, animated: false, scrollPosition: .none)
self.tableView(tableView, didSelectRowAt: indexPath)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedSection = SidebarSection(rawValue: indexPath.section)
let sidebarItem = sidebar.items[indexPath.section][indexPath.row]
guard sidebar.items.indices.contains(indexPath.section) && sidebar.items[indexPath.section].indices.contains(indexPath.row) else {
return
}
guard let vc = self.viewController else { return }
vc.turnOffSearch()
vc.notesTable.turnOffEditing()
if sidebarItem.name == NSLocalizedString("Settings", comment: "Sidebar settings") {
Timer.scheduledTimer(withTimeInterval: 0.01, repeats: false) { _ in
vc.openSettings()
self.deselectRow(at: indexPath, animated: false)
}
AudioServicesPlaySystemSound(1519)
return
}
var name = sidebarItem.name
if sidebarItem.type == .Category || sidebarItem.isSystem() {
name += " ▽"
}
if sidebarItem.type == .Tag {
name = "#\(name)"
}
let newQuery = SearchQuery()
newQuery.setType(sidebarItem.type)
newQuery.project = sidebarItem.project
newQuery.tag = nil
if selectedSection == .Tags {
newQuery.type = vc.searchQuery.type
newQuery.project = vc.searchQuery.project
newQuery.tag = sidebarItem.name
deselectAllTags()
} else {
deselectAllProjects()
deselectAllTags()
}
selectRow(at: indexPath, animated: false, scrollPosition: .none)
vc.reloadNotesTable(with: newQuery) {
DispatchQueue.main.async {
vc.currentFolder.text = name
guard vc.notesTable.notes.count > 0 else {
self.unloadAllTags()
return
}
let path = IndexPath(row: 0, section: 0)
vc.notesTable.scrollToRow(at: path, at: .top, animated: true)
if selectedSection != .Tags {
self.loadAllTags()
vc.resizeSidebar(withAnimation: true)
}
}
}
}
public func selectCurrentProject() {
guard let vc = self.viewController else { return }
var indexPath: IndexPath = IndexPath(row: 0, section: 0)
if let type = vc.searchQuery.type,
let ip = getIndexPathBy(type: type) {
indexPath = ip
} else if let project = vc.searchQuery.project,
let ip = getIndexPathBy(project: project) {
indexPath = ip
}
let sidebarItem = sidebar.items[indexPath.section][indexPath.row]
let name = sidebarItem.name + " ▽"
let newQuery = SearchQuery()
newQuery.setType(sidebarItem.type)
newQuery.project = sidebarItem.project
selectRow(at: indexPath, animated: false, scrollPosition: .none)
vc.reloadNotesTable(with: newQuery) {
DispatchQueue.main.async {
vc.currentFolder.text = name
}
}
}
private func deselectAllTags() {
if let selectedIndexPaths = indexPathsForSelectedRows {
for indexPathItem in selectedIndexPaths {
if indexPathItem.section == SidebarSection.Tags.rawValue {
deselectRow(at: indexPathItem, animated: false)
}
}
}
}
private func deselectAllProjects() {
if let selectedIndexPaths = indexPathsForSelectedRows {
for indexPathItem in selectedIndexPaths {
if indexPathItem.section == SidebarSection.Projects.rawValue
|| indexPathItem.section == SidebarSection.System.rawValue {
deselectRow(at: indexPathItem, animated: false)
}
}
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = UIColor.clear
cell.textLabel?.mixedTextColor = MixedColor(normal: 0xffffff, night: 0xffffff)
if let sidebarCell = cell as? SidebarTableCellView {
if let sidebarItem = (cell as! SidebarTableCellView).sidebarItem, sidebarItem.type == .Tag || sidebarItem.type == .Category {
sidebarCell.icon.constraints[1].constant = 0
sidebarCell.labelConstraint.constant = 0
sidebarCell.contentView.setNeedsLayout()
sidebarCell.contentView.layoutIfNeeded()
}
}
}
public func deselectAll() {
if let paths = indexPathsForSelectedRows {
for path in paths {
deselectRow(at: path, animated: false)
}
}
}
// MARK: Gradient settings
func updatePoints() {
if horizontalMode {
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5)
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5)
} else {
gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1)
}
}
func updateLocations() {
gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
}
func updateColors() {
if NightNight.theme == .night{
let startNightTheme = UIColor(red:0.14, green:0.14, blue:0.14, alpha:1.0)
let endNightTheme = UIColor(red:0.12, green:0.11, blue:0.12, alpha:1.0)
gradientLayer.colors = [startNightTheme.cgColor, endNightTheme.cgColor]
} else {
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
}
}
public func getSidebarItem(project: Project? = nil) -> SidebarItem? {
if let project = project, sidebar.items.count > 1 {
return sidebar.items[1].first(where: { $0.project == project })
}
guard let indexPath = indexPathForSelectedRow else { return nil }
let item = sidebar.items[indexPath.section][indexPath.row]
return item
}
func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
guard let vc = viewController else { return }
guard let indexPath = coordinator.destinationIndexPath, let cell = tableView.cellForRow(at: indexPath) as? SidebarTableCellView else { return }
guard let sidebarItem = cell.sidebarItem else { return }
_ = coordinator.session.loadObjects(ofClass: URL.self) { item in
let pathList = item as [URL]
for url in pathList {
guard let note = Storage.sharedInstance().getBy(url: url) else { continue }
switch sidebarItem.type {
case .Category, .Archive, .Inbox:
guard let project = sidebarItem.project else { break }
self.move(note: note, in: project)
case .Trash:
note.remove()
vc.notesTable.removeRows(notes: [note])
default:
break
}
}
vc.notesTable.isEditing = false
}
}
func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
guard let indexPath = destinationIndexPath,
let cell = tableView.cellForRow(at: indexPath) as? SidebarTableCellView,
let sidebarItem = cell.sidebarItem
else { return UITableViewDropProposal(operation: .cancel) }
if sidebarItem.project != nil || sidebarItem.type == .Trash {
return UITableViewDropProposal(operation: .copy)
}
return UITableViewDropProposal(operation: .cancel)
}
private func move(note: Note, in project: Project) {
guard let vc = viewController else { return }
let dstURL = project.url.appendingPathComponent(note.name)
if note.project != project {
note.moveImages(to: project)
if note.isEncrypted() {
_ = note.lock()
}
guard note.move(to: dstURL) else {
let alert = UIAlertController(title: "Oops 👮♂️", message: "File with this name already exist", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
vc.present(alert, animated: true, completion: nil)
note.moveImages(to: note.project)
return
}
note.url = dstURL
note.parseURL()
note.project = project
// resets tags in sidebar
removeTags(in: [note])
// reload tags (in remove tags operation notn fitted)
_ = note.scanContentTags()
vc.notesTable.removeRows(notes: [note])
vc.notesTable.insertRows(notes: [note])
}
}
public func getSidebarProjects() -> [Project]? {
guard let indexPaths = UIApplication.getVC().sidebarTableView?.indexPathsForSelectedRows else { return nil }
var projects = [Project]()
for indexPath in indexPaths {
let item = sidebar.items[indexPath.section][indexPath.row]
if let project = item.project {
projects.append(project)
}
}
if projects.count > 0 {
return projects
}
if let root = Storage.sharedInstance().getRootProject() {
return [root]
}
return nil
}
public func getAllTags(projects: [Project]? = nil) -> [String] {
var tags = [String]()
if let projects = projects {
for project in projects {
let projectTags = project.getAllTags()
for tag in projectTags {
if !tags.contains(tag) {
tags.append(tag)
}
}
}
}
return tags.sorted()
}
private func getAllTags(notes: [Note]? = nil) -> [String] {
var tags = [String]()
if let notes = notes {
for note in notes {
for tag in note.tags {
if !tags.contains(tag) {
tags.append(tag)
}
}
}
}
return tags.sorted()
}
public func loadAllTags() {
guard
UserDefaultsManagement.inlineTags,
let vc = viewController
else { return }
unloadAllTags()
var tags = [String]()
switch vc.searchQuery.type {
case .Inbox, .All, .Todo:
let notes = vc.notesTable.notes
tags = getAllTags(notes: notes)
break
case .Category:
guard let project = vc.searchQuery.project else { return }
tags = getAllTags(projects: [project])
break
default:
return
}
guard tags.count > 0 else { return }
var indexPaths = [IndexPath]()
for tag in tags {
let position = self.sidebar.items[2].count
let element = SidebarItem(name: tag, type: .Tag)
self.sidebar.items[2].insert(element, at: position)
indexPaths.append(IndexPath(row: position, section: 2))
}
insertRows(at: indexPaths, with: .automatic)
}
public func unloadAllTags() {
guard sidebar.items[2].count > 0 else { return }
let rows = numberOfRows(inSection: 2)
if rows > 0 {
self.sidebar.items[2].removeAll()
var indexPaths = [IndexPath]()
for index in stride(from: rows - 1, to: -1, by: -1) {
indexPaths.append(IndexPath(row: index, section: 2))
}
deleteRows(at: indexPaths, with: .automatic)
}
}
public func removeTags(in notes: [Note]) {
for note in notes {
note.tags.removeAll()
}
loadTags(notes: notes)
}
public func loadTags(notes: [Note]) {
var toInsert = [String]()
var toDelete = [String]()
for note in notes {
guard let vc = viewController,
let query = createQueryWithoutTags(),
vc.isFit(note: note, searchQuery: query)
else { continue }
let result = note.scanContentTags()
if result.0.count > 0 {
toInsert.append(contentsOf: result.0)
}
if result.1.count > 0 {
toDelete.append(contentsOf: result.1)
note.tags.removeAll(where: { result.1.contains($0) })
}
}
toInsert = Array(Set(toInsert))
toDelete = Array(Set(toDelete))
insert(tags: toInsert)
delete(tags: toDelete)
}
public func insert(tags: [String]) {
let currentTags = sidebar.items[2].compactMap({ $0.name })
var toInsert = [String]()
for tag in tags {
if currentTags.contains(tag) {
continue
}
toInsert.append(tag)
}
guard toInsert.count > 0 else { return }
let nonSorted = currentTags + toInsert
let sorted = nonSorted.sorted()
var indexPaths = [IndexPath]()
for tag in toInsert {
guard let index = sorted.firstIndex(of: tag) else { continue }
indexPaths.append(IndexPath(row: index, section: 2))
}
sidebar.items[2] = sorted.compactMap({ SidebarItem(name: $0, type: .Tag) })
insertRows(at: indexPaths, with: .fade)
}
public func delete(tags: [String]) {
guard let vc = viewController else { return }
var allTags = [String]()
if let project = vc.searchQuery.project {
allTags = project.getAllTags()
} else if let type = vc.searchQuery.type {
var notes = [Note]()
switch type {
case .All:
notes = Storage.shared().noteList
break
case .Inbox:
notes = Storage.shared().noteList.filter({ $0.project.isDefault })
break
case .Todo:
notes = Storage.shared().noteList.filter({ $0.content.string.contains("- [ ] ") })
default:
break
}
for note in notes {
allTags.append(contentsOf: note.tags)
}
}
let currentTags = sidebar.items[2].compactMap({ $0.name })
var toRemovePaths = [IndexPath]()
var toRemoveTags = [String]()
for tag in tags {
if !allTags.contains(tag) {
if let row = currentTags.firstIndex(of: tag) {
toRemovePaths.append(IndexPath(row: row, section: 2))
toRemoveTags.append(tag)
}
}
}
sidebar.items[2].removeAll(where: { toRemoveTags.contains($0.name) })
deleteRows(at: toRemovePaths, with: .fade)
deSelectTagIfNonExist(tags: toRemoveTags)
}
private func createQueryWithoutTags() -> SearchQuery? {
guard let vc = viewController else { return nil }
let query = SearchQuery()
query.project = vc.searchQuery.project
if let type = vc.searchQuery.type {
query.type = type
if query.project != nil && type == .Tag {
query.type = .Category
}
}
return query
}
private func deSelectTagIfNonExist(tags: [String]) {
guard let vc = viewController,
let tag = vc.searchQuery.tag
else { return }
guard tags.contains(tag) else { return }
if let project = vc.searchQuery.project,
let index = getIndexPathBy(project: project)
{
tableView(self, didSelectRowAt: index)
return
}
if let type = vc.searchQuery.type,
let index = getIndexPathBy(type: type) {
tableView(self, didSelectRowAt: index)
}
}
public func getSelectedSidebarItem() -> SidebarItem? {
guard let vc = viewController, let project = vc.searchQuery.project else { return nil }
let items = sidebar.items
for item in items {
for subItem in item {
if subItem.project == project {
return subItem
}
}
}
return nil
}
public func getIndexPathBy(project: Project) -> IndexPath? {
for (sectionId, section) in sidebar.items.enumerated() {
for (rowId, item) in section.enumerated() {
if item.project === project {
let indexPath = IndexPath(row: rowId, section: sectionId)
return indexPath
}
}
}
return nil
}
public func getIndexPathBy(tag: String) -> IndexPath? {
let tagsSection = SidebarSection.Tags.rawValue
for (rowId, item) in sidebar.items[tagsSection].enumerated() {
if item.name == tag {
let indexPath = IndexPath(row: rowId, section: tagsSection)
return indexPath
}
}
return nil
}
public func getIndexPathBy(type: SidebarItemType) -> IndexPath? {
let section = SidebarSection.System.rawValue
for (rowId, item) in sidebar.items[section].enumerated() {
if item.type == type {
let indexPath = IndexPath(row: rowId, section: section)
return indexPath
}
}
return nil
}
public func insertRows(projects: [Project]) {
let currentProjects = sidebar.items[1].compactMap({ $0.project })
var toInsert = [Project]()
for project in projects {
if currentProjects.contains(project) {
continue
}
if !project.showInSidebar {
continue
}
toInsert.append(project)
}
guard toInsert.count > 0 else { return }
let nonSorted = currentProjects + toInsert
let sorted = nonSorted.sorted { $0.label < $1.label }
var indexPaths = [IndexPath]()
for project in toInsert {
guard let index = sorted.firstIndex(of: project) else { continue }
indexPaths.append(IndexPath(row: index, section: 1))
}
sidebar.items[1] = sorted.compactMap({ SidebarItem(name: $0.label, project: $0, type: .Category) })
insertRows(at: indexPaths, with: .fade)
}
public func removeRows(projects: [Project]) {
guard projects.count > 0, let vc = viewController else { return }
var deselectCurrent = false
var indexPaths = [IndexPath]()
for project in projects {
if let index = sidebar.items[1].firstIndex(where: { $0.project == project }) {
indexPaths.append(IndexPath(row: index, section: 1))
if project == vc.searchQuery.project {
deselectCurrent = true
}
vc.storage.remove(project: project)
sidebar.items[1].remove(at: index)
}
}
deleteRows(at: indexPaths, with: .automatic)
if deselectCurrent {
vc.notesTable.notes.removeAll()
vc.notesTable.reloadData()
let indexPath = IndexPath(row: 0, section: 0)
tableView(self, didSelectRowAt: indexPath)
}
}
public func select(project: Project) {
guard let indexPath = getIndexPathBy(project: project) else { return }
tableView(self, didSelectRowAt: indexPath)
}
public func select(tag: String) {
guard let indexPath = getIndexPathBy(tag: tag) else { return }
tableView(self, didSelectRowAt: indexPath)
guard let bvc = UIApplication.shared.windows[0].rootViewController as? BasicViewController else {
return
}
bvc.containerController.selectController(atIndex: 0, animated: true)
}
public func restoreSelection(for search: SearchQuery) {
if let type = search.type {
let index = getIndexPathBy(type: type)
selectRow(at: index, animated: false, scrollPosition: .none)
}
if let project = search.project {
let index = getIndexPathBy(project: project)
selectRow(at: index, animated: false, scrollPosition: .none)
}
if let tag = search.tag {
let index = getIndexPathBy(tag: tag)
selectRow(at: index, animated: false, scrollPosition: .none)
}
}
public func remove(tag: String) {
guard let indexPath = getIndexPathBy(tag: tag) else { return }
sidebar.items[2].removeAll(where: { $0.name == tag})
deleteRows(at: [indexPath], with: .automatic)
selectCurrentProject()
}
}
| 32.581957 | 177 | 0.574331 |
0873d853278304f270d3b6ca205acc3833d64e20 | 1,395 | import DateProvider
import Foundation
import UniqueIdentifierGenerator
import WorkerAlivenessProvider
import WorkerCapabilities
public final class SingleBucketQueueEnqueuerProvider: BucketEnqueuerProvider {
private let dateProvider: DateProvider
private let uniqueIdentifierGenerator: UniqueIdentifierGenerator
private let workerAlivenessProvider: WorkerAlivenessProvider
private let workerCapabilitiesStorage: WorkerCapabilitiesStorage
public init(
dateProvider: DateProvider,
uniqueIdentifierGenerator: UniqueIdentifierGenerator,
workerAlivenessProvider: WorkerAlivenessProvider,
workerCapabilitiesStorage: WorkerCapabilitiesStorage
) {
self.dateProvider = dateProvider
self.uniqueIdentifierGenerator = uniqueIdentifierGenerator
self.workerAlivenessProvider = workerAlivenessProvider
self.workerCapabilitiesStorage = workerCapabilitiesStorage
}
public func createBucketEnqueuer(
bucketQueueHolder: BucketQueueHolder
) -> BucketEnqueuer {
SingleBucketQueueEnqueuer(
bucketQueueHolder: bucketQueueHolder,
dateProvider: dateProvider,
uniqueIdentifierGenerator: uniqueIdentifierGenerator,
workerAlivenessProvider: workerAlivenessProvider,
workerCapabilitiesStorage: workerCapabilitiesStorage
)
}
}
| 37.702703 | 78 | 0.768459 |
efbec6a2c8849790af8e7643d45888c3a8b2870d | 2,347 | import UIKit
final class LargeIconButtonItemViewCell: UITableViewCell {
// MARK: - Public accessors
var title: String {
get {
return itemView.title
}
set {
itemView.title = newValue
}
}
var icon: UIImage {
get {
return itemView.image
}
set {
itemView.image = newValue
}
}
var leftButtonTitle: String {
get {
return itemView.leftButtonTitle
}
set {
itemView.leftButtonTitle = newValue
}
}
var rightButtonTitle: String {
get {
return itemView.rightButtonTitle
}
set {
itemView.rightButtonTitle = newValue
}
}
var leftButtonPressHandler: (() -> Void)?
var rightButtonPressHandler: (() -> Void)?
// MARK: - Creating a View Object
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
// MARK: - UI properties
private lazy var itemView: LargeIconButtonItemView = {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.output = self
return $0
}(LargeIconButtonItemView())
// MARK: - Setup view
private func setupView() {
contentView.addSubview(itemView)
let constraints = [
itemView.leading.constraint(equalTo: contentView.leading),
itemView.top.constraint(equalTo: contentView.top),
contentView.trailing.constraint(equalTo: itemView.trailing),
contentView.bottom.constraint(equalTo: itemView.bottom),
]
NSLayoutConstraint.activate(constraints)
}
override func layoutSubviews() {
super.layoutSubviews()
separatorInset.left = itemView.leftSeparatorInset + contentView.frame.minX
}
}
extension LargeIconButtonItemViewCell: LargeIconButtonItemViewOutput {
func didPressLeftButton(in itemView: LargeIconButtonItemViewInput) {
leftButtonPressHandler?()
}
func didPressRightButton(in itemView: LargeIconButtonItemViewInput) {
rightButtonPressHandler?()
}
}
| 25.236559 | 82 | 0.615254 |
1e6fba0e740065d87e078d01853f07a24d98f4e1 | 346 | import Foundation
extension HBDateCache {
static var rfc1123Formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "EEE, d MMM yyy HH:mm:ss z"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter
}()
}
| 28.833333 | 60 | 0.67052 |
8fe56e6a25502255d411a0578644baa0dcc80649 | 907 | //
// Preview_Landscape.swift
// 100Views
//
// Created by Mark Moeykens on 9/27/19.
// Copyright © 2019 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct Preview_Landscape: View {
var body: some View {
VStack(spacing: 20) {
Text("Previews").font(.largeTitle)
Text("Landscape").foregroundColor(.gray)
Text("You currently cannot rotate a previewed device. But one option is to set a fixed width and height for your preview.")
.frame(maxWidth: .infinity)
.padding()
.background(Color.red)
.layoutPriority(1)
.foregroundColor(.white)
}.font(.title)
}
}
struct Preview_Landscape_Previews: PreviewProvider {
static var previews: some View {
Preview_Landscape()
.previewLayout(PreviewLayout.fixed(width: 896, height: 414))
}
}
| 28.34375 | 135 | 0.6086 |
757f96db3fdc12b83cd3dc3c34fac5cf3fb2dec3 | 4,766 | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019-2020 Datadog, Inc.
*/
import XCTest
@testable import Datadog
fileprivate class MockEventConsumer: WebLogEventConsumer, WebRUMEventConsumer {
private(set) var consumedLogEvents: [JSON] = []
private(set) var consumedInternalLogEvents: [JSON] = []
private(set) var consumedRUMEvents: [JSON] = []
func consume(event: JSON, internalLog: Bool) throws {
if internalLog {
consumedInternalLogEvents.append(event)
} else {
consumedLogEvents.append(event)
}
}
func consume(event: JSON) throws {
consumedRUMEvents.append(event)
}
}
class WebEventBridgeTests: XCTestCase {
private let mockLogEventConsumer = MockEventConsumer()
private let mockRUMEventConsumer = MockEventConsumer()
lazy var eventBridge = WebEventBridge(
logEventConsumer: mockLogEventConsumer,
rumEventConsumer: mockRUMEventConsumer
)
// MARK: - Parsing
func testWhenMessageIsInvalid_itFailsParsing() {
let messageInvalidJSON = """
{ 123: foobar }
"""
XCTAssertThrowsError(
try eventBridge.consume(messageInvalidJSON),
"Non-string keys (123) should throw"
)
}
// MARK: - Routing
func testWhenEventTypeIsMissing_itThrows() {
let messageMissingEventType = """
{"event":{"date":1635932927012,"error":{"origin":"console"}}}
"""
XCTAssertThrowsError(
try eventBridge.consume(messageMissingEventType),
"Missing eventType should throw"
) { error in
XCTAssertEqual(
error as? WebEventError,
WebEventError.missingKey(key: WebEventBridge.Constants.eventTypeKey)
)
}
}
func testWhenEventTypeIsLog_itGoesToLogEventConsumer() throws {
let messageLog = """
{"eventType":"log","event":{"date":1635932927012,"error":{"origin":"console"},"message":"console error: error","session_id":"0110cab4-7471-480e-aa4e-7ce039ced355","status":"error","view":{"referrer":"","url":"https://datadoghq.dev/browser-sdk-test-playground"}},"tags":["browser_sdk_version:3.6.13"]}
"""
try eventBridge.consume(messageLog)
XCTAssertEqual(mockLogEventConsumer.consumedLogEvents.count, 1)
XCTAssertEqual(mockLogEventConsumer.consumedInternalLogEvents.count, 0)
XCTAssertEqual(mockLogEventConsumer.consumedRUMEvents.count, 0)
XCTAssertEqual(mockRUMEventConsumer.consumedLogEvents.count, 0)
XCTAssertEqual(mockRUMEventConsumer.consumedInternalLogEvents.count, 0)
XCTAssertEqual(mockRUMEventConsumer.consumedRUMEvents.count, 0)
let consumedEvent = try XCTUnwrap(mockLogEventConsumer.consumedLogEvents.first)
XCTAssertEqual(consumedEvent["session_id"] as? String, "0110cab4-7471-480e-aa4e-7ce039ced355")
XCTAssertEqual((consumedEvent["view"] as? JSON)?["url"] as? String, "https://datadoghq.dev/browser-sdk-test-playground")
}
func testWhenEventTypeIsNonLog_itGoesToRUMEventConsumer() throws {
let messageRUM = """
{"eventType":"view","event":{"application":{"id":"xxx"},"date":1635933113708,"service":"super","session":{"id":"0110cab4-7471-480e-aa4e-7ce039ced355","type":"user"},"type":"view","view":{"action":{"count":0},"cumulative_layout_shift":0,"dom_complete":152800000,"dom_content_loaded":118300000,"dom_interactive":116400000,"error":{"count":0},"first_contentful_paint":121300000,"id":"64308fd4-83f9-48cb-b3e1-1e91f6721230","in_foreground_periods":[],"is_active":true,"largest_contentful_paint":121299000,"load_event":152800000,"loading_time":152800000,"loading_type":"initial_load","long_task":{"count":0},"referrer":"","resource":{"count":3},"time_spent":3120000000,"url":"http://localhost:8080/test.html"},"_dd":{"document_version":2,"drift":0,"format_version":2,"session":{"plan":2}}},"tags":["browser_sdk_version:3.6.13"]}
"""
try eventBridge.consume(messageRUM)
XCTAssertEqual(
mockLogEventConsumer.consumedLogEvents.count + mockLogEventConsumer.consumedInternalLogEvents.count,
0
)
XCTAssertEqual(mockRUMEventConsumer.consumedRUMEvents.count, 1)
let consumedEvent = try XCTUnwrap(mockRUMEventConsumer.consumedRUMEvents.first)
XCTAssertEqual((consumedEvent["session"] as? JSON)?["id"] as? String, "0110cab4-7471-480e-aa4e-7ce039ced355")
XCTAssertEqual((consumedEvent["view"] as? JSON)?["url"] as? String, "http://localhost:8080/test.html")
}
}
| 47.66 | 830 | 0.690936 |
b95342a8381f31580bfd2e3724422ebb67cac262 | 1,396 | class Solution {
// Solution @ Sergey Leschev, Belarusian State University
// 372. Super Pow
// Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
// Example 1:
// Input: a = 2, b = [3]
// Output: 8
// Example 2:
// Input: a = 2, b = [1,0]
// Output: 1024
// Example 3:
// Input: a = 1, b = [4,3,3,8,5,2]
// Output: 1
// Example 4:
// Input: a = 2147483647, b = [2,0,0]
// Output: 1198
// Constraints:
// 1 <= a <= 2^31 - 1
// 1 <= b.length <= 2000
// 0 <= b[i] <= 9
// b doesn't contain leading zeros.
func superPow(_ a: Int, _ b: [Int]) -> Int {
var mod = 1337
var res = 1
func quickPow(num1: Int, num2: Int) -> Int{
var num1 = num1
var num2 = num2
var res = 1
num1 %= mod
while num2 > 0 {
if (num2 & 1) != 0 { res = (res * num1) % mod }
num1 = (num1 * num1) % mod
num2 >>= 1
}
return res
}
var a = a
for num in b.reversed() {
res = (res * quickPow(num1: a, num2: num)) % mod
a = quickPow(num1: a, num2: 10)
}
return res
}
} | 23.266667 | 150 | 0.436246 |
1e189904f1a2eef7d3f6d9b5dc5cbcceba32f7eb | 852 | //
// CommandSpec.swift
// Commandant
//
// Created by Syo Ikeda on 1/5/16.
// Copyright © 2016 Carthage. All rights reserved.
//
import Commandant
import Nimble
import Quick
import Result
class CommandWrapperSpec: QuickSpec {
override func spec() {
describe("CommandWrapper.usage") {
it("should not crash for a command with NoOptions") {
let command = NoOptionsCommand()
let registry = CommandRegistry<CommandantError<()>>()
registry.register(command)
let wrapper = registry[command.verb]
expect(wrapper).notTo(beNil())
expect(wrapper?.usage()).to(beNil())
}
}
}
}
struct NoOptionsCommand: CommandProtocol {
var verb: String { return "verb" }
var function: String { return "function" }
func run(_ options: NoOptions<CommandantError<()>>) -> Result<(), CommandantError<()>> {
return .success(())
}
}
| 21.846154 | 89 | 0.685446 |
90fa3a8af6e87c95a7633489d14153d5a9238fef | 8,218 | //
// HoorayDetailViewModelTests.swift
// HooraySceneTests
//
// Created by sudo.park on 2021/08/26.
//
import XCTest
import RxSwift
import Domain
import UnitTestHelpKit
import UsecaseDoubles
import HoorayScene
class HoorayDetailViewModelTests: BaseTestCase, WaitObservableEvents {
var disposeBag: DisposeBag!
var dummyHoorayDetail: HoorayDetail!
var dummyHooray: Hooray! { self.dummyHoorayDetail.hoorayInfo }
override func setUpWithError() throws {
self.disposeBag = .init()
let uid = "uid:0"
let acks = (0..<3).map{ HoorayAckInfo(hoorayID: uid,
ackUserID: "a:\($0)", ackAt: TimeStamp($0))}
let reactions = (0..<3).map { HoorayReaction(hoorayID: uid,
reactionID: "r:\($0)",
reactMemberID: "m:\($0)",
icon: .emoji("🤓"), reactAt: TimeStamp($0))}
self.dummyHoorayDetail = .dummy(0, acks: acks, reactions: reactions)
}
override func tearDownWithError() throws {
self.disposeBag = nil
self.dummyHoorayDetail = nil
}
func makeViewModel(shouldLoadDetailFail: Bool = false) -> HoorayDetailViewModel {
let hoorayID = self.dummyHooray.uid
var hoorayScenario = BaseStubHoorayUsecase.Scenario()
hoorayScenario.loadHoorayResult = shouldLoadDetailFail
? .failure(ApplicationErrors.invalid)
: .success(self.dummyHoorayDetail)
let stubHoorayUsecase = BaseStubHoorayUsecase(hoorayScenario)
var memberScenario = BaseStubMemberUsecase.Scenario()
let publisher = Member(uid: self.dummyHooray.publisherID, nickName: "some", icon: .emoji("😒"))
memberScenario.members = .success([publisher])
memberScenario.currentMember = Member(uid: self.dummyHoorayDetail.reactions.first?.reactMemberID ?? "some")
let stubMemberUsecase = BaseStubMemberUsecase(scenario: memberScenario)
let stubPlaceUsecase = StubPlaceUsecase()
stubPlaceUsecase.stubPlace = Place.dummy(0)
let stubRouter = StubRouter()
return HoorayDetailViewModelImple(hoorayID: hoorayID,
hoorayUsecase: stubHoorayUsecase,
memberUsecase: stubMemberUsecase,
placeUsecase: stubPlaceUsecase,
router: stubRouter)
}
}
// MARK: - show detail
extension HoorayDetailViewModelTests {
func testViewModel_loadHoorayDetail() {
// given
let expect = expectation(description: "무야호 상세내역 조회 이후에 cellViewModel 방출")
let viewModel = self.makeViewModel()
// when
let cellViewModels = self.waitFirstElement(expect, for: viewModel.cellViewModels) {
viewModel.loadDetail()
}
// then
XCTAssertEqual(cellViewModels?.count, 3)
}
func testViewModel_whenLoadFailDetail_showLoadFailed() {
// given
let expect = expectation(description: "무야호 상세내역 조회 이후에 cellViewModel 방출")
let viewModel = self.makeViewModel(shouldLoadDetailFail: true)
// when
let isLoadingFail: Void? = self.waitFirstElement(expect, for: viewModel.isLoadingFail) {
viewModel.loadDetail()
}
// then
XCTAssertNotNil(isLoadingFail)
}
}
extension HoorayDetailViewModelTests {
func testViewModel_headerCell() {
// given
let expect = expectation(description: "header cell")
let viewModel = self.makeViewModel()
// when
let cellViewModels = self.waitFirstElement(expect, for: viewModel.cellViewModels) {
viewModel.loadDetail()
}
// then
let headerCells = cellViewModels?.compactMap{ $0 as? HoorayDetailHeaderCellViewModel }
XCTAssertEqual(headerCells?.count, 1)
}
func testViewModel_provideMemberInfo() {
// given
let expect = expectation(description: "member 정보 레이지하게 제공")
let viewModel = self.makeViewModel()
// when
let publisherID = self.dummyHooray.publisherID
let memberInfo = self.waitFirstElement(expect, for: viewModel.memberInfo(for: publisherID))
// then
XCTAssertNotNil(memberInfo)
}
func testViewModel_providePlaceName() {
// given
let expect = expectation(description: "장소 이름 제공")
let viewModel = self.makeViewModel()
// when
let placeID = self.dummyHooray.placeID ?? "some"
let placeName = self.waitFirstElement(expect, for: viewModel.placeName(for: placeID))
// then
XCTAssertNotNil(placeName)
}
}
extension HoorayDetailViewModelTests {
func testViewModel_contentCell() {
// given
let expect = expectation(description: "content cell 구성")
let viewModel = self.makeViewModel()
// when
let cellViewModels = self.waitFirstElement(expect, for: viewModel.cellViewModels) {
viewModel.loadDetail()
}
// then
let contentCells = cellViewModels?.compactMap{ $0 as? HoorayDetailContentCellViewModel }
XCTAssertEqual(contentCells?.count, 1)
XCTAssertEqual(contentCells?.first?.message, self.dummyHooray.message)
XCTAssertEqual(contentCells?.first?.tags, self.dummyHooray.tags)
XCTAssertEqual(contentCells?.first?.image, self.dummyHooray.image)
}
}
// TODO: 리액션도 통합으로
extension HoorayDetailViewModelTests {
func testViewModel_reactionsCell() {
// given
let expect = expectation(description: "content cell 구성")
let viewModel = self.makeViewModel()
// when
let cellViewModels = self.waitFirstElement(expect, for: viewModel.cellViewModels) {
viewModel.loadDetail()
}
// then
let reactionsCells = cellViewModels?.compactMap{ $0 as? HoorayDetailReactionsCellViewModel }
XCTAssertEqual(reactionsCells?.count, 1)
}
func testViewModel_provideAckCount() {
// given
let expect = expectation(description: "ack count 제공")
let viewodel = self.makeViewModel()
// when
let counts = self.waitFirstElement(expect, for: viewodel.ackCount, skip: 1) {
viewodel.loadDetail()
}
// then
XCTAssertEqual(counts, 3)
}
func testViewModel_provideReactions() {
// given
let expect = expectation(description: "reaction 제공")
let viewodel = self.makeViewModel()
// when
let reactions = self.waitFirstElement(expect, for: viewodel.reactions, skip: 1) {
viewodel.loadDetail()
}
// then
XCTAssertEqual(reactions?.count, 1)
XCTAssertEqual(reactions?.first?.icon, .emoji("🤓"))
XCTAssertEqual(reactions?.first?.count, 3)
}
func testViewModel_provideReactionWithIsMineMark() {
// given
let expect = expectation(description: "reaction 제공시 내가 반응했나 정보도 같이 제공")
let viewodel = self.makeViewModel()
// when
let reactions = self.waitFirstElement(expect, for: viewodel.reactions, skip: 1) {
viewodel.loadDetail()
}
// then
let myReactions = reactions?.filter{ $0.isIncludeMine }
XCTAssertEqual(myReactions?.count, 1)
}
}
// TODO: 코멘트는 추후 통합 코멘트로 붙임
extension HoorayDetailViewModelTests {
// comments
}
extension HoorayDetailViewModelTests {
class StubRouter: HoorayDetailRouting { }
class StubPlaceUsecase: BaseStubPlaceUsecase {
var stubPlace: Place?
override func place(_ placeID: String) -> Observable<Place> {
return self.stubPlace.map{ Observable.just($0) } ?? .error(ApplicationErrors.invalid)
}
}
}
| 31.72973 | 115 | 0.60404 |
798abd45b4f0db5afc1d0705ee62c6f6bdc27a27 | 419 | import Suborbital
class FetchSwift: Suborbital.Runnable {
func run(input: String) -> String {
let url = "https://postman-echo.com/post"
let body = "hello, postman!"
let resp = Suborbital.HttpPost(url: url, body: body)
Suborbital.LogInfo(msg: resp)
return Suborbital.HttpGet(url: input)
}
}
@_cdecl("init")
func `init`() {
Suborbital.Set(runnable: FetchSwift())
} | 22.052632 | 60 | 0.630072 |
ac241c84d85fcbe5e55e1e8d41fd6459a8fb2511 | 7,084 | //
// Realm+Rx.swift
// RealmKit
//
// Copyright © 2020 E-SOFT, OOO. All rights reserved.
//
import Foundation
import RealmSwift
import RxSwift
// MARK: Realm type extensions
extension Realm: ReactiveCompatible {}
extension Reactive where Base == Realm {
/**
Returns bindable sink wich adds object sequence to the current Realm
- parameter: update - update according to Realm.UpdatePolicy
- parameter: onError - closure to implement custom error handling
- returns: `AnyObserver<S>`, which you can use to subscribe an `Observable` to
*/
public func add<S: Sequence>(update: Realm.UpdatePolicy = .error, onError: ((S?, Error) -> Void)? = nil)
-> AnyObserver<S> where S.Iterator.Element: Object {
RealmObserver(realm: base) { realm, elements, error in
guard let realm = realm else {
onError?(nil, error ?? RxRealmError.unknown)
return
}
do {
try realm.write {
realm.add(elements, update: update)
}
} catch let e {
onError?(elements, e)
}
}
.asObserver()
}
/**
Returns bindable sink wich adds an object to Realm
- parameter: update - update according to Realm.UpdatePolicy
- parameter: onError - closure to implement custom error handling
- returns: `AnyObserver<O>`, which you can use to subscribe an `Observable` to
*/
public func add<O: Object>(update: Realm.UpdatePolicy = .error,
onError: ((O?, Error) -> Void)? = nil) -> AnyObserver<O> {
RealmObserver(realm: base) { realm, element, error in
guard let realm = realm else {
onError?(nil, error ?? RxRealmError.unknown)
return
}
do {
try realm.write {
realm.add(element, update: update)
}
} catch let e {
onError?(element, e)
}
}.asObserver()
}
/**
Returns bindable sink wich deletes objects in sequence from Realm.
- parameter: onError - closure to implement custom error handling
- returns: `AnyObserver<S>`, which you can use to subscribe an `Observable` to
*/
public func delete<S: Sequence>(onError: ((S?, Error) -> Void)? = nil)
-> AnyObserver<S> where S.Iterator.Element: Object {
RealmObserver(realm: base, binding: { realm, elements, error in
guard let realm = realm else {
onError?(nil, error ?? RxRealmError.unknown)
return
}
do {
try realm.write {
realm.delete(elements)
}
} catch let e {
onError?(elements, e)
}
}).asObserver()
}
/**
Returns bindable sink wich deletes objects in sequence from Realm.
- parameter: onError - closure to implement custom error handling
- returns: `AnyObserver<O>`, which you can use to subscribe an `Observable` to
*/
public func delete<O: Object>(onError: ((O?, Error) -> Void)? = nil) -> AnyObserver<O> {
RealmObserver(realm: base, binding: { realm, element, error in
guard let realm = realm else {
onError?(nil, error ?? RxRealmError.unknown)
return
}
do {
try realm.write {
realm.delete(element)
}
} catch let e {
onError?(element, e)
}
}).asObserver()
}
}
extension Reactive where Base == Realm {
/**
Returns bindable sink wich adds object sequence to a Realm
- parameter: configuration (by default uses `Realm.Configuration.defaultConfiguration`)
to use to get a Realm for the write operations
- parameter: update - update according to Realm.UpdatePolicy
- parameter: onError - closure to implement custom error handling
- returns: `AnyObserver<S>`, which you can use to subscribe an `Observable` to
*/
public static func add<S: Sequence>(configuration: Realm.Configuration = Realm.Configuration.defaultConfiguration,
update: Realm.UpdatePolicy = .error,
onError: ((S?, Error) -> Void)? = nil) -> AnyObserver<S> where S.Iterator.Element: Object {
RealmObserver(configuration: configuration) { realm, elements, error in
guard let realm = realm else {
onError?(nil, error ?? RxRealmError.unknown)
return
}
do {
try realm.write {
realm.add(elements, update: update)
}
} catch let e {
onError?(elements, e)
}
}.asObserver()
}
/**
Returns bindable sink which adds an object to a Realm
- parameter: configuration (by default uses `Realm.Configuration.defaultConfiguration`)
to use to get a Realm for the write operations
- parameter: update - update according to Realm.UpdatePolicy
- parameter: onError - closure to implement custom error handling
- returns: `AnyObserver<O>`, which you can use to subscribe an `Observable` to
*/
public static func add<O: Object>(configuration: Realm.Configuration = Realm.Configuration.defaultConfiguration,
update: Realm.UpdatePolicy = .error,
onError: ((O?, Error) -> Void)? = nil) -> AnyObserver<O> {
RealmObserver(configuration: configuration) { realm, element, error in
guard let realm = realm else {
onError?(nil, error ?? RxRealmError.unknown)
return
}
do {
try realm.write {
realm.add(element, update: update)
}
} catch let e {
onError?(element, e)
}
}.asObserver()
}
/**
Returns bindable sink, which deletes objects in sequence from Realm.
- parameter: onError - closure to implement custom error handling
- returns: `AnyObserver<S>`, which you can use to subscribe an `Observable` to
*/
public static func delete<S: Sequence>(onError: ((S?, Error) -> Void)? = nil)
-> AnyObserver<S> where S.Iterator.Element: Object {
AnyObserver { event in
guard let elements = event.element,
var generator = elements.makeIterator() as S.Iterator?,
let first = generator.next(),
let realm = first.realm else {
onError?(nil, RxRealmError.unknown)
return
}
do {
try realm.write {
realm.delete(elements)
}
} catch let e {
onError?(elements, e)
}
}
}
/**
Returns bindable sink, which deletes object from Realm
- parameter: onError - closure to implement custom error handling
- returns: `AnyObserver<O>`, which you can use to subscribe an `Observable` to
*/
public static func delete<O: Object>(onError: ((O?, Error) -> Void)? = nil) -> AnyObserver<O> {
AnyObserver { event in
guard let element = event.element, let realm = element.realm else {
onError?(nil, RxRealmError.unknown)
return
}
do {
try realm.write {
realm.delete(element)
}
} catch let e {
onError?(element, e)
}
}
}
}
| 32.796296 | 129 | 0.599944 |
e50fd5d1cc6663bc034909739b514ca245d331d6 | 3,471 | /**
* Copyright (c) 2017 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 UIKit
let NotificationPurchasedMovieOnPhone = "PurchasedMovieOnPhone"
let NotificationPurchasedMovieOnWatch = "PurchasedMovieOnWatch"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var notificationCenter: NotificationCenter = {
return NotificationCenter.default
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
setupTheme(application: application)
setupWatchConnectivity()
setupNotificationCenter()
return true
}
// MARK: - Theme
private func setupTheme(application: UIApplication) {
// UINavigationBar
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor(red:1, green:1, blue:1, alpha:1)]
UINavigationBar.appearance().barTintColor = UIColor(red: 157.0/255.0, green: 42.0/255.0, blue: 42.0/255.0, alpha: 1.0)
// UIScrollView and UITableView
UITableView.appearance().backgroundColor = UIColor(red: 43/255.0, green: 43/255.0, blue: 43/255.0, alpha: 1)
// Application
application.statusBarStyle = UIStatusBarStyle.lightContent
}
// MARK: - Notification Center
private func setupNotificationCenter() {
notificationCenter.addObserver(forName: NSNotification.Name(rawValue: NotificationPurchasedMovieOnPhone), object: nil, queue: nil) { (notification:Notification) -> Void in
self.sendPurchasedMoviesToWatch(notification)
}
}
}
// MARK: - Watch Connectivity
extension AppDelegate {
func setupWatchConnectivity() {
// TODO: Update to set up watch connectivity
}
func sendPurchasedMoviesToWatch(_ notification: Notification) {
// TODO: Update to send purchased movies to the watch
}
}
| 40.835294 | 175 | 0.753961 |
4b525aa3d4f6206dfb7069d7b37be01f55cecc6f | 6,402 | //
// TableViewWithEditingCommandsViewController.swift
// RxExample
//
// Created by carlos on 26/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
/**
Another way to do "MVVM". There are different ideas what does MVVM mean depending on your background.
It's kind of similar like FRP.
In the end, it doesn't really matter what jargon are you using.
This would be the ideal case, but it's really hard to model complex views this way
because it's not possible to observe partial model changes.
*/
struct TableViewEditingCommandsViewModel {
let favoriteUsers: [User]
let users: [User]
func executeCommand(_ command: TableViewEditingCommand) -> TableViewEditingCommandsViewModel {
switch command {
case let .setUsers(users):
return TableViewEditingCommandsViewModel(favoriteUsers: favoriteUsers, users: users)
case let .setFavoriteUsers(favoriteUsers):
return TableViewEditingCommandsViewModel(favoriteUsers: favoriteUsers, users: users)
case let .deleteUser(indexPath):
var all = [self.favoriteUsers, self.users]
all[indexPath.section].remove(at: indexPath.row)
return TableViewEditingCommandsViewModel(favoriteUsers: all[0], users: all[1])
case let .moveUser(from, to):
var all = [self.favoriteUsers, self.users]
let user = all[from.section][from.row]
all[from.section].remove(at: from.row)
all[to.section].insert(user, at: to.row)
return TableViewEditingCommandsViewModel(favoriteUsers: all[0], users: all[1])
}
}
}
enum TableViewEditingCommand {
case setUsers(users: [User])
case setFavoriteUsers(favoriteUsers: [User])
case deleteUser(indexPath: IndexPath)
case moveUser(from: IndexPath, to: IndexPath)
}
class TableViewWithEditingCommandsViewController: ViewController, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let dataSource = TableViewWithEditingCommandsViewController.configureDataSource()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.editButtonItem
let superMan = User(
firstName: "Super",
lastName: "Man",
imageURL: "http://nerdreactor.com/wp-content/uploads/2015/02/Superman1.jpg"
)
let watMan = User(firstName: "Wat",
lastName: "Man",
imageURL: "http://www.iri.upc.edu/files/project/98/main.GIF"
)
let loadFavoriteUsers = RandomUserAPI.sharedAPI
.getExampleUserResultSet()
.map(TableViewEditingCommand.setUsers)
let initialLoadCommand = Observable.just(TableViewEditingCommand.setFavoriteUsers(favoriteUsers: [superMan, watMan]))
.concat(loadFavoriteUsers)
.observeOn(MainScheduler.instance)
let deleteUserCommand = tableView.rx.itemDeleted.map(TableViewEditingCommand.deleteUser)
let moveUserCommand = tableView
.rx.itemMoved
.map(TableViewEditingCommand.moveUser)
let initialState = TableViewEditingCommandsViewModel(favoriteUsers: [], users: [])
let viewModel = Observable.of(initialLoadCommand, deleteUserCommand, moveUserCommand)
.merge()
.scan(initialState) { $0.executeCommand($1) }
.shareReplay(1)
viewModel
.map {
[
SectionModel(model: "Favorite Users", items: $0.favoriteUsers),
SectionModel(model: "Normal Users", items: $0.users)
]
}
.bindTo(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableView.rx.itemSelected
.withLatestFrom(viewModel) { i, viewModel in
let all = [viewModel.favoriteUsers, viewModel.users]
return all[i.section][i.row]
}
.subscribe(onNext: { [weak self] user in
self?.showDetailsForUser(user)
})
.disposed(by: disposeBag)
// customization using delegate
// RxTableViewDelegateBridge will forward correct messages
tableView.rx.setDelegate(self)
.disposed(by: disposeBag)
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.isEditing = editing
}
// MARK: Table view delegate ;)
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let title = dataSource[section]
let label = UILabel(frame: CGRect.zero)
// hacky I know :)
label.text = " \(title)"
label.textColor = UIColor.white
label.backgroundColor = UIColor.darkGray
label.alpha = 0.9
return label
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
// MARK: Navigation
private func showDetailsForUser(_ user: User) {
let storyboard = UIStoryboard(name: "TableViewWithEditingCommands", bundle: Bundle(identifier: "RxExample-iOS"))
let viewController = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
viewController.user = user
self.navigationController?.pushViewController(viewController, animated: true)
}
// MARK: Work over Variable
static func configureDataSource() -> RxTableViewSectionedReloadDataSource<SectionModel<String, User>> {
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, User>>()
dataSource.configureCell = { (_, tv, ip, user: User) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = user.firstName + " " + user.lastName
return cell
}
dataSource.titleForHeaderInSection = { dataSource, sectionIndex in
return dataSource[sectionIndex].model
}
dataSource.canEditRowAtIndexPath = { (ds, ip) in
return true
}
dataSource.canMoveRowAtIndexPath = { _ in
return true
}
return dataSource
}
}
| 34.793478 | 130 | 0.651671 |
b99ca47a6c3b56e7b08e0e890fe94116197a0da9 | 222 | //
// QuikCodeApp.swift
// QuikCode
//
// Created by Conor on 08/06/2021.
//
import SwiftUI
@main
struct QuikCodeApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 12.333333 | 35 | 0.554054 |
75d0e6033102f99f2953b379d499545886182c4c | 2,038 | import SwiftUI
// MARK: - SecondaryAction+Action
public extension WhatsNew.SecondaryAction {
/// A WhatsNew Secondary Action
enum Action {
/// Present View
case present(AnyView)
/// Custom Action
case custom((Binding<PresentationMode>) -> Void)
}
}
// MARK: - Action+present
public extension WhatsNew.SecondaryAction.Action {
/// Present View on WhatsNewView
/// - Parameters:
/// - content: The ViewBuilder closure that produces the Content View
static func present<Content: View>(
@ViewBuilder
_ content: () -> Content
) -> Self {
.present(.init(content()))
}
}
// MARK: - Action+dismiss
public extension WhatsNew.SecondaryAction.Action {
/// Dismiss WhatsNewView
static let dismiss: Self = .custom { presentationMode in
presentationMode.wrappedValue.dismiss()
}
}
// MARK: - Action+openURL
public extension WhatsNew.SecondaryAction.Action {
/// Open a URL
/// - Parameters:
/// - url: The URL that should be opened
/// - application: The UIApplication used to open the URL. Default value `.shared`
static func openURL(
_ url: URL?
) -> Self {
.custom { _ in
// Verify URL is available
guard let url = url else {
// Otherwise return out of function
return
}
// Open URL
#if os(macOS)
NSWorkspace.shared.open(
url
)
#else
UIApplication.shared.open(
url,
options: .init()
)
#endif
}
}
}
// MARK: - Action+PresentedView
extension WhatsNew.SecondaryAction.Action {
/// The WhatsNew Secondary Action PresentedView
struct PresentedView: Identifiable {
/// The identifier
var id: UUID = .init()
/// The View
let view: AnyView
}
}
| 21.913978 | 88 | 0.546124 |
4be43963d75a32dc942d7f3cd6bc1ba261c1abd4 | 2,801 | //
// LocationService.swift
// WeatherForecast
//
// Created by Giftbot on 2020/02/22.
// Copyright © 2020 Giftbot. All rights reserved.
//
import CoreLocation
// MARK: - DelegateProtocol
protocol LocationManagerDelegate: class {
typealias Location = CLLocation
func locationManagerShouldRequestAuthorization(_ manager: LocationManager)
func locationManager(_ manager: LocationManager, didReceiveAddress address: String?)
func locationManager(_ manager: LocationManager, didReceiveLocation location: Location)
}
// MARK: - LocationManager
final class LocationManager: NSObject {
private let manager = CLLocationManager()
private var latestUpdateDate = Date(timeIntervalSinceNow: -10)
weak var delegate: LocationManagerDelegate?
override init() {
super.init()
manager.delegate = self
requestAuthorization()
}
private func requestAuthorization() {
switch CLLocationManager.authorizationStatus() {
case .notDetermined:
manager.requestWhenInUseAuthorization()
case .authorizedAlways, .authorizedWhenInUse: break
default:
delegate?.locationManagerShouldRequestAuthorization(self)
}
}
func startUpdatingLocation() {
manager.startUpdatingLocation()
}
}
// MARK: - CLLocationManagerDelegate
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedWhenInUse, .authorizedAlways:
manager.startUpdatingLocation()
default: break
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
manager.stopUpdatingLocation()
let currentDate = Date()
if abs(latestUpdateDate.timeIntervalSince(currentDate)) > 2 {
reverseGeocoding(location: location)
delegate?.locationManager(self, didReceiveLocation: location)
latestUpdateDate = currentDate
}
}
private func reverseGeocoding(location: CLLocation) {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { [weak self] (placemarks, error) in
guard let self = self else { return }
guard error == nil else { return print(error!.localizedDescription) }
guard let place = placemarks?.first else { return }
let locality = place.locality ?? ""
let subLocality = place.subLocality ?? ""
let thoroughfare = place.thoroughfare ?? ""
let address = locality + " " + (!subLocality.isEmpty ? subLocality : thoroughfare)
DispatchQueue.main.async {
self.delegate?.locationManager(
self, didReceiveAddress: locality.isEmpty ? nil : address
)
}
}
}
}
| 29.484211 | 108 | 0.717244 |
fba7bff8a4f0026b50d937db06cf5600f4fcddcd | 937 | //
// EventHierarchyUITests.swift
// EventHierarchyUITests
//
// Created by Emilio Peláez on 8/1/22.
//
import XCTest
class EventHierarchyUITests: XCTestCase {
override func setUpWithError() throws {
continueAfterFailure = false
}
override func tearDownWithError() throws {}
func testExample() throws {
let app = XCUIApplication()
app.launch()
app.buttons["Test 0"].tap()
XCTAssert(true)
app.buttons["Test 1"].tap()
XCTAssert(app.alerts["Test 1"].exists)
app.buttons["Close"].tap()
app.buttons["Test 2"].tap()
XCTAssert(app.alerts["Test 2"].exists)
app.buttons["Close"].tap()
app.buttons["Test 4"].tap()
XCTAssert(app.alerts["Test 4"].exists)
app.buttons["Close"].tap()
app.buttons["Test 5"].tap()
XCTAssert(app.alerts["Test 5"].exists)
app.buttons["Close"].tap()
app.buttons["Test 6"].tap()
XCTAssert(app.alerts["Test 6"].exists)
}
}
| 17.036364 | 44 | 0.643543 |
ed267c4f097dba638c1777047517c884de7ca98c | 652 | //
// MTLRenderPassDescriptor+extensions.swift
// MetalTest
//
// Created by Lukasz Domaradzki on 26/12/2018.
// Copyright © 2018 Lukasz Domaradzki. All rights reserved.
//
import UIKit
import Metal
extension MTLRenderPassDescriptor {
convenience init(texture: MTLTexture, sampleTex: MTLTexture, clearColor: UIColor = .clear) {
self.init()
colorAttachments[0].texture = sampleTex
colorAttachments[0].resolveTexture = texture
colorAttachments[0].loadAction = .clear
colorAttachments[0].storeAction = .multisampleResolve
colorAttachments[0].clearColor = MTLClearColor(color: clearColor)
}
}
| 28.347826 | 96 | 0.716258 |
8fef671a931d72986b36b925ca8d35a95c31f142 | 13,922 | //
// Statuses.swift
// TwitterAPIKit
//
// Created by Yoshiki Kudo on 2015/07/04.
// Copyright © 2015年 Yoshiki Kudo. All rights reserved.
//
import Foundation
import APIKit
public protocol StatusesRequestType: TwitterAPIRequestType {}
public protocol StatusesGetRequestType: StatusesRequestType {}
public protocol StatusesPostRequestType: StatusesRequestType {}
public extension StatusesRequestType {
public var baseURL: NSURL {
return NSURL(string: "https://api.twitter.com/1.1/statuses")!
}
}
public extension StatusesGetRequestType {
public var method: APIKit.HTTPMethod {
return .GET
}
}
public extension StatusesPostRequestType {
public var method: APIKit.HTTPMethod {
return .POST
}
}
public enum TwitterStatuses {
///
/// https://dev.twitter.com/rest/reference/get/statuses/mentions_timeline
///
public struct MentionsTimeline: StatusesGetRequestType, MultipleTweetsResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/mentions_timeline.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
count: Int,
sinceIDStr: String? = nil,
maxIDStr: String? = nil,
trimUser: Bool = false,
contributorDetails: Bool = false,
includeEntities: Bool = false){
self.client = client
self._parameters = [
"count": count,
"since_id": sinceIDStr,
"max_id": maxIDStr,
"trim_user": trimUser,
"contributor_details": contributorDetails,
"include_entities": includeEntities
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> [Tweets] {
return try tweetsFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/get/statuses/user_timeline
///
public struct UserTimeline: StatusesGetRequestType, MultipleTweetsResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/user_timeline.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
user: User,
count: Int,
sinceIDStr: String? = nil,
maxIDStr: String? = nil,
trimUser: Bool = false,
excludeReplies: Bool = true,
contributorDetails: Bool = false,
includeRts: Bool = true){
self.client = client
self._parameters = [
"user": user as? AnyObject,
"count": count,
"since_id": sinceIDStr,
"max_id": maxIDStr,
"trim_user": trimUser,
"exclude_replies": excludeReplies,
"include_rts": includeRts
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> [Tweets] {
return try tweetsFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/get/statuses/home_timeline
///
public struct HomeTimeline: StatusesGetRequestType, MultipleTweetsResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/home_timeline.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
count: Int,
sinceIDStr: String? = nil,
maxIDStr: String? = nil,
trimUser: Bool = false,
excludeReplies: Bool = true,
contributorDetails: Bool = false,
includeEntities: Bool = false){
self.client = client
self._parameters = [
"count": count,
"since_id": sinceIDStr,
"max_id": maxIDStr,
"trim_user": trimUser,
"exclude_replies": excludeReplies,
"contributor_details": contributorDetails,
"include_entities": includeEntities
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> [Tweets] {
return try tweetsFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/get/statuses/retweets_of_me
///
public struct RetweetsOfMe: StatusesGetRequestType, MultipleTweetsResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/retweets_of_me.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
count: Int,
sinceIDStr: String? = nil,
maxIDStr: String? = nil,
trimUser: Bool = true,
includeEntities: Bool = false,
includeUserEntities: Bool = false){
self.client = client
self._parameters = [
"count": count,
"since_id": sinceIDStr,
"max_id": maxIDStr,
"trim_user": trimUser,
"include_entities": includeEntities,
"include_user_entities": includeUserEntities
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> [Tweets] {
return try tweetsFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/get/statuses/retweets/%3Aid
///
public struct Retweets: StatusesGetRequestType, MultipleTweetsResponseType {
public let client: OAuthAPIClient
public let idStr: String
public var path: String {
return "/retweets/" + idStr + ".json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
idStr: String,
count: Int = 20,
trimUser: Bool = true){
self.client = client
self.idStr = idStr
self._parameters = [
"id": idStr,
"count": count,
"trim_user": trimUser
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> [Tweets] {
return try tweetsFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/get/statuses/show/%3Aid
///
public struct Show: StatusesGetRequestType, SingleTweetResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/show.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
idStr: String,
trimUser: Bool = false,
includeMyRetweet: Bool = true,
includeEntities: Bool = false){
self.client = client
self._parameters = [
"id": idStr,
"trim_user": trimUser,
"include_my_retweet": includeMyRetweet,
"include_entities": includeEntities
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Tweets {
return try tweetFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/post/statuses/destroy/%3Aid
///
public struct Destroy: StatusesPostRequestType, SingleTweetResponseType {
public let client: OAuthAPIClient
public let idStr: String
public var path: String {
return "/destroy/" + idStr + ".json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
idStr: String,
trimUser: Bool = false){
self.client = client
self.idStr = idStr
self._parameters = [
"id": idStr,
"trim_user": trimUser
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Tweets {
return try tweetFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/post/statuses/update
///
public struct Update: StatusesPostRequestType, SingleTweetResponseType {
public let client: OAuthAPIClient
public var path: String {
return "/update.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
status: String,
inReplyToStatusIDStr: String? = nil,
possiblySensitive: Bool = false,
lat: Double? = nil,
long: Double? = nil,
placeID: String? = nil,
displayCoordinates: Bool = false,
trimUser: Bool = true,
mediaIDs: [String]? = nil){
self.client = client
self._parameters = [
"status": status,
"in_reply_to_status_id": inReplyToStatusIDStr,
"possibly_sensitive": possiblySensitive,
"lat": lat,
"long": long,
"place_id": placeID,
"display_coordinates": displayCoordinates,
"trim_user": trimUser,
// TODO: media_ids 対応
"media_ids": nil
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Tweets {
return try tweetFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/post/statuses/retweet/%3Aid
///
public struct Retweet: StatusesPostRequestType, SingleTweetResponseType {
public let client: OAuthAPIClient
public let idStr: String
public var path: String {
return "/retweet/" + idStr + ".json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
idStr: String,
trimUser: Bool = true){
self.client = client
self.idStr = idStr
self._parameters = [
"id": idStr,
"trim_user": trimUser
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> Tweets {
return try tweetFromObject(object, URLResponse)
}
}
///
/// https://dev.twitter.com/rest/reference/get/statuses/retweeters/ids
///
public struct Retweeters: StatusesGetRequestType {
public let client: OAuthAPIClient
public var path: String {
return "/retweeters/ids.json"
}
private let _parameters: [String: AnyObject?]
public var parameters: AnyObject? {
return queryStringsFromParameters(_parameters)
}
public init(
_ client: OAuthAPIClient,
idStr: String,
cursorStr: String = "-1",
stringifyIds: Bool = true){
self.client = client
self._parameters = [
"id": idStr,
"cursor": cursorStr,
"stringify_ids": stringifyIds
]
}
public func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) throws -> RetweetIDs {
guard let
dictionary = object as? [String: AnyObject],
ids = RetweetIDs(dictionary: dictionary) else {
throw DecodeError.Fail
}
return ids
}
}
}
| 32.376744 | 112 | 0.532251 |
76fb0ca057c8afb9927473f6797691c1a6c30964 | 2,599 | import UIKit
class Solution {
func setZeroes(_ matrix: inout [[Int]]) {
var left = false
var top = false
var right = false
var bottom = false
let row = matrix.count
let column = matrix.first!.count
if row == 0 || column == 0 {
return
}
if row == 1 {
var hasZ = false
for j in 0..<column {
hasZ = hasZ || (matrix[0][j] == 0)
}
if hasZ {
for j in 0..<column {
matrix[0][j] = 0
}
}
return
}
if column == 1 {
var hasZ = false
for i in 0..<row {
hasZ = hasZ || (matrix[i][0] == 0)
}
if hasZ {
for i in 0..<row {
matrix[i][0] = 0
}
}
return
}
for i in 0..<column {
if matrix[0][i] == 0 {
top = true
break
}
}
for i in 0..<column {
if matrix[row - 1][i] == 0 {
bottom = true
break
}
}
for j in 0..<row {
if matrix[j][0] == 0 {
left = true
break
}
}
for j in 0..<row {
if matrix[j][column - 1] == 0 {
right = true
break
}
}
for i in 1..<row - 1 {
for j in 1..<column - 1 {
if matrix[i][j] == 0 {
matrix[i][0] = 0
matrix[0][j] = 0
}
}
}
for i in 1..<row - 1 {
if matrix[i][0] == 0 || matrix[i][column - 1] == 0 {
for j in 0..<column {
matrix[i][j] = 0
}
}
}
for j in 1..<column - 1 {
if matrix[0][j] == 0 || matrix[row - 1][j] == 0 {
for i in 0..<row {
matrix[i][j] = 0
}
}
}
if left {
for i in 0..<row {
matrix[i][0] = 0
}
}
if right {
for i in 0..<row {
matrix[i][column - 1] = 0
}
}
if top {
for j in 0..<column {
matrix[0][j] = 0
}
}
if bottom {
for j in 0..<column {
matrix[row - 1][j] = 0
}
}
}
}
| 24.518868 | 64 | 0.293574 |
f7ac4cc05b25c63a4d3fd8ff7037169b3d9a3991 | 1,479 | import Foundation
import RxSwift
import UIKit
protocol LoginViewModel: AutoMockable {
func loginUser(token: String) -> Single<Result<TokenExchangeResponseVo, HttpRequestError>>
}
// sourcery: InjectRegister = "LoginViewModel"
class AppLoginViewModel: LoginViewModel {
private let userManager: UserManager
private let userRepository: UserRepository
private let logger: ActivityLogger
private let schedulers: RxSchedulers
init(userManager: UserManager, dataDestroyer _: DataDestroyer, userRepository: UserRepository, logger: ActivityLogger, schedulers: RxSchedulers) {
self.userManager = userManager
self.userRepository = userRepository
self.logger = logger
self.schedulers = schedulers
}
func loginUser(token: String) -> Single<Result<TokenExchangeResponseVo, HttpRequestError>> {
userRepository.exchangeToken(token)
.do(onSuccess: { result in
if case .success(let successfulResponse) = result {
self.userManager.userId = successfulResponse.user.id
self.userManager.authToken = successfulResponse.user.accessToken
self.logger.appEventOccurred(.login, extras: [
.method: "Passwordless"
])
self.logger.setUserId(id: String(successfulResponse.user.id))
}
}).subscribeOn(schedulers.background).observeOn(schedulers.ui)
}
}
| 38.921053 | 150 | 0.676133 |
fe8d693499c979053a7957495f60e1122002de9b | 348 | //
// Mutation.swift
// Prex
//
// Created by marty-suzuki on 2018/09/29.
// Copyright © 2018 marty-suzuki. All rights reserved.
//
/// Represents mutation that mutate state by actions
public protocol Mutation {
associatedtype Action: Prex.Action
associatedtype State: Prex.State
func mutate(action: Action, state: inout State)
}
| 21.75 | 55 | 0.70977 |
62f1b3fb4e91bf2dd5c2c5aa304f03deb3859b89 | 2,209 | //
// AppDelegate.swift
// CircularGradientProgressBarDemo
//
// Created by Darius Jankauskas on 24/08/2017.
// Copyright © 2017 Darius Jankauskas. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 47 | 285 | 0.759167 |
876784ca6b1f26937f5ad737f5bbe5842d7e7cd0 | 12,630 | // RUN: %empty-directory(%t)
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk-nosource) -I %t -I %S/Inputs/custom-modules -print-module -source-filename %s -module-to-print=Newtype -skip-unavailable -access-filter-public > %t.printed.A.txt
// RUN: %FileCheck %s -check-prefix=PRINT -strict-whitespace < %t.printed.A.txt
// RUN: %target-typecheck-verify-swift -sdk %clang-importer-sdk -I %S/Inputs/custom-modules -I %t
// REQUIRES: objc_interop
// PRINT-LABEL: struct ErrorDomain : _ObjectiveCBridgeable, Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: String)
// PRINT-NEXT: init(rawValue: String)
// PRINT-NEXT: var rawValue: String { get }
// PRINT-NEXT: typealias RawValue = String
// PRINT-NEXT: typealias _ObjectiveCType = NSString
// PRINT-NEXT: }
// PRINT-NEXT: extension ErrorDomain {
// PRINT-NEXT: func process()
// PRINT-NEXT: static let one: ErrorDomain
// PRINT-NEXT: static let errTwo: ErrorDomain
// PRINT-NEXT: static let three: ErrorDomain
// PRINT-NEXT: static let fourErrorDomain: ErrorDomain
// PRINT-NEXT: static let stillAMember: ErrorDomain
// PRINT-NEXT: }
// PRINT-NEXT: struct Food {
// PRINT-NEXT: init()
// PRINT-NEXT: }
// PRINT-NEXT: extension Food {
// PRINT-NEXT: static let err: ErrorDomain
// PRINT-NEXT: }
// PRINT-NEXT: struct ClosedEnum : _ObjectiveCBridgeable, Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(rawValue: String)
// PRINT-NEXT: var rawValue: String { get }
// PRINT-NEXT: typealias RawValue = String
// PRINT-NEXT: typealias _ObjectiveCType = NSString
// PRINT-NEXT: }
// PRINT-NEXT: extension ClosedEnum {
// PRINT-NEXT: static let firstClosedEntryEnum: ClosedEnum
// PRINT-NEXT: static let secondEntry: ClosedEnum
// PRINT-NEXT: static let thirdEntry: ClosedEnum
// PRINT-NEXT: }
// PRINT-NEXT: struct IUONewtype : _ObjectiveCBridgeable, Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: String)
// PRINT-NEXT: init(rawValue: String)
// PRINT-NEXT: var rawValue: String { get }
// PRINT-NEXT: typealias RawValue = String
// PRINT-NEXT: typealias _ObjectiveCType = NSString
// PRINT-NEXT: }
// PRINT-NEXT: struct MyFloat : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: Float)
// PRINT-NEXT: init(rawValue: Float)
// PRINT-NEXT: let rawValue: Float
// PRINT-NEXT: typealias RawValue = Float
// PRINT-NEXT: }
// PRINT-NEXT: extension MyFloat {
// PRINT-NEXT: static let globalFloat: MyFloat{{$}}
// PRINT-NEXT: static let PI: MyFloat{{$}}
// PRINT-NEXT: static let version: MyFloat{{$}}
// PRINT-NEXT: }
//
// PRINT-LABEL: struct MyInt : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: Int32)
// PRINT-NEXT: init(rawValue: Int32)
// PRINT-NEXT: let rawValue: Int32
// PRINT-NEXT: typealias RawValue = Int32
// PRINT-NEXT: }
// PRINT-NEXT: extension MyInt {
// PRINT-NEXT: static let zero: MyInt{{$}}
// PRINT-NEXT: static let one: MyInt{{$}}
// PRINT-NEXT: }
// PRINT-NEXT: let kRawInt: Int32
// PRINT-NEXT: func takesMyInt(_: MyInt)
//
// PRINT-LABEL: extension NSURLResourceKey {
// PRINT-NEXT: static let isRegularFileKey: NSURLResourceKey
// PRINT-NEXT: static let isDirectoryKey: NSURLResourceKey
// PRINT-NEXT: static let localizedNameKey: NSURLResourceKey
// PRINT-NEXT: }
// PRINT-NEXT: extension NSNotification.Name {
// PRINT-NEXT: static let Foo: NSNotification.Name
// PRINT-NEXT: static let bar: NSNotification.Name
// PRINT-NEXT: static let NSWibble: NSNotification.Name
// PRINT-NEXT: }
// PRINT-NEXT: let kNotification: String
// PRINT-NEXT: let Notification: String
// PRINT-NEXT: let swiftNamedNotification: String
//
// PRINT-LABEL: struct CFNewType : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: CFString)
// PRINT-NEXT: init(rawValue: CFString)
// PRINT-NEXT: let rawValue: CFString
// PRINT-NEXT: typealias RawValue = CFString
// PRINT-NEXT: }
// PRINT-NEXT: extension CFNewType {
// PRINT-NEXT: static let MyCFNewTypeValue: CFNewType
// PRINT-NEXT: static let MyCFNewTypeValueUnauditedButConst: CFNewType
// PRINT-NEXT: static var MyCFNewTypeValueUnaudited: Unmanaged<CFString>
// PRINT-NEXT: }
// PRINT-NEXT: func FooAudited() -> CFNewType
// PRINT-NEXT: func FooUnaudited() -> Unmanaged<CFString>
//
// PRINT-LABEL: struct MyABINewType : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: CFString)
// PRINT-NEXT: init(rawValue: CFString)
// PRINT-NEXT: let rawValue: CFString
// PRINT-NEXT: typealias RawValue = CFString
// PRINT-NEXT: }
// PRINT-NEXT: typealias MyABIOldType = CFString
// PRINT-NEXT: extension MyABINewType {
// PRINT-NEXT: static let global: MyABINewType!
// PRINT-NEXT: }
// PRINT-NEXT: let kMyABIOldTypeGlobal: MyABIOldType!
// PRINT-NEXT: func getMyABINewType() -> MyABINewType!
// PRINT-NEXT: func getMyABIOldType() -> MyABIOldType!
// PRINT-NEXT: func takeMyABINewType(_: MyABINewType!)
// PRINT-NEXT: func takeMyABIOldType(_: MyABIOldType!)
// PRINT-NEXT: func takeMyABINewTypeNonNull(_: MyABINewType)
// PRINT-NEXT: func takeMyABIOldTypeNonNull(_: MyABIOldType)
// PRINT-LABEL: struct MyABINewTypeNS : _ObjectiveCBridgeable, Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: String)
// PRINT-NEXT: init(rawValue: String)
// PRINT-NEXT: var rawValue: String { get }
// PRINT-NEXT: typealias RawValue = String
// PRINT-NEXT: typealias _ObjectiveCType = NSString
// PRINT-NEXT: }
// PRINT-NEXT: typealias MyABIOldTypeNS = NSString
// PRINT-NEXT: func getMyABINewTypeNS() -> MyABINewTypeNS!
// PRINT-NEXT: func getMyABIOldTypeNS() -> String!
// PRINT-NEXT: func takeMyABINewTypeNonNullNS(_: MyABINewTypeNS)
// PRINT-NEXT: func takeMyABIOldTypeNonNullNS(_: String)
//
// PRINT-NEXT: struct NSSomeContext {
// PRINT-NEXT: init()
// PRINT-NEXT: init(i: Int32)
// PRINT-NEXT: var i: Int32
// PRINT-NEXT: }
// PRINT-NEXT: extension NSSomeContext {
// PRINT-NEXT: struct Name : _ObjectiveCBridgeable, Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: String)
// PRINT-NEXT: init(rawValue: String)
// PRINT-NEXT: var rawValue: String { get }
// PRINT-NEXT: typealias RawValue = String
// PRINT-NEXT: typealias _ObjectiveCType = NSString
// PRINT-NEXT: }
// PRINT-NEXT: }
// PRINT-NEXT: extension NSSomeContext.Name {
// PRINT-NEXT: static let myContextName: NSSomeContext.Name
// PRINT-NEXT: }
//
// PRINT-NEXT: struct TRef : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: OpaquePointer)
// PRINT-NEXT: init(rawValue: OpaquePointer)
// PRINT-NEXT: let rawValue: OpaquePointer
// PRINT-NEXT: typealias RawValue = OpaquePointer
// PRINT-NEXT: }
// PRINT-NEXT: struct ConstTRef : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: OpaquePointer)
// PRINT-NEXT: init(rawValue: OpaquePointer)
// PRINT-NEXT: let rawValue: OpaquePointer
// PRINT-NEXT: typealias RawValue = OpaquePointer
// PRINT-NEXT: }
// PRINT-NEXT: func create_T() -> TRef
// PRINT-NEXT: func create_ConstT() -> ConstTRef
// PRINT-NEXT: func destroy_T(_: TRef!)
// PRINT-NEXT: func destroy_ConstT(_: ConstTRef!)
// PRINT-NEXT: extension TRef {
// PRINT-NEXT: func mutatePointee()
// PRINT-NEXT: mutating func mutate()
// PRINT-NEXT: }
// PRINT-NEXT: extension ConstTRef {
// PRINT-NEXT: func use()
// PRINT-NEXT: }
//
// PRINT-NEXT: struct TRefRef : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: UnsafeMutablePointer<OpaquePointer>)
// PRINT-NEXT: init(rawValue: UnsafeMutablePointer<OpaquePointer>)
// PRINT-NEXT: let rawValue: UnsafeMutablePointer<OpaquePointer>
// PRINT-NEXT: typealias RawValue = UnsafeMutablePointer<OpaquePointer>
// PRINT-NEXT: }
// PRINT-NEXT: struct ConstTRefRef : Hashable, Equatable, _SwiftNewtypeWrapper, RawRepresentable, @unchecked Sendable {
// PRINT-NEXT: init(_ rawValue: UnsafePointer<OpaquePointer>)
// PRINT-NEXT: init(rawValue: UnsafePointer<OpaquePointer>)
// PRINT-NEXT: let rawValue: UnsafePointer<OpaquePointer>
// PRINT-NEXT: typealias RawValue = UnsafePointer<OpaquePointer>
// PRINT-NEXT: }
// PRINT-NEXT: func create_TRef() -> TRefRef
// PRINT-NEXT: func create_ConstTRef() -> ConstTRefRef
// PRINT-NEXT: func destroy_TRef(_: TRefRef!)
// PRINT-NEXT: func destroy_ConstTRef(_: ConstTRefRef!)
// PRINT-NEXT: extension TRefRef {
// PRINT-NEXT: func mutatePointee()
// PRINT-NEXT: mutating func mutate()
// PRINT-NEXT: }
// PRINT-NEXT: extension ConstTRefRef {
// PRINT-NEXT: func use()
// PRINT-NEXT: }
import Newtype
func tests() {
let errOne = ErrorDomain.one
errOne.process()
let fooErr = Food.err
fooErr.process()
Food().process() // expected-error{{value of type 'Food' has no member 'process'}}
let thirdEnum = ClosedEnum.thirdEntry
thirdEnum.process()
// expected-error@-1{{value of type 'ClosedEnum' has no member 'process'}}
let _ = ErrorDomain(rawValue: thirdEnum.rawValue)
let _ = ClosedEnum(rawValue: errOne.rawValue)
let _ = NSNotification.Name.Foo
let _ = NSNotification.Name.bar
let _ : CFNewType = CFNewType.MyCFNewTypeValue
let _ : CFNewType = CFNewType.MyCFNewTypeValueUnauditedButConst
let _ : CFNewType = CFNewType.MyCFNewTypeValueUnaudited
// expected-error@-1{{cannot convert value of type 'Unmanaged<CFString>?' to specified type 'CFNewType'}}
}
func acceptSwiftNewtypeWrapper<T : _SwiftNewtypeWrapper>(_ t: T) { }
func acceptEquatable<T : Equatable>(_ t: T) { }
func acceptHashable<T : Hashable>(_ t: T) { }
func acceptObjectiveCBridgeable<T : _ObjectiveCBridgeable>(_ t: T) { }
func testConformances(ed: ErrorDomain) {
acceptSwiftNewtypeWrapper(ed)
acceptEquatable(ed)
acceptHashable(ed)
acceptObjectiveCBridgeable(ed)
}
func testFixit() {
let _ = NSMyContextName
// expected-error@-1{{'NSMyContextName' has been renamed to 'NSSomeContext.Name.myContextName'}} {{10-25=NSSomeContext.Name.myContextName}}
}
func testNonEphemeralInitParams(x: OpaquePointer) {
var x = x
_ = TRefRef(&x) // expected-warning {{inout expression creates a temporary pointer, but argument #1 should be a pointer that outlives the call to 'init(_:)'}}
// expected-note@-1 {{implicit argument conversion from 'OpaquePointer' to 'UnsafeMutablePointer<OpaquePointer>' produces a pointer valid only for the duration of the call}}
// expected-note@-2 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = TRefRef(rawValue: &x) // expected-warning {{inout expression creates a temporary pointer, but argument 'rawValue' should be a pointer that outlives the call to 'init(rawValue:)'}}
// expected-note@-1 {{implicit argument conversion from 'OpaquePointer' to 'UnsafeMutablePointer<OpaquePointer>' produces a pointer valid only for the duration of the call}}
// expected-note@-2 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = ConstTRefRef(&x) // expected-warning {{inout expression creates a temporary pointer, but argument #1 should be a pointer that outlives the call to 'init(_:)'}}
// expected-note@-1 {{implicit argument conversion from 'OpaquePointer' to 'UnsafePointer<OpaquePointer>' produces a pointer valid only for the duration of the call}}
// expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = ConstTRefRef(rawValue: &x) // expected-warning {{inout expression creates a temporary pointer, but argument 'rawValue' should be a pointer that outlives the call to 'init(rawValue:)'}}
// expected-note@-1 {{implicit argument conversion from 'OpaquePointer' to 'UnsafePointer<OpaquePointer>' produces a pointer valid only for the duration of the call}}
// expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
}
| 49.143969 | 222 | 0.726524 |
216a4f500cc8f92d672cccc5cfa8b153b2121edb | 988 | //
// Duolingo.swift
// Appz
//
// Created by MARYAM ALJAME on 2/19/18.
// Copyright © 2018 kitz. All rights reserved.
//
public extension Applications {
public struct Duolingo: ExternalApplication {
public typealias ActionType = Applications.Duolingo.Action
public let scheme = "duolingo:"
public let fallbackURL = "https://www.duolingo.com"
public let appStoreId = "570060128"
public init() {}
}
}
// MARK: - Actions
public extension Applications.Duolingo {
public enum Action {
case open
}
}
extension Applications.Duolingo.Action: ExternalApplicationAction {
public var paths: ActionPaths {
switch self {
case .open:
return ActionPaths(
app: Path(
pathComponents: ["app"],
queryParameters: [:]
),
web: Path()
)
}
}
}
| 20.583333 | 67 | 0.538462 |
9c75018eab2b7a52637dfa5d443b46b62264c34f | 1,343 | // Copyright © 2020 Mark Moeykens. All rights reserved. | @BigMtnStudio
import SwiftUI
struct MGE_Shapes: View {
@State private var changeView = false
@Namespace var namespace
var body: some View {
VStack(spacing: 20.0) {
TitleText("MatchedGeometryEffect")
SubtitleText("Shapes")
BannerText("Shapes are great candidates for the matchedGeometryEffect. You can smoothly transition from one shape to another without much problem.", backColor: .green, textColor: .black)
Spacer()
if changeView {
Rectangle()
.fill(Color.green)
.overlay(Text("View 2"))
.matchedGeometryEffect(id: "change", in: namespace)
.onTapGesture { changeView.toggle() }
} else {
Circle()
.fill(Color.green)
.overlay(Text("View 1"))
.matchedGeometryEffect(id: "change", in: namespace)
.frame(width: 100, height: 100)
.onTapGesture { changeView.toggle() }
}
}
.animation(.default)
.font(.title)
}
}
struct MGE_Shapes_Previews: PreviewProvider {
static var previews: some View {
MGE_Shapes()
}
}
| 32.756098 | 198 | 0.539092 |
8955783e8466184445e1738e1d250593235d1a74 | 959 | //
// FavoritesInterfaces.swift
// Superheroes
//
// Created by Adam Cseke on 2022. 03. 02..
// Copyright (c) 2022. levivig. All rights reserved.
//
// This file was generated by the 🐍 VIPER generator
//
import UIKit
protocol FavoritesWireframeInterface: WireframeInterface {
func pushToDetails(hero: Heroes)
}
protocol FavoritesViewInterface: ViewInterface {
func reloadCollectionView()
}
protocol FavoritesPresenterInterface: PresenterInterface {
func numberOfSections() -> Int
func numberOfItem(in section: Int) -> Int
func cellForItem(at indexPath: IndexPath) -> Heroes
func getFavorites()
func favoritesButtonTapped(indexPath: IndexPath)
func pushToDetails(hero: Heroes)
}
protocol FavoritesInteractorInterface: InteractorInterface {
func isInTheFavorites(entity: Heroes) -> Bool
func delete(entity: Heroes, completion: BoolCompletition?)
func insert(entity: Heroes, completion: BoolCompletition?)
}
| 27.4 | 62 | 0.749739 |
e81154a2ae7c507093d3b7ea744e268b5ec5f3d9 | 14,244 | //
// Copyright © 2019 Essential Developer. All rights reserved.
//
import XCTest
import UIKit
import MVC
import FeedFeature
final class FeedUIIntegrationTests: XCTestCase {
func test_feedView_hasTitle() {
let (sut, _) = makeSUT()
sut.loadViewIfNeeded()
XCTAssertEqual(sut.title, localized("FEED_VIEW_TITLE"))
}
func test_loadFeedActions_requestFeedFromLoader() {
let (sut, loader) = makeSUT()
XCTAssertEqual(loader.loadFeedCallCount, 0, "Expected no loading requests before view is loaded")
sut.loadViewIfNeeded()
XCTAssertEqual(loader.loadFeedCallCount, 1, "Expected a loading request once view is loaded")
sut.simulateUserInitiatedFeedReload()
XCTAssertEqual(loader.loadFeedCallCount, 2, "Expected another loading request once user initiates a reload")
sut.simulateUserInitiatedFeedReload()
XCTAssertEqual(loader.loadFeedCallCount, 3, "Expected yet another loading request once user initiates another reload")
}
func test_loadingFeedIndicator_isVisibleWhileLoadingFeed() {
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
XCTAssertTrue(sut.isShowingLoadingIndicator, "Expected loading indicator once view is loaded")
loader.completeFeedLoading(at: 0)
XCTAssertFalse(sut.isShowingLoadingIndicator, "Expected no loading indicator once loading completes successfully")
sut.simulateUserInitiatedFeedReload()
XCTAssertTrue(sut.isShowingLoadingIndicator, "Expected loading indicator once user initiates a reload")
loader.completeFeedLoadingWithError(at: 1)
XCTAssertFalse(sut.isShowingLoadingIndicator, "Expected no loading indicator once user initiated loading completes with error")
}
func test_loadFeedCompletion_rendersSuccessfullyLoadedFeed() {
let image0 = makeImage(description: "a description", location: "a location")
let image1 = makeImage(description: nil, location: "another location")
let image2 = makeImage(description: "another description", location: nil)
let image3 = makeImage(description: nil, location: nil)
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
assertThat(sut, isRendering: [])
loader.completeFeedLoading(with: [image0], at: 0)
assertThat(sut, isRendering: [image0])
sut.simulateUserInitiatedFeedReload()
loader.completeFeedLoading(with: [image0, image1, image2, image3], at: 1)
assertThat(sut, isRendering: [image0, image1, image2, image3])
}
func test_loadFeedCompletion_doesNotAlterCurrentRenderingStateOnError() {
let image0 = makeImage()
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [image0], at: 0)
assertThat(sut, isRendering: [image0])
sut.simulateUserInitiatedFeedReload()
loader.completeFeedLoadingWithError(at: 1)
assertThat(sut, isRendering: [image0])
}
func test_loadFeedCompletion_rendersErrorMessageOnErrorUntilNextReload() {
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
XCTAssertEqual(sut.errorMessage, nil)
loader.completeFeedLoadingWithError(at: 0)
XCTAssertEqual(sut.errorMessage, localized("FEED_VIEW_CONNECTION_ERROR"))
sut.simulateUserInitiatedFeedReload()
XCTAssertEqual(sut.errorMessage, nil)
}
func test_errorView_dismissesErrorMessageOnTap() {
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
XCTAssertEqual(sut.errorMessage, nil)
loader.completeFeedLoadingWithError(at: 0)
XCTAssertEqual(sut.errorMessage, localized("FEED_VIEW_CONNECTION_ERROR"))
sut.simulateTapOnErrorMessage()
XCTAssertEqual(sut.errorMessage, nil)
}
func test_feedImageView_loadsImageURLWhenVisible() {
let image0 = makeImage(url: URL(string: "http://url-0.com")!)
let image1 = makeImage(url: URL(string: "http://url-1.com")!)
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [image0, image1])
XCTAssertEqual(loader.loadedImageURLs, [], "Expected no image URL requests until views become visible")
sut.simulateFeedImageViewVisible(at: 0)
XCTAssertEqual(loader.loadedImageURLs, [image0.url], "Expected first image URL request once first view becomes visible")
sut.simulateFeedImageViewVisible(at: 1)
XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected second image URL request once second view also becomes visible")
}
func test_feedImageView_cancelsImageLoadingWhenNotVisibleAnymore() {
let image0 = makeImage(url: URL(string: "http://url-0.com")!)
let image1 = makeImage(url: URL(string: "http://url-1.com")!)
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [image0, image1])
XCTAssertEqual(loader.cancelledImageURLs, [], "Expected no cancelled image URL requests until image is not visible")
sut.simulateFeedImageViewNotVisible(at: 0)
XCTAssertEqual(loader.cancelledImageURLs, [image0.url], "Expected one cancelled image URL request once first image is not visible anymore")
sut.simulateFeedImageViewNotVisible(at: 1)
XCTAssertEqual(loader.cancelledImageURLs, [image0.url, image1.url], "Expected two cancelled image URL requests once second image is also not visible anymore")
}
func test_feedImageViewLoadingIndicator_isVisibleWhileLoadingImage() {
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [makeImage(), makeImage()])
let view0 = sut.simulateFeedImageViewVisible(at: 0)
let view1 = sut.simulateFeedImageViewVisible(at: 1)
XCTAssertEqual(view0?.isShowingImageLoadingIndicator, true, "Expected loading indicator for first view while loading first image")
XCTAssertEqual(view1?.isShowingImageLoadingIndicator, true, "Expected loading indicator for second view while loading second image")
loader.completeImageLoading(at: 0)
XCTAssertEqual(view0?.isShowingImageLoadingIndicator, false, "Expected no loading indicator for first view once first image loading completes successfully")
XCTAssertEqual(view1?.isShowingImageLoadingIndicator, true, "Expected no loading indicator state change for second view once first image loading completes successfully")
loader.completeImageLoadingWithError(at: 1)
XCTAssertEqual(view0?.isShowingImageLoadingIndicator, false, "Expected no loading indicator state change for first view once second image loading completes with error")
XCTAssertEqual(view1?.isShowingImageLoadingIndicator, false, "Expected no loading indicator for second view once second image loading completes with error")
}
func test_feedImageView_rendersImageLoadedFromURL() {
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [makeImage(), makeImage()])
let view0 = sut.simulateFeedImageViewVisible(at: 0)
let view1 = sut.simulateFeedImageViewVisible(at: 1)
XCTAssertEqual(view0?.renderedImage, .none, "Expected no image for first view while loading first image")
XCTAssertEqual(view1?.renderedImage, .none, "Expected no image for second view while loading second image")
let imageData0 = UIImage.make(withColor: .red).pngData()!
loader.completeImageLoading(with: imageData0, at: 0)
XCTAssertEqual(view0?.renderedImage, imageData0, "Expected image for first view once first image loading completes successfully")
XCTAssertEqual(view1?.renderedImage, .none, "Expected no image state change for second view once first image loading completes successfully")
let imageData1 = UIImage.make(withColor: .blue).pngData()!
loader.completeImageLoading(with: imageData1, at: 1)
XCTAssertEqual(view0?.renderedImage, imageData0, "Expected no image state change for first view once second image loading completes successfully")
XCTAssertEqual(view1?.renderedImage, imageData1, "Expected image for second view once second image loading completes successfully")
}
func test_feedImageViewRetryButton_isVisibleOnImageURLLoadError() {
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [makeImage(), makeImage()])
let view0 = sut.simulateFeedImageViewVisible(at: 0)
let view1 = sut.simulateFeedImageViewVisible(at: 1)
XCTAssertEqual(view0?.isShowingRetryAction, false, "Expected no retry action for first view while loading first image")
XCTAssertEqual(view1?.isShowingRetryAction, false, "Expected no retry action for second view while loading second image")
let imageData = UIImage.make(withColor: .red).pngData()!
loader.completeImageLoading(with: imageData, at: 0)
XCTAssertEqual(view0?.isShowingRetryAction, false, "Expected no retry action for first view once first image loading completes successfully")
XCTAssertEqual(view1?.isShowingRetryAction, false, "Expected no retry action state change for second view once first image loading completes successfully")
loader.completeImageLoadingWithError(at: 1)
XCTAssertEqual(view0?.isShowingRetryAction, false, "Expected no retry action state change for first view once second image loading completes with error")
XCTAssertEqual(view1?.isShowingRetryAction, true, "Expected retry action for second view once second image loading completes with error")
}
func test_feedImageViewRetryButton_isVisibleOnInvalidImageData() {
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [makeImage()])
let view = sut.simulateFeedImageViewVisible(at: 0)
XCTAssertEqual(view?.isShowingRetryAction, false, "Expected no retry action while loading image")
let invalidImageData = Data("invalid image data".utf8)
loader.completeImageLoading(with: invalidImageData, at: 0)
XCTAssertEqual(view?.isShowingRetryAction, true, "Expected retry action once image loading completes with invalid image data")
}
func test_feedImageViewRetryAction_retriesImageLoad() {
let image0 = makeImage(url: URL(string: "http://url-0.com")!)
let image1 = makeImage(url: URL(string: "http://url-1.com")!)
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [image0, image1])
let view0 = sut.simulateFeedImageViewVisible(at: 0)
let view1 = sut.simulateFeedImageViewVisible(at: 1)
XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected two image URL request for the two visible views")
loader.completeImageLoadingWithError(at: 0)
loader.completeImageLoadingWithError(at: 1)
XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected only two image URL requests before retry action")
view0?.simulateRetryAction()
XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url, image0.url], "Expected third imageURL request after first view retry action")
view1?.simulateRetryAction()
XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url, image0.url, image1.url], "Expected fourth imageURL request after second view retry action")
}
func test_feedImageView_preloadsImageURLWhenNearVisible() {
let image0 = makeImage(url: URL(string: "http://url-0.com")!)
let image1 = makeImage(url: URL(string: "http://url-1.com")!)
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [image0, image1])
XCTAssertEqual(loader.loadedImageURLs, [], "Expected no image URL requests until image is near visible")
sut.simulateFeedImageViewNearVisible(at: 0)
XCTAssertEqual(loader.loadedImageURLs, [image0.url], "Expected first image URL request once first image is near visible")
sut.simulateFeedImageViewNearVisible(at: 1)
XCTAssertEqual(loader.loadedImageURLs, [image0.url, image1.url], "Expected second image URL request once second image is near visible")
}
func test_feedImageView_cancelsImageURLPreloadingWhenNotNearVisibleAnymore() {
let image0 = makeImage(url: URL(string: "http://url-0.com")!)
let image1 = makeImage(url: URL(string: "http://url-1.com")!)
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [image0, image1])
XCTAssertEqual(loader.cancelledImageURLs, [], "Expected no cancelled image URL requests until image is not near visible")
sut.simulateFeedImageViewNotNearVisible(at: 0)
XCTAssertEqual(loader.cancelledImageURLs, [image0.url], "Expected first cancelled image URL request once first image is not near visible anymore")
sut.simulateFeedImageViewNotNearVisible(at: 1)
XCTAssertEqual(loader.cancelledImageURLs, [image0.url, image1.url], "Expected second cancelled image URL request once second image is not near visible anymore")
}
func test_feedImageView_doesNotRenderLoadedImageWhenNotVisibleAnymore() {
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [makeImage()])
let view = sut.simulateFeedImageViewNotVisible(at: 0)
loader.completeImageLoading(with: anyImageData())
XCTAssertNil(view?.renderedImage, "Expected no rendered image when an image load finishes after the view is not visible anymore")
}
func test_loadFeedCompletion_dispatchesFromBackgroundToMainThread() {
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
let exp = expectation(description: "Wait for background queue")
DispatchQueue.global().async {
loader.completeFeedLoading(at: 0)
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
}
func test_loadImageDataCompletion_dispatchesFromBackgroundToMainThread() {
let (sut, loader) = makeSUT()
sut.loadViewIfNeeded()
loader.completeFeedLoading(with: [makeImage()])
_ = sut.simulateFeedImageViewVisible(at: 0)
let exp = expectation(description: "Wait for background queue")
DispatchQueue.global().async {
loader.completeImageLoading(with: self.anyImageData(), at: 0)
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
}
// MARK: - Helpers
private func makeSUT(file: StaticString = #filePath, line: UInt = #line) -> (sut: FeedViewController, loader: LoaderSpy) {
let loader = LoaderSpy()
let sut = FeedUIComposer.feedComposedWith(feedLoader: loader, imageLoader: loader)
trackForMemoryLeaks(loader, file: file, line: line)
trackForMemoryLeaks(sut, file: file, line: line)
return (sut, loader)
}
private func makeImage(description: String? = nil, location: String? = nil, url: URL = URL(string: "http://any-url.com")!) -> FeedImage {
return FeedImage(id: UUID(), description: description, location: location, url: url)
}
private func anyImageData() -> Data {
return UIImage.make(withColor: .red).pngData()!
}
}
| 43.559633 | 171 | 0.776818 |
914a8c2e0e66a286b331f7b4efda4cac1eefcdc9 | 7,142 | //
// YSBangumiHeaderItemView.swift
// ysbilibili
//
// Created by MOLBASE on 2017/8/7.
// Copyright © 2017年 YangShen. All rights reserved.
//
import UIKit
fileprivate let kBangumiItemCellReuseKey = "kBangumiItemCellReuseKey"
class YSBangumiHeaderItemView: UIView {
var listArray: [YSBangumiCollectModel]? {
didSet{
contentCollectionView.reloadData()
if let count = listArray?.count {
titleRightLabel.text = "更新至 第\(count)话"
}
}
}
// MARK - 懒加载控件
fileprivate lazy var contentCollectionView: UICollectionView = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .horizontal
flowLayout.itemSize = CGSize(width: kScreenWidth/2.7, height: 80)
let contentCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
contentCollectionView.delegate = self
contentCollectionView.dataSource = self
contentCollectionView.backgroundColor = kHomeBackColor
contentCollectionView.register(YSBangumiItemCollectionCell.self, forCellWithReuseIdentifier: kBangumiItemCellReuseKey)
contentCollectionView.contentInset = UIEdgeInsetsMake(0, 20, 0, 20)
return contentCollectionView
}()
fileprivate lazy var titleLeftLabel: UILabel = {
let titleLeftLabel = UILabel()
titleLeftLabel.text = "选集"
return titleLeftLabel
}()
lazy var titleRightLabel : UILabel = {
let titleRightLabel = UILabel()
titleRightLabel.textColor = UIColor.lightGray
titleRightLabel.font = UIFont.systemFont(ofSize: 14)
return titleRightLabel
}()
lazy var titleArrowImageView: UIImageView = {
let titleArrowImageView = UIImageView()
titleArrowImageView.image = UIImage(named: "more_arrow")
titleArrowImageView.contentMode = .center
return titleArrowImageView
}()
lazy var lineView: UIImageView = {
let lineView = UIImageView()
lineView.backgroundColor = kCellLineGrayColor
return lineView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(contentCollectionView)
self.addSubview(titleArrowImageView)
self.addSubview(titleRightLabel)
self.addSubview(titleLeftLabel)
self.addSubview(lineView)
self.backgroundColor = kHomeBackColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
titleLeftLabel.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(15)
make.top.equalTo(self).offset(15)
}
titleArrowImageView.snp.makeConstraints { (make) in
make.centerY.equalTo(titleLeftLabel)
make.right.equalTo(self).offset(-10)
make.size.equalTo(CGSize(width: 25, height: 25))
}
titleRightLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(titleArrowImageView)
make.right.equalTo(titleArrowImageView.snp.left).offset(-5)
}
contentCollectionView.snp.makeConstraints { (make) in
make.top.equalTo(titleLeftLabel.snp.bottom).offset(15)
make.left.right.equalTo(self)
make.bottom.equalTo(self).offset(-15)
}
lineView.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(self)
make.height.equalTo(0.5)
}
}
}
//======================================================================
// MARK:- collectionView delegate datasource
//======================================================================
extension YSBangumiHeaderItemView: UICollectionViewDelegate,UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let count = listArray?.count else {return 0}
return count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kBangumiItemCellReuseKey, for: indexPath) as! YSBangumiItemCollectionCell
cell.index = indexPath.row
if let listModel = listArray?[indexPath.row] {
cell.detailModel = listModel
}
if (listArray?.count) != nil {
if indexPath.row == 0 {
cell.isShowing = true
}else {
cell.isShowing = false
}
}
return cell
}
}
//======================================================================
// MARK:- collcetionview cell
//======================================================================
class YSBangumiItemCollectionCell: UICollectionViewCell {
var index: Int = 0 {
didSet {
titleLabel.text = "第\(index + 1)话"
}
}
var detailModel: YSBangumiCollectModel? {
didSet {
guard let content = detailModel?.index_title else {return}
contentLabel.text = content
}
}
var isShowing = false {
didSet {
if isShowing {
self.ysBorderColor = kNavBarColor
titleLabel.textColor = kNavBarColor
contentLabel.textColor = kNavBarColor
} else {
self.ysBorderColor = UIColor.lightGray
titleLabel.textColor = UIColor.black
contentLabel.textColor = UIColor.black
}
}
}
// MARK - 懒加载控件
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.text = "title"
titleLabel.font = UIFont.systemFont(ofSize: 15)
return titleLabel
}()
lazy var contentLabel: UILabel = {
let contentLabel = UILabel()
contentLabel.text = "lalal"
contentLabel.font = UIFont.systemFont(ofSize: 12)
contentLabel.numberOfLines = 0
return contentLabel
}()
// MARK - life cycle
override init(frame: CGRect) {
super.init(frame: frame)
self.ysBorderColor = UIColor.lightGray
self.ysCornerRadius = 5
self.ysBorderWidth = 1
self.backgroundColor = UIColor.white
self.addSubview(titleLabel)
self.addSubview(contentLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(10)
make.top.equalTo(self)
}
contentLabel.snp.makeConstraints { (make) in
make.left.equalTo(titleLabel)
make.right.equalTo(self).offset(-10)
make.top.equalTo(titleLabel.snp.bottom)
make.bottom.equalTo(self).offset(-10)
}
}
}
| 33.848341 | 148 | 0.601652 |
e25a7c88cc7b515c64d246c93f280084df6688c9 | 244 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
case
let
{
for {
func i( ) {
protocol P {
class B
{
let a {
class
case ,
| 14.352941 | 87 | 0.713115 |
69cd345200f287c6c4cc32f7f513bce1f2451c1a | 881 | //
// extension.swift
// YouTube
//
// Created by Haik Aslanyan on 6/24/16.
// Copyright © 2016 Haik Aslanyan. All rights reserved.
//
import UIKit
// uicolor init simplified
extension UIColor{
class func rbg(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
let color = UIColor.init(red: r/255, green: g/255, blue: b/255, alpha: 1)
return color
}
}
// UIImage with downloadable content
extension UIImage {
class func contentOfURL(link: String) -> UIImage {
let url = URL.init(string: link)!
var image = UIImage()
do{
let data = try Data.init(contentsOf: url)
image = UIImage.init(data: data)!
} catch _ {
print("error downloading images")
}
return image
}
}
enum stateOfVC {
case minimized
case fullScreen
case hidden
}
enum Direction {
case up
case left
case none
}
| 18.744681 | 81 | 0.624291 |
038bf7ce0eca5a545484cd10b662c1e17824472a | 7,124 | import UIKit
@objc (WMFNavigationBarHiderDelegate)
public protocol NavigationBarHiderDelegate: NSObjectProtocol {
func navigationBarHider(_ hider: NavigationBarHider, didSetNavigationBarPercentHidden: CGFloat, extendedViewPercentHidden: CGFloat, animated: Bool)
}
extension CGFloat {
func wmf_adjustedForRange(_ lower: CGFloat, upper: CGFloat, step: CGFloat) -> CGFloat {
if self < lower + step {
return lower
} else if self > upper - step {
return upper
} else if isNaN || isInfinite {
return lower
} else {
return self
}
}
var wmf_normalizedPercentage: CGFloat {
return wmf_adjustedForRange(0, upper: 1, step: 0.01)
}
}
@objc(WMFNavigationBarHider)
public class NavigationBarHider: NSObject {
@objc public weak var navigationBar: NavigationBar?
@objc public weak var delegate: NavigationBarHiderDelegate?
fileprivate var isUserScrolling: Bool = false
fileprivate var isScrollingToTop: Bool = false
var initialScrollY: CGFloat = 0
var initialNavigationBarPercentHidden: CGFloat = 0
public var isNavigationBarHidingEnabled: Bool = true // setting this to false will only hide the extended view
@objc public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
guard let navigationBar = navigationBar else {
return
}
isUserScrolling = true
initialScrollY = scrollView.contentOffset.y + scrollView.contentInset.top
initialNavigationBarPercentHidden = navigationBar.navigationBarPercentHidden
}
@objc public func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard let navigationBar = navigationBar else {
return
}
guard isUserScrolling || isScrollingToTop else {
return
}
let animated = false
let currentExtendedViewPercentHidden = navigationBar.extendedViewPercentHidden
let currentNavigationBarPercentHidden = navigationBar.navigationBarPercentHidden
var extendedViewPercentHidden = currentExtendedViewPercentHidden
var navigationBarPercentHidden = currentNavigationBarPercentHidden
let scrollY = scrollView.contentOffset.y + scrollView.contentInset.top
let extendedViewHeight = navigationBar.extendedView.frame.size.height
if extendedViewHeight > 0 {
extendedViewPercentHidden = (scrollY/extendedViewHeight).wmf_normalizedPercentage
}
let barHeight = navigationBar.bar.frame.size.height
if !isNavigationBarHidingEnabled {
navigationBarPercentHidden = 0
} else if initialScrollY < extendedViewHeight + barHeight {
navigationBarPercentHidden = ((scrollY - extendedViewHeight)/barHeight).wmf_normalizedPercentage
} else if scrollY <= extendedViewHeight + barHeight {
navigationBarPercentHidden = min(initialNavigationBarPercentHidden, ((scrollY - extendedViewHeight)/barHeight).wmf_normalizedPercentage)
} else if initialNavigationBarPercentHidden == 0 && initialScrollY > extendedViewHeight + barHeight {
navigationBarPercentHidden = ((scrollY - initialScrollY)/barHeight).wmf_normalizedPercentage
}
guard currentExtendedViewPercentHidden != extendedViewPercentHidden || currentNavigationBarPercentHidden != navigationBarPercentHidden else {
return
}
navigationBar.setNavigationBarPercentHidden(navigationBarPercentHidden, extendedViewPercentHidden: extendedViewPercentHidden, animated: animated, additionalAnimations:{
self.delegate?.navigationBarHider(self, didSetNavigationBarPercentHidden: navigationBarPercentHidden, extendedViewPercentHidden: extendedViewPercentHidden, animated: animated)
})
}
@objc public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
guard let navigationBar = navigationBar else {
return
}
let extendedViewHeight = navigationBar.extendedView.frame.size.height
let barHeight = navigationBar.bar.frame.size.height
let top = 0 - scrollView.contentInset.top
let targetOffsetY = targetContentOffset.pointee.y - top
if targetOffsetY < extendedViewHeight + barHeight {
if targetOffsetY < 0.5 * extendedViewHeight { // both visible
targetContentOffset.pointee = CGPoint(x: 0, y: top)
} else if targetOffsetY < extendedViewHeight + 0.5 * barHeight { // only nav bar visible
targetContentOffset.pointee = CGPoint(x: 0, y: top + extendedViewHeight)
} else if targetOffsetY < extendedViewHeight + barHeight {
targetContentOffset.pointee = CGPoint(x: 0, y: top + extendedViewHeight + barHeight)
}
return
}
if initialScrollY < extendedViewHeight + barHeight && targetOffsetY > extendedViewHeight + barHeight { // let it naturally hide
return
}
isUserScrolling = false
let animated = true
let extendedViewPercentHidden = navigationBar.extendedViewPercentHidden
let currentNavigationBarPercentHidden = navigationBar.navigationBarPercentHidden
var navigationBarPercentHidden: CGFloat = currentNavigationBarPercentHidden
if !isNavigationBarHidingEnabled {
navigationBarPercentHidden = 0
} else if velocity.y > 0 {
navigationBarPercentHidden = 1
} else if velocity.y < 0 {
navigationBarPercentHidden = 0
} else if navigationBarPercentHidden < 0.5 {
navigationBarPercentHidden = 0
} else {
navigationBarPercentHidden = 1
}
guard navigationBarPercentHidden != currentNavigationBarPercentHidden else {
return
}
navigationBar.setNavigationBarPercentHidden(navigationBarPercentHidden, extendedViewPercentHidden: extendedViewPercentHidden, animated: animated, additionalAnimations:{
self.delegate?.navigationBarHider(self, didSetNavigationBarPercentHidden: navigationBarPercentHidden, extendedViewPercentHidden: extendedViewPercentHidden, animated: animated)
})
}
@objc public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
isUserScrolling = false
}
@objc public func scrollViewWillScrollToTop(_ scrollView: UIScrollView) {
guard let navigationBar = navigationBar else {
return
}
initialNavigationBarPercentHidden = navigationBar.navigationBarPercentHidden
initialScrollY = scrollView.contentOffset.y + scrollView.contentInset.top
isScrollingToTop = true
}
@objc public func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
isScrollingToTop = false
}
@objc public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
isScrollingToTop = false
}
}
| 43.439024 | 187 | 0.702555 |
9c343cc191bc5531d6112255e102d02b9bdb50f3 | 4,410 | //
// Amount.swift
// Zesame
//
// Created by Alexander Cyon on 2018-05-25.
// Copyright © 2018 Open Zesame. All rights reserved.
//
import Foundation
import BigInt
extension Double {
var decimal: Double {
return truncatingRemainder(dividingBy: 1)
}
}
private extension Amount {
static var inversionOfSmallestFraction: Double {
return pow(10, Double(Amount.decimals))
}
}
public struct Amount {
public static let totalSupply: Double = 21000000000 // 21 billion Zillings is the total supply
public static let decimals: Int = 12
/// Actually storing the value inside a Double results in limitations, we can only store 15 digits without losing precision. Please take a look at the table below to see the number of decimals you get precision with given the integer part:
/// 20 999 999 999.9991 //11 + 4
/// 9 999 999 999.99991 //10 + 5
/// 999 999 999.999991 // 9 + 6
/// 99 999 999.9999991 // 8 + 7
/// 9 999 999.99999991 // 7 + 8
/// 999 999.999999991 // 6 + 9
/// 99 999.9999999991 // 5 + 10
/// 9 999.99999999991 // 4 + 11
/// 999.999999999991 // 3 + 12
/// However, this limitations might be okay, if you are sending such big amounts as 9 billion Zillings, the first of all, congrats, you are a rich person, second, it might be okay to be constrained to 5 decimals sending such a big amount.
public let amount: Double
public init(string: String) throws {
guard let double = Double(string) else { throw Error.nonNumericString }
try self.init(double: double)
}
public init(double amount: Double, smallFractionRule: SmallFractionRule = .throwError) throws {
guard amount >= 0 else { throw Error.amountWasNegative }
guard amount <= Amount.totalSupply else { throw Error.amountExceededTotalSupply }
var amount = amount
let iosf = Amount.inversionOfSmallestFraction
let overflowsMaximumDecimalPrecision = (amount*iosf).decimal > 0
if overflowsMaximumDecimalPrecision {
switch smallFractionRule {
case .throwError: throw Error.amountContainsTooSmallFractions
case .truncate: amount = (amount * iosf).rounded() / iosf
}
}
self.amount = amount
}
public enum SmallFractionRule: Int, Equatable {
case truncate
case throwError
}
public enum Error: Int, Swift.Error, Equatable {
case nonNumericString
case amountWasNegative
case amountExceededTotalSupply
case amountContainsTooSmallFractions
}
}
extension Amount: ExpressibleByFloatLiteral {}
public extension Amount {
/// This `ExpressibleByFloatLiteral` init can result in runtime crash if passed invalid values (since the protocol requires the initializer to be non failable, but the designated initializer is).
public init(floatLiteral value: Double) {
do {
try self = Amount(double: value)
} catch {
fatalError("The `Double` value (`\(value)`) used to create amount was invalid, error: \(error)")
}
}
}
extension Amount: ExpressibleByIntegerLiteral {}
public extension Amount {
/// This `ExpressibleByIntegerLiteral` init can result in runtime crash if passed invalid values (since the protocol requires the initializer to be non failable, but the designated initializer is).
public init(integerLiteral value: Int) {
do {
try self = Amount(double: Double(value))
} catch {
fatalError("The `Int` value (`\(value)`) used to create amount was invalid, error: \(error)")
}
}
}
extension Amount: ExpressibleByStringLiteral {}
public extension Amount {
/// This `ExpressibleByStringLiteral` init can result in runtime crash if passed invalid values (since the protocol requires the initializer to be non failable, but the designated initializer is).
public init(stringLiteral value: String) {
do {
try self = Amount(string: value)
} catch {
fatalError("The `String` value (`\(value)`) used to create amount was invalid, error: \(error)")
}
}
}
extension Amount: CustomStringConvertible {
public var description: String {
return "\(amount) ZILs"
}
}
| 37.372881 | 243 | 0.651927 |
e8ce4a9e86528937afe86e2c6ff7ecf77656a8d9 | 1,136 | // Queue
//
// Basic Operations
//
// enqueue(value) - Inserts a new value at the end of the queue
// dequeue() - Dequeue and return the value at the front of the queue
class Queue<T: Equatable> : Printable {
var items: [T]? = []
func enqueue(value:T) {
items?.append(value)
}
func dequeue() -> T? {
if items?.count > 0 {
let obj = items?.removeAtIndex(0)
return obj
}
else {
return nil
}
}
var isEmpty: Bool {
if let items = self.items {
return items.isEmpty
}
else {
return true
}
}
var description : String {
var description = ""
if let tempItems = self.items {
while !(self.isEmpty) {
description += "\(self.dequeue()!) "
}
self.items = tempItems
}
return description
}
}
var queue = Queue<Int>()
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.enqueue(40)
queue.description
queue.dequeue()
queue.dequeue()
queue.dequeue()
queue.description
| 18.933333 | 69 | 0.523768 |
236a6f7e906f5a74c0e79417ac22776b1b1afefa | 1,757 | //
// ShareImageViewController.swift
// nbro
//
// Created by Peter Gammelgaard Poulsen on 07/02/2017.
// Copyright © 2017 Bob. All rights reserved.
//
import Foundation
import SVGKit
class StickerModel {
let sticker: Sticker
var rotation: Float = 0
var position: CGPoint = .zero
var scale: Float = 1
var transform: CGAffineTransform = .identity
init(sticker: Sticker) {
self.sticker = sticker
}
func size() -> CGSize {
let image = sticker.currentSVG
let aspectRatio = image.hasSize() ? image.size.width / image.size.height : 1
let maximum: CGFloat = 500
let width = aspectRatio >= 1 ? maximum : maximum * aspectRatio
let height = aspectRatio <= 1 ? maximum : maximum * (1 / aspectRatio)
return CGSize(width: width, height: height)
}
}
class ShareImageViewController: UIViewController {
let generator: ImageGenerator
let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
return imageView
}()
init(image: UIImage, stickers: [StickerModel], scale: Float) {
self.generator = ImageGenerator(image: image, stickers: stickers, scale: scale)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
imageView.snp.makeConstraints { (make) in
make.edges.equalTo(imageView.superview!)
}
generator.generate { image in
self.imageView.image = image
}
}
}
| 27.030769 | 87 | 0.619237 |
e4eedae16028c5771c6c759e0bfda14ec168f48f | 120,285 | //===----------------------------------------------------------------------===//
//
// 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 MediaConnect {
// MARK: Enums
public enum Algorithm: String, CustomStringConvertible, Codable {
case aes128
case aes192
case aes256
public var description: String { return self.rawValue }
}
public enum Colorimetry: String, CustomStringConvertible, Codable {
case bt2020 = "BT2020"
case bt2100 = "BT2100"
case bt601 = "BT601"
case bt709 = "BT709"
case st20651 = "ST2065-1"
case st20653 = "ST2065-3"
case xyz = "XYZ"
public var description: String { return self.rawValue }
}
public enum DurationUnits: String, CustomStringConvertible, Codable {
case months = "MONTHS"
public var description: String { return self.rawValue }
}
public enum EncoderProfile: String, CustomStringConvertible, Codable {
case high
case main
public var description: String { return self.rawValue }
}
public enum EncodingName: String, CustomStringConvertible, Codable {
case jxsv
case pcm
case raw
case smpte291
public var description: String { return self.rawValue }
}
public enum EntitlementStatus: String, CustomStringConvertible, Codable {
case disabled = "DISABLED"
case enabled = "ENABLED"
public var description: String { return self.rawValue }
}
public enum FailoverMode: String, CustomStringConvertible, Codable {
case failover = "FAILOVER"
case merge = "MERGE"
public var description: String { return self.rawValue }
}
public enum KeyType: String, CustomStringConvertible, Codable {
case speke
case srtPassword = "srt-password"
case staticKey = "static-key"
public var description: String { return self.rawValue }
}
public enum MediaStreamType: String, CustomStringConvertible, Codable {
case ancillaryData = "ancillary-data"
case audio
case video
public var description: String { return self.rawValue }
}
public enum NetworkInterfaceType: String, CustomStringConvertible, Codable {
case efa
case ena
public var description: String { return self.rawValue }
}
public enum PriceUnits: String, CustomStringConvertible, Codable {
case hourly = "HOURLY"
public var description: String { return self.rawValue }
}
public enum `Protocol`: String, CustomStringConvertible, Codable {
case cdi
case rist
case rtp
case rtpFec = "rtp-fec"
case srtListener = "srt-listener"
case st2110Jpegxs = "st2110-jpegxs"
case zixiPull = "zixi-pull"
case zixiPush = "zixi-push"
public var description: String { return self.rawValue }
}
public enum Range: String, CustomStringConvertible, Codable {
case full = "FULL"
case fullprotect = "FULLPROTECT"
case narrow = "NARROW"
public var description: String { return self.rawValue }
}
public enum ReservationState: String, CustomStringConvertible, Codable {
case active = "ACTIVE"
case canceled = "CANCELED"
case expired = "EXPIRED"
case processing = "PROCESSING"
public var description: String { return self.rawValue }
}
public enum ResourceType: String, CustomStringConvertible, Codable {
case mbpsOutboundBandwidth = "Mbps_Outbound_Bandwidth"
public var description: String { return self.rawValue }
}
public enum ScanMode: String, CustomStringConvertible, Codable {
case interlace
case progressive
case progressiveSegmentedFrame = "progressive-segmented-frame"
public var description: String { return self.rawValue }
}
public enum SourceType: String, CustomStringConvertible, Codable {
case entitled = "ENTITLED"
case owned = "OWNED"
public var description: String { return self.rawValue }
}
public enum State: String, CustomStringConvertible, Codable {
case disabled = "DISABLED"
case enabled = "ENABLED"
public var description: String { return self.rawValue }
}
public enum Status: String, CustomStringConvertible, Codable {
case active = "ACTIVE"
case deleting = "DELETING"
case error = "ERROR"
case standby = "STANDBY"
case starting = "STARTING"
case stopping = "STOPPING"
case updating = "UPDATING"
public var description: String { return self.rawValue }
}
public enum Tcs: String, CustomStringConvertible, Codable {
case bt2100linhlg = "BT2100LINHLG"
case bt2100linpq = "BT2100LINPQ"
case density = "DENSITY"
case hlg = "HLG"
case linear = "LINEAR"
case pq = "PQ"
case sdr = "SDR"
case st20651 = "ST2065-1"
case st4281 = "ST428-1"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct AddFlowMediaStreamsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The Amazon Resource Name (ARN) of the flow.
public let flowArn: String
/// The media streams that you want to add to the flow.
public let mediaStreams: [AddMediaStreamRequest]
public init(flowArn: String, mediaStreams: [AddMediaStreamRequest]) {
self.flowArn = flowArn
self.mediaStreams = mediaStreams
}
private enum CodingKeys: String, CodingKey {
case mediaStreams
}
}
public struct AddFlowMediaStreamsResponse: AWSDecodableShape {
/// The ARN of the flow that you added media streams to.
public let flowArn: String?
/// The media streams that you added to the flow.
public let mediaStreams: [MediaStream]?
public init(flowArn: String? = nil, mediaStreams: [MediaStream]? = nil) {
self.flowArn = flowArn
self.mediaStreams = mediaStreams
}
private enum CodingKeys: String, CodingKey {
case flowArn
case mediaStreams
}
}
public struct AddFlowOutputsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The flow that you want to add outputs to.
public let flowArn: String
/// A list of outputs that you want to add.
public let outputs: [AddOutputRequest]
public init(flowArn: String, outputs: [AddOutputRequest]) {
self.flowArn = flowArn
self.outputs = outputs
}
private enum CodingKeys: String, CodingKey {
case outputs
}
}
public struct AddFlowOutputsResponse: AWSDecodableShape {
/// The ARN of the flow that these outputs were added to.
public let flowArn: String?
/// The details of the newly added outputs.
public let outputs: [Output]?
public init(flowArn: String? = nil, outputs: [Output]? = nil) {
self.flowArn = flowArn
self.outputs = outputs
}
private enum CodingKeys: String, CodingKey {
case flowArn
case outputs
}
}
public struct AddFlowSourcesRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The flow that you want to mutate.
public let flowArn: String
/// A list of sources that you want to add.
public let sources: [SetSourceRequest]
public init(flowArn: String, sources: [SetSourceRequest]) {
self.flowArn = flowArn
self.sources = sources
}
private enum CodingKeys: String, CodingKey {
case sources
}
}
public struct AddFlowSourcesResponse: AWSDecodableShape {
/// The ARN of the flow that these sources were added to.
public let flowArn: String?
/// The details of the newly added sources.
public let sources: [Source]?
public init(flowArn: String? = nil, sources: [Source]? = nil) {
self.flowArn = flowArn
self.sources = sources
}
private enum CodingKeys: String, CodingKey {
case flowArn
case sources
}
}
public struct AddFlowVpcInterfacesRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The flow that you want to mutate.
public let flowArn: String
/// A list of VPC interfaces that you want to add.
public let vpcInterfaces: [VpcInterfaceRequest]
public init(flowArn: String, vpcInterfaces: [VpcInterfaceRequest]) {
self.flowArn = flowArn
self.vpcInterfaces = vpcInterfaces
}
private enum CodingKeys: String, CodingKey {
case vpcInterfaces
}
}
public struct AddFlowVpcInterfacesResponse: AWSDecodableShape {
/// The ARN of the flow that these VPC interfaces were added to.
public let flowArn: String?
/// The details of the newly added VPC interfaces.
public let vpcInterfaces: [VpcInterface]?
public init(flowArn: String? = nil, vpcInterfaces: [VpcInterface]? = nil) {
self.flowArn = flowArn
self.vpcInterfaces = vpcInterfaces
}
private enum CodingKeys: String, CodingKey {
case flowArn
case vpcInterfaces
}
}
public struct AddMediaStreamRequest: AWSEncodableShape {
/// The attributes that you want to assign to the new media stream.
public let attributes: MediaStreamAttributesRequest?
/// The sample rate (in Hz) for the stream. If the media stream type is video or ancillary data, set this value to 90000. If the media stream type is audio, set this value to either 48000 or 96000.
public let clockRate: Int?
/// A description that can help you quickly identify what your media stream is used for.
public let description: String?
/// A unique identifier for the media stream.
public let mediaStreamId: Int
/// A name that helps you distinguish one media stream from another.
public let mediaStreamName: String
/// The type of media stream.
public let mediaStreamType: MediaStreamType
/// The resolution of the video.
public let videoFormat: String?
public init(attributes: MediaStreamAttributesRequest? = nil, clockRate: Int? = nil, description: String? = nil, mediaStreamId: Int, mediaStreamName: String, mediaStreamType: MediaStreamType, videoFormat: String? = nil) {
self.attributes = attributes
self.clockRate = clockRate
self.description = description
self.mediaStreamId = mediaStreamId
self.mediaStreamName = mediaStreamName
self.mediaStreamType = mediaStreamType
self.videoFormat = videoFormat
}
private enum CodingKeys: String, CodingKey {
case attributes
case clockRate
case description
case mediaStreamId
case mediaStreamName
case mediaStreamType
case videoFormat
}
}
public struct AddOutputRequest: AWSEncodableShape {
/// The range of IP addresses that should be allowed to initiate output requests to this flow. These IP addresses should be in the form of a Classless Inter-Domain Routing (CIDR) block; for example, 10.0.0.0/16.
public let cidrAllowList: [String]?
/// A description of the output. This description appears only on the AWS Elemental MediaConnect console and will not be seen by the end user.
public let description: String?
/// The IP address from which video will be sent to output destinations.
public let destination: String?
/// The type of key used for the encryption. If no keyType is provided, the service will use the default setting (static-key).
public let encryption: Encryption?
/// The maximum latency in milliseconds for Zixi-based streams.
public let maxLatency: Int?
/// The media streams that are associated with the output, and the parameters for those associations.
public let mediaStreamOutputConfigurations: [MediaStreamOutputConfigurationRequest]?
/// The minimum latency in milliseconds for SRT-based streams. In streams that use the SRT protocol, this value that you set on your MediaConnect source or output represents the minimal potential latency of that connection. The latency of the stream is set to the highest number between the sender’s minimum latency and the receiver’s minimum latency.
public let minLatency: Int?
/// The name of the output. This value must be unique within the current flow.
public let name: String?
/// The port to use when content is distributed to this output.
public let port: Int?
/// The protocol to use for the output.
public let `protocol`: `Protocol`
/// The remote ID for the Zixi-pull output stream.
public let remoteId: String?
/// The smoothing latency in milliseconds for RIST, RTP, and RTP-FEC streams.
public let smoothingLatency: Int?
/// The stream ID that you want to use for this transport. This parameter applies only to Zixi-based streams.
public let streamId: String?
/// The name of the VPC interface attachment to use for this output.
public let vpcInterfaceAttachment: VpcInterfaceAttachment?
public init(cidrAllowList: [String]? = nil, description: String? = nil, destination: String? = nil, encryption: Encryption? = nil, maxLatency: Int? = nil, mediaStreamOutputConfigurations: [MediaStreamOutputConfigurationRequest]? = nil, minLatency: Int? = nil, name: String? = nil, port: Int? = nil, protocol: `Protocol`, remoteId: String? = nil, smoothingLatency: Int? = nil, streamId: String? = nil, vpcInterfaceAttachment: VpcInterfaceAttachment? = nil) {
self.cidrAllowList = cidrAllowList
self.description = description
self.destination = destination
self.encryption = encryption
self.maxLatency = maxLatency
self.mediaStreamOutputConfigurations = mediaStreamOutputConfigurations
self.minLatency = minLatency
self.name = name
self.port = port
self.`protocol` = `protocol`
self.remoteId = remoteId
self.smoothingLatency = smoothingLatency
self.streamId = streamId
self.vpcInterfaceAttachment = vpcInterfaceAttachment
}
private enum CodingKeys: String, CodingKey {
case cidrAllowList
case description
case destination
case encryption
case maxLatency
case mediaStreamOutputConfigurations
case minLatency
case name
case port
case `protocol`
case remoteId
case smoothingLatency
case streamId
case vpcInterfaceAttachment
}
}
public struct CreateFlowRequest: AWSEncodableShape {
/// The Availability Zone that you want to create the flow in. These options are limited to the Availability Zones within the current AWS Region.
public let availabilityZone: String?
/// The entitlements that you want to grant on a flow.
public let entitlements: [GrantEntitlementRequest]?
/// The media streams that you want to add to the flow. You can associate these media streams with sources and outputs on the flow.
public let mediaStreams: [AddMediaStreamRequest]?
/// The name of the flow.
public let name: String
/// The outputs that you want to add to this flow.
public let outputs: [AddOutputRequest]?
public let source: SetSourceRequest?
public let sourceFailoverConfig: FailoverConfig?
public let sources: [SetSourceRequest]?
/// The VPC interfaces you want on the flow.
public let vpcInterfaces: [VpcInterfaceRequest]?
public init(availabilityZone: String? = nil, entitlements: [GrantEntitlementRequest]? = nil, mediaStreams: [AddMediaStreamRequest]? = nil, name: String, outputs: [AddOutputRequest]? = nil, source: SetSourceRequest? = nil, sourceFailoverConfig: FailoverConfig? = nil, sources: [SetSourceRequest]? = nil, vpcInterfaces: [VpcInterfaceRequest]? = nil) {
self.availabilityZone = availabilityZone
self.entitlements = entitlements
self.mediaStreams = mediaStreams
self.name = name
self.outputs = outputs
self.source = source
self.sourceFailoverConfig = sourceFailoverConfig
self.sources = sources
self.vpcInterfaces = vpcInterfaces
}
private enum CodingKeys: String, CodingKey {
case availabilityZone
case entitlements
case mediaStreams
case name
case outputs
case source
case sourceFailoverConfig
case sources
case vpcInterfaces
}
}
public struct CreateFlowResponse: AWSDecodableShape {
public let flow: Flow?
public init(flow: Flow? = nil) {
self.flow = flow
}
private enum CodingKeys: String, CodingKey {
case flow
}
}
public struct DeleteFlowRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The ARN of the flow that you want to delete.
public let flowArn: String
public init(flowArn: String) {
self.flowArn = flowArn
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteFlowResponse: AWSDecodableShape {
/// The ARN of the flow that was deleted.
public let flowArn: String?
/// The status of the flow when the DeleteFlow process begins.
public let status: Status?
public init(flowArn: String? = nil, status: Status? = nil) {
self.flowArn = flowArn
self.status = status
}
private enum CodingKeys: String, CodingKey {
case flowArn
case status
}
}
public struct DescribeFlowRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The ARN of the flow that you want to describe.
public let flowArn: String
public init(flowArn: String) {
self.flowArn = flowArn
}
private enum CodingKeys: CodingKey {}
}
public struct DescribeFlowResponse: AWSDecodableShape {
public let flow: Flow?
public let messages: Messages?
public init(flow: Flow? = nil, messages: Messages? = nil) {
self.flow = flow
self.messages = messages
}
private enum CodingKeys: String, CodingKey {
case flow
case messages
}
}
public struct DescribeOfferingRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "offeringArn", location: .uri("OfferingArn"))
]
/// The Amazon Resource Name (ARN) of the offering.
public let offeringArn: String
public init(offeringArn: String) {
self.offeringArn = offeringArn
}
private enum CodingKeys: CodingKey {}
}
public struct DescribeOfferingResponse: AWSDecodableShape {
public let offering: Offering?
public init(offering: Offering? = nil) {
self.offering = offering
}
private enum CodingKeys: String, CodingKey {
case offering
}
}
public struct DescribeReservationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "reservationArn", location: .uri("ReservationArn"))
]
/// The Amazon Resource Name (ARN) of the reservation.
public let reservationArn: String
public init(reservationArn: String) {
self.reservationArn = reservationArn
}
private enum CodingKeys: CodingKey {}
}
public struct DescribeReservationResponse: AWSDecodableShape {
public let reservation: Reservation?
public init(reservation: Reservation? = nil) {
self.reservation = reservation
}
private enum CodingKeys: String, CodingKey {
case reservation
}
}
public struct DestinationConfiguration: AWSDecodableShape {
/// The IP address where contents of the media stream will be sent.
public let destinationIp: String
/// The port to use when the content of the media stream is distributed to the output.
public let destinationPort: Int
/// The VPC interface that is used for the media stream associated with the output.
public let interface: Interface
/// The IP address that the receiver requires in order to establish a connection with the flow. This value is represented by the elastic network interface IP address of the VPC. This field applies only to outputs that use the CDI or ST 2110 JPEG XS protocol.
public let outboundIp: String
public init(destinationIp: String, destinationPort: Int, interface: Interface, outboundIp: String) {
self.destinationIp = destinationIp
self.destinationPort = destinationPort
self.interface = interface
self.outboundIp = outboundIp
}
private enum CodingKeys: String, CodingKey {
case destinationIp
case destinationPort
case interface
case outboundIp
}
}
public struct DestinationConfigurationRequest: AWSEncodableShape {
/// The IP address where you want MediaConnect to send contents of the media stream.
public let destinationIp: String
/// The port that you want MediaConnect to use when it distributes the media stream to the output.
public let destinationPort: Int
/// The VPC interface that you want to use for the media stream associated with the output.
public let interface: InterfaceRequest
public init(destinationIp: String, destinationPort: Int, interface: InterfaceRequest) {
self.destinationIp = destinationIp
self.destinationPort = destinationPort
self.interface = interface
}
private enum CodingKeys: String, CodingKey {
case destinationIp
case destinationPort
case interface
}
}
public struct EncodingParameters: AWSDecodableShape {
/// A value that is used to calculate compression for an output. The bitrate of the output is calculated as follows: Output bitrate = (1 / compressionFactor) * (source bitrate) This property only applies to outputs that use the ST 2110 JPEG XS protocol, with a flow source that uses the CDI protocol. Valid values are floating point numbers in the range of 3.0 to 10.0, inclusive.
public let compressionFactor: Double
/// A setting on the encoder that drives compression settings. This property only applies to video media streams associated with outputs that use the ST 2110 JPEG XS protocol, with a flow source that uses the CDI protocol.
public let encoderProfile: EncoderProfile
public init(compressionFactor: Double, encoderProfile: EncoderProfile) {
self.compressionFactor = compressionFactor
self.encoderProfile = encoderProfile
}
private enum CodingKeys: String, CodingKey {
case compressionFactor
case encoderProfile
}
}
public struct EncodingParametersRequest: AWSEncodableShape {
/// A value that is used to calculate compression for an output. The bitrate of the output is calculated as follows: Output bitrate = (1 / compressionFactor) * (source bitrate) This property only applies to outputs that use the ST 2110 JPEG XS protocol, with a flow source that uses the CDI protocol. Valid values are floating point numbers in the range of 3.0 to 10.0, inclusive.
public let compressionFactor: Double
/// A setting on the encoder that drives compression settings. This property only applies to video media streams associated with outputs that use the ST 2110 JPEG XS protocol, if at least one source on the flow uses the CDI protocol.
public let encoderProfile: EncoderProfile
public init(compressionFactor: Double, encoderProfile: EncoderProfile) {
self.compressionFactor = compressionFactor
self.encoderProfile = encoderProfile
}
private enum CodingKeys: String, CodingKey {
case compressionFactor
case encoderProfile
}
}
public struct Encryption: AWSEncodableShape & AWSDecodableShape {
/// The type of algorithm that is used for the encryption (such as aes128, aes192, or aes256).
public let algorithm: Algorithm?
/// A 128-bit, 16-byte hex value represented by a 32-character string, to be used with the key for encrypting content. This parameter is not valid for static key encryption.
public let constantInitializationVector: String?
/// The value of one of the devices that you configured with your digital rights management (DRM) platform key provider. This parameter is required for SPEKE encryption and is not valid for static key encryption.
public let deviceId: String?
/// The type of key that is used for the encryption. If no keyType is provided, the service will use the default setting (static-key).
public let keyType: KeyType?
/// The AWS Region that the API Gateway proxy endpoint was created in. This parameter is required for SPEKE encryption and is not valid for static key encryption.
public let region: String?
/// An identifier for the content. The service sends this value to the key server to identify the current endpoint. The resource ID is also known as the content ID. This parameter is required for SPEKE encryption and is not valid for static key encryption.
public let resourceId: String?
/// The ARN of the role that you created during setup (when you set up AWS Elemental MediaConnect as a trusted entity).
public let roleArn: String
/// The ARN of the secret that you created in AWS Secrets Manager to store the encryption key. This parameter is required for static key encryption and is not valid for SPEKE encryption.
public let secretArn: String?
/// The URL from the API Gateway proxy that you set up to talk to your key server. This parameter is required for SPEKE encryption and is not valid for static key encryption.
public let url: String?
public init(algorithm: Algorithm? = nil, constantInitializationVector: String? = nil, deviceId: String? = nil, keyType: KeyType? = nil, region: String? = nil, resourceId: String? = nil, roleArn: String, secretArn: String? = nil, url: String? = nil) {
self.algorithm = algorithm
self.constantInitializationVector = constantInitializationVector
self.deviceId = deviceId
self.keyType = keyType
self.region = region
self.resourceId = resourceId
self.roleArn = roleArn
self.secretArn = secretArn
self.url = url
}
private enum CodingKeys: String, CodingKey {
case algorithm
case constantInitializationVector
case deviceId
case keyType
case region
case resourceId
case roleArn
case secretArn
case url
}
}
public struct Entitlement: AWSDecodableShape {
/// Percentage from 0-100 of the data transfer cost to be billed to the subscriber.
public let dataTransferSubscriberFeePercent: Int?
/// A description of the entitlement.
public let description: String?
/// The type of encryption that will be used on the output that is associated with this entitlement.
public let encryption: Encryption?
/// The ARN of the entitlement.
public let entitlementArn: String
/// An indication of whether the entitlement is enabled.
public let entitlementStatus: EntitlementStatus?
/// The name of the entitlement.
public let name: String
/// The AWS account IDs that you want to share your content with. The receiving accounts (subscribers) will be allowed to create their own flow using your content as the source.
public let subscribers: [String]
public init(dataTransferSubscriberFeePercent: Int? = nil, description: String? = nil, encryption: Encryption? = nil, entitlementArn: String, entitlementStatus: EntitlementStatus? = nil, name: String, subscribers: [String]) {
self.dataTransferSubscriberFeePercent = dataTransferSubscriberFeePercent
self.description = description
self.encryption = encryption
self.entitlementArn = entitlementArn
self.entitlementStatus = entitlementStatus
self.name = name
self.subscribers = subscribers
}
private enum CodingKeys: String, CodingKey {
case dataTransferSubscriberFeePercent
case description
case encryption
case entitlementArn
case entitlementStatus
case name
case subscribers
}
}
public struct FailoverConfig: AWSEncodableShape & AWSDecodableShape {
/// The type of failover you choose for this flow. MERGE combines the source streams into a single stream, allowing graceful recovery from any single-source loss. FAILOVER allows switching between different streams.
public let failoverMode: FailoverMode?
/// Search window time to look for dash-7 packets
public let recoveryWindow: Int?
/// The priority you want to assign to a source. You can have a primary stream and a backup stream or two equally prioritized streams.
public let sourcePriority: SourcePriority?
public let state: State?
public init(failoverMode: FailoverMode? = nil, recoveryWindow: Int? = nil, sourcePriority: SourcePriority? = nil, state: State? = nil) {
self.failoverMode = failoverMode
self.recoveryWindow = recoveryWindow
self.sourcePriority = sourcePriority
self.state = state
}
private enum CodingKeys: String, CodingKey {
case failoverMode
case recoveryWindow
case sourcePriority
case state
}
}
public struct Flow: AWSDecodableShape {
/// The Availability Zone that you want to create the flow in. These options are limited to the Availability Zones within the current AWS.
public let availabilityZone: String
/// A description of the flow. This value is not used or seen outside of the current AWS Elemental MediaConnect account.
public let description: String?
/// The IP address from which video will be sent to output destinations.
public let egressIp: String?
/// The entitlements in this flow.
public let entitlements: [Entitlement]
/// The Amazon Resource Name (ARN), a unique identifier for any AWS resource, of the flow.
public let flowArn: String
/// The media streams that are associated with the flow. After you associate a media stream with a source, you can also associate it with outputs on the flow.
public let mediaStreams: [MediaStream]?
/// The name of the flow.
public let name: String
/// The outputs in this flow.
public let outputs: [Output]
public let source: Source
public let sourceFailoverConfig: FailoverConfig?
public let sources: [Source]?
/// The current status of the flow.
public let status: Status
/// The VPC Interfaces for this flow.
public let vpcInterfaces: [VpcInterface]?
public init(availabilityZone: String, description: String? = nil, egressIp: String? = nil, entitlements: [Entitlement], flowArn: String, mediaStreams: [MediaStream]? = nil, name: String, outputs: [Output], source: Source, sourceFailoverConfig: FailoverConfig? = nil, sources: [Source]? = nil, status: Status, vpcInterfaces: [VpcInterface]? = nil) {
self.availabilityZone = availabilityZone
self.description = description
self.egressIp = egressIp
self.entitlements = entitlements
self.flowArn = flowArn
self.mediaStreams = mediaStreams
self.name = name
self.outputs = outputs
self.source = source
self.sourceFailoverConfig = sourceFailoverConfig
self.sources = sources
self.status = status
self.vpcInterfaces = vpcInterfaces
}
private enum CodingKeys: String, CodingKey {
case availabilityZone
case description
case egressIp
case entitlements
case flowArn
case mediaStreams
case name
case outputs
case source
case sourceFailoverConfig
case sources
case status
case vpcInterfaces
}
}
public struct Fmtp: AWSDecodableShape {
/// The format of the audio channel.
public let channelOrder: String?
/// The format that is used for the representation of color.
public let colorimetry: Colorimetry?
/// The frame rate for the video stream, in frames/second. For example: 60000/1001. If you specify a whole number, MediaConnect uses a ratio of N/1. For example, if you specify 60, MediaConnect uses 60/1 as the exactFramerate.
public let exactFramerate: String?
/// The pixel aspect ratio (PAR) of the video.
public let par: String?
/// The encoding range of the video.
public let range: Range?
/// The type of compression that was used to smooth the video’s appearance
public let scanMode: ScanMode?
/// The transfer characteristic system (TCS) that is used in the video.
public let tcs: Tcs?
public init(channelOrder: String? = nil, colorimetry: Colorimetry? = nil, exactFramerate: String? = nil, par: String? = nil, range: Range? = nil, scanMode: ScanMode? = nil, tcs: Tcs? = nil) {
self.channelOrder = channelOrder
self.colorimetry = colorimetry
self.exactFramerate = exactFramerate
self.par = par
self.range = range
self.scanMode = scanMode
self.tcs = tcs
}
private enum CodingKeys: String, CodingKey {
case channelOrder
case colorimetry
case exactFramerate
case par
case range
case scanMode
case tcs
}
}
public struct FmtpRequest: AWSEncodableShape {
/// The format of the audio channel.
public let channelOrder: String?
/// The format that is used for the representation of color.
public let colorimetry: Colorimetry?
/// The frame rate for the video stream, in frames/second. For example: 60000/1001. If you specify a whole number, MediaConnect uses a ratio of N/1. For example, if you specify 60, MediaConnect uses 60/1 as the exactFramerate.
public let exactFramerate: String?
/// The pixel aspect ratio (PAR) of the video.
public let par: String?
/// The encoding range of the video.
public let range: Range?
/// The type of compression that was used to smooth the video’s appearance.
public let scanMode: ScanMode?
/// The transfer characteristic system (TCS) that is used in the video.
public let tcs: Tcs?
public init(channelOrder: String? = nil, colorimetry: Colorimetry? = nil, exactFramerate: String? = nil, par: String? = nil, range: Range? = nil, scanMode: ScanMode? = nil, tcs: Tcs? = nil) {
self.channelOrder = channelOrder
self.colorimetry = colorimetry
self.exactFramerate = exactFramerate
self.par = par
self.range = range
self.scanMode = scanMode
self.tcs = tcs
}
private enum CodingKeys: String, CodingKey {
case channelOrder
case colorimetry
case exactFramerate
case par
case range
case scanMode
case tcs
}
}
public struct GrantEntitlementRequest: AWSEncodableShape {
/// Percentage from 0-100 of the data transfer cost to be billed to the subscriber.
public let dataTransferSubscriberFeePercent: Int?
/// A description of the entitlement. This description appears only on the AWS Elemental MediaConnect console and will not be seen by the subscriber or end user.
public let description: String?
/// The type of encryption that will be used on the output that is associated with this entitlement.
public let encryption: Encryption?
/// An indication of whether the new entitlement should be enabled or disabled as soon as it is created. If you don’t specify the entitlementStatus field in your request, MediaConnect sets it to ENABLED.
public let entitlementStatus: EntitlementStatus?
/// The name of the entitlement. This value must be unique within the current flow.
public let name: String?
/// The AWS account IDs that you want to share your content with. The receiving accounts (subscribers) will be allowed to create their own flows using your content as the source.
public let subscribers: [String]
public init(dataTransferSubscriberFeePercent: Int? = nil, description: String? = nil, encryption: Encryption? = nil, entitlementStatus: EntitlementStatus? = nil, name: String? = nil, subscribers: [String]) {
self.dataTransferSubscriberFeePercent = dataTransferSubscriberFeePercent
self.description = description
self.encryption = encryption
self.entitlementStatus = entitlementStatus
self.name = name
self.subscribers = subscribers
}
private enum CodingKeys: String, CodingKey {
case dataTransferSubscriberFeePercent
case description
case encryption
case entitlementStatus
case name
case subscribers
}
}
public struct GrantFlowEntitlementsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The list of entitlements that you want to grant.
public let entitlements: [GrantEntitlementRequest]
/// The flow that you want to grant entitlements on.
public let flowArn: String
public init(entitlements: [GrantEntitlementRequest], flowArn: String) {
self.entitlements = entitlements
self.flowArn = flowArn
}
private enum CodingKeys: String, CodingKey {
case entitlements
}
}
public struct GrantFlowEntitlementsResponse: AWSDecodableShape {
/// The entitlements that were just granted.
public let entitlements: [Entitlement]?
/// The ARN of the flow that these entitlements were granted to.
public let flowArn: String?
public init(entitlements: [Entitlement]? = nil, flowArn: String? = nil) {
self.entitlements = entitlements
self.flowArn = flowArn
}
private enum CodingKeys: String, CodingKey {
case entitlements
case flowArn
}
}
public struct InputConfiguration: AWSDecodableShape {
/// The IP address that the flow listens on for incoming content for a media stream.
public let inputIp: String
/// The port that the flow listens on for an incoming media stream.
public let inputPort: Int
/// The VPC interface where the media stream comes in from.
public let interface: Interface
public init(inputIp: String, inputPort: Int, interface: Interface) {
self.inputIp = inputIp
self.inputPort = inputPort
self.interface = interface
}
private enum CodingKeys: String, CodingKey {
case inputIp
case inputPort
case interface
}
}
public struct InputConfigurationRequest: AWSEncodableShape {
/// The port that you want the flow to listen on for an incoming media stream.
public let inputPort: Int
/// The VPC interface that you want to use for the incoming media stream.
public let interface: InterfaceRequest
public init(inputPort: Int, interface: InterfaceRequest) {
self.inputPort = inputPort
self.interface = interface
}
private enum CodingKeys: String, CodingKey {
case inputPort
case interface
}
}
public struct Interface: AWSDecodableShape {
/// The name of the VPC interface.
public let name: String
public init(name: String) {
self.name = name
}
private enum CodingKeys: String, CodingKey {
case name
}
}
public struct InterfaceRequest: AWSEncodableShape {
/// The name of the VPC interface.
public let name: String
public init(name: String) {
self.name = name
}
private enum CodingKeys: String, CodingKey {
case name
}
}
public struct ListEntitlementsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken"))
]
/// The maximum number of results to return per API request. For example, you submit a ListEntitlements request with MaxResults set at 5. Although 20 items match your request, the service returns no more than the first 5 items. (The service also returns a NextToken value that you can use to fetch the next batch of results.) The service might return fewer results than the MaxResults value. If MaxResults is not included in the request, the service defaults to pagination with a maximum of 20 results per page.
public let maxResults: Int?
/// The token that identifies which batch of results that you want to see. For example, you submit a ListEntitlements request with MaxResults set at 5. The service returns the first batch of results (up to 5) and a NextToken value. To see the next batch of results, you can submit the ListEntitlements request a second time and specify the NextToken value.
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListEntitlementsResponse: AWSDecodableShape {
/// A list of entitlements that have been granted to you from other AWS accounts.
public let entitlements: [ListedEntitlement]?
/// The token that identifies which batch of results that you want to see. For example, you submit a ListEntitlements request with MaxResults set at 5. The service returns the first batch of results (up to 5) and a NextToken value. To see the next batch of results, you can submit the ListEntitlements request a second time and specify the NextToken value.
public let nextToken: String?
public init(entitlements: [ListedEntitlement]? = nil, nextToken: String? = nil) {
self.entitlements = entitlements
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case entitlements
case nextToken
}
}
public struct ListFlowsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken"))
]
/// The maximum number of results to return per API request. For example, you submit a ListFlows request with MaxResults set at 5. Although 20 items match your request, the service returns no more than the first 5 items. (The service also returns a NextToken value that you can use to fetch the next batch of results.) The service might return fewer results than the MaxResults value. If MaxResults is not included in the request, the service defaults to pagination with a maximum of 10 results per page.
public let maxResults: Int?
/// The token that identifies which batch of results that you want to see. For example, you submit a ListFlows request with MaxResults set at 5. The service returns the first batch of results (up to 5) and a NextToken value. To see the next batch of results, you can submit the ListFlows request a second time and specify the NextToken value.
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListFlowsResponse: AWSDecodableShape {
/// A list of flow summaries.
public let flows: [ListedFlow]?
/// The token that identifies which batch of results that you want to see. For example, you submit a ListFlows request with MaxResults set at 5. The service returns the first batch of results (up to 5) and a NextToken value. To see the next batch of results, you can submit the ListFlows request a second time and specify the NextToken value.
public let nextToken: String?
public init(flows: [ListedFlow]? = nil, nextToken: String? = nil) {
self.flows = flows
self.nextToken = nextToken
}
private enum CodingKeys: String, CodingKey {
case flows
case nextToken
}
}
public struct ListOfferingsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken"))
]
/// The maximum number of results to return per API request. For example, you submit a ListOfferings request with MaxResults set at 5. Although 20 items match your request, the service returns no more than the first 5 items. (The service also returns a NextToken value that you can use to fetch the next batch of results.) The service might return fewer results than the MaxResults value. If MaxResults is not included in the request, the service defaults to pagination with a maximum of 10 results per page.
public let maxResults: Int?
/// The token that identifies which batch of results that you want to see. For example, you submit a ListOfferings request with MaxResults set at 5. The service returns the first batch of results (up to 5) and a NextToken value. To see the next batch of results, you can submit the ListOfferings request a second time and specify the NextToken value.
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListOfferingsResponse: AWSDecodableShape {
/// The token that identifies which batch of results that you want to see. For example, you submit a ListOfferings request with MaxResults set at 5. The service returns the first batch of results (up to 5) and a NextToken value. To see the next batch of results, you can submit the ListOfferings request a second time and specify the NextToken value.
public let nextToken: String?
/// A list of offerings that are available to this account in the current AWS Region.
public let offerings: [Offering]?
public init(nextToken: String? = nil, offerings: [Offering]? = nil) {
self.nextToken = nextToken
self.offerings = offerings
}
private enum CodingKeys: String, CodingKey {
case nextToken
case offerings
}
}
public struct ListReservationsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "maxResults", location: .querystring("maxResults")),
AWSMemberEncoding(label: "nextToken", location: .querystring("nextToken"))
]
/// The maximum number of results to return per API request. For example, you submit a ListReservations request with MaxResults set at 5. Although 20 items match your request, the service returns no more than the first 5 items. (The service also returns a NextToken value that you can use to fetch the next batch of results.) The service might return fewer results than the MaxResults value. If MaxResults is not included in the request, the service defaults to pagination with a maximum of 10 results per page.
public let maxResults: Int?
/// The token that identifies which batch of results that you want to see. For example, you submit a ListReservations request with MaxResults set at 5. The service returns the first batch of results (up to 5) and a NextToken value. To see the next batch of results, you can submit the ListOfferings request a second time and specify the NextToken value.
public let nextToken: String?
public init(maxResults: Int? = nil, nextToken: String? = nil) {
self.maxResults = maxResults
self.nextToken = nextToken
}
public func validate(name: String) throws {
try self.validate(self.maxResults, name: "maxResults", parent: name, max: 1000)
try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListReservationsResponse: AWSDecodableShape {
/// The token that identifies which batch of results that you want to see. For example, you submit a ListReservations request with MaxResults set at 5. The service returns the first batch of results (up to 5) and a NextToken value. To see the next batch of results, you can submit the ListReservations request a second time and specify the NextToken value.
public let nextToken: String?
/// A list of all reservations that have been purchased by this account in the current AWS Region.
public let reservations: [Reservation]?
public init(nextToken: String? = nil, reservations: [Reservation]? = nil) {
self.nextToken = nextToken
self.reservations = reservations
}
private enum CodingKeys: String, CodingKey {
case nextToken
case reservations
}
}
public struct ListTagsForResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri("ResourceArn"))
]
/// The Amazon Resource Name (ARN) that identifies the AWS Elemental MediaConnect resource for which to list the tags.
public let resourceArn: String
public init(resourceArn: String) {
self.resourceArn = resourceArn
}
private enum CodingKeys: CodingKey {}
}
public struct ListTagsForResourceResponse: AWSDecodableShape {
/// A map from tag keys to values. Tag keys can have a maximum character length of 128 characters, and tag values can have a maximum length of 256 characters.
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct ListedEntitlement: AWSDecodableShape {
/// Percentage from 0-100 of the data transfer cost to be billed to the subscriber.
public let dataTransferSubscriberFeePercent: Int?
/// The ARN of the entitlement.
public let entitlementArn: String
/// The name of the entitlement.
public let entitlementName: String
public init(dataTransferSubscriberFeePercent: Int? = nil, entitlementArn: String, entitlementName: String) {
self.dataTransferSubscriberFeePercent = dataTransferSubscriberFeePercent
self.entitlementArn = entitlementArn
self.entitlementName = entitlementName
}
private enum CodingKeys: String, CodingKey {
case dataTransferSubscriberFeePercent
case entitlementArn
case entitlementName
}
}
public struct ListedFlow: AWSDecodableShape {
/// The Availability Zone that the flow was created in.
public let availabilityZone: String
/// A description of the flow.
public let description: String
/// The ARN of the flow.
public let flowArn: String
/// The name of the flow.
public let name: String
/// The type of source. This value is either owned (originated somewhere other than an AWS Elemental MediaConnect flow owned by another AWS account) or entitled (originated at an AWS Elemental MediaConnect flow owned by another AWS account).
public let sourceType: SourceType
/// The current status of the flow.
public let status: Status
public init(availabilityZone: String, description: String, flowArn: String, name: String, sourceType: SourceType, status: Status) {
self.availabilityZone = availabilityZone
self.description = description
self.flowArn = flowArn
self.name = name
self.sourceType = sourceType
self.status = status
}
private enum CodingKeys: String, CodingKey {
case availabilityZone
case description
case flowArn
case name
case sourceType
case status
}
}
public struct MediaStream: AWSDecodableShape {
/// Attributes that are related to the media stream.
public let attributes: MediaStreamAttributes?
/// The sample rate for the stream. This value is measured in Hz.
public let clockRate: Int?
/// A description that can help you quickly identify what your media stream is used for.
public let description: String?
/// The format type number (sometimes referred to as RTP payload type) of the media stream. MediaConnect assigns this value to the media stream. For ST 2110 JPEG XS outputs, you need to provide this value to the receiver.
public let fmt: Int
/// A unique identifier for the media stream.
public let mediaStreamId: Int
/// A name that helps you distinguish one media stream from another.
public let mediaStreamName: String
/// The type of media stream.
public let mediaStreamType: MediaStreamType
/// The resolution of the video.
public let videoFormat: String?
public init(attributes: MediaStreamAttributes? = nil, clockRate: Int? = nil, description: String? = nil, fmt: Int, mediaStreamId: Int, mediaStreamName: String, mediaStreamType: MediaStreamType, videoFormat: String? = nil) {
self.attributes = attributes
self.clockRate = clockRate
self.description = description
self.fmt = fmt
self.mediaStreamId = mediaStreamId
self.mediaStreamName = mediaStreamName
self.mediaStreamType = mediaStreamType
self.videoFormat = videoFormat
}
private enum CodingKeys: String, CodingKey {
case attributes
case clockRate
case description
case fmt
case mediaStreamId
case mediaStreamName
case mediaStreamType
case videoFormat
}
}
public struct MediaStreamAttributes: AWSDecodableShape {
/// A set of parameters that define the media stream.
public let fmtp: Fmtp
/// The audio language, in a format that is recognized by the receiver.
public let lang: String?
public init(fmtp: Fmtp, lang: String? = nil) {
self.fmtp = fmtp
self.lang = lang
}
private enum CodingKeys: String, CodingKey {
case fmtp
case lang
}
}
public struct MediaStreamAttributesRequest: AWSEncodableShape {
/// The settings that you want to use to define the media stream.
public let fmtp: FmtpRequest?
/// The audio language, in a format that is recognized by the receiver.
public let lang: String?
public init(fmtp: FmtpRequest? = nil, lang: String? = nil) {
self.fmtp = fmtp
self.lang = lang
}
private enum CodingKeys: String, CodingKey {
case fmtp
case lang
}
}
public struct MediaStreamOutputConfiguration: AWSDecodableShape {
/// The transport parameters that are associated with each outbound media stream.
public let destinationConfigurations: [DestinationConfiguration]?
/// The format that was used to encode the data. For ancillary data streams, set the encoding name to smpte291. For audio streams, set the encoding name to pcm. For video, 2110 streams, set the encoding name to raw. For video, JPEG XS streams, set the encoding name to jxsv.
public let encodingName: EncodingName
/// Encoding parameters
public let encodingParameters: EncodingParameters?
/// The name of the media stream.
public let mediaStreamName: String
public init(destinationConfigurations: [DestinationConfiguration]? = nil, encodingName: EncodingName, encodingParameters: EncodingParameters? = nil, mediaStreamName: String) {
self.destinationConfigurations = destinationConfigurations
self.encodingName = encodingName
self.encodingParameters = encodingParameters
self.mediaStreamName = mediaStreamName
}
private enum CodingKeys: String, CodingKey {
case destinationConfigurations
case encodingName
case encodingParameters
case mediaStreamName
}
}
public struct MediaStreamOutputConfigurationRequest: AWSEncodableShape {
/// The transport parameters that you want to associate with the media stream.
public let destinationConfigurations: [DestinationConfigurationRequest]?
/// The format that will be used to encode the data. For ancillary data streams, set the encoding name to smpte291. For audio streams, set the encoding name to pcm. For video, 2110 streams, set the encoding name to raw. For video, JPEG XS streams, set the encoding name to jxsv.
public let encodingName: EncodingName
/// A collection of parameters that determine how MediaConnect will convert the content. These fields only apply to outputs on flows that have a CDI source.
public let encodingParameters: EncodingParametersRequest?
/// The name of the media stream that is associated with the output.
public let mediaStreamName: String
public init(destinationConfigurations: [DestinationConfigurationRequest]? = nil, encodingName: EncodingName, encodingParameters: EncodingParametersRequest? = nil, mediaStreamName: String) {
self.destinationConfigurations = destinationConfigurations
self.encodingName = encodingName
self.encodingParameters = encodingParameters
self.mediaStreamName = mediaStreamName
}
private enum CodingKeys: String, CodingKey {
case destinationConfigurations
case encodingName
case encodingParameters
case mediaStreamName
}
}
public struct MediaStreamSourceConfiguration: AWSDecodableShape {
/// The format that was used to encode the data. For ancillary data streams, set the encoding name to smpte291. For audio streams, set the encoding name to pcm. For video, 2110 streams, set the encoding name to raw. For video, JPEG XS streams, set the encoding name to jxsv.
public let encodingName: EncodingName
/// The transport parameters that are associated with an incoming media stream.
public let inputConfigurations: [InputConfiguration]?
/// The name of the media stream.
public let mediaStreamName: String
public init(encodingName: EncodingName, inputConfigurations: [InputConfiguration]? = nil, mediaStreamName: String) {
self.encodingName = encodingName
self.inputConfigurations = inputConfigurations
self.mediaStreamName = mediaStreamName
}
private enum CodingKeys: String, CodingKey {
case encodingName
case inputConfigurations
case mediaStreamName
}
}
public struct MediaStreamSourceConfigurationRequest: AWSEncodableShape {
/// The format you want to use to encode the data. For ancillary data streams, set the encoding name to smpte291. For audio streams, set the encoding name to pcm. For video, 2110 streams, set the encoding name to raw. For video, JPEG XS streams, set the encoding name to jxsv.
public let encodingName: EncodingName
/// The transport parameters that you want to associate with the media stream.
public let inputConfigurations: [InputConfigurationRequest]?
/// The name of the media stream.
public let mediaStreamName: String
public init(encodingName: EncodingName, inputConfigurations: [InputConfigurationRequest]? = nil, mediaStreamName: String) {
self.encodingName = encodingName
self.inputConfigurations = inputConfigurations
self.mediaStreamName = mediaStreamName
}
private enum CodingKeys: String, CodingKey {
case encodingName
case inputConfigurations
case mediaStreamName
}
}
public struct Messages: AWSDecodableShape {
/// A list of errors that might have been generated from processes on this flow.
public let errors: [String]
public init(errors: [String]) {
self.errors = errors
}
private enum CodingKeys: String, CodingKey {
case errors
}
}
public struct Offering: AWSDecodableShape {
/// The type of currency that is used for billing. The currencyCode used for all reservations is US dollars.
public let currencyCode: String
/// The length of time that your reservation would be active.
public let duration: Int
/// The unit of measurement for the duration of the offering.
public let durationUnits: DurationUnits
/// The Amazon Resource Name (ARN) that MediaConnect assigns to the offering.
public let offeringArn: String
/// A description of the offering.
public let offeringDescription: String
/// The cost of a single unit. This value, in combination with priceUnits, makes up the rate.
public let pricePerUnit: String
/// The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the rate.
public let priceUnits: PriceUnits
/// A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering.
public let resourceSpecification: ResourceSpecification
public init(currencyCode: String, duration: Int, durationUnits: DurationUnits, offeringArn: String, offeringDescription: String, pricePerUnit: String, priceUnits: PriceUnits, resourceSpecification: ResourceSpecification) {
self.currencyCode = currencyCode
self.duration = duration
self.durationUnits = durationUnits
self.offeringArn = offeringArn
self.offeringDescription = offeringDescription
self.pricePerUnit = pricePerUnit
self.priceUnits = priceUnits
self.resourceSpecification = resourceSpecification
}
private enum CodingKeys: String, CodingKey {
case currencyCode
case duration
case durationUnits
case offeringArn
case offeringDescription
case pricePerUnit
case priceUnits
case resourceSpecification
}
}
public struct Output: AWSDecodableShape {
/// Percentage from 0-100 of the data transfer cost to be billed to the subscriber.
public let dataTransferSubscriberFeePercent: Int?
/// A description of the output.
public let description: String?
/// The address where you want to send the output.
public let destination: String?
/// The type of key used for the encryption. If no keyType is provided, the service will use the default setting (static-key).
public let encryption: Encryption?
/// The ARN of the entitlement on the originator''s flow. This value is relevant only on entitled flows.
public let entitlementArn: String?
/// The IP address that the receiver requires in order to establish a connection with the flow. For public networking, the ListenerAddress is represented by the elastic IP address of the flow. For private networking, the ListenerAddress is represented by the elastic network interface IP address of the VPC. This field applies only to outputs that use the Zixi pull or SRT listener protocol.
public let listenerAddress: String?
/// The input ARN of the AWS Elemental MediaLive channel. This parameter is relevant only for outputs that were added by creating a MediaLive input.
public let mediaLiveInputArn: String?
/// The configuration for each media stream that is associated with the output.
public let mediaStreamOutputConfigurations: [MediaStreamOutputConfiguration]?
/// The name of the output. This value must be unique within the current flow.
public let name: String
/// The ARN of the output.
public let outputArn: String
/// The port to use when content is distributed to this output.
public let port: Int?
/// Attributes related to the transport stream that are used in the output.
public let transport: Transport?
/// The name of the VPC interface attachment to use for this output.
public let vpcInterfaceAttachment: VpcInterfaceAttachment?
public init(dataTransferSubscriberFeePercent: Int? = nil, description: String? = nil, destination: String? = nil, encryption: Encryption? = nil, entitlementArn: String? = nil, listenerAddress: String? = nil, mediaLiveInputArn: String? = nil, mediaStreamOutputConfigurations: [MediaStreamOutputConfiguration]? = nil, name: String, outputArn: String, port: Int? = nil, transport: Transport? = nil, vpcInterfaceAttachment: VpcInterfaceAttachment? = nil) {
self.dataTransferSubscriberFeePercent = dataTransferSubscriberFeePercent
self.description = description
self.destination = destination
self.encryption = encryption
self.entitlementArn = entitlementArn
self.listenerAddress = listenerAddress
self.mediaLiveInputArn = mediaLiveInputArn
self.mediaStreamOutputConfigurations = mediaStreamOutputConfigurations
self.name = name
self.outputArn = outputArn
self.port = port
self.transport = transport
self.vpcInterfaceAttachment = vpcInterfaceAttachment
}
private enum CodingKeys: String, CodingKey {
case dataTransferSubscriberFeePercent
case description
case destination
case encryption
case entitlementArn
case listenerAddress
case mediaLiveInputArn
case mediaStreamOutputConfigurations
case name
case outputArn
case port
case transport
case vpcInterfaceAttachment
}
}
public struct PurchaseOfferingRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "offeringArn", location: .uri("OfferingArn"))
]
/// The Amazon Resource Name (ARN) of the offering.
public let offeringArn: String
/// The name that you want to use for the reservation.
public let reservationName: String
/// The date and time that you want the reservation to begin, in Coordinated Universal Time (UTC). You can specify any date and time between 12:00am on the first day of the current month to the current time on today's date, inclusive. Specify the start in a 24-hour notation. Use the following format: YYYY-MM-DDTHH:mm:SSZ, where T and Z are literal characters. For example, to specify 11:30pm on March 5, 2020, enter 2020-03-05T23:30:00Z.
public let start: String
public init(offeringArn: String, reservationName: String, start: String) {
self.offeringArn = offeringArn
self.reservationName = reservationName
self.start = start
}
private enum CodingKeys: String, CodingKey {
case reservationName
case start
}
}
public struct PurchaseOfferingResponse: AWSDecodableShape {
public let reservation: Reservation?
public init(reservation: Reservation? = nil) {
self.reservation = reservation
}
private enum CodingKeys: String, CodingKey {
case reservation
}
}
public struct RemoveFlowMediaStreamRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn")),
AWSMemberEncoding(label: "mediaStreamName", location: .uri("MediaStreamName"))
]
/// The Amazon Resource Name (ARN) of the flow.
public let flowArn: String
/// The name of the media stream that you want to remove.
public let mediaStreamName: String
public init(flowArn: String, mediaStreamName: String) {
self.flowArn = flowArn
self.mediaStreamName = mediaStreamName
}
private enum CodingKeys: CodingKey {}
}
public struct RemoveFlowMediaStreamResponse: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the flow.
public let flowArn: String?
/// The name of the media stream that was removed.
public let mediaStreamName: String?
public init(flowArn: String? = nil, mediaStreamName: String? = nil) {
self.flowArn = flowArn
self.mediaStreamName = mediaStreamName
}
private enum CodingKeys: String, CodingKey {
case flowArn
case mediaStreamName
}
}
public struct RemoveFlowOutputRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn")),
AWSMemberEncoding(label: "outputArn", location: .uri("OutputArn"))
]
/// The flow that you want to remove an output from.
public let flowArn: String
/// The ARN of the output that you want to remove.
public let outputArn: String
public init(flowArn: String, outputArn: String) {
self.flowArn = flowArn
self.outputArn = outputArn
}
private enum CodingKeys: CodingKey {}
}
public struct RemoveFlowOutputResponse: AWSDecodableShape {
/// The ARN of the flow that is associated with the output you removed.
public let flowArn: String?
/// The ARN of the output that was removed.
public let outputArn: String?
public init(flowArn: String? = nil, outputArn: String? = nil) {
self.flowArn = flowArn
self.outputArn = outputArn
}
private enum CodingKeys: String, CodingKey {
case flowArn
case outputArn
}
}
public struct RemoveFlowSourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn")),
AWSMemberEncoding(label: "sourceArn", location: .uri("SourceArn"))
]
/// The flow that you want to remove a source from.
public let flowArn: String
/// The ARN of the source that you want to remove.
public let sourceArn: String
public init(flowArn: String, sourceArn: String) {
self.flowArn = flowArn
self.sourceArn = sourceArn
}
private enum CodingKeys: CodingKey {}
}
public struct RemoveFlowSourceResponse: AWSDecodableShape {
/// The ARN of the flow that is associated with the source you removed.
public let flowArn: String?
/// The ARN of the source that was removed.
public let sourceArn: String?
public init(flowArn: String? = nil, sourceArn: String? = nil) {
self.flowArn = flowArn
self.sourceArn = sourceArn
}
private enum CodingKeys: String, CodingKey {
case flowArn
case sourceArn
}
}
public struct RemoveFlowVpcInterfaceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn")),
AWSMemberEncoding(label: "vpcInterfaceName", location: .uri("VpcInterfaceName"))
]
/// The flow that you want to remove a VPC interface from.
public let flowArn: String
/// The name of the VPC interface that you want to remove.
public let vpcInterfaceName: String
public init(flowArn: String, vpcInterfaceName: String) {
self.flowArn = flowArn
self.vpcInterfaceName = vpcInterfaceName
}
private enum CodingKeys: CodingKey {}
}
public struct RemoveFlowVpcInterfaceResponse: AWSDecodableShape {
/// The ARN of the flow that is associated with the VPC interface you removed.
public let flowArn: String?
/// IDs of network interfaces associated with the removed VPC interface that Media Connect was unable to remove.
public let nonDeletedNetworkInterfaceIds: [String]?
/// The name of the VPC interface that was removed.
public let vpcInterfaceName: String?
public init(flowArn: String? = nil, nonDeletedNetworkInterfaceIds: [String]? = nil, vpcInterfaceName: String? = nil) {
self.flowArn = flowArn
self.nonDeletedNetworkInterfaceIds = nonDeletedNetworkInterfaceIds
self.vpcInterfaceName = vpcInterfaceName
}
private enum CodingKeys: String, CodingKey {
case flowArn
case nonDeletedNetworkInterfaceIds
case vpcInterfaceName
}
}
public struct Reservation: AWSDecodableShape {
/// The type of currency that is used for billing. The currencyCode used for your reservation is US dollars.
public let currencyCode: String
/// The length of time that this reservation is active. MediaConnect defines this value in the offering.
public let duration: Int
/// The unit of measurement for the duration of the reservation. MediaConnect defines this value in the offering.
public let durationUnits: DurationUnits
/// The day and time that this reservation expires. This value is calculated based on the start date and time that you set and the offering's duration.
public let end: String
/// The Amazon Resource Name (ARN) that MediaConnect assigns to the offering.
public let offeringArn: String
/// A description of the offering. MediaConnect defines this value in the offering.
public let offeringDescription: String
/// The cost of a single unit. This value, in combination with priceUnits, makes up the rate. MediaConnect defines this value in the offering.
public let pricePerUnit: String
/// The unit of measurement that is used for billing. This value, in combination with pricePerUnit, makes up the rate. MediaConnect defines this value in the offering.
public let priceUnits: PriceUnits
/// The Amazon Resource Name (ARN) that MediaConnect assigns to the reservation when you purchase an offering.
public let reservationArn: String
/// The name that you assigned to the reservation when you purchased the offering.
public let reservationName: String
/// The status of your reservation.
public let reservationState: ReservationState
/// A definition of the amount of outbound bandwidth that you would be reserving if you purchase the offering. MediaConnect defines the values that make up the resourceSpecification in the offering.
public let resourceSpecification: ResourceSpecification
/// The day and time that the reservation becomes active. You set this value when you purchase the offering.
public let start: String
public init(currencyCode: String, duration: Int, durationUnits: DurationUnits, end: String, offeringArn: String, offeringDescription: String, pricePerUnit: String, priceUnits: PriceUnits, reservationArn: String, reservationName: String, reservationState: ReservationState, resourceSpecification: ResourceSpecification, start: String) {
self.currencyCode = currencyCode
self.duration = duration
self.durationUnits = durationUnits
self.end = end
self.offeringArn = offeringArn
self.offeringDescription = offeringDescription
self.pricePerUnit = pricePerUnit
self.priceUnits = priceUnits
self.reservationArn = reservationArn
self.reservationName = reservationName
self.reservationState = reservationState
self.resourceSpecification = resourceSpecification
self.start = start
}
private enum CodingKeys: String, CodingKey {
case currencyCode
case duration
case durationUnits
case end
case offeringArn
case offeringDescription
case pricePerUnit
case priceUnits
case reservationArn
case reservationName
case reservationState
case resourceSpecification
case start
}
}
public struct ResourceSpecification: AWSDecodableShape {
/// The amount of outbound bandwidth that is discounted in the offering.
public let reservedBitrate: Int?
/// The type of resource and the unit that is being billed for.
public let resourceType: ResourceType
public init(reservedBitrate: Int? = nil, resourceType: ResourceType) {
self.reservedBitrate = reservedBitrate
self.resourceType = resourceType
}
private enum CodingKeys: String, CodingKey {
case reservedBitrate
case resourceType
}
}
public struct RevokeFlowEntitlementRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "entitlementArn", location: .uri("EntitlementArn")),
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The ARN of the entitlement that you want to revoke.
public let entitlementArn: String
/// The flow that you want to revoke an entitlement from.
public let flowArn: String
public init(entitlementArn: String, flowArn: String) {
self.entitlementArn = entitlementArn
self.flowArn = flowArn
}
private enum CodingKeys: CodingKey {}
}
public struct RevokeFlowEntitlementResponse: AWSDecodableShape {
/// The ARN of the entitlement that was revoked.
public let entitlementArn: String?
/// The ARN of the flow that the entitlement was revoked from.
public let flowArn: String?
public init(entitlementArn: String? = nil, flowArn: String? = nil) {
self.entitlementArn = entitlementArn
self.flowArn = flowArn
}
private enum CodingKeys: String, CodingKey {
case entitlementArn
case flowArn
}
}
public struct SetSourceRequest: AWSEncodableShape {
/// The type of encryption that is used on the content ingested from this source.
public let decryption: Encryption?
/// A description for the source. This value is not used or seen outside of the current AWS Elemental MediaConnect account.
public let description: String?
/// The ARN of the entitlement that allows you to subscribe to this flow. The entitlement is set by the flow originator, and the ARN is generated as part of the originator's flow.
public let entitlementArn: String?
/// The port that the flow will be listening on for incoming content.
public let ingestPort: Int?
/// The smoothing max bitrate for RIST, RTP, and RTP-FEC streams.
public let maxBitrate: Int?
/// The maximum latency in milliseconds. This parameter applies only to RIST-based and Zixi-based streams.
public let maxLatency: Int?
/// The size of the buffer (in milliseconds) to use to sync incoming source data.
public let maxSyncBuffer: Int?
/// The media streams that are associated with the source, and the parameters for those associations.
public let mediaStreamSourceConfigurations: [MediaStreamSourceConfigurationRequest]?
/// The minimum latency in milliseconds for SRT-based streams. In streams that use the SRT protocol, this value that you set on your MediaConnect source or output represents the minimal potential latency of that connection. The latency of the stream is set to the highest number between the sender’s minimum latency and the receiver’s minimum latency.
public let minLatency: Int?
/// The name of the source.
public let name: String?
/// The protocol that is used by the source.
public let `protocol`: `Protocol`?
/// The stream ID that you want to use for this transport. This parameter applies only to Zixi-based streams.
public let streamId: String?
/// The name of the VPC interface to use for this source.
public let vpcInterfaceName: String?
/// The range of IP addresses that should be allowed to contribute content to your source. These IP addresses should be in the form of a Classless Inter-Domain Routing (CIDR) block; for example, 10.0.0.0/16.
public let whitelistCidr: String?
public init(decryption: Encryption? = nil, description: String? = nil, entitlementArn: String? = nil, ingestPort: Int? = nil, maxBitrate: Int? = nil, maxLatency: Int? = nil, maxSyncBuffer: Int? = nil, mediaStreamSourceConfigurations: [MediaStreamSourceConfigurationRequest]? = nil, minLatency: Int? = nil, name: String? = nil, protocol: `Protocol`? = nil, streamId: String? = nil, vpcInterfaceName: String? = nil, whitelistCidr: String? = nil) {
self.decryption = decryption
self.description = description
self.entitlementArn = entitlementArn
self.ingestPort = ingestPort
self.maxBitrate = maxBitrate
self.maxLatency = maxLatency
self.maxSyncBuffer = maxSyncBuffer
self.mediaStreamSourceConfigurations = mediaStreamSourceConfigurations
self.minLatency = minLatency
self.name = name
self.`protocol` = `protocol`
self.streamId = streamId
self.vpcInterfaceName = vpcInterfaceName
self.whitelistCidr = whitelistCidr
}
private enum CodingKeys: String, CodingKey {
case decryption
case description
case entitlementArn
case ingestPort
case maxBitrate
case maxLatency
case maxSyncBuffer
case mediaStreamSourceConfigurations
case minLatency
case name
case `protocol`
case streamId
case vpcInterfaceName
case whitelistCidr
}
}
public struct Source: AWSDecodableShape {
/// Percentage from 0-100 of the data transfer cost to be billed to the subscriber.
public let dataTransferSubscriberFeePercent: Int?
/// The type of encryption that is used on the content ingested from this source.
public let decryption: Encryption?
/// A description for the source. This value is not used or seen outside of the current AWS Elemental MediaConnect account.
public let description: String?
/// The ARN of the entitlement that allows you to subscribe to content that comes from another AWS account. The entitlement is set by the content originator and the ARN is generated as part of the originator's flow.
public let entitlementArn: String?
/// The IP address that the flow will be listening on for incoming content.
public let ingestIp: String?
/// The port that the flow will be listening on for incoming content.
public let ingestPort: Int?
/// The media streams that are associated with the source, and the parameters for those associations.
public let mediaStreamSourceConfigurations: [MediaStreamSourceConfiguration]?
/// The name of the source.
public let name: String
/// The ARN of the source.
public let sourceArn: String
/// Attributes related to the transport stream that are used in the source.
public let transport: Transport?
/// The name of the VPC interface that is used for this source.
public let vpcInterfaceName: String?
/// The range of IP addresses that should be allowed to contribute content to your source. These IP addresses should be in the form of a Classless Inter-Domain Routing (CIDR) block; for example, 10.0.0.0/16.
public let whitelistCidr: String?
public init(dataTransferSubscriberFeePercent: Int? = nil, decryption: Encryption? = nil, description: String? = nil, entitlementArn: String? = nil, ingestIp: String? = nil, ingestPort: Int? = nil, mediaStreamSourceConfigurations: [MediaStreamSourceConfiguration]? = nil, name: String, sourceArn: String, transport: Transport? = nil, vpcInterfaceName: String? = nil, whitelistCidr: String? = nil) {
self.dataTransferSubscriberFeePercent = dataTransferSubscriberFeePercent
self.decryption = decryption
self.description = description
self.entitlementArn = entitlementArn
self.ingestIp = ingestIp
self.ingestPort = ingestPort
self.mediaStreamSourceConfigurations = mediaStreamSourceConfigurations
self.name = name
self.sourceArn = sourceArn
self.transport = transport
self.vpcInterfaceName = vpcInterfaceName
self.whitelistCidr = whitelistCidr
}
private enum CodingKeys: String, CodingKey {
case dataTransferSubscriberFeePercent
case decryption
case description
case entitlementArn
case ingestIp
case ingestPort
case mediaStreamSourceConfigurations
case name
case sourceArn
case transport
case vpcInterfaceName
case whitelistCidr
}
}
public struct SourcePriority: AWSEncodableShape & AWSDecodableShape {
/// The name of the source you choose as the primary source for this flow.
public let primarySource: String?
public init(primarySource: String? = nil) {
self.primarySource = primarySource
}
private enum CodingKeys: String, CodingKey {
case primarySource
}
}
public struct StartFlowRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The ARN of the flow that you want to start.
public let flowArn: String
public init(flowArn: String) {
self.flowArn = flowArn
}
private enum CodingKeys: CodingKey {}
}
public struct StartFlowResponse: AWSDecodableShape {
/// The ARN of the flow that you started.
public let flowArn: String?
/// The status of the flow when the StartFlow process begins.
public let status: Status?
public init(flowArn: String? = nil, status: Status? = nil) {
self.flowArn = flowArn
self.status = status
}
private enum CodingKeys: String, CodingKey {
case flowArn
case status
}
}
public struct StopFlowRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The ARN of the flow that you want to stop.
public let flowArn: String
public init(flowArn: String) {
self.flowArn = flowArn
}
private enum CodingKeys: CodingKey {}
}
public struct StopFlowResponse: AWSDecodableShape {
/// The ARN of the flow that you stopped.
public let flowArn: String?
/// The status of the flow when the StopFlow process begins.
public let status: Status?
public init(flowArn: String? = nil, status: Status? = nil) {
self.flowArn = flowArn
self.status = status
}
private enum CodingKeys: String, CodingKey {
case flowArn
case status
}
}
public struct TagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri("ResourceArn"))
]
/// The Amazon Resource Name (ARN) that identifies the AWS Elemental MediaConnect resource to which to add tags.
public let resourceArn: String
/// A map from tag keys to values. Tag keys can have a maximum character length of 128 characters, and tag values can have a maximum length of 256 characters.
public let tags: [String: String]
public init(resourceArn: String, tags: [String: String]) {
self.resourceArn = resourceArn
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags
}
}
public struct Transport: AWSDecodableShape {
/// The range of IP addresses that should be allowed to initiate output requests to this flow. These IP addresses should be in the form of a Classless Inter-Domain Routing (CIDR) block; for example, 10.0.0.0/16.
public let cidrAllowList: [String]?
/// The smoothing max bitrate for RIST, RTP, and RTP-FEC streams.
public let maxBitrate: Int?
/// The maximum latency in milliseconds. This parameter applies only to RIST-based and Zixi-based streams.
public let maxLatency: Int?
/// The size of the buffer (in milliseconds) to use to sync incoming source data.
public let maxSyncBuffer: Int?
/// The minimum latency in milliseconds for SRT-based streams. In streams that use the SRT protocol, this value that you set on your MediaConnect source or output represents the minimal potential latency of that connection. The latency of the stream is set to the highest number between the sender’s minimum latency and the receiver’s minimum latency.
public let minLatency: Int?
/// The protocol that is used by the source or output.
public let `protocol`: `Protocol`
/// The remote ID for the Zixi-pull stream.
public let remoteId: String?
/// The smoothing latency in milliseconds for RIST, RTP, and RTP-FEC streams.
public let smoothingLatency: Int?
/// The stream ID that you want to use for this transport. This parameter applies only to Zixi-based streams.
public let streamId: String?
public init(cidrAllowList: [String]? = nil, maxBitrate: Int? = nil, maxLatency: Int? = nil, maxSyncBuffer: Int? = nil, minLatency: Int? = nil, protocol: `Protocol`, remoteId: String? = nil, smoothingLatency: Int? = nil, streamId: String? = nil) {
self.cidrAllowList = cidrAllowList
self.maxBitrate = maxBitrate
self.maxLatency = maxLatency
self.maxSyncBuffer = maxSyncBuffer
self.minLatency = minLatency
self.`protocol` = `protocol`
self.remoteId = remoteId
self.smoothingLatency = smoothingLatency
self.streamId = streamId
}
private enum CodingKeys: String, CodingKey {
case cidrAllowList
case maxBitrate
case maxLatency
case maxSyncBuffer
case minLatency
case `protocol`
case remoteId
case smoothingLatency
case streamId
}
}
public struct UntagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resourceArn", location: .uri("ResourceArn")),
AWSMemberEncoding(label: "tagKeys", location: .querystring("tagKeys"))
]
/// The Amazon Resource Name (ARN) that identifies the AWS Elemental MediaConnect resource from which to delete tags.
public let resourceArn: String
/// The keys of the tags to be removed.
public let tagKeys: [String]
public init(resourceArn: String, tagKeys: [String]) {
self.resourceArn = resourceArn
self.tagKeys = tagKeys
}
private enum CodingKeys: CodingKey {}
}
public struct UpdateEncryption: AWSEncodableShape {
/// The type of algorithm that is used for the encryption (such as aes128, aes192, or aes256).
public let algorithm: Algorithm?
/// A 128-bit, 16-byte hex value represented by a 32-character string, to be used with the key for encrypting content. This parameter is not valid for static key encryption.
public let constantInitializationVector: String?
/// The value of one of the devices that you configured with your digital rights management (DRM) platform key provider. This parameter is required for SPEKE encryption and is not valid for static key encryption.
public let deviceId: String?
/// The type of key that is used for the encryption. If no keyType is provided, the service will use the default setting (static-key).
public let keyType: KeyType?
/// The AWS Region that the API Gateway proxy endpoint was created in. This parameter is required for SPEKE encryption and is not valid for static key encryption.
public let region: String?
/// An identifier for the content. The service sends this value to the key server to identify the current endpoint. The resource ID is also known as the content ID. This parameter is required for SPEKE encryption and is not valid for static key encryption.
public let resourceId: String?
/// The ARN of the role that you created during setup (when you set up AWS Elemental MediaConnect as a trusted entity).
public let roleArn: String?
/// The ARN of the secret that you created in AWS Secrets Manager to store the encryption key. This parameter is required for static key encryption and is not valid for SPEKE encryption.
public let secretArn: String?
/// The URL from the API Gateway proxy that you set up to talk to your key server. This parameter is required for SPEKE encryption and is not valid for static key encryption.
public let url: String?
public init(algorithm: Algorithm? = nil, constantInitializationVector: String? = nil, deviceId: String? = nil, keyType: KeyType? = nil, region: String? = nil, resourceId: String? = nil, roleArn: String? = nil, secretArn: String? = nil, url: String? = nil) {
self.algorithm = algorithm
self.constantInitializationVector = constantInitializationVector
self.deviceId = deviceId
self.keyType = keyType
self.region = region
self.resourceId = resourceId
self.roleArn = roleArn
self.secretArn = secretArn
self.url = url
}
private enum CodingKeys: String, CodingKey {
case algorithm
case constantInitializationVector
case deviceId
case keyType
case region
case resourceId
case roleArn
case secretArn
case url
}
}
public struct UpdateFailoverConfig: AWSEncodableShape {
/// The type of failover you choose for this flow. MERGE combines the source streams into a single stream, allowing graceful recovery from any single-source loss. FAILOVER allows switching between different streams.
public let failoverMode: FailoverMode?
/// Recovery window time to look for dash-7 packets
public let recoveryWindow: Int?
/// The priority you want to assign to a source. You can have a primary stream and a backup stream or two equally prioritized streams.
public let sourcePriority: SourcePriority?
public let state: State?
public init(failoverMode: FailoverMode? = nil, recoveryWindow: Int? = nil, sourcePriority: SourcePriority? = nil, state: State? = nil) {
self.failoverMode = failoverMode
self.recoveryWindow = recoveryWindow
self.sourcePriority = sourcePriority
self.state = state
}
private enum CodingKeys: String, CodingKey {
case failoverMode
case recoveryWindow
case sourcePriority
case state
}
}
public struct UpdateFlowEntitlementRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "entitlementArn", location: .uri("EntitlementArn")),
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// A description of the entitlement. This description appears only on the AWS Elemental MediaConnect console and will not be seen by the subscriber or end user.
public let description: String?
/// The type of encryption that will be used on the output associated with this entitlement.
public let encryption: UpdateEncryption?
/// The ARN of the entitlement that you want to update.
public let entitlementArn: String
/// An indication of whether you want to enable the entitlement to allow access, or disable it to stop streaming content to the subscriber’s flow temporarily. If you don’t specify the entitlementStatus field in your request, MediaConnect leaves the value unchanged.
public let entitlementStatus: EntitlementStatus?
/// The flow that is associated with the entitlement that you want to update.
public let flowArn: String
/// The AWS account IDs that you want to share your content with. The receiving accounts (subscribers) will be allowed to create their own flow using your content as the source.
public let subscribers: [String]?
public init(description: String? = nil, encryption: UpdateEncryption? = nil, entitlementArn: String, entitlementStatus: EntitlementStatus? = nil, flowArn: String, subscribers: [String]? = nil) {
self.description = description
self.encryption = encryption
self.entitlementArn = entitlementArn
self.entitlementStatus = entitlementStatus
self.flowArn = flowArn
self.subscribers = subscribers
}
private enum CodingKeys: String, CodingKey {
case description
case encryption
case entitlementStatus
case subscribers
}
}
public struct UpdateFlowEntitlementResponse: AWSDecodableShape {
/// The new configuration of the entitlement that you updated.
public let entitlement: Entitlement?
/// The ARN of the flow that this entitlement was granted on.
public let flowArn: String?
public init(entitlement: Entitlement? = nil, flowArn: String? = nil) {
self.entitlement = entitlement
self.flowArn = flowArn
}
private enum CodingKeys: String, CodingKey {
case entitlement
case flowArn
}
}
public struct UpdateFlowMediaStreamRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn")),
AWSMemberEncoding(label: "mediaStreamName", location: .uri("MediaStreamName"))
]
/// The attributes that you want to assign to the media stream.
public let attributes: MediaStreamAttributesRequest?
/// The sample rate (in Hz) for the stream. If the media stream type is video or ancillary data, set this value to 90000. If the media stream type is audio, set this value to either 48000 or 96000.
public let clockRate: Int?
/// Description
public let description: String?
/// The Amazon Resource Name (ARN) of the flow.
public let flowArn: String
/// The name of the media stream that you want to update.
public let mediaStreamName: String
/// The type of media stream.
public let mediaStreamType: MediaStreamType?
/// The resolution of the video.
public let videoFormat: String?
public init(attributes: MediaStreamAttributesRequest? = nil, clockRate: Int? = nil, description: String? = nil, flowArn: String, mediaStreamName: String, mediaStreamType: MediaStreamType? = nil, videoFormat: String? = nil) {
self.attributes = attributes
self.clockRate = clockRate
self.description = description
self.flowArn = flowArn
self.mediaStreamName = mediaStreamName
self.mediaStreamType = mediaStreamType
self.videoFormat = videoFormat
}
private enum CodingKeys: String, CodingKey {
case attributes
case clockRate
case description
case mediaStreamType
case videoFormat
}
}
public struct UpdateFlowMediaStreamResponse: AWSDecodableShape {
/// The ARN of the flow that is associated with the media stream that you updated.
public let flowArn: String?
/// The media stream that you updated.
public let mediaStream: MediaStream?
public init(flowArn: String? = nil, mediaStream: MediaStream? = nil) {
self.flowArn = flowArn
self.mediaStream = mediaStream
}
private enum CodingKeys: String, CodingKey {
case flowArn
case mediaStream
}
}
public struct UpdateFlowOutputRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn")),
AWSMemberEncoding(label: "outputArn", location: .uri("OutputArn"))
]
/// The range of IP addresses that should be allowed to initiate output requests to this flow. These IP addresses should be in the form of a Classless Inter-Domain Routing (CIDR) block; for example, 10.0.0.0/16.
public let cidrAllowList: [String]?
/// A description of the output. This description appears only on the AWS Elemental MediaConnect console and will not be seen by the end user.
public let description: String?
/// The IP address where you want to send the output.
public let destination: String?
/// The type of key used for the encryption. If no keyType is provided, the service will use the default setting (static-key).
public let encryption: UpdateEncryption?
/// The flow that is associated with the output that you want to update.
public let flowArn: String
/// The maximum latency in milliseconds for Zixi-based streams.
public let maxLatency: Int?
/// The media streams that are associated with the output, and the parameters for those associations.
public let mediaStreamOutputConfigurations: [MediaStreamOutputConfigurationRequest]?
/// The minimum latency in milliseconds for SRT-based streams. In streams that use the SRT protocol, this value that you set on your MediaConnect source or output represents the minimal potential latency of that connection. The latency of the stream is set to the highest number between the sender’s minimum latency and the receiver’s minimum latency.
public let minLatency: Int?
/// The ARN of the output that you want to update.
public let outputArn: String
/// The port to use when content is distributed to this output.
public let port: Int?
/// The protocol to use for the output.
public let `protocol`: `Protocol`?
/// The remote ID for the Zixi-pull stream.
public let remoteId: String?
/// The smoothing latency in milliseconds for RIST, RTP, and RTP-FEC streams.
public let smoothingLatency: Int?
/// The stream ID that you want to use for this transport. This parameter applies only to Zixi-based streams.
public let streamId: String?
/// The name of the VPC interface attachment to use for this output.
public let vpcInterfaceAttachment: VpcInterfaceAttachment?
public init(cidrAllowList: [String]? = nil, description: String? = nil, destination: String? = nil, encryption: UpdateEncryption? = nil, flowArn: String, maxLatency: Int? = nil, mediaStreamOutputConfigurations: [MediaStreamOutputConfigurationRequest]? = nil, minLatency: Int? = nil, outputArn: String, port: Int? = nil, protocol: `Protocol`? = nil, remoteId: String? = nil, smoothingLatency: Int? = nil, streamId: String? = nil, vpcInterfaceAttachment: VpcInterfaceAttachment? = nil) {
self.cidrAllowList = cidrAllowList
self.description = description
self.destination = destination
self.encryption = encryption
self.flowArn = flowArn
self.maxLatency = maxLatency
self.mediaStreamOutputConfigurations = mediaStreamOutputConfigurations
self.minLatency = minLatency
self.outputArn = outputArn
self.port = port
self.`protocol` = `protocol`
self.remoteId = remoteId
self.smoothingLatency = smoothingLatency
self.streamId = streamId
self.vpcInterfaceAttachment = vpcInterfaceAttachment
}
private enum CodingKeys: String, CodingKey {
case cidrAllowList
case description
case destination
case encryption
case maxLatency
case mediaStreamOutputConfigurations
case minLatency
case port
case `protocol`
case remoteId
case smoothingLatency
case streamId
case vpcInterfaceAttachment
}
}
public struct UpdateFlowOutputResponse: AWSDecodableShape {
/// The ARN of the flow that is associated with the updated output.
public let flowArn: String?
/// The new settings of the output that you updated.
public let output: Output?
public init(flowArn: String? = nil, output: Output? = nil) {
self.flowArn = flowArn
self.output = output
}
private enum CodingKeys: String, CodingKey {
case flowArn
case output
}
}
public struct UpdateFlowRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn"))
]
/// The flow that you want to update.
public let flowArn: String
public let sourceFailoverConfig: UpdateFailoverConfig?
public init(flowArn: String, sourceFailoverConfig: UpdateFailoverConfig? = nil) {
self.flowArn = flowArn
self.sourceFailoverConfig = sourceFailoverConfig
}
private enum CodingKeys: String, CodingKey {
case sourceFailoverConfig
}
}
public struct UpdateFlowResponse: AWSDecodableShape {
public let flow: Flow?
public init(flow: Flow? = nil) {
self.flow = flow
}
private enum CodingKeys: String, CodingKey {
case flow
}
}
public struct UpdateFlowSourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "flowArn", location: .uri("FlowArn")),
AWSMemberEncoding(label: "sourceArn", location: .uri("SourceArn"))
]
/// The type of encryption used on the content ingested from this source.
public let decryption: UpdateEncryption?
/// A description for the source. This value is not used or seen outside of the current AWS Elemental MediaConnect account.
public let description: String?
/// The ARN of the entitlement that allows you to subscribe to this flow. The entitlement is set by the flow originator, and the ARN is generated as part of the originator's flow.
public let entitlementArn: String?
/// The flow that is associated with the source that you want to update.
public let flowArn: String
/// The port that the flow will be listening on for incoming content.
public let ingestPort: Int?
/// The smoothing max bitrate for RIST, RTP, and RTP-FEC streams.
public let maxBitrate: Int?
/// The maximum latency in milliseconds. This parameter applies only to RIST-based and Zixi-based streams.
public let maxLatency: Int?
/// The size of the buffer (in milliseconds) to use to sync incoming source data.
public let maxSyncBuffer: Int?
/// The media streams that are associated with the source, and the parameters for those associations.
public let mediaStreamSourceConfigurations: [MediaStreamSourceConfigurationRequest]?
/// The minimum latency in milliseconds for SRT-based streams. In streams that use the SRT protocol, this value that you set on your MediaConnect source or output represents the minimal potential latency of that connection. The latency of the stream is set to the highest number between the sender’s minimum latency and the receiver’s minimum latency.
public let minLatency: Int?
/// The protocol that is used by the source.
public let `protocol`: `Protocol`?
/// The ARN of the source that you want to update.
public let sourceArn: String
/// The stream ID that you want to use for this transport. This parameter applies only to Zixi-based streams.
public let streamId: String?
/// The name of the VPC interface to use for this source.
public let vpcInterfaceName: String?
/// The range of IP addresses that should be allowed to contribute content to your source. These IP addresses should be in the form of a Classless Inter-Domain Routing (CIDR) block; for example, 10.0.0.0/16.
public let whitelistCidr: String?
public init(decryption: UpdateEncryption? = nil, description: String? = nil, entitlementArn: String? = nil, flowArn: String, ingestPort: Int? = nil, maxBitrate: Int? = nil, maxLatency: Int? = nil, maxSyncBuffer: Int? = nil, mediaStreamSourceConfigurations: [MediaStreamSourceConfigurationRequest]? = nil, minLatency: Int? = nil, protocol: `Protocol`? = nil, sourceArn: String, streamId: String? = nil, vpcInterfaceName: String? = nil, whitelistCidr: String? = nil) {
self.decryption = decryption
self.description = description
self.entitlementArn = entitlementArn
self.flowArn = flowArn
self.ingestPort = ingestPort
self.maxBitrate = maxBitrate
self.maxLatency = maxLatency
self.maxSyncBuffer = maxSyncBuffer
self.mediaStreamSourceConfigurations = mediaStreamSourceConfigurations
self.minLatency = minLatency
self.`protocol` = `protocol`
self.sourceArn = sourceArn
self.streamId = streamId
self.vpcInterfaceName = vpcInterfaceName
self.whitelistCidr = whitelistCidr
}
private enum CodingKeys: String, CodingKey {
case decryption
case description
case entitlementArn
case ingestPort
case maxBitrate
case maxLatency
case maxSyncBuffer
case mediaStreamSourceConfigurations
case minLatency
case `protocol`
case streamId
case vpcInterfaceName
case whitelistCidr
}
}
public struct UpdateFlowSourceResponse: AWSDecodableShape {
/// The ARN of the flow that you want to update.
public let flowArn: String?
/// The settings for the source of the flow.
public let source: Source?
public init(flowArn: String? = nil, source: Source? = nil) {
self.flowArn = flowArn
self.source = source
}
private enum CodingKeys: String, CodingKey {
case flowArn
case source
}
}
public struct VpcInterface: AWSDecodableShape {
/// Immutable and has to be a unique against other VpcInterfaces in this Flow
public let name: String
/// IDs of the network interfaces created in customer's account by MediaConnect.
public let networkInterfaceIds: [String]
/// The type of network interface.
public let networkInterfaceType: NetworkInterfaceType
/// Role Arn MediaConnect can assumes to create ENIs in customer's account
public let roleArn: String
/// Security Group IDs to be used on ENI.
public let securityGroupIds: [String]
/// Subnet must be in the AZ of the Flow
public let subnetId: String
public init(name: String, networkInterfaceIds: [String], networkInterfaceType: NetworkInterfaceType, roleArn: String, securityGroupIds: [String], subnetId: String) {
self.name = name
self.networkInterfaceIds = networkInterfaceIds
self.networkInterfaceType = networkInterfaceType
self.roleArn = roleArn
self.securityGroupIds = securityGroupIds
self.subnetId = subnetId
}
private enum CodingKeys: String, CodingKey {
case name
case networkInterfaceIds
case networkInterfaceType
case roleArn
case securityGroupIds
case subnetId
}
}
public struct VpcInterfaceAttachment: AWSEncodableShape & AWSDecodableShape {
/// The name of the VPC interface to use for this output.
public let vpcInterfaceName: String?
public init(vpcInterfaceName: String? = nil) {
self.vpcInterfaceName = vpcInterfaceName
}
private enum CodingKeys: String, CodingKey {
case vpcInterfaceName
}
}
public struct VpcInterfaceRequest: AWSEncodableShape {
/// The name of the VPC Interface. This value must be unique within the current flow.
public let name: String
/// The type of network interface. If this value is not included in the request, MediaConnect uses ENA as the networkInterfaceType.
public let networkInterfaceType: NetworkInterfaceType?
/// Role Arn MediaConnect can assumes to create ENIs in customer's account
public let roleArn: String
/// Security Group IDs to be used on ENI.
public let securityGroupIds: [String]
/// Subnet must be in the AZ of the Flow
public let subnetId: String
public init(name: String, networkInterfaceType: NetworkInterfaceType? = nil, roleArn: String, securityGroupIds: [String], subnetId: String) {
self.name = name
self.networkInterfaceType = networkInterfaceType
self.roleArn = roleArn
self.securityGroupIds = securityGroupIds
self.subnetId = subnetId
}
private enum CodingKeys: String, CodingKey {
case name
case networkInterfaceType
case roleArn
case securityGroupIds
case subnetId
}
}
}
| 45.927835 | 519 | 0.656557 |
7188f1af74eb9339b0af145d513abee4b3e022fc | 478 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -parse-stdlib -Xfrontend -disable-access-control -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
import Swift
print(String(Int32(Builtin.bitcast_FPIEEE32_Int32(Float32(1)._value)), radix: 16)) // CHECK: {{^}}3f800000{{$}}
print(String(UInt64(Builtin.bitcast_FPIEEE64_Int64(Float64(1)._value)), radix: 16)) // CHECK: {{^}}3ff0000000000000{{$}}
| 39.833333 | 120 | 0.698745 |
16601f36794b483f397250eae7242052f2f8938e | 6,554 | //
// AppDelegate.swift
// Lesson_MVP_Demo
//
// Created by 朱佩 on 16/5/24.
// Copyright © 2016年 Andy zhu. All rights reserved.
//
import UIKit
import CoreData
import QorumLogs
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//这个第三方库生效的话,需要安装XcodeColor插件,否则无效
QorumLogs.enabled = true
QorumOnlineLogs.enabled = true
QorumLogs.minimumLogLevelShown = 2
QorumOnlineLogs.minimumLogLevelShown = 4 // Its a good idea to have OnlineLog level a bit higher
QorumLogs.colorsForLogLevels[0] = QLColor(r: 255, g: 255, b: 0)
QorumLogs.colorsForLogLevels[1] = QLColor(r: 255, g: 20, b: 147)
QorumLogs.test()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "skinrun.Lesson_MVP_Demo" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Lesson_MVP_Demo", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 54.165289 | 291 | 0.716204 |
6778244209abe748876f106c4f98583126d5986f | 1,211 | // swift-tools-version:5.3
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "SwiftUICores",
platforms: [
.iOS(.v13)
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "SwiftUICores",
targets: ["SwiftUICores"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/Alamofire/Alamofire", from: "5.0.0"),
.package(url: "https://github.com/Alamofire/AlamofireImage", from: "4.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "SwiftUICores",
dependencies: ["Alamofire", "AlamofireImage"]),
.testTarget(
name: "SwiftUICoresTests",
dependencies: ["SwiftUICores"]),
]
)
| 36.69697 | 117 | 0.628406 |
bbbdeaa814b52c4421667dda81a47646208d66f5 | 4,440 | //
// WidgetsListViewController.swift
// DJIUXSDK
//
// Copyright © 2018-2019 DJI
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import DJIUXSDKBeta
protocol WidgetSelectionDelegate: class {
func widgetSelected(_ widget: DUXBetaBaseWidget?)
}
class WidgetsListViewController: UITableViewController {
weak var delegate: WidgetSelectionDelegate?
static let widgetDescriptions:[String:String] = [
"Map Widget":"Widget that displays the aircraft's state and information on the map this includes aircraft location, home location, aircraft trail path, aircraft heading, and No Fly Zones.",
"Battery Widget" : "Widget that displays aircraft battery level.",
"Compass Widget" : "Displays the position of the aircraft in relation to the home point and pilot location.",
"Dashboard Widget" : "Compound widget that aggregates important information about the aircraft into a dashboard.",
"Vision Widget" : "Widget to display the vision status/collision avodance status, of the aircraft. It's state depends on sensors availability, flight mode, and aircraft type.",
]
static let widgets:[DUXBetaBaseWidget] = [DUXBetaMapWidget(),
DUXBetaBatteryWidget(),
DUXBetaCompassWidget(),
DUXBetaDashboardWidget(),
DUXBetaVisionWidget()]
static let widgetTitles:[String] = ["Map Widget",
"Battery Widget",
"Compass Widget",
"Dashboard Widget",
"Vision Widget"]
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func close () {
self.dismiss(animated: true) { }
}
// MARK: UITableViewDelegate
public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let widget = WidgetsListViewController.widgets[indexPath.row]
delegate?.widgetSelected(widget)
if let singleWidgetViewController = delegate as? SingleWidgetViewController {
let title = WidgetsListViewController.widgetTitles[indexPath.row]
singleWidgetViewController.title = title
singleWidgetViewController.widgetDescriptionLabel.text = WidgetsListViewController.widgetDescriptions[title]
splitViewController?.showDetailViewController(singleWidgetViewController, sender: nil)
}
}
// MARK: UITableViewDataSource
public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return WidgetsListViewController.widgets.count
}
public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "WidgetsListCellIdentifier", for: indexPath)
cell.textLabel?.text = WidgetsListViewController.widgetTitles[indexPath.row]
return cell
}
}
| 49.88764 | 241 | 0.64482 |
5b82f024f3c30515e8a5e2d4676f63f21aedb265 | 11,239 | import Basic
import Foundation
import TuistCore
import xcodeproj
protocol ConfigGenerating: AnyObject {
func generateProjectConfig(project: Project,
pbxproj: PBXProj,
fileElements: ProjectFileElements,
options: GenerationOptions) throws -> XCConfigurationList
func generateTargetConfig(_ target: Target,
pbxTarget: PBXTarget,
pbxproj: PBXProj,
fileElements: ProjectFileElements,
graph: Graphing,
options: GenerationOptions,
sourceRootPath: AbsolutePath) throws
}
final class ConfigGenerator: ConfigGenerating {
// MARK: - Attributes
let fileGenerator: FileGenerating
// MARK: - Init
init(fileGenerator: FileGenerating = FileGenerator()) {
self.fileGenerator = fileGenerator
}
// MARK: - ConfigGenerating
func generateProjectConfig(project: Project,
pbxproj: PBXProj,
fileElements: ProjectFileElements,
options _: GenerationOptions) throws -> XCConfigurationList {
/// Configuration list
let configurationList = XCConfigurationList(buildConfigurations: [])
pbxproj.add(object: configurationList)
try generateProjectSettingsFor(buildConfiguration: .debug,
configuration: project.settings?.debug,
project: project,
fileElements: fileElements,
pbxproj: pbxproj,
configurationList: configurationList)
try generateProjectSettingsFor(buildConfiguration: .release,
configuration: project.settings?.release,
project: project,
fileElements: fileElements,
pbxproj: pbxproj,
configurationList: configurationList)
return configurationList
}
func generateTargetConfig(_ target: Target,
pbxTarget: PBXTarget,
pbxproj: PBXProj,
fileElements: ProjectFileElements,
graph: Graphing,
options _: GenerationOptions,
sourceRootPath: AbsolutePath) throws {
let configurationList = XCConfigurationList(buildConfigurations: [])
pbxproj.add(object: configurationList)
pbxTarget.buildConfigurationList = configurationList
try generateTargetSettingsFor(target: target,
buildConfiguration: .debug,
configuration: target.settings?.debug,
fileElements: fileElements,
graph: graph,
pbxproj: pbxproj,
configurationList: configurationList,
sourceRootPath: sourceRootPath)
try generateTargetSettingsFor(target: target,
buildConfiguration: .release,
configuration: target.settings?.release,
fileElements: fileElements,
graph: graph,
pbxproj: pbxproj,
configurationList: configurationList,
sourceRootPath: sourceRootPath)
}
// MARK: - Fileprivate
private func generateProjectSettingsFor(buildConfiguration: BuildConfiguration,
configuration: Configuration?,
project: Project,
fileElements: ProjectFileElements,
pbxproj: PBXProj,
configurationList: XCConfigurationList) throws {
let variant: BuildSettingsProvider.Variant = (buildConfiguration == .debug) ? .debug : .release
let defaultConfigSettings = BuildSettingsProvider.projectDefault(variant: variant)
let defaultSettingsAll = BuildSettingsProvider.projectDefault(variant: .all)
var settings: [String: Any] = [:]
extend(buildSettings: &settings, with: defaultSettingsAll)
extend(buildSettings: &settings, with: project.settings?.base ?? [:])
extend(buildSettings: &settings, with: defaultConfigSettings)
let variantBuildConfiguration = XCBuildConfiguration(name: buildConfiguration.rawValue.capitalized,
baseConfiguration: nil,
buildSettings: [:])
if let variantConfig = configuration {
extend(buildSettings: &settings, with: variantConfig.settings)
if let xcconfig = variantConfig.xcconfig {
let fileReference = fileElements.file(path: xcconfig)
variantBuildConfiguration.baseConfiguration = fileReference
}
}
variantBuildConfiguration.buildSettings = settings
pbxproj.add(object: variantBuildConfiguration)
configurationList.buildConfigurations.append(variantBuildConfiguration)
}
private func generateTargetSettingsFor(target: Target,
buildConfiguration: BuildConfiguration,
configuration: Configuration?,
fileElements: ProjectFileElements,
graph: Graphing,
pbxproj: PBXProj,
configurationList: XCConfigurationList,
sourceRootPath: AbsolutePath) throws {
let product = settingsProviderProduct(target)
let platform = settingsProviderPlatform(target)
let variant: BuildSettingsProvider.Variant = (buildConfiguration == .debug) ? .debug : .release
var settings: [String: Any] = [:]
extend(buildSettings: &settings, with: BuildSettingsProvider.targetDefault(variant: .all,
platform: platform,
product: product,
swift: true))
extend(buildSettings: &settings, with: BuildSettingsProvider.targetDefault(variant: variant,
platform: platform,
product: product,
swift: true))
extend(buildSettings: &settings, with: target.settings?.base ?? [:])
extend(buildSettings: &settings, with: configuration?.settings ?? [:])
let variantBuildConfiguration = XCBuildConfiguration(name: buildConfiguration.rawValue.capitalized,
baseConfiguration: nil,
buildSettings: [:])
if let variantConfig = configuration {
if let xcconfig = variantConfig.xcconfig {
let fileReference = fileElements.file(path: xcconfig)
variantBuildConfiguration.baseConfiguration = fileReference
}
}
/// Target attributes
settings["PRODUCT_BUNDLE_IDENTIFIER"] = target.bundleId
if let infoPlist = target.infoPlist {
settings["INFOPLIST_FILE"] = "$(SRCROOT)/\(infoPlist.relative(to: sourceRootPath).asString)"
}
if let entitlements = target.entitlements {
settings["CODE_SIGN_ENTITLEMENTS"] = "$(SRCROOT)/\(entitlements.relative(to: sourceRootPath).asString)"
}
settings["SDKROOT"] = target.platform.xcodeSdkRoot
settings["SUPPORTED_PLATFORMS"] = target.platform.xcodeSupportedPlatforms
// TODO: We should show a warning here
if settings["SWIFT_VERSION"] == nil {
settings["SWIFT_VERSION"] = Constants.swiftVersion
}
if target.product == .staticFramework {
settings["MACH_O_TYPE"] = "staticlib"
}
if target.product.testsBundle {
let appDependency = graph.targetDependencies(path: sourceRootPath, name: target.name).first { targetNode in
targetNode.target.product == .app
}
if let app = appDependency {
settings["TEST_TARGET_NAME"] = "\(app.target.name)"
if target.product == .unitTests {
settings["TEST_HOST"] = "$(BUILT_PRODUCTS_DIR)/\(app.target.productName)/\(app.target.name)"
settings["BUNDLE_LOADER"] = "$(TEST_HOST)"
}
}
}
variantBuildConfiguration.buildSettings = settings
pbxproj.add(object: variantBuildConfiguration)
configurationList.buildConfigurations.append(variantBuildConfiguration)
}
private func settingsProviderPlatform(_ target: Target) -> BuildSettingsProvider.Platform? {
var platform: BuildSettingsProvider.Platform?
switch target.platform {
case .iOS: platform = .iOS
case .macOS: platform = .macOS
case .tvOS: platform = .tvOS
// case .watchOS: platform = .watchOS
}
return platform
}
private func settingsProviderProduct(_ target: Target) -> BuildSettingsProvider.Product? {
switch target.product {
case .app:
return .application
case .dynamicLibrary:
return .dynamicLibrary
case .staticLibrary:
return .staticLibrary
case .framework, .staticFramework:
return .framework
default:
return nil
}
}
private func extend(buildSettings: inout [String: Any], with other: [String: Any]) {
other.forEach { key, value in
if buildSettings[key] == nil || (value as? String)?.contains("$(inherited)") == false {
buildSettings[key] = value
} else {
let previousValue: Any = buildSettings[key]!
if let previousValueString = previousValue as? String, let newValueString = value as? String {
buildSettings[key] = "\(previousValueString) \(newValueString)"
} else {
buildSettings[key] = value
}
}
}
}
}
| 48.029915 | 119 | 0.523089 |
09fb7ad80b81d8a7d6bc1b6f9a1f5a3994d007fa | 18,494 | //
// DelegateProxyTest+UIKit.swift
// Tests
//
// Created by Krunoslav Zaher on 12/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
@testable import RxCocoa
@testable import RxSwift
import XCTest
// MARK: Tests
extension DelegateProxyTest {
func test_UITableViewDelegateExtension() {
performDelegateTest(UITableViewSubclass1(frame: CGRect.zero)) { ExtendTableViewDelegateProxy(tableViewSubclass: $0) }
}
func test_UITableViewDataSourceExtension() {
performDelegateTest(UITableViewSubclass2(frame: CGRect.zero)) { ExtendTableViewDataSourceProxy(tableViewSubclass: $0) }
}
@available(iOS 10.0, tvOS 10.0, *)
func test_UITableViewDataSourcePrefetchingExtension() {
performDelegateTest(UITableViewSubclass3(frame: CGRect.zero)) { ExtendTableViewDataSourcePrefetchingProxy(parentObject: $0) }
}
}
extension DelegateProxyTest {
func test_UICollectionViewDelegateExtension() {
let layout = UICollectionViewFlowLayout()
performDelegateTest(UICollectionViewSubclass1(frame: CGRect.zero, collectionViewLayout: layout)) { ExtendCollectionViewDelegateProxy(parentObject: $0) }
}
func test_UICollectionViewDataSourceExtension() {
let layout = UICollectionViewFlowLayout()
performDelegateTest(UICollectionViewSubclass2(frame: CGRect.zero, collectionViewLayout: layout)) { ExtendCollectionViewDataSourceProxy(parentObject: $0) }
}
@available(iOS 10.0, tvOS 10.0, *)
func test_UICollectionViewDataSourcePrefetchingExtension() {
let layout = UICollectionViewFlowLayout()
performDelegateTest(UICollectionViewSubclass3(frame: CGRect.zero, collectionViewLayout: layout)) { ExtendCollectionViewDataSourcePrefetchingProxy(parentObject: $0) }
}
}
extension DelegateProxyTest {
func test_UINavigationControllerDelegateExtension() {
performDelegateTest(UINavigationControllerSubclass()) { ExtendNavigationControllerDelegateProxy(navigationControllerSubclass: $0) }
}
}
extension DelegateProxyTest {
func test_UIScrollViewDelegateExtension() {
performDelegateTest(UIScrollViewSubclass(frame: CGRect.zero)) { ExtendScrollViewDelegateProxy(scrollViewSubclass: $0) }
}
}
#if os(iOS)
extension DelegateProxyTest {
func test_UISearchBarDelegateExtension() {
performDelegateTest(UISearchBarSubclass(frame: CGRect.zero)) { ExtendSearchBarDelegateProxy(searchBarSubclass: $0) }
}
}
#endif
extension DelegateProxyTest {
func test_UITextViewDelegateExtension() {
performDelegateTest(UITextViewSubclass(frame: CGRect.zero)) { ExtendTextViewDelegateProxy(textViewSubclass: $0) }
}
}
#if os(iOS)
extension DelegateProxyTest {
func test_UISearchController() {
performDelegateTest(UISearchControllerSubclass()) { ExtendSearchControllerDelegateProxy(searchControllerSubclass: $0) }
}
}
extension DelegateProxyTest {
func test_UIPickerViewExtension() {
performDelegateTest(UIPickerViewSubclass(frame: CGRect.zero)) { ExtendPickerViewDelegateProxy(pickerViewSubclass: $0) }
}
func test_UIPickerViewDataSourceExtension() {
performDelegateTest(UIPickerViewSubclass2(frame: CGRect.zero)) { ExtendPickerViewDataSourceProxy(pickerViewSubclass: $0) }
}
}
#endif
extension DelegateProxyTest {
func test_UITabBarControllerDelegateExtension() {
performDelegateTest(UITabBarControllerSubclass()) { ExtendTabBarControllerDelegateProxy(tabBarControllerSubclass: $0) }
}
}
extension DelegateProxyTest {
func test_UITabBarDelegateExtension() {
performDelegateTest(UITabBarSubclass()) { ExtendTabBarDelegateProxy(tabBarSubclass: $0) }
}
}
extension DelegateProxyTest {
/* something is wrong with subclassing mechanism.
func test_NSTextStorageDelegateExtension() {
performDelegateTest(NSTextStorageSubclass(attributedString: NSAttributedString()))
}*/
}
// MARK: Mocks
final class ExtendTableViewDelegateProxy
: RxTableViewDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UITableViewSubclass1?
init(tableViewSubclass: UITableViewSubclass1) {
self.control = tableViewSubclass
super.init(tableView: tableViewSubclass)
}
}
final class UITableViewSubclass1
: UITableView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendTableViewDataSourceProxy
: RxTableViewDataSourceProxy
, TestDelegateProtocol {
weak private(set) var control: UITableViewSubclass2?
init(tableViewSubclass: UITableViewSubclass2) {
self.control = tableViewSubclass
super.init(tableView: tableViewSubclass)
}
}
final class UITableViewSubclass2
: UITableView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if dataSource != nil {
(dataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UITableView, UITableViewDataSource> {
return self.rx.dataSource
}
func setMineForwardDelegate(_ testDelegate: UITableViewDataSource) -> Disposable {
return RxTableViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class ExtendTableViewDataSourcePrefetchingProxy
: RxTableViewDataSourcePrefetchingProxy
, TestDelegateProtocol {
weak private(set) var control: UITableViewSubclass3?
init(parentObject: UITableViewSubclass3) {
self.control = parentObject
super.init(tableView: parentObject)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class UITableViewSubclass3
: UITableView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if prefetchDataSource != nil {
(prefetchDataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UITableView, UITableViewDataSourcePrefetching> {
return self.rx.prefetchDataSource
}
func setMineForwardDelegate(_ testDelegate: UITableViewDataSourcePrefetching) -> Disposable {
return RxTableViewDataSourcePrefetchingProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendCollectionViewDelegateProxy
: RxCollectionViewDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UICollectionViewSubclass1?
init(parentObject: UICollectionViewSubclass1) {
self.control = parentObject
super.init(collectionView: parentObject)
}
}
final class UICollectionViewSubclass1
: UICollectionView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendCollectionViewDataSourceProxy
: RxCollectionViewDataSourceProxy
, TestDelegateProtocol {
weak private(set) var control: UICollectionViewSubclass2?
init(parentObject: UICollectionViewSubclass2) {
self.control = parentObject
super.init(collectionView: parentObject)
}
}
final class UICollectionViewSubclass2
: UICollectionView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if dataSource != nil {
(dataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UICollectionView, UICollectionViewDataSource> {
return self.rx.dataSource
}
func setMineForwardDelegate(_ testDelegate: UICollectionViewDataSource) -> Disposable {
return RxCollectionViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class ExtendCollectionViewDataSourcePrefetchingProxy
: RxCollectionViewDataSourcePrefetchingProxy
, TestDelegateProtocol {
weak private(set) var control: UICollectionViewSubclass3?
init(parentObject: UICollectionViewSubclass3) {
self.control = parentObject
super.init(collectionView: parentObject)
}
}
@available(iOS 10.0, tvOS 10.0, *)
final class UICollectionViewSubclass3
: UICollectionView
, TestDelegateControl {
func doThatTest(_ value: Int) {
if prefetchDataSource != nil {
(prefetchDataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UICollectionView, UICollectionViewDataSourcePrefetching> {
return self.rx.prefetchDataSource
}
func setMineForwardDelegate(_ testDelegate: UICollectionViewDataSourcePrefetching) -> Disposable {
return RxCollectionViewDataSourcePrefetchingProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendScrollViewDelegateProxy
: RxScrollViewDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UIScrollViewSubclass?
init(scrollViewSubclass: UIScrollViewSubclass) {
self.control = scrollViewSubclass
super.init(scrollView: scrollViewSubclass)
}
}
final class UIScrollViewSubclass
: UIScrollView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
#if os(iOS)
final class ExtendSearchBarDelegateProxy
: RxSearchBarDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UISearchBarSubclass?
init(searchBarSubclass: UISearchBarSubclass) {
self.control = searchBarSubclass
super.init(searchBar: searchBarSubclass)
}
}
final class UISearchBarSubclass
: UISearchBar
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UISearchBar, UISearchBarDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UISearchBarDelegate) -> Disposable {
return RxSearchBarDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
#endif
final class ExtendTextViewDelegateProxy
: RxTextViewDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UITextViewSubclass?
init(textViewSubclass: UITextViewSubclass) {
self.control = textViewSubclass
super.init(textView: textViewSubclass)
}
}
final class UITextViewSubclass
: UITextView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIScrollViewDelegate) -> Disposable {
return RxScrollViewDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
#if os(iOS)
final class ExtendSearchControllerDelegateProxy
: RxSearchControllerDelegateProxy
, TestDelegateProtocol {
init(searchControllerSubclass: UISearchControllerSubclass) {
super.init(searchController: searchControllerSubclass)
}
}
final class UISearchControllerSubclass
: UISearchController
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UISearchController, UISearchControllerDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UISearchControllerDelegate) -> Disposable {
return RxSearchControllerDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendPickerViewDelegateProxy
: RxPickerViewDelegateProxy
, TestDelegateProtocol {
init(pickerViewSubclass: UIPickerViewSubclass) {
super.init(pickerView: pickerViewSubclass)
}
}
final class UIPickerViewSubclass
: UIPickerView
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UIPickerView, UIPickerViewDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UIPickerViewDelegate) -> Disposable {
return RxPickerViewDelegateProxy.installForwardDelegate(testDelegate,
retainDelegate: false,
onProxyForObject: self)
}
}
final class ExtendPickerViewDataSourceProxy
: RxPickerViewDataSourceProxy
, TestDelegateProtocol {
weak private(set) var control: UIPickerViewSubclass2?
init(pickerViewSubclass: UIPickerViewSubclass2) {
self.control = pickerViewSubclass
super.init(pickerView: pickerViewSubclass)
}
}
final class UIPickerViewSubclass2: UIPickerView, TestDelegateControl {
func doThatTest(_ value: Int) {
if dataSource != nil {
(dataSource as! TestDelegateProtocol).testEventHappened?(value)
}
}
var delegateProxy: DelegateProxy<UIPickerView, UIPickerViewDataSource> {
return self.rx.dataSource
}
func setMineForwardDelegate(_ testDelegate: UIPickerViewDataSource) -> Disposable {
return RxPickerViewDataSourceProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendTextStorageDelegateProxy
: RxTextStorageDelegateProxy
, TestDelegateProtocol {
init(textStorageSubclass: NSTextStorageSubclass) {
super.init(textStorage: textStorageSubclass)
}
}
final class NSTextStorageSubclass
: NSTextStorage
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<NSTextStorage, NSTextStorageDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: NSTextStorageDelegate) -> Disposable {
return RxTextStorageDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class ExtendNavigationControllerDelegateProxy
: RxNavigationControllerDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UINavigationControllerSubclass?
init(navigationControllerSubclass: UINavigationControllerSubclass) {
self.control = navigationControllerSubclass
super.init(navigationController: navigationControllerSubclass)
}
}
final class ExtendTabBarControllerDelegateProxy
: RxTabBarControllerDelegateProxy
, TestDelegateProtocol {
weak private(set) var tabBarControllerSubclass: UITabBarControllerSubclass?
init(tabBarControllerSubclass: UITabBarControllerSubclass) {
self.tabBarControllerSubclass = tabBarControllerSubclass
super.init(tabBar: tabBarControllerSubclass)
}
}
final class ExtendTabBarDelegateProxy
: RxTabBarDelegateProxy
, TestDelegateProtocol {
weak private(set) var control: UITabBarSubclass?
init(tabBarSubclass: UITabBarSubclass) {
self.control = tabBarSubclass
super.init(tabBar: tabBarSubclass)
}
}
final class UINavigationControllerSubclass: UINavigationController, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UINavigationController, UINavigationControllerDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UINavigationControllerDelegate) -> Disposable {
return RxNavigationControllerDelegateProxy.installForwardDelegate(testDelegate,
retainDelegate: false,
onProxyForObject: self)
}
}
final class UITabBarControllerSubclass
: UITabBarController
, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UITabBarController, UITabBarControllerDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UITabBarControllerDelegate) -> Disposable {
return RxTabBarControllerDelegateProxy.installForwardDelegate(testDelegate, retainDelegate: false, onProxyForObject: self)
}
}
final class UITabBarSubclass: UITabBar, TestDelegateControl {
func doThatTest(_ value: Int) {
(delegate as! TestDelegateProtocol).testEventHappened?(value)
}
var delegateProxy: DelegateProxy<UITabBar, UITabBarDelegate> {
return self.rx.delegate
}
func setMineForwardDelegate(_ testDelegate: UITabBarDelegate) -> Disposable {
return RxTabBarDelegateProxy.installForwardDelegate(testDelegate,
retainDelegate: false,
onProxyForObject: self)
}
}
| 32.966132 | 173 | 0.730237 |
ed36e3a87fae1ffb3b15fe40568d4c7486eac336 | 207 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class c<T:a
protocol a:A
protocol A:A
| 25.875 | 87 | 0.768116 |
266a6ba538827ccda52e9e604ff004f4a1804c9f | 557 | //
// AppDelegate.swift
// Performance
//
// Created by Viktor Belényesi on 30/11/15.
// Copyright © 2015 Viktor Belenyesi. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| 19.892857 | 71 | 0.719928 |
acc24460b154af32ff2865c132b8f7c4b3c8cf29 | 7,366 | import Foundation
import SourceKittenFramework
private func wrapInSwitch(
variable: String = "foo",
_ str: String,
file: StaticString = #file, line: UInt = #line) -> Example {
return Example(
"""
switch \(variable) {
\(str): break
}
""", file: file, line: line)
}
private func wrapInFunc(_ str: String, file: StaticString = #file, line: UInt = #line) -> Example {
return Example("""
func example(foo: Foo) {
switch foo {
case \(str):
break
}
}
""", file: file, line: line)
}
public struct EmptyEnumArgumentsRule: SubstitutionCorrectableASTRule, ConfigurationProviderRule, AutomaticTestableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "empty_enum_arguments",
name: "Empty Enum Arguments",
description: "Arguments can be omitted when matching enums with associated values if they are not used.",
kind: .style,
nonTriggeringExamples: [
wrapInSwitch("case .bar"),
wrapInSwitch("case .bar(let x)"),
wrapInSwitch("case let .bar(x)"),
wrapInSwitch(variable: "(foo, bar)", "case (_, _)"),
wrapInSwitch("case \"bar\".uppercased()"),
wrapInSwitch(variable: "(foo, bar)", "case (_, _) where !something"),
wrapInSwitch("case (let f as () -> String)?"),
wrapInSwitch("default"),
Example("if case .bar = foo {\n}"),
Example("guard case .bar = foo else {\n}"),
Example("if foo == .bar() {}"),
Example("guard foo == .bar() else { return }"),
Example("""
if case .appStore = self.appInstaller, !UIDevice.isSimulator() {
viewController.present(self, animated: false)
} else {
UIApplication.shared.open(self.appInstaller.url)
}
""")
],
triggeringExamples: [
wrapInSwitch("case .bar↓(_)"),
wrapInSwitch("case .bar↓()"),
wrapInSwitch("case .bar↓(_), .bar2↓(_)"),
wrapInSwitch("case .bar↓() where method() > 2"),
wrapInFunc("case .bar↓(_)"),
Example("if case .bar↓(_) = foo {\n}"),
Example("guard case .bar↓(_) = foo else {\n}"),
Example("if case .bar↓() = foo {\n}"),
Example("guard case .bar↓() = foo else {\n}"),
Example("""
if case .appStore↓(_) = self.appInstaller, !UIDevice.isSimulator() {
viewController.present(self, animated: false)
} else {
UIApplication.shared.open(self.appInstaller.url)
}
""")
],
corrections: [
wrapInSwitch("case .bar↓(_)"): wrapInSwitch("case .bar"),
wrapInSwitch("case .bar↓()"): wrapInSwitch("case .bar"),
wrapInSwitch("case .bar↓(_), .bar2↓(_)"): wrapInSwitch("case .bar, .bar2"),
wrapInSwitch("case .bar↓() where method() > 2"): wrapInSwitch("case .bar where method() > 2"),
wrapInFunc("case .bar↓(_)"): wrapInFunc("case .bar"),
Example("if case .bar↓(_) = foo {"): Example("if case .bar = foo {"),
Example("guard case .bar↓(_) = foo else {"): Example("guard case .bar = foo else {")
]
)
public func validate(file: SwiftLintFile, kind: StatementKind,
dictionary: SourceKittenDictionary) -> [StyleViolation] {
return violationRanges(in: file, kind: kind, dictionary: dictionary).map {
StyleViolation(ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
public func substitution(for violationRange: NSRange, in file: SwiftLintFile) -> (NSRange, String)? {
return (violationRange, "")
}
public func violationRanges(in file: SwiftLintFile, kind: StatementKind,
dictionary: SourceKittenDictionary) -> [NSRange] {
guard kind == .case || kind == .if || kind == .guard else {
return []
}
let needsCase = kind == .if || kind == .guard
let contents = file.stringView
let callsRanges = dictionary.methodCallRanges(in: file)
return dictionary.elements.flatMap { subDictionary -> [NSRange] in
guard (subDictionary.kind == "source.lang.swift.structure.elem.pattern" ||
subDictionary.kind == "source.lang.swift.structure.elem.condition_expr"),
let byteRange = subDictionary.byteRange,
let caseRange = contents.byteRangeToNSRange(byteRange)
else {
return []
}
let emptyArgumentRegex = regex(#"\.\S+\s*(\([,\s_]*\))"#)
return emptyArgumentRegex.matches(in: file.contents, options: [], range: caseRange).compactMap { match in
let parenthesesRange = match.range(at: 1)
// avoid matches after `where` keyworkd
if let whereRange = file.match(pattern: "where", with: [.keyword], range: caseRange).first {
if whereRange.location < parenthesesRange.location {
return nil
}
// avoid matches in "(_, _) where"
if let whereByteRange = contents.NSRangeToByteRange(start: whereRange.location,
length: whereRange.length),
case let length = whereByteRange.location - byteRange.location,
case let byteRange = ByteRange(location: byteRange.location, length: length),
Set(file.syntaxMap.kinds(inByteRange: byteRange)) == [.keyword] {
return nil
}
}
if needsCase, file.match(pattern: "\\bcase\\b", with: [.keyword], range: caseRange).isEmpty {
return nil
}
if callsRanges.contains(where: parenthesesRange.intersects) {
return nil
}
return parenthesesRange
}
}
}
}
private extension SourceKittenDictionary {
func methodCallRanges(in file: SwiftLintFile) -> [NSRange] {
return substructure
.flatMap { dict -> [SourceKittenDictionary] in
// In Swift >= 5.6, calls are embedded in a `source.lang.swift.expr.argument` entry
guard SwiftVersion.current >= .fiveDotSix, dict.expressionKind == .argument else {
return [dict]
}
return dict.substructure
}
.compactMap { dict -> NSRange? in
guard dict.expressionKind == .call,
let byteRange = dict.byteRange,
let range = file.stringView.byteRangeToNSRange(byteRange),
let name = dict.name,
!name.starts(with: ".")
else {
return nil
}
return range
}
}
}
| 41.382022 | 120 | 0.53136 |
bb78957655ee9f7d8b2b2a1c042d064d2347f133 | 194 | //
// Synthesizer.swift
// SamplerDemo
//
// Created by Kanstantsin Linou on 7/5/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
enum Synthesizer {
case Arpeggio, Pad, Bass
}
| 16.166667 | 51 | 0.670103 |
46b063ce1c98559634f52bb8a53a74e34a100ac2 | 177 | //___FILEHEADER___
import Foundation
enum AnalyticsEvents: String, CaseIterable {
// MARK: - Auth events
case signIn = "signIn"
case signUp = "signUp"
}
| 14.75 | 44 | 0.649718 |
7572ec672cd911a7948e3a60bf4f4a124b34b2b6 | 9,727 | //
// FavoritesList.swift
// Forum
//
// Created by Joachim Dittman on 13/08/2017.
// Copyright © 2017 Joachim Dittman. All rights reserved.
//
import UIKit
class FavoritesListView: UIViewController,UITableViewDelegate,UITableViewDataSource {
var uc = UserController()
var tableView = UITableView()
var lectureContainer = [Lecture]()
var auctionContainer = [AuctionItem]()
let typeImagesArray = ["cirkel_workshop","cirkel_social","Cirkel_debat","cirkel_firehose","cirkel_3roundBurst","cirkel_talk"]
var dayNames = ["Fredag","Lørdag","Søndag"]
let items = ["Program","Auktion"]
var daySC = UISegmentedControl()
var type = 0
var line = UIView(frame:CGRect(x:5,y:55, width:UIScreen.main.bounds.width - 10,height:1))
var titleLabel = UILabel(frame:CGRect(x:10,y:27, width:UIScreen.main.bounds.width - 20,height:20))
var blurEffectView = UIVisualEffectView()
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = "Din oversigt".uppercased()
titleLabel.font = UIFont (name: "HelveticaNeue-Bold", size: 25)
titleLabel.textAlignment = .center
self.view.addSubview(titleLabel)
line.backgroundColor = .black
self.view.addSubview(line)
let bImage = UIButton()
bImage.frame = CGRect(x: -10,y: 2,width: 70,height: 70)
bImage.setImage(UIImage(named: "ic_exit_to_app")!.withRenderingMode(UIImageRenderingMode.alwaysTemplate), for: UIControlState())
bImage.tintColor = UIColor.black
bImage.addTarget(self, action: #selector(logOut(sender:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(bImage)
daySC = UISegmentedControl(items: items)
daySC.selectedSegmentIndex = 0
let frame = UIScreen.main.bounds
daySC.frame = CGRect(x:-2, y:55, width: frame.width + 4,height: 30)
daySC.addTarget(self, action: #selector(changeColor(sender:)), for: .valueChanged)
daySC.tintColor = .black
self.view.addSubview(daySC)
tableView.frame = CGRect(x:0,y:85, width:self.view.frame.width,height:self.view.frame.height - 132);
tableView.delegate = self
tableView.dataSource = self
tableView.register(LectureCell.self, forCellReuseIdentifier: "LectureCell")
tableView.register(AuctionListCell.self, forCellReuseIdentifier: "AuctionListCell")
tableView.backgroundColor = UIColor.clear
tableView.rowHeight = 75
tableView.separatorColor = .clear
self.view.addSubview(tableView)
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurEffectView.alpha = 0.0
self.tableView.addSubview(blurEffectView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
print("FavoriteListView")
if(type == 0)
{ tableView.rowHeight = 75
if(User.userContainer.count > 0)
{
reloadLectureFavorite()
}
}
else
{ tableView.rowHeight = 110
if(User.userContainer.count > 0)
{
reloadAuctionFavorite()
}
}
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.blurEffectView.alpha = 0.0
}, completion: nil)
}
func changeColor(sender: UISegmentedControl) {
type = sender.selectedSegmentIndex
if(type == 0)
{ tableView.rowHeight = 75
reloadLectureFavorite()
}
else
{ tableView.rowHeight = 110
reloadAuctionFavorite()
}
self.tableView.reloadData()
}
func reloadLectureFavorite()
{
lectureContainer.removeAll()
let con = uc.uc.favoriteLectures
var index = 0
while (index < 3) {
for i in con[index]!
{
i.day = index
lectureContainer.append(i)
}
index += 1
}
self.tableView.reloadData()
}
func reloadAuctionFavorite()
{
print("reload auction")
auctionContainer = uc.uc.favoriteAuctionItems
self.tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
if(type == 0)
{
return lectureContainer.count
}
else
{
return 1
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if(type == 0){
let i = lectureContainer
var index = section
if(section - 1 < 0)
{
index = 0
}
if(index > 0)
{
if("\(dayNames[i[section].day])\(i[section].startTime!)\(i[section].endTime!)" != "\(dayNames[0])\(i[section - 1].startTime!)\(i[section - 1].endTime!)")
{
return"\(dayNames[i[section].day]) \(String(describing: i[section].startTime!)) - \(i[section].endTime!)"
}
else
{
return ""
}
}
else
{
return "\(dayNames[i[section].day]) \(String(describing:i[section].startTime!)) - \(i[section].endTime!)"
}
}
else
{
return ""
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(type == 1)
{
return auctionContainer.count
}
return 1
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(type == 0)
{
let cell:LectureCell = tableView.dequeueReusableCell(withIdentifier: "LectureCell", for: indexPath) as! LectureCell
cell.favorite.setImage(UIImage(named:"heartDark"), for: UIControlState())
cell.favorite.addTarget(self, action: #selector(updateFavorite(_:)), for: UIControlEvents.touchUpInside)
let item = lectureContainer[indexPath.section]
cell.typeImage.image = UIImage(named: typeImagesArray[Int(item.type!)!])
cell.titleLabel.text = item.name?.uppercased()
cell.placeLabel.text = item.place
cell.favorite.tag = indexPath.section
cell.selectionStyle = .none
return cell
}
else
{
let cell:AuctionListCell = tableView.dequeueReusableCell(withIdentifier: "AuctionListCell", for: indexPath) as! AuctionListCell
cell.favorite.setImage(UIImage(named:"heartDark"), for: UIControlState())
cell.favorite.addTarget(self, action: #selector(updateFavorite(_:)), for: UIControlEvents.touchUpInside)
let item = auctionContainer[indexPath.row]
if(item.image != nil)
{
if((URL(string:item.image!)) != nil)
{
cell.profileImageView.kf.setImage(with:URL(string:item.image!)!, placeholder: UIImage(named:"noPic"), options: nil, progressBlock: nil, completionHandler: { (image, error, CacheType, imageURL) in })
}
}
cell.titleLabel.text = item.name?.uppercased()
cell.startBid.text = "Startbud: \(item.startBid!) DKK"
cell.donator.text = "\(item.donator!)"
cell.favorite.tag = indexPath.row
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.blurEffectView.alpha = 1.0
}, completion: nil)
if(type == 0)
{
let vc = LectureItemView()
let item = lectureContainer[indexPath.section]
vc.lc = [item]
self.present(vc, animated: true, completion: nil)
}
else
{
let vc = AuctionItemView()
let item = auctionContainer[indexPath.section]
vc.ac = [item]
self.present(vc, animated: true, completion: nil)
}
}
func updateFavorite(_ sender:AnyObject)
{
if(type == 0)
{
let item = lectureContainer[sender.tag]
print("updateFavorite")
_ = uc.removeFromFavoritList(type: "lecture", lecture: item, auctionItem: nil)
reloadLectureFavorite()
}
else
{
let item = auctionContainer[sender.tag]
print("updateFavorite")
_ = uc.removeFromFavoritList(type: "auction", lecture: nil, auctionItem: item)
reloadAuctionFavorite()
}
}
func logOut(sender:AnyObject)
{
loadedFirst = false
loggedIn = false
self.tabBarController?.selectedIndex = 1
let vc = LoginView()
vc.logOut = true
self.present(vc,animated: true,completion: nil)
}
}
| 33.541379 | 219 | 0.577876 |
29f51da3cc9ded8ab5453e1c2ac513e8c06880f6 | 3,151 | //
// CameraPreview.swift
// Campus
//
// Created by Rolando Rodriguez on 12/17/19.
// Copyright © 2019 Rolando Rodriguez. All rights reserved.
//
import UIKit
import AVFoundation
import SwiftUI
public struct CameraPreview: UIViewRepresentable {
public class VideoPreviewView: UIView {
public override class var layerClass: AnyClass {
AVCaptureVideoPreviewLayer.self
}
var videoPreviewLayer: AVCaptureVideoPreviewLayer {
return layer as! AVCaptureVideoPreviewLayer
}
let focusView: UIView = {
let focusView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
// focusView.layer.borderColor = UIColor.white.cgColor
// focusView.layer.borderWidth = 1.5
focusView.layer.cornerRadius = 25
focusView.layer.opacity = 0
focusView.backgroundColor = .clear
return focusView
}()
@objc func focusAndExposeTap(gestureRecognizer: UITapGestureRecognizer) {
let layerPoint = gestureRecognizer.location(in: gestureRecognizer.view)
let devicePoint = videoPreviewLayer.captureDevicePointConverted(fromLayerPoint: layerPoint)
self.focusView.layer.frame = CGRect(origin: layerPoint, size: CGSize(width: 50, height: 50))
NotificationCenter.default.post(.init(name: .init("UserDidRequestNewFocusPoint"), object: nil, userInfo: ["devicePoint": devicePoint] as [AnyHashable: Any]))
UIView.animate(withDuration: 0.3, animations: {
self.focusView.layer.opacity = 1
}) { (completed) in
if completed {
UIView.animate(withDuration: 0.3) {
self.focusView.layer.opacity = 0
}
}
}
}
public override func layoutSubviews() {
super.layoutSubviews()
self.layer.addSublayer(focusView.layer)
let gRecognizer = UITapGestureRecognizer(target: self, action: #selector(VideoPreviewView.focusAndExposeTap(gestureRecognizer:)))
self.addGestureRecognizer(gRecognizer)
}
}
public let session: AVCaptureSession
public init(session: AVCaptureSession) {
self.session = session
}
public func makeUIView(context: Context) -> VideoPreviewView {
let viewFinder = VideoPreviewView()
viewFinder.backgroundColor = .black
viewFinder.videoPreviewLayer.cornerRadius = 0
viewFinder.videoPreviewLayer.session = session
viewFinder.videoPreviewLayer.connection?.videoOrientation = .portrait
viewFinder.videoPreviewLayer.videoGravity = .resizeAspectFill
return viewFinder
}
public func updateUIView(_ uiView: VideoPreviewView, context: Context) {
}
}
struct CameraPreview_Previews: PreviewProvider {
static var previews: some View {
CameraPreview(session: AVCaptureSession())
.frame(height: 300)
}
}
| 35.011111 | 169 | 0.62139 |
67395a2f65f956854d271a00c5001227fe76c60c | 646 | //
// TrainerRepresentatation.swift
// AnywhereFitnessUnit2Build
//
// Created by Alex Rhodes on 9/23/19.
// Copyright © 2019 Alex Rhodes. All rights reserved.
//
import Foundation
struct TrainerResult: Codable {
var token: String
}
struct TrainerRepresentation: Equatable, Codable {
let email: String?
let username: String?
let password: String?
let instructor: Bool?
let identifier: Int?
enum CodingKeys: String, CodingKey {
case email = "email"
case username = "username"
case password = "password"
case instructor = "instructor"
case identifier = "id"
}
}
| 20.1875 | 54 | 0.653251 |
7970e20cfe09275ed08f7afd109f66685aac9111 | 3,971 | //
// AppDelegate.swift
// Clear
//
// Created by Danko, Radoslav on 16/04/2018.
// Copyright © 2018 Danko, Radoslav. All rights reserved.
//
import UIKit
import WDePOS
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
public var currentUser:WDMerchantUser?
var selectedPrinter: WDTerminal? {
get {
if let data = UserDefaults.standard.object(forKey: "selectedPrinter"){
return NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as? WDTerminal
}
return nil
}
set {
UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: newValue as Any), forKey: "selectedPrinter")
}
}
var selectedTerminal: WDTerminal? {
get {
if let data = UserDefaults.standard.object(forKey: "selectedTerminal"){
return NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as? WDTerminal
}
return nil
}
set {
UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: newValue as Any), forKey: "selectedTerminal")
}
}
var selectedCashRegister: WDCashRegister? {
get {
if let data = UserDefaults.standard.object(forKey: "selectedCashRegister"){
return NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as? WDCashRegister
}
return nil
}
set {
UserDefaults.standard.setValue(NSKeyedArchiver.archivedData(withRootObject: newValue as Any), forKey: "selectedCashRegister")
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
changeAppearance()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func changeAppearance(){
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.darkGray]
navigationBarAppearace.tintColor = UIColor.init(red: 0, green: 0.2, blue: 0.6, alpha: 1)
}
}
| 42.698925 | 285 | 0.694535 |
0a492a8180a084ebba8e8221ca0e5997142bdbb3 | 1,403 | //
// SettingsModel.swift
// CryptoAdvise
//
// Created by Aaron Halvorsen on 8/27/18.
// Copyright © 2018 Aaron Halvorsen. All rights reserved.
//
import Foundation
final class SettingsModel {
internal enum Section: String {
case settings, about, help, acknowledgements, privacy, source, logout
}
let sections: [Section] = [
.settings,
// .about,
// .help,
.acknowledgements,
// .privacy,
.source,
.logout
]
let content: [Section: String] = [
.settings: "",
.about: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
.help: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
.acknowledgements: "Graphs powered by Binance API\nTweets powered by Twitter API & Swifter library\nNews powered by NewsAPI.org",
.logout: "",
.privacy: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam",
.source: "All the Swift code for this app can be found here: github.com/halvorsen/CryptoAdvise"
]
}
| 30.5 | 168 | 0.634355 |
ab92222fe0c87a4e2e3e221a83081eecfed36658 | 166 | //
// Test.swift
// easy-weex
//
// Created by zhu zhe on 2018/11/26.
// Copyright © 2018 flyme. All rights reserved.
//
import UIKit
class Test: NSObject {
}
| 11.857143 | 48 | 0.63253 |
7246e0e8ee98fe6d6266ae6f67ab08207d0a0ce3 | 2,274 | //
// BaseProfileMoviesCell.swift
// popmovies
//
// Created by Tiago Silva on 17/07/19.
// Copyright © 2019 Tiago Silva. All rights reserved.
//
import Foundation
class BaseProfileMoviesCell: UITableViewCell {
// MARK: Constants
let MovieSmallCell = R.nib.movieSmallCell.name
let MovieCellIdentifier = "MovieCellIdentifier"
// MARK: Outlets
@IBOutlet weak var moviesCollectionView: UICollectionView!
@IBOutlet weak var moviesCollectionViewViewFlow: UICollectionViewFlowLayout! {
didSet {
moviesCollectionViewViewFlow.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
// MARK: Properties
var delegate: ProfileMoviesCellDelegate?
var movies: [Movie] = []
var listName = R.string.localizable.movieListTitle()
}
// MARK: Bind methods
extension BaseProfileMoviesCell {
func bindContent(_ movies: [Movie]) {
self.movies = movies
setupCells()
}
private func setupCells() {
moviesCollectionView.configureNibs(nibName: MovieSmallCell, identifier: MovieCellIdentifier)
}
}
extension BaseProfileMoviesCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.movies.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MovieCellIdentifier, for: indexPath) as! MovieCollectionViewCell
let movie = movies[indexPath.row]
cell.bindMovieCellDefault(movie: movie)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let movie = self.movies[indexPath.row]
delegate?.didSelectMovie(with: movie)
}
}
// MARK: Actions methods
extension BaseProfileMoviesCell {
@IBAction func didSeeAllClicked(_ sender: Any?) {
delegate?.didSeeAllClicked(with: self.movies, listName)
}
}
| 27.071429 | 139 | 0.671504 |
22a5e25eb6f44c082cd488b3cd8328fc43086fe9 | 2,376 | //
// PlayerNode.swift
// Smash Up Counter iOS
//
// Created by Cyril on 23/03/2018.
// Copyright © 2018 Cyril GY. All rights reserved.
//
import SpriteKit
// MARK: - Definition
class PlayerNode: SKNode {
// MARK: - Children nodes
fileprivate lazy var nameLabel: SKLabelNode? = {
self.childNode(withName: "name") as? SKLabelNode
}()
fileprivate lazy var pointsLabel: SKLabelNode? = {
self.childNode(withName: "points") as? SKLabelNode
}()
fileprivate lazy var firstFactionImageNode: SKSpriteNode? = {
self.childNode(withName: "first_faction_image") as? SKSpriteNode
}()
fileprivate lazy var firstFactionNameNode: SKLabelNode? = {
self.childNode(withName: "first_faction_name") as? SKLabelNode
}()
fileprivate lazy var secondFactionImageNode: SKSpriteNode? = {
self.childNode(withName: "second_faction_image") as? SKSpriteNode
}()
fileprivate lazy var secondFactionNameNode: SKLabelNode? = {
self.childNode(withName: "second_faction_name") as? SKLabelNode
}()
fileprivate lazy var incrementPointsNode: SKNode? = {
self.childNode(withName: "increment_points")
}()
fileprivate lazy var decrementPointsNode: SKNode? = {
self.childNode(withName: "decrement_points")
}()
// MARK: - Properties
private(set) var playerName: String? = nil
// MARK: - Life cycle
func setUp(withPlayer player: Player, animated: Bool) {
self.playerName = player.name
// TODO : animation
self.nameLabel?.text = player.name
self.pointsLabel?.text = "\(player.points)"
self.firstFactionNameNode?.text = player.factions[0].name
self.secondFactionNameNode?.text = player.factions[1].name
if let imageName = player.factions[0].image {
self.firstFactionImageNode?.texture = SKTexture(imageNamed: imageName)
}
if let imageName = player.factions[1].image {
self.secondFactionImageNode?.texture = SKTexture(imageNamed: imageName)
}
self.nameLabel?.applyTextStyle()
self.pointsLabel?.applyTextStyle()
self.incrementPointsNode?.applyTextStyle()
self.decrementPointsNode?.applyTextStyle()
}
}
| 28.626506 | 83 | 0.632576 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.