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
|
---|---|---|---|---|---|
7acadfa86ce56eedb31fe920cac4e471bf5851ba | 1,102 | // Copyright 2020 Itty Bitty Apps Pty Ltd
import ArgumentParser
import AppStoreConnect_Swift_SDK
import Combine
import Foundation
struct ReadBetaTesterCommand: CommonParsableCommand {
static var configuration = CommandConfiguration(
commandName: "read",
abstract: "Get information about a beta tester")
@OptionGroup()
var common: CommonOptions
@Argument(help: "The Beta tester's email address")
var email: String
@Option(help: "Number of included app resources to return.")
var limitApps: Int?
@Option(help: "Number of included build resources to return.")
var limitBuilds: Int?
@Option(help: "Number of included beta group resources to return.")
var limitBetaGroups: Int?
func run() throws {
let service = try makeService()
let tester = try service
.getBetaTester(
email: email,
limitApps: limitApps,
limitBuilds: limitBuilds,
limitBetaGroups: limitBetaGroups
)
tester.render(options: common.outputOptions)
}
}
| 26.238095 | 71 | 0.658802 |
26e1147254536126677d41b7f9afc1361e391e95 | 1,349 | //
// PlayingCardGameProtocols.swift
// BlackJack
//
// Created by Sameer Totey on 2/8/15.
// Copyright (c) 2015 Sameer Totey. All rights reserved.
//
import Foundation
protocol PlayingCardGame: CardDataSource {
var gameConfiguration: GameConfiguration {get}
func play()
func update()
}
protocol PlayingGameDelegate {
func gameDidStart(game: PlayingCardGame)
func game(game: PlayingCardGame, didStartNewHand hand: Int)
func gameDidEnd(game: PlayingCardGame)
}
protocol CardPlayerDelegate: class {
func registerPlayer(player: Player)
func updated(player: Player)
func getCard() -> BlackjackCard
func insured(player: Player)
func declinedInsurance(player: Player)
}
protocol CardPlayerObserver: class {
func currentHandStatusUpdate(hand: BlackjackHand)
func addCardToCurrentHand(card: BlackjackCard)
func addnewlySplitHand(card: BlackjackCard)
func switchHands()
}
protocol DealerObserver: class {
func currentDealerHandUpdate(hand: BlackjackHand)
func flipHoleCard()
func addCardToDealerHand(card: BlackjackCard)
func addUpCardToDealerHand(card: BlackjackCard)
func addHoleCardToDealerHand(card: BlackjackCard)
func gameCompleted()
}
protocol BlackjackGameDelegate: class {
}
protocol CardDataSource: class {
func drawACard() -> BlackjackCard
}
| 24.981481 | 63 | 0.749444 |
75f3cea53622f86ec63d99f65984c6369eb67c1b | 1,537 | import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
class DatabaseCoderTests: GRDBTestCase {
func testDatabaseCoder() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE arrays (array BLOB)")
let array = [1,2,3]
try db.execute("INSERT INTO arrays VALUES (?)", arguments: [DatabaseCoder(array)])
let row = Row.fetchOne(db, "SELECT * FROM arrays")!
let fetchedArray = ((row.value(named: "array") as DatabaseCoder).object as! NSArray).map { $0 as! Int }
XCTAssertEqual(array, fetchedArray)
}
}
}
func testDatabaseCoderInitNilFailure() {
XCTAssertNil(DatabaseCoder(nil))
}
func testDatabaseCoderFromDatabaseValueFailure() {
let databaseValue_Null = DatabaseValue.Null
let databaseValue_Int64 = Int64(1).databaseValue
let databaseValue_String = "foo".databaseValue
let databaseValue_Double = Double(100000.1).databaseValue
XCTAssertNil(DatabaseCoder.fromDatabaseValue(databaseValue_Null))
XCTAssertNil(DatabaseCoder.fromDatabaseValue(databaseValue_Int64))
XCTAssertNil(DatabaseCoder.fromDatabaseValue(databaseValue_Double))
XCTAssertNil(DatabaseCoder.fromDatabaseValue(databaseValue_String))
}
}
| 35.744186 | 119 | 0.651269 |
4663703cc69bafe188d824c6fe25b6c9444f02d1 | 2,383 | //
// DownLaTeXRenderable.swift
// Down
//
// Created by Rob Phillips on 5/31/16.
// Copyright © 2016 Glazed Donut, LLC. All rights reserved.
//
import Foundation
import libcmark
public protocol DownLaTeXRenderable: DownRenderable {
/**
Generates a LaTeX string from the `markdownString` property
- parameter options: `DownOptions` to modify parsing or rendering
- parameter width: The width to break on
- throws: `DownErrors` depending on the scenario
- returns: LaTeX string
*/
func toLaTeX(_ options: DownOptions, width: Int32) throws -> String
}
public extension DownLaTeXRenderable {
/**
Generates a LaTeX string from the `markdownString` property
- parameter options: `DownOptions` to modify parsing or rendering, defaulting to `.Default`
- parameter width: The width to break on, defaulting to 0
- throws: `DownErrors` depending on the scenario
- returns: LaTeX string
*/
func toLaTeX(_ options: DownOptions = .Default, width: Int32 = 0) throws -> String {
let ast = try DownASTRenderer.stringToAST(markdownString, options: options)
let latex = try DownLaTeXRenderer.astToLaTeX(ast, options: options, width: width)
cmark_node_free(ast)
return latex
}
}
public struct DownLaTeXRenderer {
/**
Generates a LaTeX string from the given abstract syntax tree
**Note:** caller is responsible for calling `cmark_node_free(ast)` after this returns
- parameter options: `DownOptions` to modify parsing or rendering, defaulting to `.Default`
- parameter width: The width to break on, defaulting to 0
- throws: `ASTRenderingError` if the AST could not be converted
- returns: LaTeX string
*/
public static func astToLaTeX(_ ast: UnsafeMutablePointer<cmark_node>,
options: DownOptions = .Default,
width: Int32 = 0) throws -> String {
guard let cLatexString = cmark_render_latex(ast, options.rawValue, width) else {
throw DownErrors.astRenderingError
}
defer { free(cLatexString) }
guard let latexString = String(cString: cLatexString, encoding: String.Encoding.utf8) else {
throw DownErrors.astRenderingError
}
return latexString
}
}
| 31.355263 | 100 | 0.659253 |
6ab5b59271003e32a01f04f9124efee628eb54d1 | 408 | // 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 -emit-ir
for{_=(_
[{
| 37.090909 | 79 | 0.742647 |
184d752f11455fa9ed573a3eccee39399e6b3570 | 722 | //
// Created by Daniel Strobusch on 2019-05-11.
//
import XCTest
@testable import NdArray
// swiftlint:disable:next type_name
class mapTests: XCTestCase {
func testMap() {
do {
let a = NdArray<Double>.zeros([2, 3])
let b = NdArray<Double>(copy: a)
let c = a.map {
$0 * 2
}
b *= 2
XCTAssertEqual(c.dataArray, b.dataArray)
}
do {
let a = NdArray<Double>.zeros([2, 3])[..., 2]
let b = NdArray<Double>(copy: a)
let c: NdArray<Double> = a.map {
$0 * 2
}
b *= 2
XCTAssertEqual(c.dataArray, b.dataArray)
}
}
}
| 23.290323 | 57 | 0.459834 |
f84e482898977c260e8f29cdf1ca9c40e0023247 | 829 | import Foundation
import ReactiveAPI
struct InterceptorMock: ReactiveAPIRequestInterceptor {
func intercept(_ request: URLRequest) -> URLRequest {
var mutableRequest = request
mutableRequest.addValue("Interceptor", forHTTPHeaderField: UUID().uuidString)
return mutableRequest
}
}
public class TokenInterceptor : ReactiveAPIRequestInterceptor {
private let tokenValue: () -> String
private let headerName: String
public init(tokenValue: @escaping () -> String, headerName: String) {
self.tokenValue = tokenValue
self.headerName = headerName
}
public func intercept(_ request: URLRequest) -> URLRequest {
var mutableRequest = request
mutableRequest.addValue(tokenValue(), forHTTPHeaderField: headerName)
return mutableRequest
}
}
| 29.607143 | 85 | 0.711701 |
29843b09d20d283e5f8fc49577142370742d487f | 1,388 | import Foundation
import SwiftMETAR
let METAR_URL = URL(string: "https://www.aviationweather.gov/adds/dataserver_current/current/metars.cache.csv")!
let METARs = String(data: try! Data(contentsOf: METAR_URL), encoding: .ascii)!
METARs.enumerateLines { line, stop in
guard let range = line.rangeOfCharacter(from: CharacterSet(charactersIn: ",")) else { return }
let string = String(line[line.startIndex..<range.lowerBound])
// guard string != "raw_text" else { return }
guard string.starts(with: "K") else { return }
do {
_ = try METAR.from(string: string)
} catch (let error) {
print(string)
print(" -- \(error.localizedDescription)")
}
}
let TAF_URL = URL(string: "https://www.aviationweather.gov/adds/dataserver_current/current/tafs.cache.csv")!
let TAFs = String(data: try! Data(contentsOf: TAF_URL), encoding: .ascii)!
TAFs.enumerateLines { line, stop in
guard let range = line.rangeOfCharacter(from: CharacterSet(charactersIn: ",")) else { return }
let string = String(line[line.startIndex..<range.lowerBound])
// guard string != "raw_text" else { return }
guard string.starts(with: "TAF K") else { return }
do {
_ = try TAF.from(string: string)
} catch let error {
print(string)
print(error.localizedDescription)
// fatalError(error.localizedDescription)
}
}
| 38.555556 | 112 | 0.674352 |
f9e2fcf6697fa0389813ae2f3a833fc2f5510514 | 3,597 | //
// Scan.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<A>(into seed: A, accumulator: @escaping (inout A, E) throws -> Void)
-> Observable<A> {
return Scan(source: asObservable(), seed: seed, accumulator: accumulator)
}
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<A>(_ seed: A, accumulator: @escaping (A, E) throws -> A)
-> Observable<A> {
return Scan(source: asObservable(), seed: seed) { acc, element in
let currentAcc = acc
acc = try accumulator(currentAcc, element)
}
}
}
private final class ScanSink<ElementType, O: ObserverType>: Sink<O>, ObserverType {
typealias Accumulate = O.E
typealias Parent = Scan<ElementType, Accumulate>
typealias E = ElementType
fileprivate let _parent: Parent
fileprivate var _accumulate: Accumulate
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_accumulate = parent._seed
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<ElementType>) {
switch event {
case let .next(element):
do {
try _parent._accumulator(&_accumulate, element)
forwardOn(.next(_accumulate))
} catch {
forwardOn(.error(error))
dispose()
}
case let .error(error):
forwardOn(.error(error))
dispose()
case .completed:
forwardOn(.completed)
dispose()
}
}
}
private final class Scan<Element, Accumulate>: Producer<Accumulate> {
typealias Accumulator = (inout Accumulate, Element) throws -> Void
fileprivate let _source: Observable<Element>
fileprivate let _seed: Accumulate
fileprivate let _accumulator: Accumulator
init(source: Observable<Element>, seed: Accumulate, accumulator: @escaping Accumulator) {
_source = source
_seed = seed
_accumulator = accumulator
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Accumulate {
let sink = ScanSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| 36.333333 | 169 | 0.663053 |
7a2634be27bf9c22809b8da5f4f0f1f39f461190 | 270 | ///
/// Created by George Cox on 1/24/20.
///
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, World!")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 15 | 46 | 0.611111 |
f96f88a37b045509e679e1db05ad54c1ce06a67c | 597 | //
// MIStackCollectionView.swift
// Alamofire
//
// Created by on 5.03.2020.
//
import UIKit
public class MIStackCollectionView: UICollectionView {
public override func reloadData() {
super.reloadData()
performBatchUpdates(nil) { (completed) in
self.invalidateIntrinsicContentSize()
}
}
override public var intrinsicContentSize: CGSize {
return CGSize(
width: max(collectionViewLayout.collectionViewContentSize.width, 1),
height: max(collectionViewLayout.collectionViewContentSize.height,1)
)
}
}
| 23.88 | 80 | 0.664992 |
e2ccf97aeca7a0a0db2561d95099c8691a9c298b | 23,600 | //
// TimerStyleKit.swift
// Tomate
//
// Created by Dominik Hauser on 15.07.15.
// Copyright (c) 2015 dasdom. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import UIKit
public class TimerStyleKit : NSObject {
//// Cache
private struct Cache {
static var backgroundColor: UIColor = UIColor(red: 0.141, green: 0.149, blue: 0.204, alpha: 1.000)
static var timerColor: UIColor = UIColor(red: 0.378, green: 0.670, blue: 0.961, alpha: 1.000)
static var imageOfSettings: UIImage?
static var settingsTargets: [Any]?
static var imageOfInfo: UIImage?
static var infoTargets: [Any]?
}
//// Colors
public class var backgroundColor: UIColor { return Cache.backgroundColor }
public class var timerColor: UIColor { return Cache.timerColor }
//// Drawing Methods
public class func drawTimerAppIcon(durationInSeconds: CGFloat, maxValue: CGFloat, diameter: CGFloat, dashGap: CGFloat) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()! //TODO: Safe to force-unwrap here?
//// Shadow Declarations
let shadow = NSShadow()
shadow.shadowColor = TimerStyleKit.timerColor
shadow.shadowOffset = CGSize(width: 0.1, height: -0.1)
shadow.shadowBlurRadius = 4
//// Variable Declarations
let endAngle: CGFloat = 90 - durationInSeconds * 360 / maxValue
let minutes: CGFloat = floor(maxValue / 60.0)
let dashLength: CGFloat = diameter * CGFloat.pi / minutes - dashGap
//// TimerRing Drawing
let timerRingRect = CGRect(x: 62, y: 62, width: diameter, height: diameter)
let timerRingPath = UIBezierPath()
timerRingPath.addArc(withCenter: CGPoint(x: timerRingRect.midX, y: timerRingRect.midY), radius: timerRingRect.width / 2, startAngle: -90 * CGFloat.pi/180, endAngle: -endAngle * CGFloat.pi/180, clockwise: true)
context.saveGState()
context.setShadow(offset: shadow.shadowOffset, blur: shadow.shadowBlurRadius, color: (shadow.shadowColor as! UIColor).cgColor)
TimerStyleKit.timerColor.setStroke()
timerRingPath.lineWidth = 4
context.saveGState()
//CGContextSetLineDash(context, 0, [dashLength, dashGap], 2)
context.setLineDash(phase: 0, lengths: [dashLength, dashGap]) //TODO: Unsure if this properly replaces the outdated line above
timerRingPath.stroke()
context.restoreGState()
context.restoreGState()
}
public class func drawFiveMin(durationInSeconds: CGFloat, maxValue: CGFloat, diameter: CGFloat, dashGap: CGFloat) {
//// Variable Declarations
let endAngle: CGFloat = 90 - durationInSeconds * 360 / maxValue
// let minutes: CGFloat = floor(maxValue / 60.0)
// let dashLength: CGFloat = diameter * CGFloat(M_PI) / minutes - dashGap //TODO: Never used. Why?
//// TimerRing Drawing
let timerRingRect = CGRect(x: 6, y: 6, width: diameter, height: diameter)
let timerRingPath = UIBezierPath()
timerRingPath.addArc(withCenter: CGPoint(x: timerRingRect.midX, y: timerRingRect.midY), radius: timerRingRect.width / 2, startAngle: -90 * CGFloat.pi/180, endAngle: -endAngle * CGFloat.pi/180, clockwise: true)
TimerStyleKit.timerColor.setStroke()
timerRingPath.lineWidth = 6
timerRingPath.stroke()
}
public class func drawSettings() {
//// Color Declarations
let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Group 2
//// Group 3
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 36.47, y: 18.63))
bezierPath.addLine(to: CGPoint(x: 36.15, y: 17.53))
bezierPath.addCurve(to: CGPoint(x: 33.49, y: 15.42), controlPoint1: CGPoint(x: 35.84, y: 16.32), controlPoint2: CGPoint(x: 34.74, y: 15.42))
bezierPath.addCurve(to: CGPoint(x: 32.76, y: 15.53), controlPoint1: CGPoint(x: 33.23, y: 15.42), controlPoint2: CGPoint(x: 33.02, y: 15.47))
bezierPath.addLine(to: CGPoint(x: 31.35, y: 15.89))
bezierPath.addCurve(to: CGPoint(x: 30.04, y: 14.21), controlPoint1: CGPoint(x: 30.98, y: 15.26), controlPoint2: CGPoint(x: 30.56, y: 14.74))
bezierPath.addLine(to: CGPoint(x: 30.62, y: 13.21))
bezierPath.addCurve(to: CGPoint(x: 30.88, y: 11.05), controlPoint1: CGPoint(x: 30.98, y: 12.58), controlPoint2: CGPoint(x: 31.09, y: 11.79))
bezierPath.addCurve(to: CGPoint(x: 29.57, y: 9.32), controlPoint1: CGPoint(x: 30.67, y: 10.32), controlPoint2: CGPoint(x: 30.25, y: 9.74))
bezierPath.addLine(to: CGPoint(x: 28.58, y: 8.74))
bezierPath.addCurve(to: CGPoint(x: 27.17, y: 8.37), controlPoint1: CGPoint(x: 28.16, y: 8.47), controlPoint2: CGPoint(x: 27.69, y: 8.37))
bezierPath.addCurve(to: CGPoint(x: 24.77, y: 9.79), controlPoint1: CGPoint(x: 26.18, y: 8.37), controlPoint2: CGPoint(x: 25.24, y: 8.89))
bezierPath.addLine(to: CGPoint(x: 24.19, y: 10.79))
bezierPath.addCurve(to: CGPoint(x: 22.1, y: 10.53), controlPoint1: CGPoint(x: 23.51, y: 10.63), controlPoint2: CGPoint(x: 22.78, y: 10.53))
bezierPath.addLine(to: CGPoint(x: 21.79, y: 9.11))
bezierPath.addCurve(to: CGPoint(x: 19.12, y: 7), controlPoint1: CGPoint(x: 21.47, y: 7.89), controlPoint2: CGPoint(x: 20.38, y: 7))
bezierPath.addCurve(to: CGPoint(x: 18.39, y: 7.11), controlPoint1: CGPoint(x: 18.86, y: 7), controlPoint2: CGPoint(x: 18.65, y: 7.05))
bezierPath.addLine(to: CGPoint(x: 17.29, y: 7.42))
bezierPath.addCurve(to: CGPoint(x: 15.62, y: 8.74), controlPoint1: CGPoint(x: 16.56, y: 7.63), controlPoint2: CGPoint(x: 15.99, y: 8.11))
bezierPath.addCurve(to: CGPoint(x: 15.36, y: 10.89), controlPoint1: CGPoint(x: 15.26, y: 9.37), controlPoint2: CGPoint(x: 15.15, y: 10.16))
bezierPath.addLine(to: CGPoint(x: 15.73, y: 12.37))
bezierPath.addCurve(to: CGPoint(x: 14.16, y: 13.63), controlPoint1: CGPoint(x: 15.15, y: 12.74), controlPoint2: CGPoint(x: 14.63, y: 13.16))
bezierPath.addLine(to: CGPoint(x: 13.22, y: 13.11))
bezierPath.addCurve(to: CGPoint(x: 11.81, y: 12.74), controlPoint1: CGPoint(x: 12.8, y: 12.84), controlPoint2: CGPoint(x: 12.33, y: 12.74))
bezierPath.addCurve(to: CGPoint(x: 9.41, y: 14.16), controlPoint1: CGPoint(x: 10.82, y: 12.74), controlPoint2: CGPoint(x: 9.88, y: 13.26))
bezierPath.addLine(to: CGPoint(x: 8.83, y: 15.16))
bezierPath.addCurve(to: CGPoint(x: 8.52, y: 17.16), controlPoint1: CGPoint(x: 8.41, y: 15.68), controlPoint2: CGPoint(x: 8.36, y: 16.47))
bezierPath.addCurve(to: CGPoint(x: 9.82, y: 18.89), controlPoint1: CGPoint(x: 8.73, y: 17.89), controlPoint2: CGPoint(x: 9.14, y: 18.47))
bezierPath.addLine(to: CGPoint(x: 10.76, y: 19.47))
bezierPath.addCurve(to: CGPoint(x: 10.5, y: 21.53), controlPoint1: CGPoint(x: 10.61, y: 20.16), controlPoint2: CGPoint(x: 10.5, y: 20.84))
bezierPath.addLine(to: CGPoint(x: 9.04, y: 21.89))
bezierPath.addCurve(to: CGPoint(x: 7.37, y: 23.21), controlPoint1: CGPoint(x: 8.31, y: 22.11), controlPoint2: CGPoint(x: 7.73, y: 22.58))
bezierPath.addCurve(to: CGPoint(x: 7.11, y: 25.37), controlPoint1: CGPoint(x: 7, y: 23.84), controlPoint2: CGPoint(x: 6.9, y: 24.63))
bezierPath.addLine(to: CGPoint(x: 7.32, y: 26.47))
bezierPath.addCurve(to: CGPoint(x: 9.98, y: 28.58), controlPoint1: CGPoint(x: 7.63, y: 27.68), controlPoint2: CGPoint(x: 8.73, y: 28.58))
bezierPath.addCurve(to: CGPoint(x: 10.71, y: 28.47), controlPoint1: CGPoint(x: 10.24, y: 28.58), controlPoint2: CGPoint(x: 10.45, y: 28.53))
bezierPath.addLine(to: CGPoint(x: 12.23, y: 28.05))
bezierPath.addCurve(to: CGPoint(x: 13.48, y: 29.68), controlPoint1: CGPoint(x: 12.59, y: 28.63), controlPoint2: CGPoint(x: 13.01, y: 29.16))
bezierPath.addLine(to: CGPoint(x: 12.96, y: 30.63))
bezierPath.addCurve(to: CGPoint(x: 12.7, y: 32.79), controlPoint1: CGPoint(x: 12.59, y: 31.26), controlPoint2: CGPoint(x: 12.49, y: 32.05))
bezierPath.addCurve(to: CGPoint(x: 14, y: 34.53), controlPoint1: CGPoint(x: 12.91, y: 33.53), controlPoint2: CGPoint(x: 13.32, y: 34.11))
bezierPath.addLine(to: CGPoint(x: 15, y: 35.11))
bezierPath.addCurve(to: CGPoint(x: 16.41, y: 35.47), controlPoint1: CGPoint(x: 15.41, y: 35.37), controlPoint2: CGPoint(x: 15.88, y: 35.47))
bezierPath.addCurve(to: CGPoint(x: 18.81, y: 34.05), controlPoint1: CGPoint(x: 17.4, y: 35.47), controlPoint2: CGPoint(x: 18.34, y: 34.95))
bezierPath.addLine(to: CGPoint(x: 19.33, y: 33.11))
bezierPath.addCurve(to: CGPoint(x: 21.32, y: 33.37), controlPoint1: CGPoint(x: 20.01, y: 33.26), controlPoint2: CGPoint(x: 20.64, y: 33.37))
bezierPath.addLine(to: CGPoint(x: 21.74, y: 34.89))
bezierPath.addCurve(to: CGPoint(x: 24.4, y: 37), controlPoint1: CGPoint(x: 22.05, y: 36.11), controlPoint2: CGPoint(x: 23.15, y: 37))
bezierPath.addCurve(to: CGPoint(x: 25.13, y: 36.89), controlPoint1: CGPoint(x: 24.66, y: 37), controlPoint2: CGPoint(x: 24.87, y: 36.95))
bezierPath.addLine(to: CGPoint(x: 26.23, y: 36.58))
bezierPath.addCurve(to: CGPoint(x: 28.21, y: 33.11), controlPoint1: CGPoint(x: 27.69, y: 36.16), controlPoint2: CGPoint(x: 28.58, y: 34.63))
bezierPath.addLine(to: CGPoint(x: 27.8, y: 31.58))
bezierPath.addCurve(to: CGPoint(x: 29.42, y: 30.32), controlPoint1: CGPoint(x: 28.37, y: 31.21), controlPoint2: CGPoint(x: 28.89, y: 30.79))
bezierPath.addLine(to: CGPoint(x: 30.36, y: 30.89))
bezierPath.addCurve(to: CGPoint(x: 31.77, y: 31.26), controlPoint1: CGPoint(x: 30.77, y: 31.16), controlPoint2: CGPoint(x: 31.24, y: 31.26))
bezierPath.addCurve(to: CGPoint(x: 34.17, y: 29.84), controlPoint1: CGPoint(x: 32.76, y: 31.26), controlPoint2: CGPoint(x: 33.7, y: 30.74))
bezierPath.addLine(to: CGPoint(x: 34.74, y: 28.84))
bezierPath.addCurve(to: CGPoint(x: 35.01, y: 26.68), controlPoint1: CGPoint(x: 35.11, y: 28.21), controlPoint2: CGPoint(x: 35.21, y: 27.42))
bezierPath.addCurve(to: CGPoint(x: 33.7, y: 24.95), controlPoint1: CGPoint(x: 34.8, y: 25.95), controlPoint2: CGPoint(x: 34.38, y: 25.37))
bezierPath.addLine(to: CGPoint(x: 32.76, y: 24.42))
bezierPath.addCurve(to: CGPoint(x: 33.02, y: 22.42), controlPoint1: CGPoint(x: 32.92, y: 23.74), controlPoint2: CGPoint(x: 33.02, y: 23.11))
bezierPath.addLine(to: CGPoint(x: 34.48, y: 22.05))
bezierPath.addCurve(to: CGPoint(x: 36.15, y: 20.74), controlPoint1: CGPoint(x: 35.21, y: 21.84), controlPoint2: CGPoint(x: 35.79, y: 21.37))
bezierPath.addCurve(to: CGPoint(x: 36.47, y: 18.63), controlPoint1: CGPoint(x: 36.52, y: 20.11), controlPoint2: CGPoint(x: 36.63, y: 19.37))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 35.27, y: 20.26))
bezierPath.addCurve(to: CGPoint(x: 34.22, y: 21.11), controlPoint1: CGPoint(x: 35.06, y: 20.68), controlPoint2: CGPoint(x: 34.64, y: 20.95))
bezierPath.addLine(to: CGPoint(x: 32.03, y: 21.68))
bezierPath.addLine(to: CGPoint(x: 32.03, y: 22.11))
bezierPath.addCurve(to: CGPoint(x: 31.66, y: 24.63), controlPoint1: CGPoint(x: 32.03, y: 22.95), controlPoint2: CGPoint(x: 31.92, y: 23.79))
bezierPath.addLine(to: CGPoint(x: 31.56, y: 25))
bezierPath.addLine(to: CGPoint(x: 33.18, y: 25.95))
bezierPath.addCurve(to: CGPoint(x: 34.01, y: 27), controlPoint1: CGPoint(x: 33.59, y: 26.16), controlPoint2: CGPoint(x: 33.86, y: 26.58))
bezierPath.addCurve(to: CGPoint(x: 33.86, y: 28.32), controlPoint1: CGPoint(x: 34.12, y: 27.47), controlPoint2: CGPoint(x: 34.07, y: 27.95))
bezierPath.addLine(to: CGPoint(x: 33.28, y: 29.32))
bezierPath.addCurve(to: CGPoint(x: 31.77, y: 30.21), controlPoint1: CGPoint(x: 32.97, y: 29.84), controlPoint2: CGPoint(x: 32.39, y: 30.21))
bezierPath.addCurve(to: CGPoint(x: 30.88, y: 29.95), controlPoint1: CGPoint(x: 31.45, y: 30.21), controlPoint2: CGPoint(x: 31.14, y: 30.11))
bezierPath.addLine(to: CGPoint(x: 29.26, y: 29))
bezierPath.addLine(to: CGPoint(x: 29, y: 29.26))
bezierPath.addCurve(to: CGPoint(x: 26.96, y: 30.84), controlPoint1: CGPoint(x: 28.37, y: 29.89), controlPoint2: CGPoint(x: 27.69, y: 30.42))
bezierPath.addLine(to: CGPoint(x: 26.59, y: 31.05))
bezierPath.addLine(to: CGPoint(x: 27.22, y: 33.37))
bezierPath.addCurve(to: CGPoint(x: 25.97, y: 35.53), controlPoint1: CGPoint(x: 27.48, y: 34.32), controlPoint2: CGPoint(x: 26.91, y: 35.26))
bezierPath.addLine(to: CGPoint(x: 24.87, y: 35.84))
bezierPath.addCurve(to: CGPoint(x: 24.4, y: 35.95), controlPoint1: CGPoint(x: 24.71, y: 35.95), controlPoint2: CGPoint(x: 24.56, y: 35.95))
bezierPath.addCurve(to: CGPoint(x: 22.73, y: 34.63), controlPoint1: CGPoint(x: 23.62, y: 35.95), controlPoint2: CGPoint(x: 22.94, y: 35.42))
bezierPath.addLine(to: CGPoint(x: 22.1, y: 32.32))
bezierPath.addLine(to: CGPoint(x: 21.68, y: 32.32))
bezierPath.addCurve(to: CGPoint(x: 19.18, y: 31.95), controlPoint1: CGPoint(x: 20.85, y: 32.32), controlPoint2: CGPoint(x: 20.01, y: 32.21))
bezierPath.addLine(to: CGPoint(x: 18.81, y: 31.84))
bezierPath.addLine(to: CGPoint(x: 17.87, y: 33.47))
bezierPath.addCurve(to: CGPoint(x: 16.35, y: 34.37), controlPoint1: CGPoint(x: 17.56, y: 34), controlPoint2: CGPoint(x: 16.98, y: 34.37))
bezierPath.addCurve(to: CGPoint(x: 15.47, y: 34.16), controlPoint1: CGPoint(x: 16.04, y: 34.37), controlPoint2: CGPoint(x: 15.73, y: 34.26))
bezierPath.addLine(to: CGPoint(x: 14.47, y: 33.58))
bezierPath.addCurve(to: CGPoint(x: 13.64, y: 32.53), controlPoint1: CGPoint(x: 14.06, y: 33.32), controlPoint2: CGPoint(x: 13.79, y: 32.95))
bezierPath.addCurve(to: CGPoint(x: 13.79, y: 31.21), controlPoint1: CGPoint(x: 13.53, y: 32.05), controlPoint2: CGPoint(x: 13.58, y: 31.58))
bezierPath.addLine(to: CGPoint(x: 14.73, y: 29.58))
bezierPath.addLine(to: CGPoint(x: 14.47, y: 29.32))
bezierPath.addCurve(to: CGPoint(x: 12.91, y: 27.26), controlPoint1: CGPoint(x: 13.85, y: 28.68), controlPoint2: CGPoint(x: 13.32, y: 28))
bezierPath.addLine(to: CGPoint(x: 12.7, y: 26.89))
bezierPath.addLine(to: CGPoint(x: 10.4, y: 27.53))
bezierPath.addCurve(to: CGPoint(x: 10.03, y: 27.53), controlPoint1: CGPoint(x: 10.35, y: 27.53), controlPoint2: CGPoint(x: 10.19, y: 27.53))
bezierPath.addCurve(to: CGPoint(x: 8.36, y: 26.21), controlPoint1: CGPoint(x: 9.25, y: 27.53), controlPoint2: CGPoint(x: 8.57, y: 27))
bezierPath.addLine(to: CGPoint(x: 8.05, y: 25.11))
bezierPath.addCurve(to: CGPoint(x: 8.2, y: 23.79), controlPoint1: CGPoint(x: 7.94, y: 24.63), controlPoint2: CGPoint(x: 7.99, y: 24.16))
bezierPath.addCurve(to: CGPoint(x: 9.25, y: 22.95), controlPoint1: CGPoint(x: 8.41, y: 23.37), controlPoint2: CGPoint(x: 8.83, y: 23.11))
bezierPath.addLine(to: CGPoint(x: 11.5, y: 22.32))
bezierPath.addLine(to: CGPoint(x: 11.5, y: 21.89))
bezierPath.addCurve(to: CGPoint(x: 11.81, y: 19.32), controlPoint1: CGPoint(x: 11.5, y: 21.05), controlPoint2: CGPoint(x: 11.6, y: 20.16))
bezierPath.addLine(to: CGPoint(x: 11.91, y: 18.95))
bezierPath.addLine(to: CGPoint(x: 10.29, y: 18))
bezierPath.addCurve(to: CGPoint(x: 9.46, y: 16.95), controlPoint1: CGPoint(x: 9.88, y: 17.74), controlPoint2: CGPoint(x: 9.61, y: 17.37))
bezierPath.addCurve(to: CGPoint(x: 9.61, y: 15.63), controlPoint1: CGPoint(x: 9.35, y: 16.47), controlPoint2: CGPoint(x: 9.41, y: 16))
bezierPath.addLine(to: CGPoint(x: 10.19, y: 14.63))
bezierPath.addCurve(to: CGPoint(x: 11.7, y: 13.74), controlPoint1: CGPoint(x: 10.5, y: 14.11), controlPoint2: CGPoint(x: 11.08, y: 13.74))
bezierPath.addCurve(to: CGPoint(x: 12.59, y: 14), controlPoint1: CGPoint(x: 12.02, y: 13.74), controlPoint2: CGPoint(x: 12.33, y: 13.84))
bezierPath.addLine(to: CGPoint(x: 14.26, y: 14.89))
bezierPath.addLine(to: CGPoint(x: 14.53, y: 14.63))
bezierPath.addCurve(to: CGPoint(x: 16.51, y: 13.05), controlPoint1: CGPoint(x: 15.15, y: 14), controlPoint2: CGPoint(x: 15.83, y: 13.47))
bezierPath.addLine(to: CGPoint(x: 16.88, y: 12.79))
bezierPath.addLine(to: CGPoint(x: 16.3, y: 10.58))
bezierPath.addCurve(to: CGPoint(x: 16.46, y: 9.26), controlPoint1: CGPoint(x: 16.2, y: 10.11), controlPoint2: CGPoint(x: 16.25, y: 9.63))
bezierPath.addCurve(to: CGPoint(x: 17.5, y: 8.42), controlPoint1: CGPoint(x: 16.67, y: 8.84), controlPoint2: CGPoint(x: 17.09, y: 8.58))
bezierPath.addLine(to: CGPoint(x: 18.6, y: 8.11))
bezierPath.addCurve(to: CGPoint(x: 20.74, y: 9.37), controlPoint1: CGPoint(x: 19.54, y: 7.84), controlPoint2: CGPoint(x: 20.48, y: 8.42))
bezierPath.addLine(to: CGPoint(x: 21.21, y: 11.16))
bezierPath.addLine(to: CGPoint(x: 21.37, y: 11.53))
bezierPath.addLine(to: CGPoint(x: 21.79, y: 11.53))
bezierPath.addCurve(to: CGPoint(x: 24.4, y: 11.89), controlPoint1: CGPoint(x: 22.68, y: 11.53), controlPoint2: CGPoint(x: 23.51, y: 11.63))
bezierPath.addLine(to: CGPoint(x: 24.77, y: 12))
bezierPath.addLine(to: CGPoint(x: 25.71, y: 10.32))
bezierPath.addCurve(to: CGPoint(x: 27.22, y: 9.42), controlPoint1: CGPoint(x: 26.02, y: 9.79), controlPoint2: CGPoint(x: 26.59, y: 9.42))
bezierPath.addCurve(to: CGPoint(x: 28.11, y: 9.68), controlPoint1: CGPoint(x: 27.53, y: 9.42), controlPoint2: CGPoint(x: 27.85, y: 9.53))
bezierPath.addLine(to: CGPoint(x: 29.1, y: 10.26))
bezierPath.addCurve(to: CGPoint(x: 29.94, y: 11.32), controlPoint1: CGPoint(x: 29.52, y: 10.47), controlPoint2: CGPoint(x: 29.78, y: 10.89))
bezierPath.addCurve(to: CGPoint(x: 29.78, y: 12.63), controlPoint1: CGPoint(x: 30.04, y: 11.79), controlPoint2: CGPoint(x: 29.99, y: 12.26))
bezierPath.addLine(to: CGPoint(x: 28.79, y: 14.37))
bezierPath.addLine(to: CGPoint(x: 29.05, y: 14.63))
bezierPath.addCurve(to: CGPoint(x: 30.67, y: 16.79), controlPoint1: CGPoint(x: 29.68, y: 15.26), controlPoint2: CGPoint(x: 30.2, y: 16))
bezierPath.addLine(to: CGPoint(x: 30.88, y: 17.16))
bezierPath.addLine(to: CGPoint(x: 33.02, y: 16.58))
bezierPath.addCurve(to: CGPoint(x: 35.16, y: 17.84), controlPoint1: CGPoint(x: 33.96, y: 16.32), controlPoint2: CGPoint(x: 34.9, y: 16.89))
bezierPath.addLine(to: CGPoint(x: 35.48, y: 18.95))
bezierPath.addCurve(to: CGPoint(x: 35.27, y: 20.26), controlPoint1: CGPoint(x: 35.58, y: 19.37), controlPoint2: CGPoint(x: 35.53, y: 19.84))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 21.74, y: 15.89))
bezierPath.addCurve(to: CGPoint(x: 15.73, y: 22), controlPoint1: CGPoint(x: 18.44, y: 15.89), controlPoint2: CGPoint(x: 15.73, y: 18.63))
bezierPath.addCurve(to: CGPoint(x: 21.74, y: 28.11), controlPoint1: CGPoint(x: 15.73, y: 25.37), controlPoint2: CGPoint(x: 18.44, y: 28.11))
bezierPath.addCurve(to: CGPoint(x: 27.74, y: 22), controlPoint1: CGPoint(x: 25.03, y: 28.11), controlPoint2: CGPoint(x: 27.74, y: 25.37))
bezierPath.addCurve(to: CGPoint(x: 21.74, y: 15.89), controlPoint1: CGPoint(x: 27.74, y: 18.63), controlPoint2: CGPoint(x: 25.08, y: 15.89))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 21.74, y: 27.05))
bezierPath.addCurve(to: CGPoint(x: 16.77, y: 22), controlPoint1: CGPoint(x: 18.97, y: 27.05), controlPoint2: CGPoint(x: 16.77, y: 24.79))
bezierPath.addCurve(to: CGPoint(x: 21.74, y: 16.95), controlPoint1: CGPoint(x: 16.77, y: 19.21), controlPoint2: CGPoint(x: 19.02, y: 16.95))
bezierPath.addCurve(to: CGPoint(x: 26.7, y: 22), controlPoint1: CGPoint(x: 24.45, y: 16.95), controlPoint2: CGPoint(x: 26.7, y: 19.21))
bezierPath.addCurve(to: CGPoint(x: 21.74, y: 27.05), controlPoint1: CGPoint(x: 26.7, y: 24.79), controlPoint2: CGPoint(x: 24.5, y: 27.05))
bezierPath.close()
bezierPath.miterLimit = 4;
fillColor.setFill()
bezierPath.fill()
}
public class func drawInfo() {
//// Color Declarations
let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Group 2
//// Group 3
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 22, y: 7))
bezierPath.addCurve(to: CGPoint(x: 7, y: 22), controlPoint1: CGPoint(x: 13.75, y: 7), controlPoint2: CGPoint(x: 7, y: 13.75))
bezierPath.addCurve(to: CGPoint(x: 22, y: 37), controlPoint1: CGPoint(x: 7, y: 30.25), controlPoint2: CGPoint(x: 13.75, y: 37))
bezierPath.addCurve(to: CGPoint(x: 37, y: 22), controlPoint1: CGPoint(x: 30.25, y: 37), controlPoint2: CGPoint(x: 37, y: 30.25))
bezierPath.addCurve(to: CGPoint(x: 22, y: 7), controlPoint1: CGPoint(x: 37, y: 13.75), controlPoint2: CGPoint(x: 30.25, y: 7))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 22, y: 35.85))
bezierPath.addCurve(to: CGPoint(x: 8.15, y: 22), controlPoint1: CGPoint(x: 14.38, y: 35.85), controlPoint2: CGPoint(x: 8.15, y: 29.62))
bezierPath.addCurve(to: CGPoint(x: 22, y: 8.15), controlPoint1: CGPoint(x: 8.15, y: 14.38), controlPoint2: CGPoint(x: 14.38, y: 8.15))
bezierPath.addCurve(to: CGPoint(x: 35.85, y: 22), controlPoint1: CGPoint(x: 29.62, y: 8.15), controlPoint2: CGPoint(x: 35.85, y: 14.38))
bezierPath.addCurve(to: CGPoint(x: 22, y: 35.85), controlPoint1: CGPoint(x: 35.85, y: 29.62), controlPoint2: CGPoint(x: 29.62, y: 35.85))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 22, y: 12.77))
bezierPath.addCurve(to: CGPoint(x: 20.62, y: 14.15), controlPoint1: CGPoint(x: 21.25, y: 12.77), controlPoint2: CGPoint(x: 20.62, y: 13.4))
bezierPath.addCurve(to: CGPoint(x: 22, y: 15.54), controlPoint1: CGPoint(x: 20.62, y: 14.9), controlPoint2: CGPoint(x: 21.25, y: 15.54))
bezierPath.addCurve(to: CGPoint(x: 23.38, y: 14.15), controlPoint1: CGPoint(x: 22.75, y: 15.54), controlPoint2: CGPoint(x: 23.38, y: 14.9))
bezierPath.addCurve(to: CGPoint(x: 22, y: 12.77), controlPoint1: CGPoint(x: 23.38, y: 13.35), controlPoint2: CGPoint(x: 22.81, y: 12.77))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 22, y: 19.12))
bezierPath.addCurve(to: CGPoint(x: 21.42, y: 19.69), controlPoint1: CGPoint(x: 21.65, y: 19.12), controlPoint2: CGPoint(x: 21.42, y: 19.35))
bezierPath.addLine(to: CGPoint(x: 21.42, y: 30.65))
bezierPath.addCurve(to: CGPoint(x: 22, y: 31.23), controlPoint1: CGPoint(x: 21.42, y: 31), controlPoint2: CGPoint(x: 21.65, y: 31.23))
bezierPath.addCurve(to: CGPoint(x: 22.58, y: 30.65), controlPoint1: CGPoint(x: 22.35, y: 31.23), controlPoint2: CGPoint(x: 22.58, y: 31))
bezierPath.addLine(to: CGPoint(x: 22.58, y: 19.69))
bezierPath.addCurve(to: CGPoint(x: 22, y: 19.12), controlPoint1: CGPoint(x: 22.58, y: 19.4), controlPoint2: CGPoint(x: 22.35, y: 19.12))
bezierPath.close()
bezierPath.miterLimit = 4;
fillColor.setFill()
bezierPath.fill()
}
//// Generated Images
public class var imageOfSettings: UIImage {
if Cache.imageOfSettings != nil {
return Cache.imageOfSettings!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 44, height: 44), false, 0)
TimerStyleKit.drawSettings()
Cache.imageOfSettings = UIGraphicsGetImageFromCurrentImageContext()?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
UIGraphicsEndImageContext()
return Cache.imageOfSettings!
}
public class var imageOfInfo: UIImage {
if Cache.imageOfInfo != nil {
return Cache.imageOfInfo!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 44, height: 44), false, 0)
TimerStyleKit.drawInfo()
Cache.imageOfInfo = UIGraphicsGetImageFromCurrentImageContext()?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
UIGraphicsEndImageContext()
return Cache.imageOfInfo!
}
}
@objc protocol StyleKitSettableImage {
func setImage(image: UIImage!)
}
@objc protocol StyleKitSettableSelectedImage {
func setSelectedImage(image: UIImage!)
}
| 70.447761 | 213 | 0.667288 |
ab908e638aeeaab3fced4fa514babe3d46a3d488 | 6,784 | //
// File.swift
//
//
// Created by Jake Mor on 8/27/21.
//
import Foundation
import UIKit
import AVFoundation
internal protocol BounceButtonToggleDelegate: AnyObject {
func buttonDidToggle(_ button: SWBounceButton, isOn on: Bool)
}
internal class SWBounceButton: UIButton {
// MARK: - Properties
var greedyTouches = true
var toggleValue: Any?
var toggleKey = "key"
var isOn: Bool = false
var canToggle: Bool = false
var oldTitle: String = ""
public var showLoading: Bool = false {
didSet {
if showLoading {
if oldTitle == "" {
oldTitle = self.titleLabel?.text ?? ""
}
self.setTitle("", for: .normal)
self.activityIndicator.startAnimating()
self.isEnabled = false
} else {
self.setTitle(oldTitle, for: .normal)
self.oldTitle = ""
self.activityIndicator.stopAnimating()
self.isEnabled = true
}
}
}
private let activityIndicator: UIActivityIndicatorView = {
let view = UIActivityIndicatorView()
view.hidesWhenStopped = true
view.stopAnimating()
view.translatesAutoresizingMaskIntoConstraints = false
view.color = PrimaryColor
return view
}()
var customTint: UIColor? = nil {
didSet {
if let customTint = customTint {
backgroundColor = customTint.withAlphaComponent(0.15)
setTitleColor(customTint, for: .normal)
}
}
}
var onBackgroundColor: UIColor = PrimaryButtonBackgroundColor
var offBackgroundColor: UIColor = SecondaryButtonBackgroundColor
weak var bounceButtonToggleDelegate: BounceButtonToggleDelegate?
var shouldOnlyAnimateText: Bool = false
var shouldAnimateLightly: Bool = false
var didAddTargetForCustomAction = false
var action: ((SWBounceButton) -> ())? {
didSet {
if !didAddTargetForCustomAction {
addTarget(self, action: #selector(tapped(sender:)), for: .primaryActionTriggered)
didAddTargetForCustomAction = true
}
}
}
override open var isHighlighted: Bool {
didSet {
if shouldOnlyAnimateText {
animateTitleScale(shrink: isHighlighted)
} else {
if shouldAnimateLightly {
animateScaleLightly(shrink: isHighlighted)
} else {
animateScale(shrink: isHighlighted)
}
}
super.isHighlighted = isHighlighted
}
}
// MARK: - Initializers
convenience init() {
self.init(frame: CGRect())
adjustsImageWhenHighlighted = false
}
override init(frame: CGRect) {
super.init(frame: frame)
setTitleColor(.black, for: .normal)
addTarget(self, action: #selector(tappedBounceButton(sender:)), for: .primaryActionTriggered)
addSubview(activityIndicator)
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func tapped(sender: SWBounceButton) {
action?(self)
}
@objc func tappedBounceButton(sender: SWBounceButton) {
if isEnabled {
UIImpactFeedbackGenerator(style: .light).impactOccurred()
// AudioServicesPlayAlertSound(1104)
}
shouldToggle()
}
func shouldToggle() {
if canToggle {
isOn = !isOn
bounceButtonToggleDelegate?.buttonDidToggle(self, isOn: isOn)
backgroundColor = isOn ? onBackgroundColor : offBackgroundColor
}
}
// MARK: - Animations
func animateScale(shrink: Bool) {
let duration = shrink ? 0.2 : 0.4
let damping: CGFloat = shrink ? 1 : 0.3
let scale: CGFloat = shrink ? 0.9 : 1
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: 0, options: [.allowUserInteraction, .curveEaseInOut], animations: {
self.transform = CGAffineTransform(scaleX: scale, y: scale)
self.titleLabel?.alpha = shrink ? 0.5 : 1.0
self.imageView?.alpha = shrink ? 0.5 : 1.0
}, completion: nil)
}
private func animateScaleLightly(shrink: Bool) {
let duration = shrink ? 0.2 : 0.4
let damping: CGFloat = shrink ? 1 : 0.35
let scale: CGFloat = shrink ? 0.95 : 1
UIView.animate(withDuration: duration, delay: shrink ? 0 : 0.05, usingSpringWithDamping: damping, initialSpringVelocity: 0, options: [.allowUserInteraction, .curveEaseInOut], animations: {
self.transform = CGAffineTransform(scaleX: scale, y: scale)
self.titleLabel?.alpha = shrink ? 0.5 : 1.0
self.imageView?.alpha = shrink ? 0.5 : 1.0
}, completion: nil)
}
private func animateTitleScale(shrink: Bool) {
let duration = shrink ? 0.2 : 0.4
let damping: CGFloat = 1
let alpha: CGFloat = shrink ? 0.5 : 1
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: 0, options: [.allowUserInteraction, .curveEaseInOut], animations: {
self.titleLabel?.alpha = alpha
}, completion: nil)
}
private var _borderColor: UIColor?
var borderColor: UIColor? {
didSet {
_borderColor = borderColor
self.layer.borderColor = (borderColor ?? UIColor.clear).cgColor
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
self.borderColor = _borderColor
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
if canToggle {
backgroundColor = isOn ? onBackgroundColor : offBackgroundColor
}
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// if the button is hidden/disabled/transparent it can’t be hit
if self.isHidden || !self.isUserInteractionEnabled || self.alpha < 0.01 { return nil }
let inset: CGFloat = greedyTouches ? -15 : -10
let largerFrame = self.bounds.insetBy(dx: inset, dy: inset)
// perform hit test on larger frame
return (largerFrame.contains(point)) ? self : nil
}
}
| 30.151111 | 196 | 0.599351 |
22bf2bc81cb589181d7454156d1365bfb4d58696 | 14,984 | //
// Xcode4.swift
// xcodereleases
//
// Created by Xcode Releases on 4/4/18.
// Copyright © 2018 Xcode Releases. All rights reserved.
//
import Foundation
import XCModel
let xcodes4: Array<Xcode> = [
Xcode(version: V("4H1503", "4.6.3"),
date: (2013, 06, 12),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12D75")], iOS: V("10B141")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.11.00"), clang: V("425.0.28", "4.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.6.3/xcode4630916281a.dmg"),
notes: Link("https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW600")),
checksums: Checksums(sha1: "f8f9d8a3eec9c46072c02e0007f6abe411e674f8")),
Xcode(version: V("4H1003", "4.6.2"),
date: (2013, 04, 15),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12D75")], iOS: V("10B141")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.11.00"), clang: V("425.0.28", "4.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.6.2/xcode4620419895a.dmg"),
notes: Link("https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW603")),
checksums: Checksums(sha1: "5b1918ac6173f6444196cf497a419d79970608c2")),
Xcode(version: V("4H512", "4.6.1"),
date: (2013, 03, 14),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12D75")], iOS: V("10B141")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.11.00"), clang: V("425.0.27", "4.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.6.1/xcode4610419628a.dmg"),
notes: Link("https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW612")),
checksums: Checksums(sha1: "a3bde15a30da0faba2080fb91ef65cdf7956a1ed")),
Xcode(version: V("4H127", "4.6"),
date: (2013, 01, 28),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12D75")], iOS: V("10B141")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.11.00"), clang: V("425.0.24", "4.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.6/xcode460417218a.dmg"),
notes: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.6/release_notes_xcode46gm.pdf")),
checksums: Checksums(sha1: "e677cd170fd5090ea0670bb31cb2023b58a9d323")),
Xcode(version: V("4H112f", "4.6", .dp(4)),
date: (2012, 12, 17),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12C237")], iOS: V("10B5126b")),
checksums: nil),
Xcode(version: V("4H104c", "4.6", .dp(3)),
date: (2012, 12, 03),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12C237")], iOS: V("10B5117b")),
checksums: nil),
Xcode(version: V("4H95e", "4.6", .dp(2)),
date: (2012, 11, 12),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12C237")], iOS: V("10B5105c")),
checksums: nil),
Xcode(version: V("4H90b", "4.6", .dp(1)),
date: (2012, 11, 01),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12C237")], iOS: V("10B5095e")),
checksums: nil),
Xcode(version: V("4G2008a", "4.5.2"),
date: (2012, 11, 01),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12C237")], iOS: V("10A403")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.11.00"), clang: V("421.11.66", "4.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.5.2/xcode4520418508a.dmg"),
notes: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.5.2/release_notes_xcode_4.5.2.pdf")),
checksums: Checksums(sha1: "2dea0b49f9f35b91ad2abc7f3b71889679febac1")),
Xcode(version: V("4G1004", "4.5.1"),
date: (2012, 10, 03),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12C237")], iOS: V("10A403")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.11.00"), clang: V("421.11.66", "4.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.5.1/xcode4510417539a.dmg"),
notes: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.5.1/release_notes_xcode_4.5.1.pdf")),
checksums: Checksums(sha1: "1a9e80e73f23ca0b6da961c0b691f1a94fe7e348")),
Xcode(version: V("4G182", "4.5"),
date: (2012, 09, 19),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12C237")], iOS: V("10A403")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.11.00"), clang: V("421.11.65", "4.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.5/xcode_4.5.dmg"),
notes: Link("https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW643")),
checksums: Checksums(sha1: "e461491c9251bb955ce60e2f7d7dfbc5f934321d")),
Xcode(version: V("4F1003", "4.4.1"),
date: (2012, 08, 07),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12A264")], iOS: V("9B176")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.11.00"), clang: V("421.0.60", "4.0")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.4.1/xcode_4.4.1_6938145.dmg"),
notes: Link("https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW670")),
checksums: Checksums(sha1: "4b8e927c7c58885fe91a36a21952604285b8d60f")),
Xcode(version: V("4G144l", "4.5", .gmSeed(4)),
date: (2012, 08, 06),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12A264")], iOS: V("10A5376e")),
checksums: nil),
Xcode(version: V("4G125j", "4.5", .gmSeed(3)),
date: (2012, 07, 16),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12A264")], iOS: V("10A5355e")),
checksums: nil),
Xcode(version: V("4G108j", "4.5", .gmSeed(2)),
date: (2012, 06, 25),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12A244")], iOS: V("10A5338d")),
checksums: nil),
Xcode(version: V("4G78z", "4.5", .gmSeed(1)),
date: (2012, 06, 11),
requires: "10.7",
sdks: SDKs(macOS: [V("11E52"), V("12A237")], iOS: V("10A5316k")),
checksums: nil),
Xcode(version: V("4E3002", "4.3.3"),
date: (2012, 06, 07),
requires: "10.7",
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.9.00"), clang: V("318.0.61", "3.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.3.3_for_lion/xcode_4.3.3_for_lion.dmg")),
checksums: Checksums(sha1: "d806ca8937b43a22d2f4e7c9ad8cc06e2a7298d8")),
Xcode(version: V("4E2002", "4.3.2"),
date: (2012, 03, 21),
requires: "10.7",
sdks: SDKs(iOS: V("9B176")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.9.00"), clang: V("318.0.58", "3.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.3.2/xcode_432_lion.dmg")),
checksums: Checksums(sha1: "8e2723f24f2a58af78317c115e1dc8e4f3c96b43")),
Xcode(version: V("4F134", "4.4"),
date: (2012, 03, 15),
requires: "10.7",
sdks: SDKs(iOS: V("9B174")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.11.00"), clang: V("421.0.57", "4.0")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.4_21362/xcode446938108a.dmg"),
notes: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.4_21362/release_notes_xcode44gm.pdf")),
checksums: Checksums(sha1: "d04393543564f85c2f4d82e507d596d3070e9aba")),
Xcode(version: V("4E1019", "4.3.1"),
date: (2012, 03, 05),
requires: "10.7",
sdks: SDKs(iOS: V("9B176")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.9.00"), clang: V("318.0.54", "3.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.3.1_for_lion_21267/xcode_431_lion.dmg")),
checksums: Checksums(sha1: "82d89d4029665cca28d806361e4607d9875ac9a4")),
Xcode(version: V("4F90", "4.4", .gmSeed(1)),
date: (2012, 02, 16),
requires: "10.7",
sdks: SDKs(iOS: V("9B174")),
checksums: nil),
Xcode(version: V("4E109", "4.3"),
date: (2012, 02, 12),
requires: "10.7",
sdks: SDKs(iOS: V("9A334")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.9.00"), clang: V("318.0.45", "3.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.3_for_lion_21266/xcode_43_lion.dmg"),
notes: Link("https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW699")),
checksums: Checksums(sha1: "be666d0285f492463ae4c189d265612a83cbf296")),
Xcode(version: V("4E71d", "4.3", .gmSeed(2)),
date: (2012, 01, 06),
requires: "10.7",
sdks: SDKs(iOS: V("9B5141a")),
checksums: nil),
Xcode(version: V("4E57a", "4.3", .gmSeed(1)),
date: (2011, 12, 12),
requires: "10.7",
sdks: SDKs(iOS: V("9B5127c")),
checksums: nil),
Xcode(version: V("4D502", "4.2.1"),
date: (2011, 11, 17),
requires: "10.7",
sdks: SDKs(iOS: V("9A334")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.2.1_for_lion_21265/installxcode_421_lion.dmg")),
checksums: Checksums(sha1: "2f800aadc6b51092e0375d34ac45702bcef59f5c")),
Xcode(version: V("4D199", "4.2"),
date: (2011, 10, 12),
requires: "10.7",
sdks: SDKs(iOS: V("9A334")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.1.00"), clang: V("211.10.1", "3.0")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.2_for_lion_21264/installxcode_42_lion.dmg"),
notes: Link("https://developer.apple.com/library/content/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html#//apple_ref/doc/uid/TP40001051-CH1-SW713")),
checksums: Checksums(sha1: "de748f5d096c55666b3ac22ee6fbe0e512206b36")),
Xcode(version: V("4C199", "4.2"),
date: (2011, 10, 12),
requires: "10.6.8",
sdks: SDKs(iOS: V("9A334")),
compilers: Compilers(llvm_gcc: V("5658", "4.2"), llvm: V("2336.1.00"), clang: V("211.10.1", "3.0")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.2_for_snow_leopard/xcode_4.2_for_snow_leopard.dmg"),
notes: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.2_for_snow_leopard/xcode_4.2_for_snow_leopard_readme.pdf")),
checksums: Checksums(sha1: "e65c19531be855c359eaad3f00a915213ecf2d41")),
Xcode(version: V("4B110f", "4.1"),
date: (2011, 08, 29),
requires: "10.6.8",
compilers: Compilers(gcc: V("5666", "4.2"), llvm_gcc: V("5658", "4.2"), llvm: V("2335.15.00"), clang: V("163.7.1", "2.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.1_for_snow_leopard_21110/xcode_4.1_for_snow_leopard.dmg"),
notes: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.1_for_snow_leopard_21110/xcode_4.1_for_snow_leopard_readme.pdf")),
checksums: Checksums(sha1: "5f55b5b906d9f7eeac842d63bd233a5c4021bfde")),
Xcode(version: V("4B110i", "4.1"),
date: (2011, 07, 20),
requires: "10.7",
compilers: Compilers(gcc: V("5666", "4.2"), llvm_gcc: V("5658", "4.2"), llvm: V("2335.15.00"), clang: V("163.7.1", "2.1")),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.1_for_lion_21263/installxcode_41_lion.dmg")),
checksums: Checksums(sha1: "7ccb636d51d54e88c2d27be55cbff107d5be96a0")),
Xcode(version: V("4A2002a", "4.0.2"),
date: (2011, 04, 12),
requires: "10.6.8",
compilers: Compilers(gcc: [V("5494", "4.0"), V("5666", "4.2")], llvm_gcc: [V("5658", "4.2")], llvm: [V("2335.9")], clang: [V("137", "2.0")], swift: nil),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.0.2_and_ios_sdk_4.3/xcode_4.0.2_and_ios_sdk_4.3.dmg"),
notes: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.0.2_and_ios_sdk_4.3/final_xcode_4.0.2_readme.pdf")),
checksums: Checksums(sha1: "684265b6310566c5b0080b1a47e5ddc2c680c929")),
Xcode(version: V("4A1006", "4.0.1"),
date: (2011, 03, 23),
requires: "10.6.8",
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.0.1_and_ios_sdk_4.3/xcode_4.0.1_and_ios_sdk_4.3.dmg"),
notes: Link("https://download.developer.apple.com/Developer_Tools/xcode_4.0.1_and_ios_sdk_4.3/xcode_4.0.1_readme.pdf")),
checksums: Checksums(sha1: "669258ed23e71482bc9e99f4bece6ac31f41dd38")),
Xcode(version: V("4A304a", "4.0"),
date: (2011, 03, 09),
requires: "10.6.8",
compilers: Compilers(gcc: [V("5494", "4.0"), V("5666", "4.2")], llvm_gcc: [V("5658", "4.2")], llvm: [V("2335.9")], clang: [V("137", "2.0")], swift: nil),
links: Links(download: Link("https://download.developer.apple.com/Developer_Tools/xcode_4_and_ios_sdk_4.3__final/xcode_4_and_ios_sdk_4.3__final.dmg"),
notes: Link("https://download.developer.apple.com/Developer_Tools/xcode_4_and_ios_sdk_4.3__final/xcode_4_rn.pdf")),
checksums: Checksums(sha1: "dd1b609fee9467d799e42d7ad7a2eb3838e35356"))
]
| 58.53125 | 188 | 0.604178 |
3a8ef58e64f8bf353a014c70d3880fe86cd8e09e | 8,524 | //
// HouserKeepingAddViewController.swift
// FBusiness
//
//
import UIKit
import SwiftX
import RxSwift
import RxCocoa
import Toaster
public class HouserKeepingAddViewController: BaseViewController {
@IBOutlet weak var topConstraint: NSLayoutConstraint!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var contentHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var addressField: UITextField!
@IBOutlet weak var addressDetailField: UITextField!
@IBOutlet weak var areaField: UITextField!
@IBOutlet weak var feeField: UITextField!
@IBOutlet weak var timeField: UITextField!
@IBOutlet weak var memoView: UIView!
@IBOutlet weak var memoLabel: UILabel!
@IBOutlet weak var memoLabelHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var subscribeButton: UIButton!
private let payWayView = OrderPayWayView.loadFromXib()
private let memoInputView = OrderMemoInputView.loadFromXib()
private let pickerView = HousePickerView.loadFromXib()
private var selectedDate: Date?
private var addressModel: AddressModel? {
didSet {
if let model = addressModel {
addressField.text = model.area
addressDetailField.text = model.userAddress
}
}
}
private var vmodel = HouseKeepingVModel()
override public func viewDidLoad() {
super.viewDidLoad()
registerKeyboardObserver()
_initUI()
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
isNavigationBarShadowImageHidden = false
}
@IBAction func buttonAction(_ sender: UIButton) {
UserVModel.default.verify { [weak self] (success) in
guard let weakSelf = self else { return }
guard (weakSelf.addressModel?.addressId) != nil else {
Toast.show("请选择您的地址")
return
}
guard weakSelf.areaField.text != nil else {
Toast.show("请填写房屋总面积")
return
}
guard weakSelf.timeField.text != nil else {
Toast.show("请选择服务时间")
return
}
if let weakSelf = self, success {
self?.payWayView.show(with: (Float(weakSelf.areaField.text ?? "0") ?? 0) * (CityVModel.default.currentCity?.config?.homeServiceFee ?? 12))
}
}
}
}
extension HouserKeepingAddViewController {
private func _initUI() {
navigationItem.title = "预约服务"
contentHeightConstraint.constant = 640
scrollView.contentSize = CGSize(width: UIScreen.width, height: 640)
let leftImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 18, height: 12))
leftImageView.image = UIImage(named: "icon_location_gray", in: Bundle.currentBase, compatibleWith: nil)
leftImageView.contentMode = .scaleAspectFit
addressField.leftView = leftImageView
addressField.leftViewMode = .always
let addressGesture = UITapGestureRecognizer(target: self, action: nil)
addressField.addGestureRecognizer(addressGesture)
_ = addressGesture.rx.event.asObservable()
.takeUntil(self.rx.deallocated)
.subscribe(onNext: { [weak self] (_) in
self?.view.endEditing(true)
AddressListViewController.show(with: { (model) in
self?.addressModel = model
})
})
let addressDetailGesture = UITapGestureRecognizer(target: self, action: nil)
addressDetailField.addGestureRecognizer(addressDetailGesture)
_ = addressDetailGesture.rx.event.asObservable()
.takeUntil(self.rx.deallocated)
.subscribe(onNext: { [weak self] (_) in
self?.view.endEditing(true)
AddressListViewController.show(with: { (model) in
self?.addressModel = model
})
})
_ = NotificationCenter.default.rx.notification(UITextField.textDidChangeNotification)
.takeUntil(self.rx.deallocated)
.subscribe(onNext: { [weak self] (_) in
if (self?.areaField.text ?? "") == "" {
self?.feeField.text = nil
} else {
self?.feeField.text = String(format: "总价:¥%.2f", (Float(self?.areaField.text ?? "0") ?? 0) * (CityVModel.default.currentCity?.config?.homeServiceFee ?? 12))
}
})
feeField.placeholder = String(format: "保洁服务单价:%.2f/平米", CityVModel.default.currentCity?.config?.homeServiceFee ?? 12.0)
let timeGesture = UITapGestureRecognizer(target: self, action: nil)
timeField.addGestureRecognizer(timeGesture)
_ = timeGesture.rx.event.asObservable()
.takeUntil(self.rx.deallocated)
.subscribe(onNext: { [weak self] (_) in
self?.view.endEditing(true)
self?.pickerView.show(with: self?.selectedDate ?? Date())
})
let memoGesture = UITapGestureRecognizer(target: self, action: nil)
memoView.addGestureRecognizer(memoGesture)
_ = memoGesture.rx.event.asObservable()
.takeUntil(self.rx.deallocated)
.subscribe(onNext: { [weak self] (_) in
let isEqualInitailizer = self?.memoLabel.text == "选填预约备注信息"
self?.memoInputView.show(with: isEqualInitailizer ? nil : self?.memoLabel.text)
})
Theme.decorate(button: subscribeButton)
pickerView.dismiss()
pickerView.handler = { [weak self] (value) in
guard let weakSelf = self else { return }
weakSelf.selectedDate = value
weakSelf.timeField.text = value.format(to: "yyyy-MM-dd HH:mm")
}
memoInputView.dismiss()
memoInputView.handler = { [weak self] (text) in
guard let weakSelf = self, text != "" else { return }
weakSelf.memoLabel.text = text
let height = text.heightWith(font: weakSelf.memoLabel.font, limitWidth: UIScreen.width - 30)
weakSelf.memoLabelHeightConstraint.constant = height > 85 ? 85 : height
}
payWayView.dismiss()
payWayView.enableTrustAccount = false
payWayView.handler = { [weak self] (type) in
self?._subscribe(type)
}
}
private func _subscribe(_ type: PayModel.PayType = .wxpay) {
guard let addressId = addressModel?.addressId else {
Toast.show("请选择您的地址")
return
}
guard let area = areaField.text else {
Toast.show("请填写房屋总面积")
return
}
guard timeField.text != nil else {
Toast.show("请选择服务时间")
return
}
var params: [AnyHashable: Any] = [
"addressId": addressId,
"houseArea": area,
"cityId": CityVModel.default.currentCityCode,
"payWay": type.rawValue
]
let date = selectedDate ?? Date().adding(Calendar.Component.day, value: 1)
params["serviceTime"] = Int(date.timestamp) * 1000
if memoLabel.text != "选填预约备注信息" {
params["remark"] = memoLabel.text ?? ""
}
startHUDAnimation()
vmodel.add(params, type) { [weak self] (model, error) in
self?.stopHUDAnimation()
if let model = model {
PayVModel.default.pay(with: type, model: model, isOrder: false, topNavigationController: topNavigationController, completion: nil)
}
}
}
}
extension HouserKeepingAddViewController {
static public func show(_ model: AddressModel? = nil) {
let vc = HouserKeepingAddViewController(nibName: "HouserKeepingAddViewController", bundle: Bundle.currentCommon)
vc.hidesBottomBarWhenPushed = true
topNavigationController?.pushViewController(vc, animated: true)
}
}
extension HouserKeepingAddViewController: UITextFieldDelegate {
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField == areaField {
textField.keyboardType = .numberPad
}
return true
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}
}
| 37.06087 | 176 | 0.608634 |
391e0d356f693984652302e72d26d80ce0e8ad1c | 844 | //
// AppDelegate.swift
// sdkTeste
//
// Created by Andre Terebinto on 23/04/21.
//
import Foundation
import UIKit
@UIApplicationMain
public class AppDelegate: UIResponder, UIApplicationDelegate {
static let shared = UIApplication.shared.delegate as! AppDelegate
public func pathForLocalizationFile() -> String {
var path = String()
if let language = UserDefaults.standard.object(forKey: "Language") {
if language as! String == "en" {
path = Bundle.main.path(forResource: "en", ofType: "lproj")!
} else if language as! String == "pt-BR" {
path = Bundle.main.path(forResource: "pt-BR", ofType: "lproj")!
}
} else {
path = Bundle.main.path(forResource: "pt-BR", ofType: "lproj")!
}
return path
}
}
| 26.375 | 79 | 0.595972 |
914f015204f9ac540168d668462e83cd1c777a4c | 3,926 | // Copyright 2021 Google LLC
//
// 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 MaterialComponents
import UIKit
typealias AcceptActionHandler = () -> Void
typealias CancelActionHandler = () -> Void
final class AlertViewController: UIViewController {
// MARK: IBOutlets
@IBOutlet private weak var alertTitleLabel: UILabel! {
didSet {
alertTitleLabel.attributedText = alertTitle
}
}
@IBOutlet private weak var alertDescriptionLabel: UILabel! {
didSet {
alertDescriptionLabel.attributedText = alertDescription
}
}
@IBOutlet private weak var alertDoneButton: MDCButton! {
didSet {
alertDoneButton.setTitle(alertAcceptButtonTitle, for: .normal)
}
}
@IBOutlet private weak var alertCancelButton: UIButton! {
didSet {
if let cancelButtonTitle = alertCancelButtonTitle, !cancelButtonTitle.isEmpty {
alertCancelButton.setTitle(cancelButtonTitle, for: .normal)
}
}
}
// MARK: Variables
private var acceptCompletion: AcceptActionHandler?
private var cancelCompletion: CancelActionHandler?
private var alertTitle: NSAttributedString?
private var alertDescription: NSAttributedString?
private var alertAcceptButtonTitle = ""
private var alertCancelButtonTitle: String?
init() {
super.init(nibName: "AlertViewController", bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View controller lifecycle methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
alertDoneButton.isUppercaseTitle = false
alertDoneButton.layer.cornerRadius = 4.0
}
// MARK: IBActions
@IBAction private func doneButtonTapped(_ sender: UIButton) {
// Cehck if controller is presented or added as a subview.
if let _ = presentingViewController {
dismiss(animated: true) { self.acceptCompletion?() }
} else {
acceptCompletion?()
}
}
@IBAction private func cancelButtonTapped(_ sender: UIButton) {
// Cehck if controller is presented or added as a subview.
if let _ = presentingViewController {
dismiss(animated: true) { self.cancelCompletion?() }
} else {
cancelCompletion?()
}
}
}
// MARK: External methods
extension AlertViewController {
func configureAlertView(
title: String,
description: String,
acceptButtonTitle: String,
cancelButtonTitle: String? = nil,
acceptAction: AcceptActionHandler? = nil,
cancelAction: CancelActionHandler? = nil
) {
configureAlertView(
attibutedTitle: NSAttributedString(string: title),
attibutedDescription: NSAttributedString(string: description),
acceptButtonTitle: acceptButtonTitle,
cancelButtonTitle: cancelButtonTitle,
acceptAction: acceptAction,
cancelAction: cancelAction
)
}
func configureAlertView(
attibutedTitle: NSAttributedString,
attibutedDescription: NSAttributedString,
acceptButtonTitle: String,
cancelButtonTitle: String? = nil,
acceptAction: AcceptActionHandler? = nil,
cancelAction: CancelActionHandler? = nil
) {
alertTitle = attibutedTitle
alertDescription = attibutedDescription
alertAcceptButtonTitle = acceptButtonTitle
alertCancelButtonTitle = cancelButtonTitle
acceptCompletion = acceptAction
cancelCompletion = cancelAction
}
}
| 29.081481 | 85 | 0.72593 |
71485cf78b681914a43c46c7e8a40f6d0652b518 | 4,850 | //
// ImageController.swift
// DreamDestination
//
// Created by kuroro on 16/08/2020.
// Copyright © 2020 lucasam. All rights reserved.
//
import UIKit
import FirebaseStorage
enum FetchImageError: Error {
case objectNotFound
case error
func errorDescription() -> String {
switch self {
case .objectNotFound: return "Pas encore d'image disponible pour ce lieu. Nous travaillons activement à combler ce manque."
case .error: return "Une erreur est survenue, veuillez relancer l'application en vérifiant que votre connexion internet est bien active."
}
}
}
class ImageController {
// MARK: Properties
private let storage = Storage.storage()
private var imageDownloadURL = String()
private var imageTab = [UIImage]()
private var counter = 0
// MARK: Methods
func handlingError(error: Error) -> FetchImageError {
if let errCode = StorageErrorCode(rawValue: error._code) {
switch errCode {
case .objectNotFound:
return FetchImageError.objectNotFound
default:
return FetchImageError.error
}
}
return FetchImageError.error
}
func uploadImage(_ image: UIImage, childReference: String, completionHandler: @escaping (Bool) -> Void) {
let storageRef = storage.reference()
let imageRef = storageRef.child(childReference)
let maxResolution: CGFloat = max(image.size.width, image.size.height)
let imagetest = image.rotateCameraImageToProperOrientation(maxResolution: maxResolution)
guard let data = imagetest.compress(.lowest) else {
return
}
imageRef.putData(data, metadata: nil) { (metadata, error) in
DispatchQueue.main.async {
if metadata != nil {
completionHandler(true)
} else {
completionHandler(false)
}
}
}
}
private func getImageURL(_ childReference: String) {
let storageRef = storage.reference()
let imageRef = storageRef.child(childReference)
imageRef.downloadURL { (url, _) in
guard let downloadURL = url else {
return
}
self.imageDownloadURL = downloadURL.absoluteString
}
}
func getImage(childReference: String, completionHandler: @escaping (Result<Data, FetchImageError>) -> Void) {
let convertedString = stringConverter(stringTab: [childReference])
getImageURL(convertedString[0])
let storageRef = storage.reference()
let imageRef = storageRef.child(convertedString[0])
imageRef.getData(maxSize: 5 * 1024 * 1024) { data, error in
if let data = data {
completionHandler(.success(data))
} else if let error = error {
completionHandler(.failure(self.handlingError(error: error)))
}
}
}
func getAnImagesTab(childReference: String, arrayToFetch: [String], to: Int, completionHandler: @escaping (Result<[UIImage], FetchImageError>) -> Void) {
let convertedArray = stringConverter(stringTab: arrayToFetch)
if counter == to {
completionHandler(.success(imageTab))
} else {
getImage(childReference: "\(childReference)\(convertedArray[counter])") { (result) in
switch result {
case .success(let data):
self.imageTab.append(UIImage(data: data) ?? #imageLiteral(resourceName: "loading"))
self.counter += 1
self.getAnImagesTab(childReference: childReference, arrayToFetch: convertedArray, to: to, completionHandler: completionHandler)
case .failure(let error):
completionHandler(.failure(error))
}
}
}
}
private func stringConverter(stringTab: [String]) -> [String] {
var tabConverted = stringTab
for index in 0...tabConverted.count - 1 {
var tab = tabConverted[index].map({ String($0) })
for idx in 0...tab.count - 1 {
switch tab[idx] {
case "É":
tab[idx] = "E"
case "â", "à":
tab[idx] = "a"
case "ç":
tab[idx] = "c"
case "é", "è", "ê":
tab[idx] = "e"
case "î", "ï":
tab[idx] = "i"
case "ô":
tab[idx] = "o"
default:
break
}
}
tabConverted[index] = tab.joined(separator: "")
}
return tabConverted
}
}
| 34.397163 | 157 | 0.558144 |
e07c96cfe5fbe7d11092e9e96694b8d4de006c39 | 9,101 | //
// EditRecordPopover.swift
// Timesheets
//
// Created by Paul Kirvan on 2015-01-22.
//
//
import Foundation
import UIKit
final class EditRecordPopover : UITableViewController, UITextFieldDelegate, ChangeSignificantDateDelegate
{
@IBOutlet var pilot: UITableViewCell?
@IBOutlet var passenger: UITableViewCell?
@IBOutlet var upTime: UITableViewCell?
@IBOutlet var downTime: UITableViewCell?
@IBOutlet var sequence: UITableViewCell?
@IBOutlet var vehicle: UITableViewCell?
@IBOutlet var route: UITextField?
var indexPathBeingEdited: IndexPath!
var record: FlightRecord!
var customDatePicker: ChangeSignificantDate?
enum SegueIdentifiers: String
{
case ChangePilotForRecordSegue = "ChangePilotForRecordSegue"
case ChangeOperatorForRecordSegue = "ChangeOperatorForRecordSegue"
case ChangePassengerForRecordSegue = "ChangePassengerForRecordSegue"
case ChangeSequenceForRecordSegue = "ChangeSequenceForRecordSegue"
case ChangeVehicleSegue = "ChangeVehicleSegue"
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
guard let identifier = segue.identifier, let segueIdentifer = SegueIdentifiers(rawValue: identifier) else {fatalError("Invalid segue identifier \(segue.identifier ?? "nil")")}
switch segueIdentifer
{
case .ChangePilotForRecordSegue:
let changePilot = segue.destination as? ChangePilotPopover
changePilot?.indexPathBeingEdited = indexPathBeingEdited
changePilot?.yesMeansRecord = true
changePilot?.flightRecord = record
case .ChangeOperatorForRecordSegue:
let changeOperator = segue.destination as? ChangeOperator
changeOperator?.indexPathBeingEdited = indexPathBeingEdited
changeOperator?.yesMeansRecord = true
changeOperator?.flightRecord = record
case .ChangePassengerForRecordSegue:
let changePassenger = segue.destination as? ChangePassengerPopover
changePassenger?.flightRecord = record
changePassenger?.indexPathBeingEdited = indexPathBeingEdited
changePassenger?.yesMeansRecord = true
case .ChangeSequenceForRecordSegue:
let changeSequence = segue.destination as? ChangeSequence
changeSequence?.flightRecord = record
case .ChangeVehicleSegue:
let changeVehicle = segue.destination as? ChangeVehicle
changeVehicle?.record = record
}
}
override func numberOfSections(in tableView: UITableView) -> Int
{
var returnValue = 7
let type: VehicleType = record.timesheet?.aircraft?.type ?? .glider
switch type
{
case .towplane:
if let _ = record.connectedAircraftRecord
{
returnValue = 6
}
case .winch, .auto:
returnValue = 5
default:
break
}
return returnValue
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat
{
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
guard let cell = tableView.cellForRow(at: indexPath) else {return}
if (cell == upTime) || (cell == downTime)
{
if let picker = customDatePicker
{
customDatePicker = nil
guard let previouslySelectedCell = picker.tableViewCell as? TableViewCellStylePicker else {return}
previouslySelectedCell.removePickerFromStackView()
if previouslySelectedCell !== cell
{
addPickerToCell(cell, atIndexPath:indexPath)
}
}
else
{
addPickerToCell(cell, atIndexPath: indexPath)
}
tableView.beginUpdates()
tableView.endUpdates()
}
if cell == pilot
{
if record.timesheet.aircraft.type >= .towplane
{
self.performSegue(withIdentifier: "ChangePilotForRecordSegue", sender:self)
}
else
{
self.performSegue(withIdentifier: "ChangeOperatorForRecordSegue", sender:self)
}
}
tableView.deselectRow(at: indexPath, animated:true)
}
private func addPickerToCell(_ cell: UITableViewCell, atIndexPath indexPath: IndexPath)
{
switch (indexPath as NSIndexPath).section
{
case 2:
customDatePicker = ChangeTime(record: record, upOrDown: .uptime, aircraftIsFlying: false)
case 3:
customDatePicker = ChangeTime(record: record, upOrDown: .downtime, aircraftIsFlying: false)
default:
break
}
(cell as? TableViewCellStylePicker)?.addPickerToStackView(customDatePicker!)
customDatePicker?.delegate = self
}
func dateChanged()
{
self.viewWillAppear(false)
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
addOrRemoveDoneButtonGivenTraitCollection(presentingViewController?.traitCollection, controller: self, withDoneButtonAction: "done")
pilot?.textLabel?.text = record.pilot?.fullName
passenger?.textLabel?.text = record.passenger?.fullName
sequence?.textLabel?.text = record.flightSequence
vehicle?.textLabel?.text = record.timesheet?.aircraft?.tailNumber
var label = upTime?.viewWithTag(2) as? UILabel
label?.text = record.timeUp.hoursAndMinutes
label = downTime?.viewWithTag(2) as? UILabel
label?.text = record.timeDown.hoursAndMinutes
route?.isEnabled = record.flightSequence == "Transit" ? true : false
if record.transitRoute != ""
{
route?.text = record.transitRoute
}
if record.timeUp < Date().midnight && dataModel.editorSignInTime < Date() - 30*60
{
let title = "Sign In"
let message = "You must sign in to edit records from prior days. Your license number will be logged on all edits taking place in the next half hour."
let signInAlert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel){_ in self.presentingViewController?.dismiss(animated: true)}
signInAlert.addAction(cancelAction)
let proceedAction = UIAlertAction(title: "Login", style: .default){_ in
guard let name = signInAlert.textFields?.first?.text, name.count > 0 else {self.presentingViewController?.dismiss(animated: true); return}
guard let license = signInAlert.textFields?.last?.text, license.count > 3 else {self.presentingViewController?.dismiss(animated: true); return}
dataModel.editorName = name
dataModel.editorLicense = license
dataModel.editorSignInTime = Date()
}
signInAlert.addAction(proceedAction)
signInAlert.addTextField(){textField in textField.placeholder = "Name"}
signInAlert.addTextField(){textField in textField.placeholder = "License Number"}
present(signInAlert, animated: true)
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
{
addOrRemoveDoneButtonGivenTraitCollection(controller: self, withDoneButtonAction: "done")
}
@objc func done()
{
presentingViewController?.dismiss(animated: true, completion:nil)
}
//MARK: - UITextFieldDelegate Methods
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
if string == "\n"
{
textField.resignFirstResponder()
return false
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return false
}
func textFieldDidEndEditing(_ textField: UITextField)
{
if textField == route
{
record.transitRoute = textField.text ?? ""
}
dataModel.aircraftAreaController?.becomeFirstResponder()
dataModel.saveContext()
}
}
| 35.830709 | 183 | 0.619163 |
7254843c543394c677c8fad156b171ba373f798a | 4,519 | /*
Monitr+Convertible.swift
Created By: Jacob Williams
Description: This file contains the Monitr class, which is used to continually check the
downloads directory for new content and distribute it appropriately.
License: MIT License
*/
import SwiftShell
import Dispatch
import TaskKit
enum MonitrError: Error {
case missingDependencies([Dependency])
}
enum Dependency: String {
case handbrake = "HandBrakeCLI"
case mp4v2 = "mp4track"
case ffmpeg
case mkvtoolnix = "mkvpropedit"
case transcodeVideo = "transcode-video"
static let all: [Dependency] = [.handbrake, .mp4v2, .ffmpeg, .mkvtoolnix, .transcodeVideo]
}
class ConvertibleMonitr<M>: Monitr<M> where M: ConvertibleMedia {
override init(_ config: Config, moveTaskQueue: LinkedTaskQueue, convertTaskQueue: LinkedTaskQueue) throws {
try super.init(config, moveTaskQueue: moveTaskQueue, convertTaskQueue: convertTaskQueue)
self.config.convert = config.convert
if config.convert {
try checkConversionDependencies()
}
}
override func setupTask(for media: M) -> MediaTask<M>? {
guard config.convert else {
return super.setupTask(for: media)
}
setupConversionConfig(media)
let move = MoveTask(media, plexDirectory: config.plexDirectory, deleteSubtitles: config.deleteSubtitles)
guard !media.beenConverted else {
return move
}
do {
if try media.needsConversion() {
loggerQueue.async {
logger.verbose("Need to convert: \(media.path)")
}
var convert: ConversionTask<M>
if config.convertImmediately {
convert = ConversionTask(media, priority: .high)
move.addDependency(convert)
} else {
convert = ConversionTask(media)
convert.addDependency(move)
return convert
}
}
} catch {
loggerQueue.async {
logger.error("Could not determine if '\(media.path)' needs to be converted")
logger.debug(error)
}
}
return move
}
override func addToQueue(_ task: MediaTask<M>?) {
guard let task = task else { return }
for dependency in task.dependencies {
addToQueue(dependency as? MediaTask<M>)
}
if task is ConversionTask<M> {
convertTaskQueue.add(task: task)
} else {
super.addToQueue(task)
}
}
private func setupConversionConfig(_ media: ConvertibleMedia) {
if media is Video {
(media as! Video).conversionConfig = VideoConversionConfig(config: config)
} else if media is Audio {
(media as! Audio).conversionConfig = AudioConversionConfig(config: config)
} else {
loggerQueue.async {
logger.error("Unknown Convertible Media type from \(media.path)")
}
}
}
private func checkConversionDependencies() throws {
loggerQueue.async {
logger.verbose("Making sure we have the required dependencies for transcoding \(M.self) media...")
}
let group = DispatchGroup()
let queue = DispatchQueue(label: "com.monitr.dependencies", qos: .userInteractive)
var missing: [Dependency] = []
for dependency in Dependency.all {
queue.async(group: group) {
let response = SwiftShell.run(bash: "which \(dependency.rawValue)")
if !response.succeeded || response.stdout.isEmpty {
var debugMessage = "Error determining if '\(missing)' dependency is met.\n\tReturn Code: \(response.exitcode)"
if !response.stdout.isEmpty {
debugMessage += "\n\tStandard Output: '\(response.stdout)'"
}
if !response.stderror.isEmpty {
debugMessage += "\n\tStandard Error: '\(response.stderror)'"
}
loggerQueue.async {
logger.debug(debugMessage)
}
missing.append(dependency)
}
}
}
group.wait()
guard missing.isEmpty else {
throw MonitrError.missingDependencies(missing)
}
}
}
| 32.278571 | 130 | 0.573357 |
9c8e4fb64e04854727a7148de1ba6943c25cf736 | 1,040 | //
// MinCountRule.swift
// Validation
//
// Created by Ben Shutt on 02/11/2020.
//
import Foundation
/// `ValidationRule` to check if a given `String` has greater than or equal to the `min`
/// number of characters.
public struct MinCountRule {
/// Minimum number of characters required for the entity to be valid.
///
/// This value is **inclusive**.
public var min: Int
/// Default public memberwise initializer
///
/// - Parameters:
/// - min: `Int`
public init(min: Int) {
self.min = min
}
}
// MARK: - ValidationRule
extension MinCountRule: ValidationRule {
/// Ensure `count` of the given `string` is greater than or equal to `min`.
///
/// - Parameter string: `String` input
public func validate(string: String) -> Bool {
return string.count >= min
}
public var rule: String {
return "Input must be have least \(min) character\(min.s)"
}
public var localizationKey: String {
return "_VALIDATION_RULE_MIN"
}
}
| 22.12766 | 88 | 0.618269 |
d90013f668a59b5c852d1a3c71e1ca71f0faae38 | 2,537 | //
// AppDelegate.swift
// Dimensions
//
// Created by Hans Yelek on 5/1/16.
// Copyright © 2016 Hans Yelek. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let navigationController = UINavigationController(rootViewController: ViewController())
navigationController.navigationBar.barStyle = .Black
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window!.backgroundColor = UIColor.whiteColor()
window!.rootViewController = navigationController
window!.makeKeyAndVisible()
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:.
}
}
| 45.303571 | 285 | 0.742609 |
ff69ee9bdb502c4e24c861c1934678a0769c819b | 4,108 | //
// Created by Tom Baranes on 06/05/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ContainerTransition: NSObject {
public typealias ContainerTransitionCompletion = () -> Void
// MARK: Properties
public var animationType: TransitionAnimationType?
public var transitionDuration: Duration = defaultTransitionDuration
// MARK: Private
fileprivate let container: UIView?
fileprivate let parentViewController: UIViewController?
fileprivate var viewControllers: [UITransitionContextViewControllerKey: UIViewController]?
fileprivate var views: [UITransitionContextViewKey: UIView]?
fileprivate let completion: ContainerTransitionCompletion?
// MARK: Life cycle
public init(animationType: TransitionAnimationType,
container: UIView,
parentViewController: UIViewController,
fromViewController: UIViewController?,
toViewController: UIViewController,
completion: ContainerTransitionCompletion? = nil) {
self.completion = completion
self.animationType = animationType
self.container = container
self.parentViewController = parentViewController
container.translatesAutoresizingMaskIntoConstraints = false
toViewController.view.translatesAutoresizingMaskIntoConstraints = true
toViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
toViewController.view.frame = container.bounds
fromViewController?.willMove(toParentViewController: nil)
parentViewController.addChildViewController(toViewController)
guard let fromViewController = fromViewController else {
container.addSubview(toViewController.view)
toViewController.didMove(toParentViewController: parentViewController)
completion?()
return
}
viewControllers = [UITransitionContextViewControllerKey.from: fromViewController,
UITransitionContextViewControllerKey.to: toViewController]
views = [UITransitionContextViewKey.from: fromViewController.view,
UITransitionContextViewKey.to: toViewController.view]
}
public func animate() {
guard let animationType = animationType else {
return
}
parentViewController?.view.isUserInteractionEnabled = false
let animator = AnimatorFactory.makeAnimator(transitionAnimationType: animationType)
animator?.transitionDuration = transitionDuration
animator?.animateTransition(using: self)
}
public var isAnimated: Bool { return false }
public var isInteractive: Bool { return false }
public var presentationStyle: UIModalPresentationStyle { return .none }
public var transitionWasCancelled: Bool { return false }
public var targetTransform: CGAffineTransform { return CGAffineTransform.identity }
public var containerView: UIView { return container! }
}
// MARK: - UIViewControllerContextTransitioning
extension ContainerTransition: UIViewControllerContextTransitioning {
public func viewController(forKey key: UITransitionContextViewControllerKey) -> UIViewController? {
return viewControllers?[key]
}
public func view(forKey key: UITransitionContextViewKey) -> UIView? {
return views?[key]
}
public func completeTransition(_ didComplete: Bool) {
viewControllers?[UITransitionContextViewControllerKey.from]?.view.removeFromSuperview()
viewControllers?[UITransitionContextViewControllerKey.from]?.removeFromParentViewController()
viewControllers?[UITransitionContextViewControllerKey.to]?.didMove(toParentViewController: parentViewController)
parentViewController?.view.isUserInteractionEnabled = true
completion?()
}
public func initialFrame(for vc: UIViewController) -> CGRect {
return vc.view.frame
}
public func finalFrame(for vc: UIViewController) -> CGRect {
return vc.view.frame
}
// MARK: Mandatory protocol
public func updateInteractiveTransition(_ percentComplete: CGFloat) {}
public func finishInteractiveTransition() {}
public func cancelInteractiveTransition() {}
public func pauseInteractiveTransition() {}
}
| 35.721739 | 116 | 0.769718 |
1abd48a72d5607a6c7420970d39e3f93cdf757f6 | 1,084 | //
// UIView+RxTests.swift
// Tests
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import RxCocoa
import UIKit
import XCTest
class UIViewTests : RxTest {
}
extension UIViewTests {
func testHidden_True() {
let subject = UIView(frame: CGRect.zero)
Observable.just(true).subscribe(subject.rx.isHidden).dispose()
XCTAssertTrue(subject.isHidden == true)
}
func testEnabled_False() {
let subject = UIView(frame: CGRect.zero)
Observable.just(false).subscribe(subject.rx.isHidden).dispose()
XCTAssertTrue(subject.isHidden == false)
}
}
extension UIViewTests {
func testAlpha_0() {
let subject = UIView(frame: CGRect.zero)
Observable.just(0).subscribe(subject.rx.alpha).dispose()
XCTAssertTrue(subject.alpha == 0.0)
}
func testAlpha_1() {
let subject = UIView(frame: CGRect.zero)
Observable.just(1).subscribe(subject.rx.alpha).dispose()
XCTAssertTrue(subject.alpha == 1.0)
}
}
| 22.583333 | 71 | 0.658672 |
e28e18a01034bcb99926737c04f4b01532a4a000 | 2,146 | //
// UserController.swift
// hubIO-serverPackageDescription
//
// Created by Kyle Lee on 1/21/18.
//
import Vapor
internal struct UserController {
private var drop: Droplet
internal init(drop: Droplet) {
self.drop = drop
}
internal func addRoutes() {
let group = drop.grouped("api", "users")
group.post(handler: signUp)
group.post("signIn", handler: signIn)
let secureGroup = drop.tokenMiddleware.grouped("api", "users")
secureGroup.get(handler: getAllUsers)
}
private func getAllUsers(_ request: Request) throws -> ResponseRepresentable {
let users = try User.all()
return try users.makeJSON()
}
private func signUp(_ request: Request) throws -> ResponseRepresentable {
guard
let json = request.json
else { throw Abort.badRequest }
let user = try User(json: json, drop: drop)
try user.save()
let token = try AccessToken.generate(for: user)
try token.save()
var responseJson = JSON()
try responseJson.set("user", user.makeJSON())
try responseJson.set("token", token.token)
return responseJson
}
private func signIn(_ request: Request) throws -> ResponseRepresentable {
guard let json = request.json else { throw Abort.badRequest }
let username: String = try json.get(User.Keys.username)
let password: String = try json.get(User.Keys.password)
let users = try User.makeQuery().filter(User.Keys.username, username)
guard
let user = try users.first(),
user.password == password
else { throw Abort(.badRequest, reason: "Hey dumbass, try again!") }
let token = try AccessToken.generate(for: user)
try token.save()
var responseJson = JSON()
try responseJson.set("user", user.makeJSON())
try responseJson.set("token", token.token)
return responseJson
}
}
| 24.386364 | 82 | 0.577819 |
391745a3983641e952540f6f938844e1fd0508fa | 529 | import Vapor
import HTTP
class RESTMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) throws -> Response {
let unauthorizedError = Abort(.unauthorized, reason: "Please include an API-KEY")
guard let submittedAPIKey = request.headers[HeaderKey(APIKey.keyName)]?.string else { throw unauthorizedError }
guard APIKey.apiKey == submittedAPIKey else {
throw unauthorizedError
}
return try next.respond(to: request)
}
}
| 33.0625 | 119 | 0.672968 |
4649581969c4dce8b16cdebc3b858cda44ef1b7d | 133 | import Foundation
import RealmSwift
class History: Object {
dynamic var chapter: Chapter?
dynamic var date: Date = Date()
}
| 16.625 | 35 | 0.721805 |
8984c608bc0fbc7e37d0a4f51a2d985e278485d9 | 773 | //
// FBMeCell.swift
// project -03 facebookMe
//
// Created by 杨玉京 on 2019/10/8.
// Copyright © 2019 杨玉京. All rights reserved.
//
import UIKit
class FBMeCell: UITableViewCell {
static let identifier = "FBMeBaseCell" //静态id标识
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = Specs.color.white
textLabel?.textColor = Specs.color.Black
textLabel?.font = Specs.font.large
detailTextLabel?.font = Specs.font.small
detailTextLabel?.textColor = Specs.color.lightGray
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 24.935484 | 79 | 0.650712 |
acd0c9814577b2a25f93d61b52a1351567f2f3ff | 170 | import UIKit
struct RemotePlayConfig {
let rate: Float
let title: String
let image: UIImage?
let totalDuration: Double
let currentDuration: Double
}
| 17 | 31 | 0.705882 |
38c9d71a2941d28293f4ab32954a14613f8769d7 | 918 | //
// Array+Tuple.swift
// Ash
//
// Created by John Scott on 23/06/2019.
//
import Foundation
enum Tuple<Element> {
case t0
case t1(Element)
case t2(Element, Element)
case t3(Element, Element, Element)
case t4(Element, Element, Element, Element)
case t5(Element, Element, Element, Element, Element)
case t([Element])
}
extension Array {
func tuple() -> Tuple<Element> {
if count == 0 {
return .t0
} else if count == 1 {
return .t1(self[0])
} else if count == 2 {
return .t2(self[0], self[1])
} else if count == 3 {
return .t3(self[0], self[1], self[2])
} else if count == 3 {
return .t4(self[0], self[1], self[2], self[3])
} else if count == 3 {
return .t5(self[0], self[1], self[2], self[3], self[4])
}
return .t(self)
}
}
| 22.390244 | 67 | 0.509804 |
890f2fccdcfee540c5b75ad2935cbbe628bafb04 | 2,015 | //
// PaginationManagedMixin.swift
// UIKitBase
//
// Created by Brian Strobach on 4/15/19.
// Copyright © 2019 Brian Strobach. All rights reserved.
//
import DarkMagic
import Layman
import Swiftest
import UIKit
import UIKitExtensions
import UIKitMixinable
open class PaginationManagedMixin<VC: UIViewController & PaginationManaged>: DatasourceManagedMixin<VC> {
override open func viewDidLoad() {
super.viewDidLoad()
guard let mixable = self.mixable else { return }
mixable.onDidTransitionMixins.append { [weak mixable] state in
guard let mixable = mixable else { return }
mixable.updatePaginatableViews(for: state)
}
mixable.reloadFunction = { [weak self] completion in
guard let self = self else { return }
self.mixable?.fetchNextPage(firstPage: true,
transitioningState: .loading,
reloadCompletion: { completion() })
}
}
override open func willDeinit() {
super.willDeinit()
mixable?.datasourceManagedView.loadingControls.clear()
}
override open func createSubviews() {
super.createSubviews()
mixable?.setupPaginatable()
}
override open func loadAsyncData() {
super.loadAsyncData()
mixable?.startLoadingData()
}
}
// open class PaginatableTableViewMixin<TVC: UITableViewController & PaginationManaged>: PaginationManagedMixin<TVC>
// where TVC.Datasource: UITableViewDataSource{
//
// open override func setupDelegates() {
// super.setupDelegates()
// mixable.tableView.dataSource = mixable.datasource
// }
// }
//
//
// open class PaginatableCollectionViewMixin<CVC: UICollectionViewController & PaginationManaged>: PaginationManagedMixin<CVC>
// where CVC.Datasource: UICollectionViewDataSource{
// open override func setupDelegates() {
// mixable.collectionView.dataSource = mixable.datasource
// }
// }
| 31.484375 | 126 | 0.665012 |
fbc744e6605822b7e09e320aeb5c05fb297693bd | 20,762 | //
// SpaceObjectsRouter.swift
//
// PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks
// Copyright © 2019 PubNub Inc.
// https://www.pubnub.com/
// https://www.pubnub.com/terms
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: - Router
struct SpaceObjectsRouter: HTTPRouter {
// Nested Endpoint
enum Endpoint: CustomStringConvertible {
case fetchAll(include: CustomIncludeField?, limit: Int?, start: String?, end: String?, count: Bool?)
case fetch(spaceID: String, include: CustomIncludeField?)
case create(space: PubNubSpace, include: CustomIncludeField?)
case update(space: PubNubSpace, include: CustomIncludeField?)
case delete(spaceID: String)
case fetchMembers(
spaceID: String,
include: [CustomIncludeField]?,
limit: Int?, start: String?, end: String?, count: Bool?
)
case modifyMembers(
spaceID: String,
adding: [ObjectIdentifiable], updating: [ObjectIdentifiable], removing: [String],
include: [CustomIncludeField]?,
limit: Int?, start: String?, end: String?, count: Bool?
)
var description: String {
switch self {
case .fetchAll:
return "Fetch All Space Objects"
case .fetch:
return "Fetch Space Object"
case .create:
return "Create Space Object"
case .update:
return "Update Space Object"
case .delete:
return "Delete Space Object"
case .fetchMembers:
return "Fetch Space's Members"
case .modifyMembers:
return "Modify Space's Members"
}
}
}
// Init
init(_ endpoint: Endpoint, configuration: RouterConfiguration) {
self.endpoint = endpoint
self.configuration = configuration
}
var endpoint: Endpoint
var configuration: RouterConfiguration
// Protocol Properties
var service: PubNubService {
return .objects
}
var category: String {
return endpoint.description
}
var path: Result<String, Error> {
let path: String
switch endpoint {
case .fetchAll:
path = "/v1/objects/\(subscribeKey)/spaces"
case let .fetch(spaceID, _):
path = "/v1/objects/\(subscribeKey)/spaces/\(spaceID.urlEncodeSlash)"
case .create:
path = "/v1/objects/\(subscribeKey)/spaces"
case let .update(space, _):
path = "/v1/objects/\(subscribeKey)/spaces/\(space.id.urlEncodeSlash)"
case let .delete(spaceID):
path = "/v1/objects/\(subscribeKey)/spaces/\(spaceID.urlEncodeSlash)"
case let .fetchMembers(spaceID, _, _, _, _, _):
path = "/v1/objects/\(subscribeKey)/spaces/\(spaceID.urlEncodeSlash)/users"
case let .modifyMembers(spaceID, _, _, _, _, _, _, _, _):
path = "/v1/objects/\(subscribeKey)/spaces/\(spaceID.urlEncodeSlash)/users"
}
return .success(path)
}
var queryItems: Result<[URLQueryItem], Error> {
var query = defaultQueryItems
switch endpoint {
case let .fetchAll(include, limit, start, end, count):
query.appendIfPresent(key: .include, value: include?.rawValue)
query.appendIfPresent(key: .limit, value: limit?.description)
query.appendIfPresent(key: .start, value: start?.description)
query.appendIfPresent(key: .end, value: end?.description)
query.appendIfPresent(key: .count, value: count?.description)
case let .fetch(_, include):
query.appendIfPresent(key: .include, value: include?.rawValue)
case let .create(_, include):
query.appendIfPresent(key: .include, value: include?.rawValue)
case let .update(_, include):
query.appendIfPresent(key: .include, value: include?.rawValue)
case .delete:
break
case let .fetchMembers(_, include, limit, start, end, count):
query.appendIfPresent(key: .include, value: include?.map { $0.rawValue }.csvString)
query.appendIfPresent(key: .limit, value: limit?.description)
query.appendIfPresent(key: .start, value: start?.description)
query.appendIfPresent(key: .end, value: end?.description)
query.appendIfPresent(key: .count, value: count?.description)
case let .modifyMembers(_, _, _, _, include, limit, start, end, count):
query.appendIfPresent(key: .include, value: include?.map { $0.rawValue }.csvString)
query.appendIfPresent(key: .limit, value: limit?.description)
query.appendIfPresent(key: .start, value: start?.description)
query.appendIfPresent(key: .end, value: end?.description)
query.appendIfPresent(key: .count, value: count?.description)
}
return .success(query)
}
var method: HTTPMethod {
switch endpoint {
case .fetchAll:
return .get
case .fetch:
return .get
case .create:
return .post
case .update:
return .patch
case .delete:
return .delete
case .fetchMembers:
return .get
case .modifyMembers:
return .patch
}
}
var body: Result<Data?, Error> {
switch endpoint {
case let .create(user, _):
return user.jsonDataResult.map { .some($0) }
case let .update(user, _):
return user.jsonDataResult.map { .some($0) }
case let .modifyMembers(_, adding, updating, removing, _, _, _, _, _):
return MembershipChangeset(add: adding, update: updating, remove: removing)
.encodableJSONData.map { .some($0) }
default:
return .success(nil)
}
}
var pamVersion: PAMVersionRequirement {
return .version3
}
// Validated
var validationErrorDetail: String? {
switch endpoint {
case .fetchAll:
return nil
case let .fetch(spaceID, _):
return isInvalidForReason((spaceID.isEmpty, ErrorDescription.emptySpaceID))
case let .create(space, _):
return isInvalidForReason(
(space.id.isEmpty && space.name.isEmpty, ErrorDescription.invalidPubNubSpace))
case let .update(space, _):
return isInvalidForReason(
(space.id.isEmpty && space.name.isEmpty, ErrorDescription.invalidPubNubSpace))
case let .delete(spaceID):
return isInvalidForReason((spaceID.isEmpty, ErrorDescription.emptySpaceID))
case let .fetchMembers(spaceID, _, _, _, _, _):
return isInvalidForReason((spaceID.isEmpty, ErrorDescription.emptySpaceID))
case let .modifyMembers(spaceID, adding, updating, removing, _, _, _, _, _):
return isInvalidForReason(
(spaceID.isEmpty, ErrorDescription.emptySpaceID),
(!adding.allSatisfy { !$0.id.isEmpty }, ErrorDescription.invalidJoiningMember),
(!updating.allSatisfy { !$0.id.isEmpty }, ErrorDescription.invalidUpdatingMember),
(!removing.allSatisfy { !$0.isEmpty }, ErrorDescription.invalidLeavingMember)
)
}
}
}
// MARK: - Space Protocols
public protocol PubNubSpace: PubNubObject {
var name: String { get }
var spaceDescription: String? { get }
/// Allows for other PubNubSpace objects to transcode between themselves
init(from space: PubNubSpace) throws
}
extension PubNubSpace {
public func transcode<T: PubNubSpace>(into _: T.Type) throws -> T {
return try transcode()
}
public func transcode<T: PubNubSpace>() throws -> T {
// Check if we're already that object, and return
if let custom = self as? T {
return custom
}
return try T(from: self)
}
}
public protocol PubNubMember: PubNubObject {
var userId: String { get }
var user: PubNubUser? { get set }
init(from member: PubNubMember) throws
}
extension PubNubMember {
public var id: String {
return userId
}
public func transcode<T: PubNubMember>(into _: T.Type) throws -> T {
return try transcode()
}
public func transcode<T: PubNubMember>() throws -> T {
// Check if we're already that object, and return
if let custom = self as? T {
return custom
}
return try T(from: self)
}
}
// MARK: - Response Decoder
// MARK: Protocol Spaces
struct PubNubSpacesResponseDecoder: ResponseDecoder {
typealias Payload = PubNubSpacesResponsePayload
}
public struct PubNubSpacesResponsePayload: Codable {
public let status: Int
public let data: [PubNubSpace]
public let totalCount: Int?
public let next: String?
public let prev: String?
public init(
status: Int,
data: [PubNubSpace],
totalCount: Int?,
next: String?,
prev: String?
) {
self.status = status
self.data = data
self.totalCount = totalCount
self.next = next
self.prev = prev
}
enum CodingKeys: String, CodingKey {
case status
case data
case totalCount
case next
case prev
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
data = try container.decode([SpaceObject].self, forKey: .data)
status = try container.decode(Int.self, forKey: .status)
totalCount = try container.decodeIfPresent(Int.self, forKey: .totalCount)
next = try container.decodeIfPresent(String.self, forKey: .next)
prev = try container.decodeIfPresent(String.self, forKey: .prev)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(try data.map { try $0.transcode(into: SpaceObject.self) }, forKey: .data)
try container.encode(status, forKey: .status)
try container.encodeIfPresent(totalCount, forKey: .totalCount)
try container.encodeIfPresent(next, forKey: .next)
try container.encodeIfPresent(prev, forKey: .prev)
}
}
// MARK: Spaces
public struct SpacesResponsePayload<T: PubNubSpace> {
public let status: Int
public let data: [T]
public let totalCount: Int?
public let next: String?
public let prev: String?
public init(
status: Int,
data: [T],
totalCount: Int?,
next: String?,
prev: String?
) {
self.status = status
self.data = data
self.totalCount = totalCount
self.next = next
self.prev = prev
}
public init<T: PubNubSpace>(
protocol response: PubNubSpacesResponsePayload,
into _: T.Type
) throws {
self.init(
status: response.status,
data: try response.data.map { try $0.transcode() },
totalCount: response.totalCount,
next: response.next,
prev: response.prev
)
}
}
extension SpacesResponsePayload: Codable where T: Codable {}
extension SpacesResponsePayload: Equatable where T: Equatable {}
// MARK: Protocol Space
struct PubNubSpaceResponseDecoder: ResponseDecoder {
typealias Payload = PubNubSpaceResponsePayload
}
public struct PubNubSpaceResponsePayload: Codable {
public let status: Int
public let data: PubNubSpace
public init(status: Int = 200, data: PubNubSpace) {
self.status = status
self.data = data
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ObjectResponseCodingKeys.self)
data = try container.decode(SpaceObject.self, forKey: .data)
status = try container.decode(Int.self, forKey: .status)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: ObjectsResponseCodingKeys.self)
try container.encode(try data.transcode(into: SpaceObject.self), forKey: .data)
try container.encode(status, forKey: .status)
}
}
// MARK: Space
public struct SpaceResponsePayload<T: PubNubSpace> {
public let status: Int
public let data: T
}
extension SpaceResponsePayload: Equatable where T: Equatable {}
// MARK: Protocol Members
struct PubNubMembersResponseDecoder: ResponseDecoder {
typealias Payload = PubNubMembersResponsePayload
}
public struct PubNubMembersResponsePayload: Codable {
public let status: Int
public let data: [PubNubMember]
public let totalCount: Int?
public let next: String?
public let prev: String?
public init(
status: Int,
data: [PubNubMember],
totalCount: Int?,
next: String?,
prev: String?
) {
self.status = status
self.data = data
self.totalCount = totalCount
self.next = next
self.prev = prev
}
enum CodingKeys: String, CodingKey {
case status
case data
case totalCount
case next
case prev
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ObjectsResponseCodingKeys.self)
status = try container.decode(Int.self, forKey: .status)
data = try container.decode([SpaceObjectMember].self, forKey: .data)
totalCount = try container.decodeIfPresent(Int.self, forKey: .totalCount)
next = try container.decodeIfPresent(String.self, forKey: .next)
prev = try container.decodeIfPresent(String.self, forKey: .prev)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: ObjectsResponseCodingKeys.self)
try container.encode(try data.map { try $0.transcode(into: SpaceObjectMember.self) }, forKey: .data)
try container.encode(status, forKey: .status)
try container.encodeIfPresent(totalCount, forKey: .totalCount)
try container.encodeIfPresent(next, forKey: .next)
try container.encodeIfPresent(prev, forKey: .prev)
}
}
// MARK: Members
public struct MembersResponsePayload<T: PubNubMember> {
public let status: Int
public let data: [T]
public let totalCount: Int?
public let next: String?
public let prev: String?
public init(
status: Int,
data: [T],
totalCount: Int?,
next: String?,
prev: String?
) throws {
self.status = status
self.data = data
self.totalCount = totalCount
self.next = next
self.prev = prev
}
public init<T: PubNubMember>(
protocol response: PubNubMembersResponsePayload,
into _: T.Type
) throws {
try self.init(
status: response.status,
data: try response.data.map { try $0.transcode() },
totalCount: response.totalCount,
next: response.next,
prev: response.prev
)
}
}
extension MembersResponsePayload: Equatable where T: Equatable {}
// MARK: - Space Response
public struct SpaceObject: PubNubSpace, Codable, Equatable {
public let id: String
public let name: String
public let spaceDescription: String?
public var custom: [String: JSONCodableScalar]?
public let created: Date
public let updated: Date
public let eTag: String
public init(
name: String,
id: String? = nil,
spaceDescription: String? = nil,
custom: [String: JSONCodableScalar]? = nil,
created: Date = Date.distantPast,
updated: Date? = nil,
eTag: String = ""
) {
self.id = id ?? name
self.name = name
self.spaceDescription = spaceDescription
self.custom = custom
self.created = created
self.updated = updated ?? created
self.eTag = eTag
}
public init(from space: PubNubSpace) {
self.init(
name: space.name,
id: space.id,
spaceDescription: space.spaceDescription,
custom: space.custom,
created: space.created,
updated: space.updated,
eTag: space.eTag
)
}
enum CodingKeys: String, CodingKey {
case id
case name
case spaceDescription = "description"
case custom
case created
case updated
case eTag
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
spaceDescription = try container.decodeIfPresent(String.self, forKey: .spaceDescription)
custom = try container.decodeIfPresent([String: JSONCodableScalarType].self, forKey: .custom)
created = try container.decode(Date.self, forKey: .created)
updated = try container.decode(Date.self, forKey: .updated)
eTag = try container.decode(String.self, forKey: .eTag)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(name, forKey: .name)
try container.encodeIfPresent(spaceDescription, forKey: .spaceDescription)
try container.encodeIfPresent(custom?.mapValues { $0.codableValue }, forKey: .custom)
try container.encode(created, forKey: .created)
try container.encode(updated, forKey: .updated)
try container.encode(eTag, forKey: .eTag)
}
public static func == (lhs: SpaceObject, rhs: SpaceObject) -> Bool {
return lhs.id == rhs.id &&
lhs.name == rhs.name &&
lhs.spaceDescription == rhs.spaceDescription &&
lhs.created == lhs.created &&
lhs.updated == rhs.updated &&
lhs.eTag == rhs.eTag &&
lhs.custom?.allSatisfy {
rhs.custom?[$0]?.scalarValue == $1.scalarValue
} ?? true
}
}
// MARK: - Member Response
public struct SpaceObjectMember: PubNubMember, PubNubIdentifiable, Codable, Equatable {
public let id: String
public var userId: String {
return id
}
public let custom: [String: JSONCodableScalar]?
var userObject: UserObject?
public var user: PubNubUser? {
get { return userObject }
set { userObject = try? newValue?.transcode() }
}
public let created: Date
public let updated: Date
public let eTag: String
public init(
id: String,
custom: [String: JSONCodableScalar]? = nil,
user: PubNubUser?,
created: Date = Date(),
updated: Date? = nil,
eTag: String = ""
) {
self.id = id
self.custom = custom
userObject = try? user?.transcode()
self.created = created
self.updated = updated ?? created
self.eTag = eTag
}
public init(from member: PubNubMember) throws {
self.init(
id: member.userId,
custom: member.custom,
user: member.user,
created: member.created,
updated: member.updated,
eTag: member.eTag
)
}
enum CodingKeys: String, CodingKey {
case id
case user
case custom
case created
case updated
case eTag
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
userObject = try container.decodeIfPresent(UserObject.self, forKey: .user)
custom = try container.decodeIfPresent([String: JSONCodableScalarType].self, forKey: .custom)
created = try container.decode(Date.self, forKey: .created)
updated = try container.decode(Date.self, forKey: .updated)
eTag = try container.decode(String.self, forKey: .eTag)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encodeIfPresent(userObject, forKey: .user)
try container.encodeIfPresent(custom?.mapValues { $0.codableValue }, forKey: .custom)
try container.encode(created, forKey: .created)
try container.encode(updated, forKey: .updated)
try container.encode(eTag, forKey: .eTag)
}
public static func == (lhs: SpaceObjectMember, rhs: SpaceObjectMember) -> Bool {
return lhs.id == rhs.id &&
lhs.userObject == rhs.userObject &&
lhs.created == lhs.created &&
lhs.updated == rhs.updated &&
lhs.eTag == rhs.eTag &&
lhs.custom?.allSatisfy {
rhs.custom?[$0]?.scalarValue == $1.scalarValue
} ?? true
}
}
// MARK: - Deprecated (v2.0.0)
public typealias SpaceObjectsResponsePayload = SpacesResponsePayload<SpaceObject>
extension SpaceObjectsResponsePayload {
public var spaces: [T] {
return data
}
}
public typealias UserMembership = SpaceObjectMember
public typealias SpaceMembershipResponsePayload = MembersResponsePayload<SpaceObjectMember>
extension SpaceMembershipResponsePayload {
public var memberships: [T] {
return data
}
// swiftlint:disable:next file_length
}
| 29.916427 | 104 | 0.68582 |
ef2673ec187f7b5a4874f0bfb36c045a43be6d15 | 2,170 | //
// AppDelegate.swift
// GooeyTabbarSample
//
// Created by Farid on 1/16/17.
// Copyright © 2017 ParsPay. 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.170213 | 285 | 0.75576 |
dd7ebace63281772df6f259a3a54dacec152e304 | 997 | //
// Copyright © 2017 Břetislav Štěpán.
// Licensed under MIT.
//
import Foundation
import CoreData
class CsvExporter {
func write(_ objects: [NSManagedObject], to: URL) {
let content = createCsv(objects)
try? content.write(to: to, atomically: true, encoding: String.Encoding.utf8)
}
fileprivate func createCsv(_ objects: [NSManagedObject]) -> String {
guard objects.count > 0 else { return "" }
let firstObject = objects[0]
let attribs = Array(firstObject.entity.attributesByName.keys)
let header = (attribs.reduce("", {($0 as String) + "," + $1 }) as NSString)
.substring(from: 1) + "\n"
let csv = objects.map(
{object in (attribs.map({((object.value(forKey: $0) ?? "NIL") as AnyObject).description})
.reduce("", {$0 + "," + $1}) as NSString)
.substring(from: 1) + "\n"
}).reduce("", +)
return header + csv
}
}
| 28.485714 | 101 | 0.55667 |
640e19008b00d28a9aa1553db001f6fb49285920 | 1,355 | //
// AppDelegate.swift
// Example
//
// Created by WingCH on 25/9/2020.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.621622 | 179 | 0.747601 |
f9becae5d91c38800a0c4399a27bac76994724eb | 2,557 | //
// StringExtensions.swift
// DINC
//
// Created by dhour on 4/15/16.
// Copyright © 2016 DHour. All rights reserved.
//
import Foundation
extension String {
/**
Currency w/o decimals
*/
var currencyNoDecimals: String {
let converter = NumberFormatter()
converter.decimalSeparator = "."
let styler = NumberFormatter()
styler.minimumFractionDigits = 0
styler.maximumFractionDigits = 0
styler.currencySymbol = "$"
styler.numberStyle = .currency
if let result = converter.number(from: self) {
return styler.string(from: result)!
} else {
converter.decimalSeparator = ","
if let result = converter.number(from: self) {
return styler.string(from: result)!
}
}
return ""
}
/**
Converts a raw string to a string currency w/ 2 decimals
*/
var currencyFromString: String {
let converter = NumberFormatter()
converter.decimalSeparator = "."
let styler = NumberFormatter()
styler.minimumFractionDigits = 2
styler.maximumFractionDigits = 2
styler.currencySymbol = "$"
styler.numberStyle = .currency
if let result = converter.number(from: self) {
let realNumber = Double(result)
return styler.string(from: NSNumber(value: realNumber))!
} else {
converter.decimalSeparator = ","
if let result = converter.number(from: self) {
return styler.string(from: result)!
}
}
return self
}
/**
Converts a raw string to a string currency w/ 2 decimals
*/
var currencyAppend: String {
let converter = NumberFormatter()
converter.decimalSeparator = "."
let styler = NumberFormatter()
styler.minimumFractionDigits = 2
styler.maximumFractionDigits = 2
styler.currencySymbol = "$"
styler.numberStyle = .currency
if let result = converter.number(from: self) {
let realNumber = Double(result)/100
return styler.string(from: NSNumber(value: realNumber))!
} else {
converter.decimalSeparator = ","
if let result = converter.number(from: self) {
return styler.string(from: result)!
}
}
return ""
}
}
| 26.635417 | 68 | 0.545952 |
269cc4a525986c22c91fa3295942d9353159469c | 343 | import UIKit
public struct LocaleInfo {
public var country: String
public var selected: Bool
public var flag: UIImage? {
return UIImage(named: "logo", in: Bundle.main, compatibleWith: nil)
}
init(country: String, selected: Bool) {
self.country = country
self.selected = selected
}
}
| 20.176471 | 75 | 0.623907 |
ab956fda97053ca356b93b886c956384b53ec856 | 1,685 | //
// SwiftyConfig.swift
// SwiftyStyle
//
// Created by taewan on 2017. 4. 9..
// Copyright © 2017년 taewan. All rights reserved.
//
import UIKit
import SwiftyStyle
@IBDesignable
class CustomView: UIView {}
@IBDesignable
class CustomLabel: UILabel {}
@IBDesignable
class CustomButton: UIButton {}
// MARK: - Custom Example
extension SwiftyStyle: SwiftyStyleConfigurable {
public static func swiftyStyle(config type: String, view: UIView, json: [String : Any]) {
let object = SwiftyStyle.Object(json)
switch type {
case "transform":
let x = object["x"].floatValue
let y = object["y"].floatValue
var transform = view.transform.translatedBy(x: x, y: y)
if let angle = object["angle"].float {
let rotate = angle/360
transform = transform.rotated(by: (.pi * 2) * rotate)
}
view.transform = transform
default:
break
}
}
public static func swiftyStyle(number name: String?) -> NSNumber? {
guard let name = name else {
return nil
}
switch name {
case "large": return 30
case "test": return 16
default: return nil
}
}
public static func swiftyStyle(color name: String?) -> UIColor? {
if name == "blue" {
return UIColor(red: 42.0 / 255.0, green: 125.0 / 255.0, blue: 226.0 / 255.0, alpha: 1.0)
} else if name == "grey" {
return UIColor(red: 152.0 / 255.0, green: 163.0 / 255.0, blue: 173.0 / 255.0, alpha: 1.0)
}
return nil
}
}
| 25.530303 | 102 | 0.550742 |
e29eb74e71f4ead169230e055c6dde5802090a1b | 333 | import Combine
import Foundation
protocol StateUpdater {
var updatesPublisher: AnyPublisher<State, Never> { get }
func resetNodes(with rootNode: NodeDto) -> AnyPublisher<Never, Error>
func favoriteNode(id: NodeId, at time: Date) -> AnyPublisher<Never, Error>
func unfavoriteNode(id: NodeId) -> AnyPublisher<Never, Error>
}
| 30.272727 | 76 | 0.756757 |
ffee66a81abcc0675ef9effef1d9021399f8f7a9 | 683 | //
// FFProductReportCard.swift
// Pods
//
// Created by Mackensie Alvarez on 2/18/17.
//
//
import Foundation
import SwiftyJSON
public class FFProductReportCard{
/// This returns a good or bad value.
public var good_or_bad: String
public var heading: String
/// This returns a heading for the report card.
public var text: String
/// This returns the type of report card
public var type: String
init(json: JSON) {
self.good_or_bad = json["good_or_bad"].stringValue
self.heading = json["heading"].stringValue
self.text = json["text"].stringValue
self.type = json["type"].stringValue
}
}
| 22.766667 | 58 | 0.642753 |
bf591ca91bac8153916ef47356f2b6f3dfced176 | 359 | //
// Font.swift
// StoryboardModel
//
// Created by Watanabe Toshinori on 11/26/18.
//
import Foundation
public class Font: Codable {
public var key: String
public var name: String?
public var size: String?
public var metaFont: String?
public var horizontal: String?
public var vertical: String?
}
| 14.36 | 46 | 0.62117 |
23c1dd33efbcd11ec799cd4bf6f106358313dadd | 641 | //
// PyMainThread.swift
// Pyto
//
// Created by Emma Labbé on 2/7/19.
// Copyright © 2019 Emma Labbé. All rights reserved.
//
import Foundation
@objc class PyMainThread: NSObject {
@objc static func runAsync(_ code: @escaping (() -> Void)) {
let code_ = code
DispatchQueue.main.async {
print("Will run code")
code_()
print("Ran")
}
}
@objc static func runSync(_ code: @escaping (() -> Void)) {
let code_ = code
DispatchQueue.main.sync {
print("Will run code")
code_()
print("Ran")
}
}
}
| 20.677419 | 64 | 0.516381 |
20eb82982d5e1d08d2970bb8935306ca338b2650 | 14,748 | //
// FolioReaderFontsMenu.swift
// FolioReaderKit
//
// Created by Heberti Almeida on 27/08/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
import UIKit
public enum FolioReaderFont: Int {
case andada = 0
case lato
case lora
case raleway
public static func folioReaderFont(fontName: String) -> FolioReaderFont? {
var font: FolioReaderFont?
switch fontName {
case "andada": font = .andada
case "lato": font = .lato
case "lora": font = .lora
case "raleway": font = .raleway
default: break
}
return font
}
public var cssIdentifier: String {
switch self {
case .andada: return "andada"
case .lato: return "lato"
case .lora: return "lora"
case .raleway: return "raleway"
}
}
}
public enum FolioReaderFontSize: Int {
case xs = 0
case s
case m
case l
case xl
public static func folioReaderFontSize(fontSizeStringRepresentation: String) -> FolioReaderFontSize? {
var fontSize: FolioReaderFontSize?
switch fontSizeStringRepresentation {
case "textSizeOne": fontSize = .xs
case "textSizeTwo": fontSize = .s
case "textSizeThree": fontSize = .m
case "textSizeFour": fontSize = .l
case "textSizeFive": fontSize = .xl
default: break
}
return fontSize
}
public var cssIdentifier: String {
switch self {
case .xs: return "textSizeOne"
case .s: return "textSizeTwo"
case .m: return "textSizeThree"
case .l: return "textSizeFour"
case .xl: return "textSizeFive"
}
}
}
class FolioReaderFontsMenu: UIViewController, SMSegmentViewDelegate, UIGestureRecognizerDelegate {
var menuView: UIView!
fileprivate var readerConfig: FolioReaderConfig
fileprivate var folioReader: FolioReader
init(folioReader: FolioReader, readerConfig: FolioReaderConfig) {
self.readerConfig = readerConfig
self.folioReader = folioReader
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.clear
// Tap gesture
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(FolioReaderFontsMenu.tapGesture))
tapGesture.numberOfTapsRequired = 1
tapGesture.delegate = self
view.addGestureRecognizer(tapGesture)
// Menu view
let visibleHeight: CGFloat = self.readerConfig.canChangeScrollDirection ? 222 : 170
menuView = UIView(frame: CGRect(x: 0, y: view.frame.height-visibleHeight, width: view.frame.width, height: view.frame.height))
menuView.backgroundColor = self.folioReader.isNight(self.readerConfig.nightModeMenuBackground, UIColor.white)
menuView.autoresizingMask = .flexibleWidth
menuView.layer.shadowColor = UIColor.black.cgColor
menuView.layer.shadowOffset = CGSize(width: 0, height: 0)
menuView.layer.shadowOpacity = 0.3
menuView.layer.shadowRadius = 6
menuView.layer.shadowPath = UIBezierPath(rect: menuView.bounds).cgPath
menuView.layer.rasterizationScale = UIScreen.main.scale
menuView.layer.shouldRasterize = true
view.addSubview(menuView)
let normalColor = UIColor(white: 0.5, alpha: 0.7)
let selectedColor = folioReader.isNight(readerConfig.nightTintColor, readerConfig.whiteTintColor)
let sun = UIImage(readerImageNamed: "icon-sun")
let moon = UIImage(readerImageNamed: "icon-moon")
let fontSmall = UIImage(readerImageNamed: "icon-font-small")
let fontBig = UIImage(readerImageNamed: "icon-font-big")
let sunNormal = sun?.imageTintColor(normalColor)?.withRenderingMode(.alwaysOriginal)
let moonNormal = moon?.imageTintColor(normalColor)?.withRenderingMode(.alwaysOriginal)
let fontSmallNormal = fontSmall?.imageTintColor(normalColor)?.withRenderingMode(.alwaysOriginal)
let fontBigNormal = fontBig?.imageTintColor(normalColor)?.withRenderingMode(.alwaysOriginal)
let sunSelected = sun?.imageTintColor(selectedColor)?.withRenderingMode(.alwaysOriginal)
let moonSelected = moon?.imageTintColor(selectedColor)?.withRenderingMode(.alwaysOriginal)
// Day night mode
let dayNight = SMSegmentView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 55),
separatorColour: self.readerConfig.nightModeSeparatorColor,
separatorWidth: 1,
segmentProperties: [
keySegmentTitleFont: UIFont(name: "Avenir-Light", size: 17)!,
keySegmentOnSelectionColour: UIColor.clear,
keySegmentOffSelectionColour: UIColor.clear,
keySegmentOnSelectionTextColour: selectedColor,
keySegmentOffSelectionTextColour: normalColor,
keyContentVerticalMargin: 17 as AnyObject
])
dayNight.delegate = self
dayNight.tag = 1
dayNight.addSegmentWithTitle(self.readerConfig.localizedFontMenuDay, onSelectionImage: sunSelected, offSelectionImage: sunNormal)
dayNight.addSegmentWithTitle(self.readerConfig.localizedFontMenuNight, onSelectionImage: moonSelected, offSelectionImage: moonNormal)
dayNight.selectSegmentAtIndex(self.folioReader.nightMode ? 1 : 0)
menuView.addSubview(dayNight)
// Separator
let line = UIView(frame: CGRect(x: 0, y: dayNight.frame.height+dayNight.frame.origin.y, width: view.frame.width, height: 1))
line.backgroundColor = self.readerConfig.nightModeSeparatorColor
menuView.addSubview(line)
// Fonts adjust
let fontName = SMSegmentView(frame: CGRect(x: 15, y: line.frame.height+line.frame.origin.y, width: view.frame.width-30, height: 55),
separatorColour: UIColor.clear,
separatorWidth: 0,
segmentProperties: [
keySegmentOnSelectionColour: UIColor.clear,
keySegmentOffSelectionColour: UIColor.clear,
keySegmentOnSelectionTextColour: selectedColor,
keySegmentOffSelectionTextColour: normalColor,
keyContentVerticalMargin: 17 as AnyObject
])
fontName.delegate = self
fontName.tag = 2
fontName.addSegmentWithTitle("Andada", onSelectionImage: nil, offSelectionImage: nil)
fontName.addSegmentWithTitle("Lato", onSelectionImage: nil, offSelectionImage: nil)
fontName.addSegmentWithTitle("Lora", onSelectionImage: nil, offSelectionImage: nil)
fontName.addSegmentWithTitle("Raleway", onSelectionImage: nil, offSelectionImage: nil)
// fontName.segments[0].titleFont = UIFont(name: "Andada-Regular", size: 18)!
// fontName.segments[1].titleFont = UIFont(name: "Lato-Regular", size: 18)!
// fontName.segments[2].titleFont = UIFont(name: "Lora-Regular", size: 18)!
// fontName.segments[3].titleFont = UIFont(name: "Raleway-Regular", size: 18)!
fontName.selectSegmentAtIndex(self.folioReader.currentFont.rawValue)
menuView.addSubview(fontName)
// Separator 2
let line2 = UIView(frame: CGRect(x: 0, y: fontName.frame.height+fontName.frame.origin.y, width: view.frame.width, height: 1))
line2.backgroundColor = self.readerConfig.nightModeSeparatorColor
menuView.addSubview(line2)
// Font slider size
let slider = HADiscreteSlider(frame: CGRect(x: 60, y: line2.frame.origin.y+2, width: view.frame.width-120, height: 55))
slider.tickStyle = ComponentStyle.rounded
slider.tickCount = 5
slider.tickSize = CGSize(width: 8, height: 8)
slider.thumbStyle = ComponentStyle.rounded
slider.thumbSize = CGSize(width: 28, height: 28)
slider.thumbShadowOffset = CGSize(width: 0, height: 2)
slider.thumbShadowRadius = 3
slider.thumbColor = selectedColor
slider.backgroundColor = UIColor.clear
slider.tintColor = self.readerConfig.nightModeSeparatorColor
slider.minimumValue = 0
slider.value = CGFloat(self.folioReader.currentFontSize.rawValue)
slider.addTarget(self, action: #selector(FolioReaderFontsMenu.sliderValueChanged(_:)), for: UIControlEvents.valueChanged)
// Force remove fill color
slider.layer.sublayers?.forEach({ layer in
layer.backgroundColor = UIColor.clear.cgColor
})
menuView.addSubview(slider)
// Font icons
let fontSmallView = UIImageView(frame: CGRect(x: 20, y: line2.frame.origin.y+14, width: 30, height: 30))
fontSmallView.image = fontSmallNormal
fontSmallView.contentMode = UIViewContentMode.center
menuView.addSubview(fontSmallView)
let fontBigView = UIImageView(frame: CGRect(x: view.frame.width-50, y: line2.frame.origin.y+14, width: 30, height: 30))
fontBigView.image = fontBigNormal
fontBigView.contentMode = UIViewContentMode.center
menuView.addSubview(fontBigView)
// Only continues if user can change scroll direction
guard (self.readerConfig.canChangeScrollDirection == true) else {
return
}
// Separator 3
let line3 = UIView(frame: CGRect(x: 0, y: line2.frame.origin.y+56, width: view.frame.width, height: 1))
line3.backgroundColor = self.readerConfig.nightModeSeparatorColor
menuView.addSubview(line3)
let vertical = UIImage(readerImageNamed: "icon-menu-vertical")
let horizontal = UIImage(readerImageNamed: "icon-menu-horizontal")
let verticalNormal = vertical?.imageTintColor(normalColor)?.withRenderingMode(.alwaysOriginal)
let horizontalNormal = horizontal?.imageTintColor(normalColor)?.withRenderingMode(.alwaysOriginal)
let verticalSelected = vertical?.imageTintColor(selectedColor)?.withRenderingMode(.alwaysOriginal)
let horizontalSelected = horizontal?.imageTintColor(selectedColor)?.withRenderingMode(.alwaysOriginal)
// Layout direction
let layoutDirection = SMSegmentView(frame: CGRect(x: 0, y: line3.frame.origin.y, width: view.frame.width, height: 55),
separatorColour: self.readerConfig.nightModeSeparatorColor,
separatorWidth: 1,
segmentProperties: [
keySegmentTitleFont: UIFont(name: "Avenir-Light", size: 17)!,
keySegmentOnSelectionColour: UIColor.clear,
keySegmentOffSelectionColour: UIColor.clear,
keySegmentOnSelectionTextColour: selectedColor,
keySegmentOffSelectionTextColour: normalColor,
keyContentVerticalMargin: 17 as AnyObject
])
layoutDirection.delegate = self
layoutDirection.tag = 3
layoutDirection.addSegmentWithTitle(self.readerConfig.localizedLayoutVertical, onSelectionImage: verticalSelected, offSelectionImage: verticalNormal)
layoutDirection.addSegmentWithTitle(self.readerConfig.localizedLayoutHorizontal, onSelectionImage: horizontalSelected, offSelectionImage: horizontalNormal)
var scrollDirection = FolioReaderScrollDirection(rawValue: self.folioReader.currentScrollDirection)
if scrollDirection == .defaultVertical && self.readerConfig.scrollDirection != .defaultVertical {
scrollDirection = self.readerConfig.scrollDirection
}
switch scrollDirection ?? .vertical {
case .vertical, .defaultVertical:
layoutDirection.selectSegmentAtIndex(FolioReaderScrollDirection.vertical.rawValue)
case .horizontal, .horizontalWithVerticalContent:
layoutDirection.selectSegmentAtIndex(FolioReaderScrollDirection.horizontal.rawValue)
}
menuView.addSubview(layoutDirection)
}
// MARK: - SMSegmentView delegate
func segmentView(_ segmentView: SMSegmentView, didSelectSegmentAtIndex index: Int) {
guard (self.folioReader.readerCenter?.currentPage) != nil else { return }
if segmentView.tag == 1 {
self.folioReader.nightMode = Bool(index == 1)
UIView.animate(withDuration: 0.6, animations: {
self.menuView.backgroundColor = (self.folioReader.nightMode ? self.readerConfig.nightModeBackground : UIColor.white)
self.folioReader.readerCenter?.view.backgroundColor = self.menuView.backgroundColor
})
} else if segmentView.tag == 2 {
self.folioReader.currentFont = FolioReaderFont(rawValue: index)!
} else if segmentView.tag == 3 {
guard self.folioReader.currentScrollDirection != index else {
return
}
self.folioReader.currentScrollDirection = index
}
}
// MARK: - Font slider changed
@objc func sliderValueChanged(_ sender: HADiscreteSlider) {
guard
(self.folioReader.readerCenter?.currentPage != nil),
let fontSize = FolioReaderFontSize(rawValue: Int(sender.value)) else {
return
}
self.folioReader.currentFontSize = fontSize
}
// MARK: - Gestures
@objc func tapGesture() {
dismiss()
if (self.readerConfig.shouldHideNavigationOnTap == false) {
self.folioReader.readerCenter?.showBars()
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer is UITapGestureRecognizer && touch.view == view {
return true
}
return false
}
// MARK: - Status Bar
override var prefersStatusBarHidden : Bool {
return (self.readerConfig.shouldHideNavigationOnTap == true)
}
}
| 44.288288 | 163 | 0.643545 |
22d3d3bbfc5da198073a5ebf910dc44d0d946948 | 1,073 | //
// PullRequestConfigurator.swift
// GitTest
//
// Created by Marcos Barbosa on 27/07/2018.
// Copyright © 2018 n/a. All rights reserved.
//
import Foundation
import UIKit
extension PullRequestController: PullRequestPresenterOutput{
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
}
}
extension PullRequestInteractor: PullRequestControllerOutput{
}
extension PullRequestPresenter: PullRequestInteractorOutput{
}
class PullRequestConfigurator{
static let sharedInstance = PullRequestConfigurator()
private init(){}
func configure(viewController: PullRequestController){
let router = PullRequestRouter()
router.viewController = viewController
let presenter = PullRequestPresenter()
presenter.output = viewController
let interactor = PullRequestInteractor()
interactor.output = presenter
viewController.output = interactor
viewController.router = router
}
}
| 20.634615 | 71 | 0.66822 |
e69a8c3445cad5ad2b5a2f083acf1f3769140f4d | 360 | //
// NotificationView.swift
// watchOS-Cross-Platform WatchKit Extension
//
// Created by Edgar Nzokwe on 9/19/21.
//
import SwiftUI
struct NotificationView: View {
var body: some View {
Text("Hello, World!")
}
}
struct NotificationView_Previews: PreviewProvider {
static var previews: some View {
NotificationView()
}
}
| 17.142857 | 51 | 0.666667 |
ef7e31fea123df134c0b92ac343e6d4d80d5e85c | 1,025 | //
// ASCII.SeparatorTests.swift
// Spyder Tests
//
// Created by Dima Bart on 2018-01-22.
// Copyright © 2018 Dima Bart. All rights reserved.
//
import XCTest
class ASCIISeparatorTests: XCTestCase {
// ----------------------------------
// MARK: - Length -
//
func testLength() {
let context = ASCII.RenderContext(
edgePadding: 2,
maxCellWidth: 0,
fillingLength: 100
)
let separator = ASCII.Separator()
let length = separator.length(in: context)
XCTAssertEqual(length, 100)
}
// ----------------------------------
// MARK: - Rendering -
//
func testRender() {
let context = ASCII.RenderContext(
edgePadding: 1,
maxCellWidth: 0,
fillingLength: 10
)
let separator = ASCII.Separator()
let result = separator.render(in: context)
XCTAssertEqual(result, "+--------+")
}
}
| 22.777778 | 53 | 0.482927 |
c12f3ef7f301a0b378856ca776d9d389cf2c9c7a | 944 | //
// CheckmarkCell.swift
// PinpointKit
//
// Created by Matthew Bischoff on 3/18/16.
// Copyright © 2016 Lickability. All rights reserved.
//
import UIKit
/// A `UITableViewCell` subclass that displays a checkmark in the `imageView` when `isChecked` is `true` and hides it, leaving a space when `false`.
final class CheckmarkCell: UITableViewCell {
/// Controls whether the receiver displays a checkmark in `imageView`.
var isChecked: Bool = false {
didSet {
imageView?.isHidden = !isChecked
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
imageView?.image = UIImage(named: "Checkmark", in: Bundle(for: type(of: self)), compatibleWith: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 30.451613 | 148 | 0.662076 |
f8aa4b80fd1f9a450bb668e1b19886e389dc3836 | 385 | //
// OrdersPageWorker.swift
// smartPOS
//
// Created by I Am Focused on 17/04/2021.
// Copyright (c) 2021 Clean Swift LLC. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
class OrdersPageWorker: OrdersNetworkInjected {
}
| 22.647059 | 66 | 0.719481 |
4888409630b843d7c8ed2bdacf38eb1178190ce2 | 72 | struct EditGoalRouting: Equatable {
var isPresented: Bool = false
}
| 18 | 35 | 0.736111 |
e61aa38f334a2a027ded885ef1cd849145c13dce | 10,300 | //
// Entwine
// https://github.com/tcldr/Entwine
//
// Copyright © 2019 Tristan Celder. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if canImport(Combine)
import Combine
import os.log
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publishers {
// MARK: - Publisher configuration
/// Configuration values for the `Publishers.Signpost` operator.
///
/// Pass `Publishers.SignpostConfiguration.Marker` values to the initializer to define how signposts for
/// each event should be labelled:
/// - A nil marker value will disable signposts for that event
/// - A `.default` marker value will use the event name as the event label
/// - A `.named(_:)` marker value will use the passed string as the event label
public struct SignpostConfiguration {
public struct Marker {
/// A marker that specifies a signpost should use the default label for an event
public static let `default` = Marker()
/// A marker that specifies a signpost should use the passed name as a label for an event
/// - Parameter name: The name the signpost should be labelled with
public static func named(_ name: StaticString) -> Marker {
Marker(name)
}
let name: StaticString?
init (_ name: StaticString? = nil) {
self.name = name
}
}
/// Configuration values for the `Publishers.Signpost` operator.
///
/// The default value specifies signposts should be grouped into the `com.github.tcldr.Entwine.Signpost`
/// subsystem using the `.pointsOfInterest` category (displayed in most Xcode Intruments templates
/// by default under the 'Points of Interest' instrument).
///
/// Use a `Publishers.SignpostConfiguration.Marker` value to define how signposts for each event should
/// be labelled:
/// - A nil marker value will disable signposts for that event
/// - A `.default` marker value will use the event name as the event label
/// - A `.named(_:)` marker value will use the passed string as the event label
///
/// - Parameters:
/// - log: The OSLog parameters to be used to mark signposts
/// - receiveSubscriptionMarker: A marker value to identify subscription events. A `default` value yields an event labelled `subscription`
/// - receiveMarker: A marker value to identify sequence output events. A `default` value yields an event labelled `receive`
/// - receiveCompletionMarker: A marker value to identify sequence completion events. A `default` value yields an event labelled `receiveCompletion`
/// - requestMarker: A marker value to identify demand request events. A `default` value yields an event labelled `request`
/// - cancelMarker: A marker value to identify cancellation events. A `default` value yields an event labelled `cancel`
public init(
log: OSLog = OSLog(subsystem: "com.github.tcldr.Entwine.Signpost", category: .pointsOfInterest),
receiveSubscriptionMarker: Marker? = nil,
receiveMarker: Marker? = nil,
receiveCompletionMarker: Marker? = nil,
requestMarker: Marker? = nil,
cancelMarker: Marker? = nil
) {
self.log = log
self.receiveSubscriptionMarker = receiveSubscriptionMarker
self.receiveMarker = receiveMarker
self.receiveCompletionMarker = receiveCompletionMarker
self.requestMarker = requestMarker
self.cancelMarker = cancelMarker
}
public var log: OSLog
public var receiveSubscriptionMarker: Marker?
public var receiveMarker: Marker?
public var receiveCompletionMarker: Marker?
public var requestMarker: Marker?
public var cancelMarker: Marker?
}
// MARK: - Publisher
public struct Signpost<Upstream: Publisher>: Publisher {
public typealias Output = Upstream.Output
public typealias Failure = Upstream.Failure
private let upstream: Upstream
private let configuration: SignpostConfiguration
init(upstream: Upstream, configuration: SignpostConfiguration) {
self.upstream = upstream
self.configuration = configuration
}
public func receive<S: Subscriber>(subscriber: S) where Failure == S.Failure, Output == S.Input {
upstream.subscribe(SignpostSink(downstream: subscriber, configuration: configuration))
}
}
// MARK: - Sink
fileprivate class SignpostSink<Downstream: Subscriber>: Subscriber {
typealias Input = Downstream.Input
typealias Failure = Downstream.Failure
private var downstream: Downstream
private let configuration: SignpostConfiguration
init(downstream: Downstream, configuration: SignpostConfiguration) {
self.downstream = downstream
self.configuration = configuration
}
func receive(subscription: Subscription) {
downstream.receive(subscription: SignpostSubscription(wrappedSubscription: subscription, configuration: configuration))
}
func receive(_ input: Input) -> Subscribers.Demand {
guard let marker = configuration.receiveMarker else {
return downstream.receive(input)
}
let signpostID = OSSignpostID(log: configuration.log)
os_signpost(.begin, log: configuration.log, name: marker.name ?? "receive", signpostID: signpostID)
defer { os_signpost(.end, log: configuration.log, name: marker.name ?? "receive", signpostID: signpostID) }
return downstream.receive(input)
}
func receive(completion: Subscribers.Completion<Failure>) {
guard let marker = configuration.receiveCompletionMarker else {
downstream.receive(completion: completion)
return
}
let signpostID = OSSignpostID(log: configuration.log)
os_signpost(.begin, log: configuration.log, name: marker.name ?? "receiveCompletion", signpostID: signpostID)
downstream.receive(completion: completion)
os_signpost(.end, log: configuration.log, name: marker.name ?? "receiveCompletion", signpostID: signpostID)
}
}
// MARK: - Subscription
fileprivate class SignpostSubscription: Subscription {
private let wrappedSubscription: Subscription
private let configuration: SignpostConfiguration
init(wrappedSubscription: Subscription, configuration: SignpostConfiguration) {
self.wrappedSubscription = wrappedSubscription
self.configuration = configuration
}
func request(_ demand: Subscribers.Demand) {
guard let marker = configuration.requestMarker else {
wrappedSubscription.request(demand)
return
}
let signpostID = OSSignpostID(log: configuration.log)
os_signpost(.begin, log: configuration.log, name: marker.name ?? "request", signpostID: signpostID, "%{public}@", String(describing: demand))
wrappedSubscription.request(demand)
os_signpost(.end, log: configuration.log, name: marker.name ?? "request", signpostID: signpostID)
}
func cancel() {
guard let marker = configuration.cancelMarker else {
wrappedSubscription.cancel()
return
}
let signpostID = OSSignpostID(log: configuration.log)
os_signpost(.begin, log: configuration.log, name: marker.name ?? "cancel", signpostID: signpostID)
wrappedSubscription.cancel()
os_signpost(.end, log: configuration.log, name: marker.name ?? "cancel", signpostID: signpostID)
}
}
}
// MARK: - Operator
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Publisher {
/// Marks points of interest for your publisher events as time intervals for debugging performance in Instruments.
///
/// - Parameter configuration: A configuration value specifying which events to mark as points of interest.
/// The default value specifies signposts should be grouped into the `com.github.tcldr.Entwine.Signpost`
/// subsystem using the `.pointsOfInterest` category (displayed in most Xcode Intruments templates
/// by default under the 'Points of Interest' instrument) . See `Publishers.SignpostConfiguration`
/// initializer for detailed options.
/// - Returns: A publisher that marks points of interest when specified publisher events occur
func signpost(configuration: Publishers.SignpostConfiguration = .init(receiveMarker: .default)) -> Publishers.Signpost<Self> {
Publishers.Signpost(upstream: self, configuration: configuration)
}
}
#endif
| 46.606335 | 160 | 0.655437 |
cc14c6f317999a40f42cd3351ab4c240d1e894df | 2,360 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// SSLCertificateTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension SSLCertificateTest {
static var allTests : [(String, (SSLCertificateTest) -> () throws -> Void)] {
return [
("testLoadingPemCertFromFile", testLoadingPemCertFromFile),
("testLoadingDerCertFromFile", testLoadingDerCertFromFile),
("testDerAndPemAreIdentical", testDerAndPemAreIdentical),
("testLoadingPemCertFromMemory", testLoadingPemCertFromMemory),
("testLoadingDerCertFromMemory", testLoadingDerCertFromMemory),
("testLoadingGibberishFromMemoryAsPemFails", testLoadingGibberishFromMemoryAsPemFails),
("testLoadingGibberishFromMemoryAsDerFails", testLoadingGibberishFromMemoryAsDerFails),
("testLoadingGibberishFromFileAsPemFails", testLoadingGibberishFromFileAsPemFails),
("testLoadingGibberishFromFileAsDerFails", testLoadingGibberishFromFileAsDerFails),
("testLoadingNonexistentFileAsPem", testLoadingNonexistentFileAsPem),
("testLoadingNonexistentFileAsDer", testLoadingNonexistentFileAsDer),
("testEnumeratingSanFields", testEnumeratingSanFields),
("testNonexistentSan", testNonexistentSan),
("testCommonName", testCommonName),
("testCommonNameForGeneratedCert", testCommonNameForGeneratedCert),
("testMultipleCommonNames", testMultipleCommonNames),
("testNoCommonName", testNoCommonName),
("testUnicodeCommonName", testUnicodeCommonName),
("testExtractingPublicKey", testExtractingPublicKey),
]
}
}
| 45.384615 | 103 | 0.648305 |
f582dd3199ea75fb67991026511cc35693cfe223 | 1,397 | /**
* (C) Copyright IBM Corp. 2018, 2019.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
The full input content that the service is to analyze.
*/
public struct Content: Codable, Equatable {
/**
An array of `ContentItem` objects that provides the text that is to be analyzed.
*/
public var contentItems: [ContentItem]
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case contentItems = "contentItems"
}
/**
Initialize a `Content` with member variables.
- parameter contentItems: An array of `ContentItem` objects that provides the text that is to be analyzed.
- returns: An initialized `Content`.
*/
public init(
contentItems: [ContentItem]
)
{
self.contentItems = contentItems
}
}
| 28.510204 | 111 | 0.692198 |
905337bd08394a5a480cd440ca6b4453644c337a | 2,783 | //
// Copyright © 2020 chihyinwang. All rights reserved.
//
import XCTest
import EssentialFeed
class ImageCommentsMapperTests: XCTestCase {
func test_map_throwsErrorOnNon2xxHTTPResponse() throws {
let json = makeItemsJSON([])
let samples = [199, 150, 300, 400, 500]
try samples.forEach { code in
XCTAssertThrowsError(
try ImageCommentsMapper.map(json, from: HTTPURLResponse(statusCode: code))
)
}
}
func test_map_throwsErrorOn2xxHTTPResponseWithInvalidJSON() throws {
let invalidJSON = Data("Invalid JSON".utf8)
let samples = [200, 201, 250, 280, 299]
try samples.forEach { code in
XCTAssertThrowsError(
try ImageCommentsMapper.map(invalidJSON, from: HTTPURLResponse(statusCode: code))
)
}
}
func test_map_deliversNoItemsOn2xxHTTPResponseWithEmptyJSONList() throws {
let emptyJSON = makeItemsJSON([])
let samples = [200, 201, 250, 280, 299]
try samples.forEach { code in
let result = try ImageCommentsMapper.map(emptyJSON, from: HTTPURLResponse(statusCode: code))
XCTAssertEqual(result, [])
}
}
func test_map_deliversItemsOn2xxHTTPResponseWithJSONItems() throws {
let item1 = makeItem(
id: UUID(),
message: "a message",
createdAt: (Date(timeIntervalSince1970: 1598627222), "2020-08-28T15:07:02+00:00"),
username: "a username")
let item2 = makeItem(
id: UUID(),
message: "another message",
createdAt: (Date(timeIntervalSince1970: 1577881882), "2020-01-01T12:31:22+00:00"),
username: "another username")
let json = makeItemsJSON([item1.json, item2.json])
let samples = [200, 201, 250, 280, 299]
try samples.forEach { code in
let result = try ImageCommentsMapper.map(json, from: HTTPURLResponse(statusCode: code))
XCTAssertEqual(result, [item1.model, item2.model])
}
}
// MARK: - Helpers
private func makeItem(id: UUID, message: String, createdAt: (date: Date, iso8601String: String), username: String) -> (model: ImageComment, json: [String: Any]) {
let item = ImageComment(id: id, message: message, createdAt: createdAt.date, username: username)
let json: [String: Any] = [
"id": id.uuidString,
"message": message,
"created_at": createdAt.iso8601String,
"author": [
"username": username
]
]
return (item, json)
}
}
| 32.741176 | 166 | 0.575278 |
ebcb4300da835b3347c2075f467ce56bba0b4e92 | 10,559 | //
// MatchTypeScoringConfiguration.swift
// TournamentKit
//
// Created by Jan Wittler on 20.07.20.
// Copyright © 2020 Jan Wittler. All rights reserved.
//
import Foundation
fileprivate extension Array {
subscript(optional index: Array.Index) -> Array.Element? {
return index >= count ? nil : self[index]
}
}
public protocol MatchTypeReward: Comparable {
static var zero: Self { get }
}
public protocol LocalizedDescriptionMatchTypeReward: MatchTypeReward {
var localizedDescription: String { get }
}
public struct MatchTypeScoringConfiguration<Reward: MatchTypeReward> {
public let winningMethod: WinningMethod
public let rankedRewards: [Reward]
public let overtimeConfiguration: OvertimeConfiguration?
public func rewards(for rank: UInt) -> Reward {
return rankedRewards[optional: Int(rank)] ?? .zero
}
public enum WinningMethod {
case highestScore
case lowestScore
case fixedScore(score: Int)
case flexibleScoreWithDifference(minimalScore: Int, difference: UInt)
fileprivate var sortScoresDescending: Bool {
switch self {
case .highestScore: return true
case .lowestScore: return false
case .fixedScore: return true
case .flexibleScoreWithDifference: return true
}
}
}
public struct OvertimeConfiguration {
public let rankedRewards: [Reward]
public let trigger: OvertimeTrigger
public func rewards(for rank: UInt) -> Reward {
return rankedRewards[optional: Int(rank)] ?? .zero
}
public enum OvertimeTrigger {
case bySuffix(possibleSuffixes: [String])
case byAllReachingScore(score: Int)
}
public init(rankedRewards: [Reward], trigger: OvertimeTrigger) {
if case .bySuffix(possibleSuffixes: let suffixes) = trigger {
precondition(!suffixes.isEmpty, "can't init an overtime trigger with no suffixes")
}
self.rankedRewards = rankedRewards
self.trigger = trigger
}
}
public init(winningMethod: WinningMethod, rankedRewards: [Reward], overtimeConfiguration: OvertimeConfiguration? = nil) {
if case .flexibleScoreWithDifference(_, difference: let difference) = winningMethod {
precondition(difference > 1, "the minimal allowed difference is 2")
}
self.winningMethod = winningMethod
self.rankedRewards = rankedRewards
self.overtimeConfiguration = overtimeConfiguration
}
//MARK: - Validation
/**
Evaluates whether the given results are valid for the current scoring options. If so, returns the rewards for it sorted by rank and if the results were evaluated as overtime.
- parameters:
- result: The result of the match. The keys will be included in the result to allow matching of the rewards.
- overtimeSuffix: The overtime suffix selected for the match, if any.
- returns: If the result is invalid, returns `nil`. Otherwise returns the result keys sorted by rank and associated with the reward corresponding to the rank and a boolean indicating whether the results were evaluated as overtime.
*/
public func sortedRewardsForResultIfValid<T, S: BinaryInteger>(_ result: [T : S], overtimeSuffix: String?) -> (sortedRewards: [(element: T, score: S, reward: Reward)], isOvertime: Bool)? {
let sortedResult = self.sortedResult(from: result)
let sortedScores = sortedResult.map { $0.score }
let isOvertime = self.isOvertime(sortedScores, overtimeSuffix: overtimeSuffix)
let rankedRewards = isOvertime ? overtimeConfiguration!.rankedRewards : self.rankedRewards
guard validateScoresDifferent(sortedScores, rankedRewards: rankedRewards),
validateWinningMethod(for: sortedScores) else {
return nil
}
if isOvertime {
guard validateOvertime(for: sortedScores, overtimeSuffix: overtimeSuffix) else {
return nil
}
}
else {
guard overtimeSuffix == nil else {
return nil
}
}
return (sortedResult.enumerated().map { ($0.element.object, $0.element.score, rankedRewards[optional: $0.offset] ?? .zero) }, isOvertime)
}
private func sortedResult<T, S: BinaryInteger>(from result: [T: S]) -> [(object: T, score: S)] {
let sortedResult = Array(result.map { (object: $0.key, score: $0.value) }.sorted { $0.score > $1.score })
return winningMethod.sortScoresDescending ? sortedResult : sortedResult.reversed()
}
private func validateScoresDifferent<S: Equatable>(_ sortedScores: [S], rankedRewards: [Reward]) -> Bool {
var index = 1
let rewardAt: (Int) -> Reward = { return rankedRewards[optional: $0] ?? .zero }
repeat {
defer { index += 1 }
guard index < sortedScores.count else {
if rankedRewards.count <= index {
continue
}
return false
}
guard sortedScores[index - 1] != sortedScores[index] else {
return false
}
} while rewardAt(index - 1) != rewardAt(index)
return true
}
private func validateWinningMethod<S: BinaryInteger>(for sortedScores: [S]) -> Bool {
switch winningMethod {
case .highestScore, .lowestScore:
return true
case .fixedScore(score: let score):
return sortedScores[0] == score
case .flexibleScoreWithDifference(minimalScore: let score, difference: let difference):
let scoreDifference = abs(Int(sortedScores[0]) - Int(sortedScores[1]))
if sortedScores[0] > score {
return scoreDifference == difference
}
return scoreDifference >= difference && sortedScores[0] == score
}
}
private func isOvertime<S: BinaryInteger>(_ sortedScores: [S], overtimeSuffix: String?) -> Bool {
guard let overtimeConfiguration = overtimeConfiguration else {
return false
}
switch overtimeConfiguration.trigger {
case .bySuffix: return overtimeSuffix != nil
case .byAllReachingScore(score: let score): return sortedScores.allSatisfy { $0 >= score }
}
}
private func validateOvertime<S>(for sortedScores: [S], overtimeSuffix: String?) -> Bool {
guard let overtimeConfiguration = overtimeConfiguration else {
return false
}
switch overtimeConfiguration.trigger {
case .bySuffix(possibleSuffixes: let possibleSuffixes): return overtimeSuffix != nil && possibleSuffixes.contains(overtimeSuffix!)
case .byAllReachingScore:
return true
}
}
}
//MARK: - Localized explanation
extension MatchTypeScoringConfiguration where Reward: LocalizedDescriptionMatchTypeReward {
public func localizedScoreExplanation(forPlayersCount playersCount: UInt) -> String {
var explanation: String
switch winningMethod {
case .highestScore:
explanation = NSLocalizedString("HighestScore", comment: "")
case .lowestScore:
explanation = NSLocalizedString("LowestScore", comment: "")
case .fixedScore(score: let score):
explanation = String.localizedStringWithFormat(NSLocalizedString("FixedScore", comment: ""), score)
case .flexibleScoreWithDifference(minimalScore: let score, difference: let difference):
explanation = String.localizedStringWithFormat(NSLocalizedString("FlexibleScoreWithDifference", comment: ""), score, difference, score - 1, score - 1, difference)
}
if let overtimeConfiguration = overtimeConfiguration {
explanation += "\n"
switch overtimeConfiguration.trigger {
case .bySuffix(possibleSuffixes: let suffixes):
let quotedSuffixes = suffixes.map { (Locale.current.quotationBeginDelimiter ?? "") + $0 + (Locale.current.quotationEndDelimiter ?? "") }
let suffixesText: String
let separator = ", "
if quotedSuffixes.count > 1, let last = quotedSuffixes.last {
suffixesText = quotedSuffixes.dropLast().joined(separator: separator) + " " + NSLocalizedString("Overtime.bySuffix.Or", comment: "") + " " + last
}
else {
suffixesText = quotedSuffixes.joined(separator: separator)
}
explanation += String.localizedStringWithFormat(NSLocalizedString("Overtime.bySuffix", comment: ""), suffixesText, suffixes.count)
case .byAllReachingScore(score: let score):
explanation += String.localizedStringWithFormat(NSLocalizedString("Overtime.byAllReachingScore", comment: ""), score)
}
}
let rewardExplanation: ([Reward]) -> String = {
$0.enumerated().map {
String.localizedStringWithFormat(NSLocalizedString("Reward", comment: ""), NumberFormatter.localizedString(from: NSNumber(value: $0.offset + 1), number: .ordinal), $0.element.localizedDescription) }.joined(separator: "\n")
}
if !rankedRewards.isEmpty {
let rewards = (0..<playersCount).map { self.rewards(for: $0) }
explanation += "\n\n" + NSLocalizedString("Scores.Title", comment: "") + "\n" +
rewardExplanation(rewards)
}
if let overtimeConfiguration = overtimeConfiguration {
if !overtimeConfiguration.rankedRewards.isEmpty {
let rewards = (0..<playersCount).map { overtimeConfiguration.rewards(for: $0) }
explanation += "\n\n" + NSLocalizedString("Scores.Overtime.Title", comment: "") + "\n" + rewardExplanation(rewards)
}
}
return explanation
}
}
private func NSLocalizedString(_ key: String, comment: String) -> String {
return Foundation.NSLocalizedString(key, tableName: "ScoringOptions", bundle: .module, comment: comment)
}
//MARK: - Conformances
extension Int: MatchTypeReward {}
extension Int8: MatchTypeReward {}
extension Int16: MatchTypeReward {}
extension Int32: MatchTypeReward {}
extension Int64: MatchTypeReward {}
extension Float: MatchTypeReward {}
extension Double: MatchTypeReward {}
| 43.813278 | 238 | 0.639928 |
1acda1e371b414ee510fcb0dc3f8e553d28faa4f | 1,400 | //
// YNKitUITests.swift
// YNKitUITests
//
// Created by ZHUYN on 2022/1/12.
//
import XCTest
class YNKitUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 32.55814 | 182 | 0.652857 |
79252d0daa088a9e889b4190b7a0d7314503e1e2 | 2,363 | //
// SimpleObjectService.swift
// gdSampleServer
//
// Copyright © 2016年 gdaigo. All rights reserved.
//
import UIKit
class SimpleObjectService: NSObject {
func getNowClockString() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
let now = Date()
return formatter.string(from: now)
}
func makeStringFromBuffer(buffer : inout [UInt8], size : Int) -> String {
buffer[size] = 0
return NSString(bytes: buffer, length:size + 1, encoding: String.Encoding.ascii.rawValue) as! String
}
func makeNSDataFromString(text: String) -> NSData{
return (text.data(using: String.Encoding.utf8) as NSData?)!
}
func makeUI8ArrayFromNSData(data: NSData) -> [UInt8] {
var array = Array<UInt8>(repeating: 0, count: (data.length))
data.getBytes(&array, length: (data.length))
return array
}
func getIFAddresses() -> [String] {
var addresses = [String]()
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return [] }
guard let firstAddr = ifaddr else { return [] }
// For each interface ...
for ptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
let flags = Int32(ptr.pointee.ifa_flags)
var addr = ptr.pointee.ifa_addr.pointee
// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
// Convert interface address to a human readable string:
var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),
nil, socklen_t(0), NI_NUMERICHOST) == 0) {
let address = String(cString: hostname)
addresses.append(address)
}
}
}
}
freeifaddrs(ifaddr)
return addresses
}
}
| 35.80303 | 108 | 0.567076 |
eb2218c1e3002adcefcb422c41a540375138ab95 | 1,879 | //
// Color+Ex.swift
// AUSTTravels
//
// Created by Shahriar Nasim Nafi on 24/10/21.
// Copyright © 2021 Shahriar Nasim Nafi. All rights reserved.
//
import SwiftUI
extension Color {
init(hex: String) {
self.init(UIColor(hex: hex))
}
static let green = Color(hex: "#2ABA7E")
static let greenLight = Color(hex: "#00FF94")
static let white = Color(hex: "#FFFFFF")
static let black = Color(hex: "#000000")
static let yellow = Color(hex: "#FFD856")
static let yellowLight = Color(hex: "#FCE8A7")
static let orange = Color(hex: "#E9896B")
static let ash = Color(hex: "#F0F0F0")
static let redAsh = Color(hex: "#E9896B")
static let deepAsh = Color(hex: "#C4C4C4")
static let lightAsh = Color(hex: "#F0F0F0")
}
extension UIColor {
/// For converting Hex-based colors
convenience init(hex: String) {
var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines)
hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "")
var rgb: UInt64 = 0
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
let length = hexSanitized.count
Scanner(string: hexSanitized).scanHexInt64(&rgb)
if length == 6 {
red = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
green = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
blue = CGFloat(rgb & 0x0000FF) / 255.0
} else if length == 8 {
red = CGFloat((rgb & 0xFF000000) >> 24) / 255.0
green = CGFloat((rgb & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((rgb & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(rgb & 0x000000FF) / 255.0
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
| 31.316667 | 78 | 0.571581 |
1c41f99bd0b858f8dd175c5909b99bb9f7cd5b3f | 465 | // 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
var f: NSManagedObject {
protocol a {
typealias e : e : A")
func a
| 35.769231 | 79 | 0.744086 |
eb0a5918389776d77ac01ff6d07de31833d4f150 | 460 | import Foundation
public enum RequestMakeError {
case malformedURL(URL, [URLQueryItem])
case bodyEncoderError(Error)
}
extension RequestMakeError: CustomNSError {
public var errorUserInfo: [String : Any] {
switch self {
case let .malformedURL(url, queryItems):
return ["url": url, "query_items": queryItems]
case let .bodyEncoderError(error):
return [NSUnderlyingErrorKey: error]
}
}
}
| 25.555556 | 58 | 0.654348 |
01f8a8219e1653079bfabfd76baab44536e3c499 | 6,451 | //
// WikipediaNetworking.swift
// WikipediaKit
//
// Created by Frank Rausch on 2016-07-25.
// Copyright © 2017 Raureif GmbH / Frank Rausch
//
// 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.
//
import Foundation
public class WikipediaNetworking {
public static var appAuthorEmailForAPI = ""
public static let shared: WikipediaNetworking = {
return WikipediaNetworking()
}()
public static weak var sharedActivityIndicatorDelegate: WikipediaNetworkingActivityDelegate?
let session = URLSession(configuration: URLSessionConfiguration.default)
func loadJSON(urlRequest: URLRequest,
completion: @escaping (JSONDictionary?, WikipediaError?) -> ())
-> URLSessionDataTask {
#if DEBUG
let startTime = NSDate()
print("WikipediaKit: Fetching \(urlRequest.url!.absoluteString)")
#endif
var urlRequest = urlRequest
urlRequest.setValue(self.userAgent, forHTTPHeaderField: "User-Agent")
// Here’s the weird trick to get Chinese variants (Traditional/Simplified):
urlRequest.setValue(WikipediaLanguage.systemLanguage.variant ?? WikipediaLanguage.systemLanguage.code, forHTTPHeaderField: "Accept-Language")
WikipediaNetworking.sharedActivityIndicatorDelegate?.start()
let task = session.dataTask(with: urlRequest) { data, response, error in
WikipediaNetworking.sharedActivityIndicatorDelegate?.stop()
#if DEBUG
let endNetworkingTime = NSDate()
let totalNetworkingTime: Double = endNetworkingTime.timeIntervalSince(startTime as Date)
print("WikipediaKit: \(totalNetworkingTime) seconds for network retrieval")
#endif
if let error = error {
var wikipediaError: WikipediaError
if (error as NSError).code == NSURLErrorCancelled {
wikipediaError = .cancelled
} else {
// Fallback description from NSError; tends do be rather user-unfriendly
wikipediaError = .other(error.localizedDescription)
// See http://nshipster.com/nserror/
if (error as NSError).domain == NSURLErrorDomain {
switch (error as NSError).code {
case NSURLErrorNotConnectedToInternet:
fallthrough
case NSURLErrorNetworkConnectionLost:
fallthrough
case NSURLErrorResourceUnavailable:
wikipediaError = .noInternetConnection
case NSURLErrorBadServerResponse:
wikipediaError = .badResponse
default: ()
}
}
}
completion(nil, wikipediaError)
return
}
guard let data = data,
let response = response as? HTTPURLResponse,
200...299 ~= response.statusCode
else {
completion(nil, .badResponse)
return
}
guard let json = try? JSONSerialization.jsonObject(with: data, options: []),
let jsonDictionary = json as? JSONDictionary
else {
completion(nil, .decodingError)
return
}
#if DEBUG
let endTime = NSDate()
let totalTime = endTime.timeIntervalSince(startTime as Date)
print("WikipediaKit: \(totalTime) seconds for network retrieval & JSON decoding")
#endif
completion(jsonDictionary, nil)
}
task.resume()
return task
}
public var userAgent: String = {
let framework: String
if let frameworkInfo = Bundle(for: WikipediaNetworking.self).infoDictionary,
let frameworkMarketingVersion = frameworkInfo["CFBundleShortVersionString"] as? String {
framework = "WikipediaKit/\(frameworkMarketingVersion)"
} else {
framework = "WikipediaKit"
}
if let infoDictionary = Bundle.main.infoDictionary {
let bundleName = infoDictionary[kCFBundleExecutableKey as String] as? String ?? "Unknown App"
let bundleID = infoDictionary[kCFBundleIdentifierKey as String] as? String ?? "Unkown Bundle ID"
let marketingVersionString = infoDictionary["CFBundleShortVersionString"] as? String ?? "Unknown Version"
let userAgent = "\(bundleName)/\(marketingVersionString) (\(bundleID); \(WikipediaNetworking.appAuthorEmailForAPI)) \(framework)"
#if DEBUG
print(userAgent)
if WikipediaNetworking.appAuthorEmailForAPI.isEmpty {
print("IMPORTANT: Please set your email address in WikipediaNetworking.appAuthorEmailForAPI on launch (or before making the first API call), for example in your App Delegate.\nSee https://www.mediawiki.org/wiki/API:Main_page#Identifying_your_client")
}
#endif
return userAgent
}
return framework // fallback, should never be reached
}()
}
| 43.006667 | 270 | 0.616184 |
bb2bf5e4caf119629548cca8abfac41da5d429c3 | 559 | //
// CollectionPrettyCell.swift
// 1106-douyu
//
// Created by targetcloud on 2016/11/7.
// Copyright © 2016年 targetcloud. All rights reserved.
//
import UIKit
class CollectionPrettyCell: BaseCollectionViewCell {
@IBOutlet weak var cityBtn: UIButton!
override var anchor : AnchorModel? {
didSet {
super.anchor = anchor
cityBtn.setTitle(anchor?.anchor_city, for: UIControl.State())
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| 19.964286 | 73 | 0.629696 |
1ef33e5986e65c271aafc37183a7dfab593d2fad | 224 | //
// UIGestureRecognizer+UIActionTarget.swift
// SweetUI
//
// Created by Maxim Krouk on 15/08/20.
// Copyright © 2020 @maximkrouk. All rights reserved.
//
extension UIGestureRecognizer: DefaultTargetInitializable {}
| 20.363636 | 60 | 0.741071 |
e9b69c88a26c59259e3b171eba8920290232d5ad | 406 | //
// File.swift
//
//
// Created by Alex Johnson on 12/7/19.
//
import AmplificationCircuit
// Workaround for `Foundation.Pipe` ambiguity
typealias Pipe = AmplificationCircuit.Pipe
extension Computer {
convenience init(instructions: ComputeValue...) {
let program = Array(instructions) + Array(repeating: 0, count: 256 - instructions.count)
self.init(program: program)
}
}
| 20.3 | 96 | 0.689655 |
8fbf739b25e9241a8d3985bc9fe24288eea1499e | 2,658 | //
// ViewController.swift
// SignInExample
//
// Created by Benoit PASQUIER on 04/08/2019.
// Copyright © 2019 Benoit PASQUIER. All rights reserved.
//
import UIKit
import AuthenticationServices
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .systemTeal
// Do any additional setup after loading the view.
self.setupSignInButton()
}
private func setupSignInButton() {
let signInButton = ASAuthorizationAppleIDButton()
signInButton.addTarget(self, action: #selector(ViewController.signInButtonTapped), for: .touchDown)
signInButton.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(signInButton)
NSLayoutConstraint.activate([
signInButton.centerXAnchor.constraint(equalToSystemSpacingAfter: view.centerXAnchor, multiplier: 1),
signInButton.centerYAnchor.constraint(equalToSystemSpacingBelow: view.centerYAnchor, multiplier: 1),
signInButton.heightAnchor.constraint(equalToConstant: 40),
signInButton.widthAnchor.constraint(equalToConstant: 200)
])
}
@objc private func signInButtonTapped() {
let authorizationProvider = ASAuthorizationAppleIDProvider()
let request = authorizationProvider.createRequest()
request.requestedScopes = [.email]
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.presentationContextProvider = self
authorizationController.performRequests()
}
}
extension ViewController: ASAuthorizationControllerDelegate {
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential else {
return
}
print("AppleID Crendential Authorization: userId: \(appleIDCredential.user), email: \(String(describing: appleIDCredential.email))")
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
print("AppleID Crendential failed with error: \(error.localizedDescription)")
}
}
extension ViewController: ASAuthorizationControllerPresentationContextProviding {
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return self.view.window!
}
}
| 38.521739 | 140 | 0.725357 |
71d8c7f315ac5d62252f2956ed8f4311e963d93b | 3,629 | //
// TweetDetailsViewController.swift
// Twitter
//
// Created by Nanxi Kang on 9/30/17.
// Copyright © 2017 Nanxi Kang. All rights reserved.
//
import AFNetworking
import UIKit
class TweetDetailsViewController: UIViewController {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var fullnameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var replyButton: UIButton!
@IBOutlet weak var retweetButton: UIButton!
var tweet: Tweet?
override func viewDidLoad() {
super.viewDidLoad()
if let tweet = self.tweet {
if let text = tweet.text {
contentLabel.text = text
contentLabel.sizeToFit()
}
if let user = tweet.author {
if let username = user.name {
fullnameLabel.text = username
}
if let screenName = user.screenName {
usernameLabel.text = "@\(screenName)"
}
if let url = user.profileBiggerUrl {
profileImageView.setImageWith(url)
}
}
if let date = tweet.createdAt {
timeLabel.text = date
}
if tweet.favorited {
favoriteButton.setImage(UIImage(named: "fav"), for: .normal)
} else {
favoriteButton.setImage(UIImage(named: "heart"), for: .normal)
}
} else {
favoriteButton.setImage(UIImage(named: "heart"), for: .normal)
}
replyButton.setImage(UIImage(named: "reply"), for: .normal)
retweetButton.setImage(UIImage(named: "retweet"), for: .normal)
}
@IBAction func favoriteTapped(_ sender: Any) {
if (tweet!.favorited == false) {
TwitterClient.favorite(id: tweet!.id!, onSuccess: { () -> Void in
self.tweet!.favorited = true
self.favoriteButton.setImage(UIImage(named: "fav"), for: .normal)
}, onFailure: { (error: String) -> Void in })
} else {
TwitterClient.unfavorite(id: tweet!.id!, onSuccess: { () -> Void in
self.tweet!.favorited = false
self.favoriteButton.setImage(UIImage(named: "heart"), for: .normal)
}, onFailure: { (error: String) -> Void in })
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.destination is UINavigationController) {
let controller = segue.destination as! UINavigationController
let vc = controller.topViewController!
if (vc is NewTweetViewController) {
print("new tweet")
let newTweetVc = vc as! NewTweetViewController
newTweetVc.tweetId = tweet?.id!
} else if (vc is TweetsViewController) {
let tweetsViewVc = vc as! TweetsViewController
TwitterClient.retweet(id: tweet!.id!, onSuccess: { (tweet: Tweet) -> Void in
tweetsViewVc.addTweet(tweet: tweet)
}, onFailure: { (error: String) -> Void in
})
} else {
print("transit to \(type(of: vc))")
}
}
}
}
| 35.930693 | 92 | 0.555525 |
0a4607891754c81431918c68b781ae96e296ca66 | 753 | //
// ArticleImageView.swift
// ArticleImageView
//
// Created by Milad Golchinpour on 9/18/21.
// Copyright © 2021 Milad Golchinpour. All rights reserved.
//
import SwiftUI
/// Showing article image view
struct ArticleImageView: View {
var url: String?
var body: some View {
if let url = url {
let imageURL = URL(string: url)
AsyncImage(url: imageURL) { image in
image.resizable()
.scaledToFit()
} placeholder: {
Color.gray.opacity(0.4)
}
.cornerRadius(20)
}
}
}
struct ArticleImageView_Previews: PreviewProvider {
static var previews: some View {
ArticleImageView()
}
}
| 21.514286 | 60 | 0.559097 |
26f31125af7403cc758aea090f23aabebd802bf8 | 1,079 | //
// ShareHolderViewModel.swift
// Ribbit
//
// Created by Ahsan Ali on 08/04/2021.
//
import UIKit
class ShareHolderViewModel: BaseViewModel {
private(set) var success: Bool! {
didSet {
self.bindViewModelToController()
}
}
override init() {
super.init()
proxy = NetworkProxy()
proxy.delegate = self
}
func update(answere: String) {
proxy.requestForUpdateProfile(param: ["public_shareholder": answere, "profile_completion": STEPS.shareholder.rawValue])
}
// MARK: - Delegate
override func requestDidBegin() {
super.requestDidBegin()
}
override func requestDidFinishedWithData(data: Any, reqType: RequestType) {
super.requestDidFinishedWithData(data: data, reqType: reqType)
success = true
}
override func requestDidFailedWithError(error: String, reqType: RequestType) {
super.requestDidFailedWithError(error: error, reqType: reqType)
self.bindErrorViewModelToController(error) // If need error in View Controller
}
}
| 26.317073 | 127 | 0.663577 |
1a33de86fb8c6d622c41b38c6b42653cc58847e8 | 2,136 | #if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
public extension OklabColor {
init(ns: NSColor) {
let (srgb, alpha) = ns.getSRGBComponents()
let oklab = Conversions.linearSRGBToOklab(srgb.decodeSRGBGamma())
self.lightness = oklab[0]
self.a = oklab[1]
self.b = oklab[2]
self.alpha = alpha
}
}
public extension OklabColorPolar {
init(ns: NSColor) {
self.init(OklabColor(ns: ns))
}
}
public extension NSColor {
convenience init(_ oklab: OklabColor) {
let srgb = Conversions.oklabToLinearSRGB(oklab.vector).encodeSRGBGamma()
self.init(srgbRed: CGFloat(srgb.x),
green: CGFloat(srgb.y),
blue: CGFloat(srgb.z),
alpha: CGFloat(oklab.alpha))
}
convenience init(_ oklabpolar: OklabColorPolar) {
self.init(OklabColor(oklabpolar))
}
}
internal extension NSColor {
func getSRGBComponents() -> (color: SIMD3<Channel>, alpha: Channel) {
guard let color = asValid_sRGBComponentBased()
else { return (color: .zero, alpha: 0) }
switch color.numberOfComponents {
case 4...:
let components = [color.redComponent,
color.greenComponent,
color.blueComponent]
.map(Channel.init)
return (color: SIMD3(components),
alpha: Channel(color.alphaComponent))
case ...2:
return (color: SIMD3<Channel>(repeating: Channel(color.whiteComponent)),
alpha: Channel(color.alphaComponent))
default: return (color: .zero, alpha: 0)
}
}
func asValid_sRGBComponentBased() -> NSColor? {
guard let rgb = usingType(.componentBased) else { return nil }
guard rgb.colorSpace == .extendedSRGB || rgb.colorSpace == .sRGB
else { return rgb.usingColorSpace(.extendedSRGB) }
return rgb
}
}
#endif
| 29.666667 | 88 | 0.553839 |
2f7d876f14ffdfe845ceaa5048730c757ea3b888 | 3,513 | //
// DeviceVc.swift
// ATBluetooth
//
// Created by ZGY on 2017/11/16.
//Copyright © 2017年 macpro. All rights reserved.
//
// Author: Airfight
// My GitHub: https://github.com/airfight
// My Blog: http://airfight.github.io/
// My Jane book: http://www.jianshu.com/users/17d6a01e3361
// Current Time: 2017/11/16 下午2:37
// GiantForJade: Efforts to do my best
// Real developers ship.
import UIKit
class DeviceVc: UIViewController {
//MARK: - Attributes
var device: ATBleDevice?
override func viewDidLoad() {
super.viewDidLoad()
// Print(device?.state)
}
//MARK: - Override
//MARK: - Initial Methods
//MARK: - Delegate
//MARK: - Target Methods
@IBAction func sendAction(_ sender: UIButton) {
switch sender.tag {
case 666:
// let data = Data.init(bytes: [0x12])
let data = Data.init(bytes: [0x82])
// device?.writeData(data)
ATBlueToothContext.default.writeData(data, type: ATCharacteristicWriteType.withResponse, block: { (result) in
Print(result)
})
break
case 777:
ATBlueToothContext.default.disconnectDevice()
break
case 888:
ATBlueToothContext.default.reconnectDevice(device?.uuid)
break
default:
break
}
}
//MARK: - Notification Methods
//MARK: - KVO Methods
//MARK: - UITableViewDelegate, UITableViewDataSource
//MARK: - Privater Methods
//MARK: - Setter Getter Methods
//MARK: - Life cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
atBlueTooth.connect(device)
self.title = device?.state?.description
device?.delegate = self
// updatedATBleDeviceState((device?.state)!, error: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
deinit {
}
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.
}
*/
}
extension DeviceVc:ATBleDeviceStateDelegate {
func updatedIfWriteSuccess(_ result: Result<Any>?) {
guard result != nil else {
return
}
switch result! {
case .Success(let value):
// print(String.init(data: value!, encoding: String.Encoding.ascii))
// Print(String.init(data: value!, encoding: String.Encoding.utf8))
Print(value)
case .Failure(let error):
Print(error)
}
}
func updatedATBleDeviceState(_ state: ATBleDeviceState, error: Error?) {
DispatchQueue.main.async {
self.title = "\(state.description)"
Print(state.description)
}
}
}
| 23.897959 | 119 | 0.56049 |
646f04e3be457dd6496b6e83eacb17295d5ad592 | 1,726 | //
// main.swift
// PerfectTemplate
//
// Created by Kyle Jessup on 2015-11-05.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import PerfectLib
import PerfectHTTP
import PerfectHTTPServer
// Create HTTP server.
let server = HTTPServer()
// Register your own routes and handlers
var routes = Routes()
routes.add(method: .get, uri: "/", handler: {
request, response in
response.setHeader(.contentType, value: "text/html")
response.appendBody(string: "<html><title>Perfect Server!</title><body>Running Perfect!</body></html>")
response.completed()
}
)
// Add the routes to the server.
server.addRoutes(routes)
// Set a listen port of 8282
server.serverPort = 8282
// Set a document root.
// This is optional. If you do not want to serve static content then do not set this.
// Setting the document root will automatically add a static file handler for the route /**
server.documentRoot = "./webroot"
// Gather command line options and further configure the server.
// Run the server with --help to see the list of supported arguments.
// Command line arguments will supplant any of the values set above.
configureServer(server)
do {
// Launch the HTTP server.
try server.start()
} catch PerfectError.networkError(let err, let msg) {
print("Network error thrown: \(err) \(msg)")
}
| 29.254237 | 105 | 0.659328 |
2f24f12a6fef6603d225da3e1f8de824d808444d | 1,946 | //
// TopView.swift
// LSYWeiBo
//
// Created by 李世洋 on 16/5/10.
// Copyright © 2016年 李世洋. All rights reserved.
//
import UIKit
import SDWebImage
import HYLabel
typealias downBtnCompleteion = (btn: UIButton) -> Void
typealias linkTapCompleteion = (link: String) -> Void
class TopView: UIView {
@IBOutlet weak var mbrankImageView: UIImageView!
// 用户头像
@IBOutlet weak var iconView: UIImageView!
// 用户名字
@IBOutlet weak var nameLabel: UILabel!
// 发表时间
@IBOutlet weak var timeLabel: UILabel!
// 来源
@IBOutlet weak var soureLabel: UILabel!
// 发布的内容
@IBOutlet weak var contentLabel: HYLabel!
// 认证图标
@IBOutlet weak var acatarView: UIImageView!
@IBAction func downBtnDidClick(sender: UIButton) {
downComplete!(btn: sender)
}
var downComplete: downBtnCompleteion?
var linkComplete: linkTapCompleteion?
var statues: Statuses? {
didSet{
iconView.LSY_CircleImage(url: statues?.user?.imageURL)
nameLabel.text = statues?.user?.name
nameLabel.textColor = statues?.user?.mbrank_Color
timeLabel.text = statues?.create_at_Str
mbrankImageView.image = statues?.user?.mbrankImage
soureLabel.text = "来自: " + statues!.source_sub!
contentLabel.attributedText = statues?.attributedString
acatarView.image = statues?.user?.acatarImage
}
}
override func awakeFromNib() {
super.awakeFromNib()
// 监听@谁谁谁的点击
contentLabel.userTapHandler = { (label, user, range) in
}
// 监听链接的点击
contentLabel.linkTapHandler = {[weak self] (label, link, range) in
self!.linkComplete!(link: link)
}
// 监听话题的点击
contentLabel.topicTapHandler = { (label, topic, range) in
}
}
} | 24.632911 | 74 | 0.595581 |
9b3447f338432b972531b14fc655a618e4916075 | 2,037 | //
// AppDelegate.swift
// Siri
//
// Created by Sahand Edrisian on 7/14/16.
// Copyright © 2016 Sahand Edrisian. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
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 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:.
}
}
| 45.266667 | 279 | 0.780069 |
c1b1ab3add7048078ce53c132d57da959f7fb95e | 1,733 | //
// StructureCommand.swift
// SourceKitten
//
// Created by JP Simard on 2015-01-07.
// Copyright (c) 2015 SourceKitten. All rights reserved.
//
import Commandant
import SourceKittenFramework
struct StructureCommand: CommandProtocol {
let verb = "structure"
let function = "Print Swift structure information as JSON"
struct Options: OptionsProtocol {
let file: String
let text: String
static func create(file: String) -> (_ text: String) -> Options {
return { text in
self.init(file: file, text: text)
}
}
static func evaluate(_ mode: CommandMode) -> Result<Options, CommandantError<SourceKittenError>> {
return create
<*> mode <| Option(key: "file", defaultValue: "", usage: "relative or absolute path of Swift file to parse")
<*> mode <| Option(key: "text", defaultValue: "", usage: "Swift code text to parse")
}
}
func run(_ options: Options) -> Result<(), SourceKittenError> {
do {
if !options.file.isEmpty {
if let file = File(path: options.file) {
print(try Structure(file: file))
return .success(())
}
return .failure(.readFailed(path: options.file))
}
if !options.text.isEmpty {
print(try Structure(file: File(contents: options.text)))
return .success(())
}
return .failure(
.invalidArgument(description: "either file or text must be set when calling structure")
)
} catch {
return .failure(.failed(error))
}
}
}
| 32.092593 | 124 | 0.553953 |
e52d8f9625d047d980e197b8caad0adf06fb7ad7 | 5,001 | //
// UIColor+Extensions.swift
//
import UIKit
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
convenience init(decimalRed r: Int, decimalGreen g: Int, decimalBlue b: Int, decimalAlpha a: Int = 255) {
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
func lighter(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: abs(percentage) )
}
func darker(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: -1 * abs(percentage) )
}
func adjust(by percentage: CGFloat = 30.0) -> UIColor? {
var r:CGFloat=0, g:CGFloat=0, b:CGFloat=0, a:CGFloat=0;
if(self.getRed(&r, green: &g, blue: &b, alpha: &a)){
return UIColor(red: min(r + percentage/100, 1.0),
green: min(g + percentage/100, 1.0),
blue: min(b + percentage/100, 1.0),
alpha: a)
}else{
return nil
}
}
func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
@nonobjc static var mtCollectionHeaderBackgroundColor: UIColor {
return mtGrayLightColor07
}
@nonobjc static var mtThemeColorOld: UIColor {
return #colorLiteral(red: 0.9803921569, green: 0.4, blue: 0, alpha: 1) // FA6600
}
@nonobjc static var mtThemeColor: UIColor {
return #colorLiteral(red: 0.9529411765, green: 0.4392156863, blue: 0.1294117647, alpha: 1) // F37021
}
@nonobjc static var mtThemeDeepColor: UIColor {
return #colorLiteral(red: 0.9333333333, green: 0.3254901961, blue: 0, alpha: 1) // EE5300
}
@nonobjc static var mtTriggerColor: UIColor {
return #colorLiteral(red: 0.07450980392, green: 0.7058823529, blue: 0.9960784314, alpha: 1) // 13B4FE
}
@nonobjc static var mtIndicatorActivatedColor: UIColor {
return #colorLiteral(red: 0.5882352941, green: 0.7450980392, blue: 0.1176470588, alpha: 1) // 96BE1E
}
@nonobjc static var mtIndicatorDeactivatedColor: UIColor {
return #colorLiteral(red: 0.9411764706, green: 0.1137254902, blue: 0.07058823529, alpha: 1) // F01D12
}
@nonobjc static var mtTextColor: UIColor {
return #colorLiteral(red: 0.1176470588, green: 0.1176470588, blue: 0.1176470588, alpha: 1) // 1E1E1E
}
@nonobjc static var mtGrayDarkColor01: UIColor {
return #colorLiteral(red: 0.1843137255, green: 0.1843137255, blue: 0.1843137255, alpha: 1) // 2F2F2F
}
@nonobjc static var mtAdditionalTextColor: UIColor {
return #colorLiteral(red: 0.431372549, green: 0.431372549, blue: 0.431372549, alpha: 1) // 6E6E6E
}
@nonobjc static var mtGrayColor02: UIColor {
return #colorLiteral(red: 0.568627451, green: 0.568627451, blue: 0.568627451, alpha: 1) // 919191
}
@nonobjc static var mtGrayColor03: UIColor {
return #colorLiteral(red: 0.6196078431, green: 0.6196078431, blue: 0.6196078431, alpha: 1) // 9E9E9E
}
@nonobjc static var mtGrayColor04: UIColor {
return #colorLiteral(red: 0.6274509804, green: 0.6745098039, blue: 0.6941176471, alpha: 1) // A0ACB1
}
@nonobjc static var mtGrayLightColor05: UIColor {
return #colorLiteral(red: 0.7843137255, green: 0.7843137255, blue: 0.7843137255, alpha: 1) // C8C8C8
}
@nonobjc static var mtGrayLightColor06: UIColor {
return #colorLiteral(red: 0.8470588235, green: 0.8470588235, blue: 0.8470588235, alpha: 1) // D8D8D8
}
@nonobjc static var mtGrayLightColor07: UIColor {
return #colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9411764706, alpha: 1) // F0F0F0
}
@nonobjc static var mtGrayLightColor08: UIColor {
return #colorLiteral(red: 0.9490196078, green: 0.9490196078, blue: 0.9411764706, alpha: 1) // F2F2F0
}
@nonobjc static var mtTextWhiteColor: UIColor {
return .white
}
}
| 36.50365 | 118 | 0.603279 |
56236fa17065f4c8d2286f25bfe3b406e77b1681 | 482 | //
// Comment.swift
// Metis
//
// Created by Gina De La Rosa on 11/15/17.
// Copyright © 2017 Gina Delarosa. All rights reserved.
//
import Foundation
class Comment {
var commentText: String?
var uid: String?
}
extension Comment {
static func transformComment(dict: [String: Any]) -> Comment {
let comment = Comment()
comment.commentText = dict["commentText"] as? String
comment.uid = dict["uid"] as? String
return comment
}
}
| 20.956522 | 66 | 0.634855 |
50b0357152981cfbca306a86a6b9771710a7b121 | 1,869 | //
// KeyPath+KeyPaths.swift
// CoreStore
//
// Copyright © 2019 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import CoreData
import Foundation
// MARK: - KeyPath: AnyKeyPathStringConvertible, KeyPathStringConvertible where Root: NSManagedObject, Value: AllowedObjectiveCKeyPathValue
extension KeyPath: AnyKeyPathStringConvertible, KeyPathStringConvertible where Root: NSManagedObject, Value: AllowedObjectiveCKeyPathValue {
// MARK: AnyKeyPathStringConvertible
public var cs_keyPathString: String {
// return NSExpression(forKeyPath: self).keyPath // in case _kvcKeyPathString becomes private API
return self._kvcKeyPathString!
}
// MARK: KeyPathStringConvertible
public typealias ObjectType = Root
public typealias DestinationValueType = Value
}
| 38.9375 | 140 | 0.762975 |
f7eafedf776b8a5616ffe063634a2aa02f42cfd8 | 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
(((Any)as a
case c{
class
case c,
case | 23 | 87 | 0.753623 |
fee779cc4dc1be2306e7f135793fa4ba00770dd2 | 1,199 | //
// ProcessService.swift
// FilestackSDK
//
// Created by Ruben Nine on 7/11/17.
// Copyright © 2017 Filestack. All rights reserved.
//
import Foundation
private let Shared = ProcessService()
final class ProcessService: NetworkingServiceWithBaseURL {
// MARK: - Internal Properties
let session = URLSession.filestack()
let baseURL = Constants.cdnURL
static let shared = Shared
}
// MARK: - Internal Functions
extension ProcessService {
func buildURL(tasks: String? = nil, sources: [String], key: String? = nil, security: Security? = nil) -> URL? {
var url = baseURL
if let key = key {
url.appendPathComponent(key)
}
if let tasks = tasks {
url.appendPathComponent(tasks)
}
if let security = security {
url.appendPathComponent("security=policy:\(security.encodedPolicy),signature:\(security.signature)")
}
if sources.count == 1, let source = sources.first {
// Most common case
url.appendPathComponent(source)
} else {
url.appendPathComponent("[\(sources.joined(separator: ","))]")
}
return url
}
}
| 23.98 | 115 | 0.614679 |
8af72bfbbff698ebc4975b7fc3aeeca6f1ee3ab8 | 1,691 | //
// CounterTests.swift
// TestisheUnitTests
//
// Created by dosgiandubh on 06/08/2021.
//
import XCTest
@testable import TestScenarioUsageExample
final class CounterTests: TestCase {
override class func start() {
describe("counter") {
$0.when("created with the default value") {
let counter = Counter()
$0.it("has the current value as 0") {
XCTAssertEqual(counter.currentValue, 0)
}
$0.when("has the increment block adding two") {
let customIncrement = 2
counter.incrementingClosure = { $0 + customIncrement }
$0.it("increments value by the set increment") {
counter.increment()
XCTAssertEqual(counter.currentValue, customIncrement)
}
}
$0.when("has the decrement block subtracting two") {
let customDecrement = 2
counter.decrementingClosure = { $0 - customDecrement }
$0.it("decrements value by the set decrement") {
counter.decrement()
XCTAssertEqual(counter.currentValue, -customDecrement)
}
}
}
$0.when("created with five as the initial value") {
let customInitialValue = 5
let counter = Counter(initialValue: customInitialValue)
$0.it("uses the given value") {
XCTAssertEqual(counter.currentValue, customInitialValue)
}
}
}
}
}
| 32.519231 | 78 | 0.506801 |
2f7ab4d344bc896f48a68bc7f81e08891e88d474 | 2,867 | //
// ExhibitionDataStore.swift
// NavCogMiraikan
//
/*******************************************************************************
* Copyright (c) 2021 © Miraikan - The National Museum of Emerging Science and Innovation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
import Foundation
/**
The sub-struct for multiple locations
- Parameters:
- nodeId: The destination id
- floor: The floor
*/
struct ExhibitionLocation : Decodable {
let nodeId: String
let floor: Int
}
/**
Model for EventList items
- Parameters:
- time: The time scheduled on that day
- place: The place
- event: The event id
- desc: The additional description
- onHoliday: For both weekends and public holidays
*/
struct ScheduleModel : Decodable {
let time: String
let place: String
let event: String
let description: String?
let onHoliday: Bool?
}
/**
Model for EventView details
- Parameters:
- id: event id
- title: The name displayed as link title
- talkTitle: The name for communication talk
- imageType: This is in order to determine the image scale ratio
- schedule: list of scheduled time
- desc: list of additional description
- content: The content
*/
struct EventModel : Decodable {
let id: String
let title: String
let talkTitle: String?
let imageType: String
let schedule: [String]?
let description: [String]?
let content: String
}
/**
Singleton for exhibition data transfer between different views
*/
@objc class ExhibitionDataStore: NSObject {
@objc static let shared = ExhibitionDataStore()
// var exhibitions: [ExhibitionModel]?
var schedules: [ScheduleModel]?
var events: [EventModel]?
@objc var descriptions: [String]?
}
| 28.959596 | 89 | 0.680502 |
e81084f1c96136c441bd016736d3b34b22f39a8c | 1,253 | //
// ViewController.swift
// MDCalendar
//
// Created by 梁宪松 on 2018/11/1.
// Copyright © 2018 madao. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
lazy var calendarView: MADCalendarView = {
let view = MADCalendarView.init(frame: CGRect.zero)
return view
}()
lazy var calendarHeaderView: MADCalendarTableHeaderView = {
let view = MADCalendarTableHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 313))
return view
}()
lazy var containerTableView: UITableView = {
let tableView = UITableView.init(frame: CGRect.zero, style: .grouped)
tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
tableView.backgroundColor = UIColor.white
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(containerTableView)
self.containerTableView.frame = self.view.bounds
self.calendarHeaderView.addSubview(self.calendarView)
self.calendarView.frame = self.calendarHeaderView.bounds
self.containerTableView.tableHeaderView = self.calendarHeaderView
}
}
| 28.477273 | 135 | 0.672785 |
2f9043f1e1908b3038d498d522dc28075561a270 | 3,277 | //===----------------------------------------------------------------------===//
//
// This source file is part of the KafkaNIO open source project
//
// Copyright © 2020 Thomas Bartelmess.
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// This file is auto generated from the Kafka Protocol definition. DO NOT EDIT.
import NIO
struct DeleteAclsRequest: KafkaRequest {
struct DeleteAclsFilter: KafkaRequestStruct {
/// The resource type.
let resourceTypeFilter: Int8
/// The resource name.
let resourceNameFilter: String?
/// The pattern type.
let patternTypeFilter: Int8?
/// The principal filter, or null to accept all principals.
let principalFilter: String?
/// The host filter, or null to accept all hosts.
let hostFilter: String?
/// The ACL operation.
let operation: Int8
/// The permission type.
let permissionType: Int8
let taggedFields: [TaggedField] = []
func write(into buffer: inout ByteBuffer, apiVersion: APIVersion) throws {
let lengthEncoding: IntegerEncoding = (apiVersion >= 2) ? .varint : .bigEndian
buffer.write(resourceTypeFilter)
buffer.write(resourceNameFilter, lengthEncoding: lengthEncoding)
if apiVersion >= 1 {
guard let patternTypeFilter = self.patternTypeFilter else {
throw KafkaError.missingValue
}
buffer.write(patternTypeFilter)
}
buffer.write(principalFilter, lengthEncoding: lengthEncoding)
buffer.write(hostFilter, lengthEncoding: lengthEncoding)
buffer.write(operation)
buffer.write(permissionType)
if apiVersion >= 2 {
buffer.write(taggedFields)
}
}
init(resourceTypeFilter: Int8, resourceNameFilter: String?, patternTypeFilter: Int8?, principalFilter: String?, hostFilter: String?, operation: Int8, permissionType: Int8) {
self.resourceTypeFilter = resourceTypeFilter
self.resourceNameFilter = resourceNameFilter
self.patternTypeFilter = patternTypeFilter
self.principalFilter = principalFilter
self.hostFilter = hostFilter
self.operation = operation
self.permissionType = permissionType
}
}
let apiKey: APIKey = .deleteAcls
let apiVersion: APIVersion
let clientID: String?
let correlationID: Int32
let taggedFields: [TaggedField] = []
/// The filters to use when deleting ACLs.
let filters: [DeleteAclsFilter]
func write(into buffer: inout ByteBuffer) throws {
let lengthEncoding: IntegerEncoding = (apiVersion >= 2) ? .varint : .bigEndian
writeHeader(into: &buffer, version: apiKey.requestHeaderVersion(for: apiVersion))
try buffer.write(filters, apiVersion: apiVersion, lengthEncoding: lengthEncoding)
if apiVersion >= 2 {
buffer.write(taggedFields)
}
}
}
| 37.238636 | 181 | 0.600854 |
1d369d40f49f89eb172e9871d059ce635af99fbc | 4,621 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// HTTP2FramePayloadToHTTP1CodecTests+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension HTTP2FramePayloadToHTTP1CodecTests {
@available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings")
static var allTests : [(String, (HTTP2FramePayloadToHTTP1CodecTests) -> () throws -> Void)] {
return [
("testBasicRequestServerSide", testBasicRequestServerSide),
("testRequestWithOnlyHeadServerSide", testRequestWithOnlyHeadServerSide),
("testRequestWithTrailers", testRequestWithTrailers),
("testSendingSimpleResponse", testSendingSimpleResponse),
("testResponseWithoutTrailers", testResponseWithoutTrailers),
("testResponseWith100Blocks", testResponseWith100Blocks),
("testPassingPromisesThroughWritesOnServer", testPassingPromisesThroughWritesOnServer),
("testBasicResponseClientSide", testBasicResponseClientSide),
("testResponseWithOnlyHeadClientSide", testResponseWithOnlyHeadClientSide),
("testResponseWithTrailers", testResponseWithTrailers),
("testSendingSimpleRequest", testSendingSimpleRequest),
("testRequestWithoutTrailers", testRequestWithoutTrailers),
("testResponseWith100BlocksClientSide", testResponseWith100BlocksClientSide),
("testPassingPromisesThroughWritesOnClient", testPassingPromisesThroughWritesOnClient),
("testReceiveRequestWithoutMethod", testReceiveRequestWithoutMethod),
("testReceiveRequestWithDuplicateMethod", testReceiveRequestWithDuplicateMethod),
("testReceiveRequestWithoutPath", testReceiveRequestWithoutPath),
("testReceiveRequestWithDuplicatePath", testReceiveRequestWithDuplicatePath),
("testReceiveRequestWithoutAuthority", testReceiveRequestWithoutAuthority),
("testReceiveRequestWithDuplicateAuthority", testReceiveRequestWithDuplicateAuthority),
("testReceiveRequestWithoutScheme", testReceiveRequestWithoutScheme),
("testReceiveRequestWithDuplicateScheme", testReceiveRequestWithDuplicateScheme),
("testReceiveResponseWithoutStatus", testReceiveResponseWithoutStatus),
("testReceiveResponseWithDuplicateStatus", testReceiveResponseWithDuplicateStatus),
("testReceiveResponseWithNonNumericalStatus", testReceiveResponseWithNonNumericalStatus),
("testSendRequestWithoutHost", testSendRequestWithoutHost),
("testSendRequestWithDuplicateHost", testSendRequestWithDuplicateHost),
("testFramesWithoutHTTP1EquivalentAreIgnored", testFramesWithoutHTTP1EquivalentAreIgnored),
("testWeTolerateUpperCasedHTTP1HeadersForRequests", testWeTolerateUpperCasedHTTP1HeadersForRequests),
("testWeTolerateUpperCasedHTTP1HeadersForResponses", testWeTolerateUpperCasedHTTP1HeadersForResponses),
("testWeDoNotNormalizeHeadersIfUserAskedUsNotToForRequests", testWeDoNotNormalizeHeadersIfUserAskedUsNotToForRequests),
("testWeDoNotNormalizeHeadersIfUserAskedUsNotToForResponses", testWeDoNotNormalizeHeadersIfUserAskedUsNotToForResponses),
("testWeStripIllegalHeadersAsWellAsTheHeadersNominatedByTheConnectionHeaderForRequests", testWeStripIllegalHeadersAsWellAsTheHeadersNominatedByTheConnectionHeaderForRequests),
("testWeStripIllegalHeadersAsWellAsTheHeadersNominatedByTheConnectionHeaderForResponses", testWeStripIllegalHeadersAsWellAsTheHeadersNominatedByTheConnectionHeaderForResponses),
("testServerSideWithEmptyFinalPackage", testServerSideWithEmptyFinalPackage),
("testClientSideWithEmptyFinalPackage", testClientSideWithEmptyFinalPackage),
]
}
}
| 66.014286 | 193 | 0.724951 |
29168cfbfca1e907ce21a339933b5076eefb26c7 | 11,861 | //
// ToolsServicesTests.swift
// VeryUsefulToolstoRememberTests
//
// Created by Ana Leticia Camargos on 15/04/21.
// Copyright © 2021 Ana Letícia Camargos. All rights reserved.
//
import XCTest
@testable import VeryUsefulToolstoRemember
final class ToolsServicesTests: XCTestCase {
func test_getAllTools_whenRequestFails_shouldReturnCorrectError() {
// Given
let dispatcherMock = NetworkDispatcherMock<[ToolResponseEntity]>()
let sut = makeSUT(networkDispatcher: dispatcherMock)
let errorMock = NetworkError(.internal(.noInternetConnection))
dispatcherMock.requestCodableResultToBeReturned = .failure(errorMock)
let expectedError = ToolsServiceError.genericError
// When
getAllToolsExpect(sut, toCompleteWith: .failure(expectedError))
// Then
XCTAssertEqual(String(describing: dispatcherMock.requestCodablePassedRequests), String(describing: [ToolsRequest.getTools]))
}
func test_getAllTools_whenRequestSucceeds_butResponseIsInvalid_shouldReturnCorrectError() {
// Given
let dispatcherMock = NetworkDispatcherMock<[ToolResponseEntity]>()
let sut = makeSUT(networkDispatcher: dispatcherMock)
dispatcherMock.requestCodableResultToBeReturned = .success(nil)
let expectedError = ToolsServiceError.responseParse
// When
getAllToolsExpect(sut, toCompleteWith: .failure(expectedError))
// Then
XCTAssertEqual(String(describing: dispatcherMock.requestCodablePassedRequests), String(describing: [ToolsRequest.getTools]))
}
func test_getAllTools_whenRequestSucceedsWithValidResponse_shouldReturnCorrectData() {
// Given
let dispatcherMock = NetworkDispatcherMock<[ToolResponseEntity]>()
let sut = makeSUT(networkDispatcher: dispatcherMock)
dispatcherMock.requestCodableResultToBeReturned = .success([.mock])
let expectedResponse = [ToolResponseEntity.mock]
// When
getAllToolsExpect(sut, toCompleteWith: .success(expectedResponse))
// Then
XCTAssertEqual(String(describing: dispatcherMock.requestCodablePassedRequests), String(describing: [ToolsRequest.getTools]))
}
func test_deleteTool_whenRequestFails_shouldReturnCorrectError() {
// Given
let dispatcherMock = NetworkDispatcherMock<NoEntity>()
let sut = makeSUT(networkDispatcher: dispatcherMock)
let errorMock = NetworkError(.internal(.noInternetConnection))
dispatcherMock.dispatchResultToBeReturned = .failure(errorMock)
let expectedError = ToolsServiceError.genericError
// When
deleteToolExpect(sut, toCompleteWith: .failure(expectedError))
// Then
XCTAssertEqual(String(describing: dispatcherMock.dispatchPassedRequests), String(describing: [ToolsRequest.deleteTool(id: .zero)]))
}
func test_deleteTool_whenRequestSucceeds_shouldReturnSuccess() {
// Given
let dispatcherMock = NetworkDispatcherMock<NoEntity>()
let sut = makeSUT(networkDispatcher: dispatcherMock)
dispatcherMock.dispatchResultToBeReturned = .success(.init(status: .http(200), data: nil))
let expectedResponse = NoEntity()
// When
deleteToolExpect(sut, toCompleteWith: .success(expectedResponse))
// Then
XCTAssertEqual(String(describing: dispatcherMock.dispatchPassedRequests), String(describing: [ToolsRequest.deleteTool(id: .zero)]))
}
func test_createNewTool_whenRequestFails_shouldReturnCorrectError() {
// Given
let dispatcherMock = NetworkDispatcherMock<ToolResponseEntity>()
let sut = makeSUT(networkDispatcher: dispatcherMock)
let errorMock = NetworkError(.internal(.noInternetConnection))
dispatcherMock.requestCodableResultToBeReturned = .failure(errorMock)
let expectedError = ToolsServiceError.genericError
// When
createNewToolExpect(sut, toCompleteWith: .failure(expectedError))
// Then
XCTAssertEqual(String(describing: dispatcherMock.requestCodablePassedRequests), String(describing: [ToolsRequest.createNewTool(.mock)]))
}
func test_createNewTool_whenRequestSucceeds_butResponseIsInvalid_shouldReturnCorrectError() {
// Given
let dispatcherMock = NetworkDispatcherMock<ToolResponseEntity>()
let sut = makeSUT(networkDispatcher: dispatcherMock)
dispatcherMock.requestCodableResultToBeReturned = .success(nil)
let expectedError = ToolsServiceError.responseParse
// When
createNewToolExpect(sut, toCompleteWith: .failure(expectedError))
// Then
XCTAssertEqual(String(describing: dispatcherMock.requestCodablePassedRequests), String(describing: [ToolsRequest.createNewTool(.mock)]))
}
func test_createNewTool_whenRequestSucceedsWithValidResponse_shouldReturnCorrectData() {
// Given
let dispatcherMock = NetworkDispatcherMock<ToolResponseEntity>()
let sut = makeSUT(networkDispatcher: dispatcherMock)
dispatcherMock.requestCodableResultToBeReturned = .success(.mock)
let expectedResponse = ToolResponseEntity.mock
// When
createNewToolExpect(sut, toCompleteWith: .success(expectedResponse))
// Then
XCTAssertEqual(String(describing: dispatcherMock.requestCodablePassedRequests), String(describing: [ToolsRequest.createNewTool(.mock)]))
}
func test_searchForTool_whenRequestFails_shouldReturnCorrectError() {
// Given
let dispatcherMock = NetworkDispatcherMock<[ToolResponseEntity]>()
let sut = makeSUT(networkDispatcher: dispatcherMock)
let errorMock = NetworkError(.internal(.noInternetConnection))
dispatcherMock.requestCodableResultToBeReturned = .failure(errorMock)
let expectedError = ToolsServiceError.genericError
// When
searchForToolExpect(sut, toCompleteWith: .failure(expectedError))
// Then
XCTAssertEqual(String(describing: dispatcherMock.requestCodablePassedRequests), String(describing: [ToolsRequest.searchTools(.init(text: ""))]))
}
func test_searchForTool_whenRequestSucceedsWithValidResponse_shouldReturnCorrectData() {
// Given
let dispatcherMock = NetworkDispatcherMock<[ToolResponseEntity]>()
let sut = makeSUT(networkDispatcher: dispatcherMock)
dispatcherMock.requestCodableResultToBeReturned = .success([.mock])
let expectedResponse = [ToolResponseEntity.mock]
// When
searchForToolExpect(sut, toCompleteWith: .success(expectedResponse))
// Then
XCTAssertEqual(String(describing: dispatcherMock.requestCodablePassedRequests), String(describing: [ToolsRequest.searchTools(.init(text: ""))]))
}
// MARK: - Test Helpers
private func makeSUT(networkDispatcher: NetworkDispatcher) -> ToolsServices {
let sut = ToolsServices(networkDispatcher: networkDispatcher)
return sut
}
private func getAllToolsExpect(
_ sut: ToolsServices,
toCompleteWith expectedResult: Result<[ToolResponseEntity], ToolsServiceError>,
file: StaticString = #file,
line: UInt = #line
) {
let exp = expectation(description: "Wait for completion")
sut.getAllTools { receivedResult in
switch (receivedResult, expectedResult) {
case let (.success(receivedItems), .success(expectedItems)):
XCTAssertEqual(String(describing: receivedItems), String(describing: expectedItems), file: file, line: line)
case let (.failure(receivedError), .failure(expectedError)):
XCTAssertEqual(receivedError, expectedError, file: file, line: line)
default:
XCTFail("Expected result \(expectedResult) got \(receivedResult) instead", file: file, line: line)
}
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
}
private func deleteToolExpect(
_ sut: ToolsServices,
toCompleteWith expectedResult: Result<NoEntity, ToolsServiceError>,
file: StaticString = #file,
line: UInt = #line
) {
trackForMemoryLeaks(sut, file: file, line: line)
let exp = expectation(description: "Wait for completion")
sut.deleteTool(id: .zero) { receivedResult in
switch (receivedResult, expectedResult) {
case let (.success(receivedItems), .success(expectedItems)):
XCTAssertEqual(String(describing: receivedItems), String(describing: expectedItems), file: file, line: line)
case let (.failure(receivedError), .failure(expectedError)):
XCTAssertEqual(receivedError, expectedError, file: file, line: line)
default:
XCTFail("Expected result \(expectedResult) got \(receivedResult) instead", file: file, line: line)
}
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
}
private func createNewToolExpect(
_ sut: ToolsServices,
toCompleteWith expectedResult: Result<ToolResponseEntity, ToolsServiceError>,
file: StaticString = #file,
line: UInt = #line
) {
trackForMemoryLeaks(sut, file: file, line: line)
let exp = expectation(description: "Wait for completion")
sut.createNewTool(parameters: .mock) { receivedResult in
switch (receivedResult, expectedResult) {
case let (.success(receivedItems), .success(expectedItems)):
XCTAssertEqual(String(describing: receivedItems), String(describing: expectedItems), file: file, line: line)
case let (.failure(receivedError), .failure(expectedError)):
XCTAssertEqual(receivedError, expectedError, file: file, line: line)
default:
XCTFail("Expected result \(expectedResult) got \(receivedResult) instead", file: file, line: line)
}
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
}
private func searchForToolExpect(
_ sut: ToolsServices,
toCompleteWith expectedResult: Result<[ToolResponseEntity], ToolsServiceError>,
file: StaticString = #file,
line: UInt = #line
) {
let exp = expectation(description: "Wait for completion")
sut.searchForTool(parameters: .init(text: "")) { receivedResult in
switch (receivedResult, expectedResult) {
case let (.success(receivedItems), .success(expectedItems)):
XCTAssertEqual(String(describing: receivedItems), String(describing: expectedItems), file: file, line: line)
case let (.failure(receivedError), .failure(expectedError)):
XCTAssertEqual(receivedError, expectedError, file: file, line: line)
default:
XCTFail("Expected result \(expectedResult) got \(receivedResult) instead", file: file, line: line)
}
exp.fulfill()
}
wait(for: [exp], timeout: 1.0)
}
}
extension CreateNewToolParameters {
static var mock: CreateNewToolParameters {
.init(
title: "Notion",
link: "https://notion.so",
description: "All in one tool to organize teams and ideas. Write, plan, collaborate, and get organized.",
tags: ["organization", "planning", "collaboration", "writing"]
)
}
}
extension AddNewTool.Request {
static var mock: AddNewTool.Request {
.init(
toolName: "Notion",
toolLink: "https://notion.so",
toolDescription: "All in one tool to organize teams and ideas. Write, plan, collaborate, and get organized.",
toolTags: ["organization", "planning", "collaboration", "writing"]
)
}
}
| 43.288321 | 152 | 0.683416 |
64595e302f19540ec996285479b6c628d1b0c5ea | 4,412 | //
// Concentration.swift
// Concentration
//
// Created by Кирилл Афонин on 10/01/2019.
// Copyright © 2019 krrl. All rights reserved.
//
import Foundation
struct Concentration {
// a deck of all cards
private(set) var cards = [Card]()
private(set) var points = 0
private(set) var flipCount = 0
private(set) var theEnd = false
// themes and emojis
private var emojiChoices = ["Halloween" : "🎃👻🦇👹👿🤯💀🐵",
"Winter" : "🏒🌨🎅🏻🥶☃❅🎄🎁",
"Sports" : "⚽️🏀⚾️🏈🥎🏐🎾🏉🎱",
"Music" : "🎤🎧🎼🎹🎸🎷🥁🎻🎺",
"Vehicles" : "🚗🚕🚎🚓🚑🚜🚒🏎🛵",
"Love" : "❤️💙💚💛🧡💜🖤💝💟",
]
// default theme key
var themeKey = "Halloween"
// at the game start deals the needed number of pairs, shuffles them and chose the theme
init(numberOfPairsOfCards: Int) {
//assert(numberOfPairsOfCards < 0, "Concentration.init(\(numberOfPairsOfCards)): there is no pairs")
for _ in 1...numberOfPairsOfCards {
let card = Card()
cards += [card, card]
}
cards.shuffle()
var emojiChoicesKeys = Array(emojiChoices.keys)
let randomIndex = Int(emojiChoicesKeys.count.arc4random)
themeKey = emojiChoicesKeys[randomIndex]
}
private var emojiDictionary = [Card:String]()
// picks an emoji randomly or return ??
mutating func emoji(for card: Card) -> String {
if emojiDictionary[card] == nil, emojiChoices.count > 0 {
let randomIndex = emojiChoices[themeKey]!.index((emojiChoices[themeKey]?.startIndex)!, offsetBy: (emojiChoices[themeKey]?.count.arc4random)!)
emojiDictionary[card] = String(emojiChoices[themeKey]!.remove(at: randomIndex))
}
return emojiDictionary[card] ?? "?"
}
// checks if only one card is faced up
private var indexOfOneAndOnlyFaceUpCards: Int? {
get {
return cards.indices.filter { cards[$0].isFaceUp }.oneAndOnly
}
set {
for index in cards.indices {
cards[index].isFaceUp = (index == newValue)
}
}
}
// flips the card and cheks matching
mutating func chooseCard(at index: Int) {
assert(cards.indices.contains(index), "Concentration.chooseCards(ar \(index): there is no such index")
if !cards[index].isMatched {
flipCount += 1
if let matchIndex = indexOfOneAndOnlyFaceUpCards, matchIndex != index {
// check is card match
if cards[matchIndex] == cards[index] {
cards[matchIndex].isMatched = true
cards[index].isMatched = true
points += 2
cards[matchIndex].wasFacedUp = false
cards[index].wasFacedUp = false
if cards.indices.filter({ cards[$0].isMatched }).count == cards.indices.count {
theEnd = true
cards[matchIndex].isFaceUp = false
cards[index].isFaceUp = false
return
}
}
cards[index].isFaceUp = true
if cards[index].wasFacedUp {
points -= 1
} else {
cards[index].wasFacedUp = true
}
if cards[matchIndex].wasFacedUp {
points -= 1
} else {
cards[matchIndex].wasFacedUp = true
}
} else {
// either no cards or 2 cards are face up
indexOfOneAndOnlyFaceUpCards = index
}
}
}
mutating func resetGame() {
points = 0
flipCount = 0
theEnd = false
for index in cards.indices {
cards[index].isFaceUp = false
cards[index].isMatched = false
cards[index].wasFacedUp = false
}
}
}
// adds randomizer to Int
extension Int {
var arc4random: Int {
return Int(arc4random_uniform(UInt32(self)))
}
}
// returns element if it is only one element in Collection
extension Collection {
var oneAndOnly: Element? {
return count == 1 ? first : nil
}
}
| 33.938462 | 153 | 0.515639 |
cc87fd414d103bc3e08260ae1f22505b727cd53d | 3,965 | //
// PGDate.swift
// LittlinkRouterPerfect
//
// Created by Brent Royal-Gordon on 12/2/16.
//
//
import Foundation
/// Representation of a PostgreSQL DATE value, identifying a particular day in the
/// Gregorian calendar without a time.
///
/// A `PGDate` includes a day, month, year, and era (A.D. or B.C.). There are
/// also two special `PGDate`s, `distantPast` and `distantFuture`, which do not
/// have these fields and come before or after every other date.
public enum PGDate {
/// Represents whether a date is in A.D. or B.C.
public enum Era: Int {
/// Date is in the B.C. era.
case bc = 0
/// Date is in the A.D. era.
case ad = 1
}
/// A date before all other dates. PostgreSQL calls this `-infinity`.
case distantPast
/// An ordinary date, as opposed to `distantPast` or `distantFuture`.
case date(era: Era, year: Int, month: Int, day: Int)
/// A date after all other dates. PostgreSQL calls this `infinity`.
case distantFuture
/// Create an ordinary date.
///
/// - Parameter era: The era. Defaults to `ad`.
/// - Parameter year: The year. Defaults to `0`.
/// - Parameter month: The month. Defaults to `0`.
/// - Parameter day: The day. Defaults to `0`.
init(era: Era = .ad, year: Int = 0, month: Int = 0, day: Int = 0) {
self = .date(era: .ad, year: year, month: month, day: day)
}
}
extension PGDate {
/// Whether the year is in A.D. or B.C.
public var era: Era {
get {
return properties.era
}
set {
properties.era = newValue
}
}
/// The year of the date. Valid values are from `1` to `Int.max`, though this
/// is not enforced.
public var year: Int {
get {
return properties.year
}
set {
properties.year = newValue
}
}
/// The month of the date. Valid values are from `1` to `12`, though this
/// is not enforced.
public var month: Int {
get {
return properties.month
}
set {
properties.month = newValue
}
}
/// The day of the date. Valid values are from `1` to `31`, though this
/// is not enforced.
public var day: Int {
get {
return properties.day
}
set {
properties.day = newValue
}
}
private var properties: (era: Era, year: Int, month: Int, day: Int) {
get {
guard case let .date(era, year, month, day) = self else {
return (.ad, 0, 0, 0)
}
return (era, year, month, day)
}
set {
self = .date(era: newValue.era, year: newValue.year, month: newValue.month, day: newValue.day)
}
}
}
extension PGDate {
/// Create a date from the `DateComponents` instance.
///
/// - Parameter components: The `DateComponents` instance to convert. This
/// must include at last `year`, `month`, and `day` fields.
/// The `era` field will also be used if present.
public init?(_ components: DateComponents) {
guard let year = components.year, let month = components.month, let day = components.day else {
return nil
}
let era = components.era.flatMap(Era.init(rawValue:)) ?? .ad
self = .date(era: era, year: year, month: month, day: day)
}
}
extension DateComponents {
/// Create date components from the `PGDate` instance.
///
/// - Parameter date: The `PGDate` instance to convert. This must not be
/// `PGDate.distantPast` or `PGDate.distantFuture`.
public init?(_ date: PGDate) {
guard case let .date(era, year, month, day) = date else {
return nil
}
self.init(era: era.rawValue, year: year, month: month, day: day)
}
}
| 30.5 | 106 | 0.555107 |
d975c5464434170802fa70c0a9ce53c88ffa86b9 | 3,521 | //
// AllListsViewController.swift
// Checklists
//
// Created by Fahim Farook on 04/08/2020.
// Copyright © 2020 Razeware. All rights reserved.
//
import UIKit
class AllListsViewController: UITableViewController, ListDetailViewControllerDelegate {
let cellIdentifier = "ChecklistCell"
var dataModel: DataModel!
override func viewDidLoad() {
super.viewDidLoad()
// Enable large titles
navigationController?.navigationBar.prefersLargeTitles = true
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowChecklist" {
let controller = segue.destination as! ChecklistViewController
controller.checklist = sender as? Checklist
} else if segue.identifier == "AddChecklist" {
let controller = segue.destination as! ListDetailViewController
controller.delegate = self
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataModel.lists.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
// Update cell information
let checklist = dataModel.lists[indexPath.row]
cell.textLabel!.text = checklist.name
cell.accessoryType = .detailDisclosureButton
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let checklist = dataModel.lists[indexPath.row]
performSegue(withIdentifier: "ShowChecklist", sender: checklist)
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
dataModel.lists.remove(at: indexPath.row)
let indexPaths = [indexPath]
tableView.deleteRows(at: indexPaths, with: .automatic)
}
override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) {
let controller = storyboard!.instantiateViewController(withIdentifier: "ListDetailViewController") as! ListDetailViewController
controller.delegate = self
let checklist = dataModel.lists[indexPath.row]
controller.checklistToEdit = checklist
navigationController?.pushViewController(controller, animated: true)
}
// MARK: - List Detail View Controller Delegates
func listDetailViewControllerDidCancel(_ controller: ListDetailViewController) {
navigationController?.popViewController(animated: true)
}
func listDetailViewController(_ controller: ListDetailViewController, didFinishAdding checklist: Checklist) {
let newRowIndex = dataModel.lists.count
dataModel.lists.append(checklist)
let indexPath = IndexPath(row: newRowIndex, section: 0)
let indexPaths = [indexPath]
tableView.insertRows(at: indexPaths, with: .automatic)
navigationController?.popViewController(animated: true)
}
func listDetailViewController(_ controller: ListDetailViewController, didFinishEditing checklist: Checklist) {
if let index = dataModel.lists.firstIndex(of: checklist) {
let indexPath = IndexPath(row: index, section: 0)
if let cell = tableView.cellForRow(at: indexPath) {
cell.textLabel!.text = checklist.name
}
}
navigationController?.popViewController(animated: true)
}
}
| 36.677083 | 135 | 0.754899 |
e060ec9d1a74c16b85ae9b058ae6620c7c291b68 | 3,392 | //
// YelpClient.swift
// Yelp
//
// Created by Timothy Lee on 9/19/14.
// Copyright (c) 2014 Timothy Lee. All rights reserved.
//
import UIKit
// You can register for Yelp API keys here: http://www.yelp.com/developers/manage_api_keys
let yelpConsumerKey = "vxKwwcR_NMQ7WaEiQBK_CA"
let yelpConsumerSecret = "33QCvh5bIF5jIHR5klQr7RtBDhQ"
let yelpToken = "uRcRswHFYa1VkDrGV6LAW2F8clGh5JHV"
let yelpTokenSecret = "mqtKIxMIR4iBtBPZCmCLEb-Dz3Y"
enum YelpSortMode: Int {
case BestMatched = 0, Distance, HighestRated
var description : String {
switch self {
case .BestMatched: return "Best Match"
case .Distance: return "Distance"
case .HighestRated: return "Rating"
}
}
}
class YelpClient: BDBOAuth1RequestOperationManager {
var accessToken: String!
var accessSecret: String!
class var sharedInstance : YelpClient {
struct Static {
static var token : dispatch_once_t = 0
static var instance : YelpClient? = nil
}
dispatch_once(&Static.token) {
Static.instance = YelpClient(consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret, accessToken: yelpToken, accessSecret: yelpTokenSecret)
}
return Static.instance!
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(consumerKey key: String!, consumerSecret secret: String!, accessToken: String!, accessSecret: String!) {
self.accessToken = accessToken
self.accessSecret = accessSecret
var baseUrl = NSURL(string: "http://api.yelp.com/v2/")
super.init(baseURL: baseUrl, consumerKey: key, consumerSecret: secret);
var token = BDBOAuth1Credential(token: accessToken, secret: accessSecret, expiration: nil)
self.requestSerializer.saveAccessToken(token)
}
func searchWithTerm(term: String, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation {
return searchWithTerm(term, sort: nil, categories: nil, deals: nil, completion: completion)
}
func searchWithTerm(term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation {
// For additional parameters, see http://www.yelp.com/developers/documentation/v2/search_api
// Default the location to San Francisco
var parameters: [String : AnyObject] = ["term": term, "ll": "37.785771,-122.406165"]
if sort != nil {
parameters["sort"] = sort!.rawValue
}
if categories != nil && categories!.count > 0 {
parameters["category_filter"] = ",".join(categories!)
}
if deals != nil {
parameters["deals_filter"] = deals!
}
println(parameters)
return self.GET("search", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
var dictionaries = response["businesses"] as? [NSDictionary]
if dictionaries != nil {
completion(Business.businesses(array: dictionaries!), nil)
}
}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
completion(nil, error)
})
}
}
| 36.473118 | 168 | 0.636203 |
019558fa7a630707801ba14eaae64d04036114a3 | 424 | //
// PossibleAnswer.swift
// ForYouAndMe
//
// Created by Leonardo Passeri on 28/05/2020.
//
import Foundation
struct PossibleAnswer {
let id: String
let type: String
let text: String
let correct: Bool
}
extension PossibleAnswer: JSONAPIMappable {}
extension PossibleAnswer: Equatable {
static func == (lhs: PossibleAnswer, rhs: PossibleAnswer) -> Bool {
return lhs.id == rhs.id
}
}
| 16.96 | 71 | 0.67217 |
90116ea73119006af5ed7fbddf4681b203f7032e | 2,341 | //
// AdaptiveStack.swift
// ARPinView
//
// Created by Dennis Hernandez on 9/24/21.
// https://www.hackingwithswift.com/quick-start/swiftui/how-to-automatically-switch-between-hstack-and-vstack-based-on-size-class
//JIC we are in linux
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftUI
public enum StackType {
case Vertical, Horizontal
}
/// Adaptive stack lets you conditionally choose a vstack or hstack
///
/// Call this just like a normal stack, except pass a ``StackType`` to let it know how to behave.
///
/// Example:
///
/// ManualStack(stackType: .Vertical){
/// ForEach(allInTheRainbowsColors, id:\.self){ color in
/// Rectangle()
/// .frame(width: 200.0, height:50.0)
/// .foregroundColor(color)
/// }
/// }
///
/// I very much stole and butcher this from [Hacking With Swift](https://www.hackingwithswift.com/quick-start/swiftui/how-to-automatically-switch-between-hstack-and-vstack-based-on-size-class)
public struct ManualStack<Content: View>: View {
///Set this to ``StackType`` `Vertical` for a `VStack` and `Horizontal` for and `HStack`.
public var isVertical:Bool = true
public let horizontalAlignment: HorizontalAlignment
public let verticalAlignment: VerticalAlignment
public let spacing: CGFloat?
public let content: () -> Content
public init(isVertical:Bool, horizontalAlignment: HorizontalAlignment = .center, verticalAlignment: VerticalAlignment = .center, spacing: CGFloat? = nil, @ViewBuilder content: @escaping () -> Content) {
self.isVertical = isVertical
self.horizontalAlignment = horizontalAlignment
self.verticalAlignment = verticalAlignment
self.spacing = spacing
self.content = content
}
public var body: some View {
Group {
if isVertical == true {
VStack(alignment: horizontalAlignment, spacing: spacing, content: content)
} else {
HStack(alignment: verticalAlignment, spacing: spacing, content: content)
}
}
}
}
struct ContentView: View {
var body: some View {
ManualStack(isVertical: false) {
Text("""
Horizontal when there's lots of space\r
but\r
Vertical when space is restricted
""")
}
}
}
#endif
| 33.442857 | 206 | 0.653994 |
5d3e21c0a38eca7e11c694a0fa6fd06e42dd33c9 | 96 | import Foundation
protocol RouterContract {
func presentLogin()
func presentSuccess()
}
| 12 | 25 | 0.75 |
e82d3311836a7cb75bfa5e38c56279497af8907c | 1,512 | //
// Location.swift
// SayTheirNames
//
// Copyright (c) 2020 Say Their Names Team (https://github.com/Say-Their-Name)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
struct Location: Codable {
let name: String
private enum CodingKeys: String, CodingKey {
case name
}
}
extension Location: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(name)
}
}
extension Location: FilterCategory {}
| 36 | 81 | 0.73082 |
034aea7e62814eb84519cf2025748a96b76cbdaa | 379 | import StructUtils
public struct ModuleDeclaration: Withable {
public var moduleID = ""
// Qualifiers
public var explicit = false
public var framework = false
// Attributes
public var attributes = [String]()
// Module members
public var members = [ModuleMember]()
public init() {}
}
extension ModuleDeclaration: ModuleDeclarationProtocol, ModuleMember {}
| 18.95 | 71 | 0.725594 |
7abca42fc0f1a5f7747e7430ccadddb4acc4a3c2 | 4,232 | // Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
import MaterialComponents.MaterialNavigationBar
import MaterialComponents.MaterialButtons
import MaterialComponents.MaterialTypography
class NavigationBarButtonTitleFontTests: XCTestCase {
var navigationBar: MDCNavigationBar!
override func setUp() {
super.setUp()
navigationBar = MDCNavigationBar()
}
override func tearDown() {
navigationBar = nil
super.tearDown()
}
private func recursiveSubviews(of superview: UIView) -> [UIView] {
var subviews = superview.subviews
for subview in superview.subviews {
subviews.append(contentsOf: recursiveSubviews(of: subview))
}
return subviews
}
func testDefaultFontBehavior() {
// Given
navigationBar.leadingBarButtonItems = [
UIBarButtonItem(title: "Text", style: .plain, target: nil, action: nil)
]
navigationBar.trailingBarButtonItems = [
UIBarButtonItem(title: "Text 2", style: .plain, target: nil, action: nil)
]
// Then
for view in recursiveSubviews(of: navigationBar) {
if let button = view as? MDCButton {
if let font = button.titleFont(for: .normal) {
XCTAssertTrue(font.mdc_isSimplyEqual(MDCTypography.buttonFont()))
} else {
XCTAssertTrue(false, "The button's titleFont for .normal should not be nil.")
}
}
}
}
func testCustomFontIsSetForNewButtons() {
// Given
let font = UIFont.systemFont(ofSize: 100)
// When
navigationBar.setButtonsTitleFont(font, for: .normal)
navigationBar.leadingBarButtonItems = [
UIBarButtonItem(title: "Text", style: .plain, target: nil, action: nil)
]
navigationBar.trailingBarButtonItems = [
UIBarButtonItem(title: "Text 2", style: .plain, target: nil, action: nil)
]
// Then
for view in recursiveSubviews(of: navigationBar) {
if let button = view as? MDCButton {
XCTAssertEqual(button.titleFont(for: .normal), font)
XCTAssertEqual(button.titleLabel?.font, font)
}
}
}
func testCustomFontIsSetForExistingButtons() {
// Given
let font = UIFont.systemFont(ofSize: 100)
// When
navigationBar.leadingBarButtonItems = [
UIBarButtonItem(title: "Text", style: .plain, target: nil, action: nil)
]
navigationBar.trailingBarButtonItems = [
UIBarButtonItem(title: "Text 2", style: .plain, target: nil, action: nil)
]
navigationBar.setButtonsTitleFont(font, for: .normal)
// Then
for view in recursiveSubviews(of: navigationBar) {
if let button = view as? MDCButton {
XCTAssertEqual(button.titleFont(for: .normal), font)
XCTAssertEqual(button.titleLabel?.font, font)
}
}
}
func testCustomFontFallbackBehavior() {
// Given
let normalFont = UIFont.systemFont(ofSize: 100)
let selectedFont = UIFont.systemFont(ofSize: 50)
// When
navigationBar.setButtonsTitleFont(normalFont, for: .normal)
navigationBar.setButtonsTitleFont(selectedFont, for: .selected)
navigationBar.leadingBarButtonItems = [
UIBarButtonItem(title: "Text", style: .plain, target: nil, action: nil)
]
navigationBar.trailingBarButtonItems = [
UIBarButtonItem(title: "Text 2", style: .plain, target: nil, action: nil)
]
// Then
for view in recursiveSubviews(of: navigationBar) {
if let button = view as? MDCButton {
button.isSelected = true
XCTAssertEqual(button.titleLabel?.font, selectedFont)
button.isSelected = false
XCTAssertEqual(button.titleLabel?.font, normalFont)
}
}
}
}
| 30.666667 | 87 | 0.688563 |
912b4e28c7f56cc4ed6e3c993a60e58f40f123d3 | 3,085 | //
// Xcore
// Copyright © 2017 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
// MARK: - UIViewController
extension UIViewController {
static func runOnceSwapSelectors() {
swizzle(
UIViewController.self,
originalSelector: #selector(UIViewController.viewDidAppear(_:)),
swizzledSelector: #selector(UIViewController.swizzled_viewDidAppear(_:))
)
swizzle(
UIViewController.self,
originalSelector: #selector(UIViewController.viewWillDisappear(_:)),
swizzledSelector: #selector(UIViewController.swizzled_viewWillDisappear(_:))
)
swizzle_hidesBottomBarWhenPushed_runOnceSwapSelectors()
swizzle_chrome_runOnceSwapSelectors()
}
}
extension UIViewController {
private struct AssociatedKey {
static var didAddKeyboardNotificationObservers = "didAddKeyboardNotificationObservers"
}
private var didAddKeyboardNotificationObservers: Bool {
get { associatedObject(&AssociatedKey.didAddKeyboardNotificationObservers, default: false) }
set { setAssociatedObject(&AssociatedKey.didAddKeyboardNotificationObservers, value: newValue) }
}
@objc private func swizzled_viewDidAppear(_ animated: Bool) {
swizzled_viewDidAppear(animated)
// Swizzled `viewDidAppear` and `viewWillDisappear` for keyboard notifications.
// Registering keyboard notifications in `viewDidLoad` results in unexpected
// keyboard behavior: when popping the viewController while the keyboard is
// presented, keyboard will not dismiss in concurrent with the popping progress.
if !didAddKeyboardNotificationObservers {
_addKeyboardNotificationObservers()
didAddKeyboardNotificationObservers = true
}
}
@objc private func swizzled_viewWillDisappear(_ animated: Bool) {
swizzled_viewWillDisappear(animated)
if didAddKeyboardNotificationObservers {
_removeKeyboardNotificationObservers()
didAddKeyboardNotificationObservers = false
}
}
}
// MARK: - UIView
extension UIView {
static func _runOnceSwapSelectors() {
swizzle(
UIView.self,
originalSelector: #selector(UIView.layoutSubviews),
swizzledSelector: #selector(UIView.swizzled_view_layoutSubviews)
)
}
private struct AssociatedKey {
static var didAddKeyboardNotificationObservers = "didAddKeyboardNotificationObservers"
}
private var didAddKeyboardNotificationObservers: Bool {
get { associatedObject(&AssociatedKey.didAddKeyboardNotificationObservers, default: false) }
set { setAssociatedObject(&AssociatedKey.didAddKeyboardNotificationObservers, value: newValue) }
}
@objc private func swizzled_view_layoutSubviews() {
swizzled_view_layoutSubviews()
if !didAddKeyboardNotificationObservers {
_addKeyboardNotificationObservers()
didAddKeyboardNotificationObservers = true
}
}
}
| 34.662921 | 104 | 0.708266 |
03442d2d3b26e97465d641fc6b3b10e4af36c799 | 292 | //
// See LICENSE folder for this template’s licensing information.
//
// Abstract:
// Instantiates a live view and passes it to the PlaygroundSupport framework.
//
import PlaygroundSupport
import SwiftUI
import UserModule
PlaygroundPage.current.setLiveView(PlaygroundManager.shared.vc)
| 22.461538 | 78 | 0.794521 |
14bc1e62e5339a34539d1837a3be8a056be3012d | 2,129 | /// Copyright (c) 2021 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.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// 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 Settings {
static let thumbnailSize =
CGSize(width: 150, height: 250)
static let defaultElementSize =
CGSize(width: 250, height: 180)
static let borderColor: Color = .blue
static let borderWidth: CGFloat = 5
}
| 49.511628 | 83 | 0.753405 |
9b32521464e2b89145fb19384fb23f29b2ec649c | 5,881 | //
// APCacheManager.swift
// ApplicasterSDK
//
// Created by Avi Levin on 12/11/2017.
// Copyright © 2017 Applicaster Ltd. All rights reserved.
//
import UIKit
@objc public class APCacheManager: NSObject {
#if targetEnvironment(macCatalyst)
static let urlCache = URLCache(memoryCapacity: 10 * 1024 * 1024,
diskCapacity: 50 * 1024 * 1024,
directory: nil)
#else
static let urlCache = URLCache(memoryCapacity: 10 * 1024 * 1024,
diskCapacity: 50 * 1024 * 1024,
diskPath: "cache_manager.path")
#endif
@objc public static let shared = APCacheManager()
private var fileCompletions: [APFileLoadingCompletion] = []
// MARK: - Initialization
override private init() {
super.init()
}
// MARK: - Public Methods
@objc public func saveObjectToCache(_ object: JsonSerializableProtocol, identifier: String?) {
let cachedModel = APCachedModel(object: object, identifier: identifier ?? "")
_ = cachedModel.saveObjectToStorage()
}
@objc public func loadObjectFromCache(forClass classType: AnyClass, identifier: String?) -> JsonSerializableProtocol? {
var retValue: JsonSerializableProtocol?
guard let classType = classType as? JsonSerializableProtocol.Type else {
return nil
}
let model = APCachedModel(object: classType.init(), identifier: identifier ?? "")
if model.loadObjectFromStorage() == true {
retValue = model.object
}
return retValue
}
@objc public func deleteObjectFromCache(_ object: JsonSerializableProtocol, identifier: String?) {
let cachedModel = APCachedModel(object: object, identifier: identifier ?? "")
cachedModel.deleteLocalStorage()
}
@objc public func getLocalPath(forUrlString urlString: String, useMd5UrlFilename: Bool) -> URL? {
guard let url = URL(string: urlString) else {
return nil
}
var file: APFile?
if useMd5UrlFilename {
let filename = "\(urlString.toMd5hash()).\(url.pathExtension)"
file = APFile(filename: filename, url: urlString)
} else {
file = APFile(filename: url.lastPathComponent, url: urlString)
}
return file?.isInLocalStorage() == true ? file?.localURLPath() : nil
}
@objc public func getLocalPath(forUrlString urlString: String) -> URL? {
guard let url = URL(string: urlString) else {
return nil
}
let file = APFile(filename: url.lastPathComponent, url: urlString)
return file.localURLPath()
}
@objc public func download(urlString: String, completion: ((_ success: Bool) -> Void)?) {
guard let url = URL(string: urlString) else {
completion?(false)
return
}
let file = APFile(filename: url.lastPathComponent, url: urlString)
download(file: file, completion: completion)
}
public func download(file: APFile,
completion: ((_ success: Bool) -> Void)?) {
// There can be only 2 states here, the same file is already been downloaded or not
if let downloadedFile = getFileCompletionFromArray(file: file),
let completion = completion {
// Check if file download has already been finshed so we can't add a new completion object
if downloadedFile.didFinish {
// Check of file was saved on disk
let success = file.isInLocalStorage()
// Send completion on main theard
DispatchQueue.main.async {
completion(success)
}
} else {
downloadedFile.completionArray.append(completion)
}
} else {
// Create a new FileCompletion object
let fileCompletionObject = APFileLoadingCompletion(file: file, completion: completion)
// Insert the object to fileCompletionArray
fileCompletions.append(fileCompletionObject)
// Start download
APCacheHelper.download(file: file, completion: { success in
// Try to get the completion object from the array
guard let fileCompletion = self.getFileCompletionFromArray(file: file) else {
// remember, the method completion closer is optional
guard let completion = completion else {
return
}
return completion(file.isInLocalStorage())
}
// Close array before notify
fileCompletion.didFinish = true
// Notify all registered completion array
for completion in fileCompletion.completionArray {
// Send completion on main theard
DispatchQueue.main.async {
completion(success || file.isInLocalStorage())
}
}
// Remove fileCompletionObject
self.synchronized(lock: self, block: {
if let index = self.fileCompletions.firstIndex(of: fileCompletion) {
self.fileCompletions.remove(at: index)
}
})
})
}
}
func synchronized(lock: AnyObject, block: () throws -> Void) rethrows {
objc_sync_enter(lock)
defer {
objc_sync_exit(lock)
}
try block()
}
func getFileCompletionFromArray(file: APFile) -> APFileLoadingCompletion? {
return fileCompletions.first(where: { $0.file.filename == file.filename && $0.file.url == file.url })
}
}
| 37.458599 | 123 | 0.580854 |
ed0ea18ca728f94b1084787fae35b159013bcc59 | 254 | //
// FurnituresApp.swift
// Furnitures
//
// Created by Luan Nguyen on 08/12/2020.
//
import SwiftUI
@main
struct FurnituresApp: App {
// MARK: - BODY
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 13.368421 | 41 | 0.559055 |
b91a2db98c7d8cc4d35b1296eea3e79167df3a7d | 1,447 | //
// MyButton.swift
// GCProgressSample
//
// Created by keygx on 2016/03/12.
// Copyright © 2016年 keygx. All rights reserved.
//
import UIKit
class MyButton: UIButton {
enum ButtonStatus {
case normal
case highlighted
case selected
case disabled
}
var status: ButtonStatus = .normal {
didSet {
switch status {
case .disabled:
isEnabled = false
default:
isEnabled = true
}
apply()
}
}
private let defaultColor: UIColor = UIColor(red: 0.0/255.0, green: 122.0/255.0, blue: 255.0/255.0, alpha: 1.0)
private let disabledColor: UIColor = UIColor.lightGray
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
status = .normal
layer.cornerRadius = 4.0
layer.borderWidth = 1.0
}
func apply() {
switch status {
case .disabled:
setTitleColor(disabledColor, for: .disabled)
layer.borderColor = disabledColor.cgColor
default:
setTitleColor(defaultColor, for: UIControlState())
layer.borderColor = defaultColor.cgColor
}
}
}
| 21.597015 | 114 | 0.539737 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.