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
|
---|---|---|---|---|---|
e89f4cbc399fdb94ea5bffbc157cd4a41dd11ce6 | 604 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2020 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
public struct InternalError: Error {
private let description: String
public init(_ description: String) {
assertionFailure(description)
self.description = "Internal error. Please file a bug at https://bugs.swift.org with this info. \(description)"
}
}
| 33.555556 | 119 | 0.740066 |
22c8c84e56d2c0a72d2e0dc1b63886ff62fa68fa | 498 | //
// AppDelegate.swift
// SimonSaysGame
//
// Created by Joe Lucero on 6/26/18.
// Copyright © 2018 Joe Lucero. 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
}
}
| 20.75 | 143 | 0.732932 |
381c9150fcd56b28c998e7e63ccc305fe233ae3e | 893 | //
// AppConfigurator.swift
// AviasalesSDKTemplate
//
// Created by Dim on 22.11.2017.
// Copyright © 2017 Go Travel Un Limited. All rights reserved.
//
import Foundation
import Appodeal
@objcMembers
class AppConfigurator: NSObject {
static func configure() {
configureAviasalesSDK()
configureAppodeal()
}
}
private extension AppConfigurator {
static func configureAviasalesSDK() {
let token = ConfigManager.shared.apiToken
let marker = ConfigManager.shared.partnerMarker
let locale = Locale.current.identifier
let configuration = AviasalesSDKInitialConfiguration(apiToken: token, apiLocale: locale, partnerMarker: marker)
AviasalesSDK.setup(with: configuration)
}
static func configureAppodeal() {
Appodeal.initialize(withApiKey: ConfigManager.shared.appodealKey, types: .interstitial)
}
}
| 23.5 | 119 | 0.712206 |
d95a37ef4ef82ef7e7e374b2af1bd5515e84b3cc | 583 | //
// PurchaseTests.swift
// PurchaseManager
//
// Created by Ziad on 12/7/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import XCTest
@testable import PurchaseManager
class PurchaseTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
}
| 22.423077 | 111 | 0.653516 |
bf1dbcc7a7ff29d474891530a7df63fa28da37fb | 852 | import UIKit
public protocol NibLoadable: Identifiable where Self: UIView {
static var bundle: Bundle { get }
static var nibName: String { get }
static var nib: UINib { get }
static func instantiate(withOwner: Any?) -> UIView
}
public extension NibLoadable {
static var bundle: Bundle {
return Bundle(for: Self.self)
}
static var nibName: String {
return String(describing: self)
}
static var nib: UINib {
return UINib(nibName: nibName, bundle: bundle)
}
static func instantiate(withOwner: Any? = nil) -> UIView {
let nibs = nib.instantiate(withOwner: withOwner, options: nil)
guard let view = nibs.lazy.compactMap({ $0 as? UIView }).first else {
fatalError("Could not instantiate \(identifier) from nib file.")
}
return view
}
}
| 26.625 | 77 | 0.63615 |
f753fecdaf16c96fae6330068ab7a1a05bbc4001 | 1,479 | //
// Double+Extension.swift
// APJExtensionsiOSTests
//
// Created by Angelo Pino on 23/04/2020.
// Copyright © 2020 Pino, Angelo. All rights reserved.
//
import Foundation
public extension Double {
var formatUsingAbbrevation: String {
let numFormatter = NumberFormatter()
typealias Abbrevation = (threshold: Double, divisor: Double, suffix: String)
let abbreviations: [Abbrevation] = [(0, 1, ""),
(1000.0, 1000.0, "K"),
(100_000.0, 1_000_000.0, "M"),
(100_000_000.0, 1_000_000_000.0, "B")]
let absVal = abs(self)
let abbreviation: Abbrevation = abbreviations.reduce(abbreviations[0]) { (result: Abbrevation, current: (threshold: Double, divisor: Double, suffix: String)) -> Abbrevation in
if (absVal < current.threshold) {
return result
}
return current
}
let value = NSNumber(value: self / abbreviation.divisor)
numFormatter.positiveSuffix = abbreviation.suffix
numFormatter.negativeSuffix = abbreviation.suffix
numFormatter.allowsFloats = true
numFormatter.minimumIntegerDigits = 1
numFormatter.minimumFractionDigits = 0
numFormatter.maximumFractionDigits = 1
return numFormatter.string(from: value) ?? String(self)
}
}
| 36.073171 | 183 | 0.580798 |
f480f952be31b521495cf4e5099f33e7e41513de | 717 | //
// TipCalculator.swift
// TipCalculator
//
// Created by Nguyen Nhan on 5/21/16.
// Copyright © 2016 Nguyen Nhan. All rights reserved.
//
import Foundation
class TipCalculator {
var billAmount: Double
var tipPercent: Int
var tip: Double {
get {
return calculateTipBy(self.tipPercent)
}
}
var total: Double {
get {
return billAmount + tip
}
}
init(billAmount: Double, tipPercent: Int) {
self.billAmount = billAmount
self.tipPercent = tipPercent
}
func calculateTipBy(tipPercent: Int) -> Double {
return self.billAmount * Double(tipPercent) / 100
}
} | 18.384615 | 57 | 0.569038 |
33f41d29d11bb8caea835520727ef4c8c9aea060 | 3,211 | // RUN: %swift -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main9NamespaceC5ValueVySi_GMf" = internal constant <{
// CHECk-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32{{(, \[4 x i8\])?}}, i64
// CHECK-SAME: }> <{
// i8** @"$sB[[INT]]_WV",
// getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main9NamespaceC5ValueVySi_GWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8 }>* @"$s4main9NamespaceC5ValueVMn" to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
final class Namespace<Arg> {
struct Value {
let first: Arg
}
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main9NamespaceC5ValueVySi_GMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Namespace.Value(first: 13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueVMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_1]]:
// CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]]
// CHECK: br i1 [[EQUAL_TYPES_1_1]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED_1]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main9NamespaceC5ValueVySi_GMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE_1]], i8* undef, i8* undef, %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8 }>* @"$s4main9NamespaceC5ValueVMn" to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| 53.516667 | 348 | 0.631579 |
ef531246a46bd7207aee272822cd18af18be4cb6 | 997 | //
// TaskSchedulerTests.swift
// TaskSchedulerTests
//
// Created by Ben Oztalay on 9/18/15.
// Copyright © 2015 Ben Oztalay. All rights reserved.
//
import XCTest
@testable import TaskScheduler
class TaskSchedulerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| 26.945946 | 111 | 0.641926 |
fe523a844fb003f692c4db97e7b97575501185b7 | 1,197 | //
// MultipleType.swift
// Codable
//
// Created by Nick Lin on 2018/5/26.
// Copyright © 2018年 Nick Lin. All rights reserved.
//
import Foundation
struct MultipleType: Codable {
var count: Int
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
if let val = try? values.decode(String.self, forKey: CodingKeys.count) {
if let value = Int(val) {
count = value
} else if let value = Double(val) {
count = Int(value)
} else {
throw DecodingError.typeMismatch(MultipleType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for MultipleType.count"))
}
} else if let val = try? values.decode(Int.self, forKey: CodingKeys.count) {
count = val
} else if let val = try? values.decode(Double.self, forKey: CodingKeys.count) {
count = Int(val)
} else {
throw DecodingError.typeMismatch(MultipleType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for MultipleType.count"))
}
}
}
| 35.205882 | 177 | 0.624896 |
e6b818b41e314026b7df3e9ae9fabe271615fb84 | 4,439 | //
// NVActivityIndicatorAnimationBallClipRotatePulse.swift
// NVActivityIndicatorView
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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(UIKit)
import UIKit
class NVActivityIndicatorAnimationBallClipRotatePulse: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let duration: CFTimeInterval = 1
let timingFunction = CAMediaTimingFunction(controlPoints: 0.09, 0.57, 0.49, 0.9)
smallCircleWith(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color)
bigCircleWith(duration: duration, timingFunction: timingFunction, layer: layer, size: size, color: color)
}
func smallCircleWith(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: UIColor) {
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform.scale")
animation.keyTimes = [0, 0.3, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.3, 1]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circleSize = size.width / 2
let circle = NVActivityIndicatorShape.circle.layerWith(x: 0, y: 0, size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2,
y: (layer.bounds.size.height - circleSize) / 2,
width: circleSize,
height: circleSize)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
func bigCircleWith(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGSize, color: UIColor) {
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction]
scaleAnimation.values = [1, 0.6, 1]
scaleAnimation.duration = duration
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.timingFunctions = [timingFunction, timingFunction]
rotateAnimation.values = [0, Double.pi, 2 * Double.pi]
rotateAnimation.duration = duration
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circle = NVActivityIndicatorShape.ringTwoHalfVertical.layerWith(x: 0, y: 0, size: size, color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
#endif
| 43.519608 | 141 | 0.686191 |
26d3a25240c44f5e7883469bdc6b7081c69fbc14 | 811 | //
// InverseVolatilitySort.swift
// SwiftStreamgraph
//
// Created by Sean Zehnder on 3/3/17.
// Based on Lee Byron and Martin Wattenberg's Processing Streamgraph code
// Available here: https://github.com/leebyron/streamgraph_generato
// AND obj_streamgraph-generator
// Available here: https://github.com/dominikus/obj_streamgraph-generator
//
import Foundation
class InverseVolatilitySort:LayerSort {
override var name:String {
return "Inverse Volatility Sorting, Evenly Weighted"
}
override func sort(layers:[Layer]) -> [Layer]? {
let sorted = layers.sorted(by: { (p, q) -> Bool in
let volatilityDiff = p.volatility - q.volatility
return (10000000 * volatilityDiff) < 0
})
return self.orderToOutside(layers: sorted)
}
}
| 30.037037 | 74 | 0.681874 |
486c596ec8713f5babd39c8ada153e56434c9d70 | 1,980 | //
// EpubConfig.swift
// AEXML
//
// Created by 小发工作室 on 2019/11/21.
//
import Foundation
import UIKit
import epub_kitty
class EpubConfig: NSObject {
open var config: FolioReaderConfig!
open var tintColor: UIColor = UIColor.green
open var allowSharing: Bool = false
open var scrollDirection: FolioReaderScrollDirection = FolioReaderScrollDirection.vertical
init(Identifier: String,tintColor: UIColor, allowSharing: Bool,scrollDirection: String) {
self.config = FolioReaderConfig(withIdentifier: Identifier)
self.tintColor = tintColor
self.allowSharing = allowSharing
if scrollDirection == "vertical"{
self.config.scrollDirection = FolioReaderScrollDirection.vertical
}else {
self.config.scrollDirection = FolioReaderScrollDirection.horizontal
}
super.init()
self.readerConfiguration()
}
private func readerConfiguration() {
self.config.shouldHideNavigationOnTap = true
self.config.scrollDirection = self.scrollDirection
self.config.enableTTS = false
self.config.displayTitle = true
self.config.allowSharing = self.allowSharing
// self.config.tintColor = self.tintColor
self.config.canChangeFontStyle = false
// Custom sharing quote background
self.config.quoteCustomBackgrounds = []
if let image = UIImage(named: "demo-bg") {
let customImageQuote = QuoteImage(withImage: image, alpha: 0.6, backgroundColor: UIColor.black)
self.config.quoteCustomBackgrounds.append(customImageQuote)
}
let textColor = UIColor(red:0.86, green:0.73, blue:0.70, alpha:1.0)
let customColor = UIColor(red:0.30, green:0.26, blue:0.20, alpha:1.0)
let customQuote = QuoteImage(withColor: customColor, alpha: 1.0, textColor: textColor)
self.config.quoteCustomBackgrounds.append(customQuote)
}
}
| 35.357143 | 107 | 0.676263 |
0af6820f157348b8e6bbe6746d2e7a4c4182b9c0 | 2,147 | //
// ServiceTexasInstrumentsFirmwareUpdate.swift
// BluetoothMessageProtocol
//
// Created by Kevin Hoogheem on 9/9/17.
//
// 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
/// BLE Texas Instruments Firmware Update Service
@available(swift 4.0)
@available(iOS 10.0, tvOS 10.0, watchOS 3.0, OSX 10.12, *)
open class ServiceTexasInstrumentsFirmwareUpdate: Service {
/// Service Name
public static var name: String {
return "Texas Instruments Firmware Update"
}
/// Service UUID
public static var uuidString: String {
return "F000FFC0-0451-4000-B000-000000000000"
}
/// Service Uniform Identifier
public static var uniformIdentifier: String {
return "com.ti.service.firmware_update"
}
/// Creates Texas Instruments Firmware Update Service
public init() {
super.init(name: ServiceTexasInstrumentsFirmwareUpdate.name,
uuidString: ServiceTexasInstrumentsFirmwareUpdate.uuidString,
uniformIdentifier: ServiceTexasInstrumentsFirmwareUpdate.uniformIdentifier
)
}
}
| 39.036364 | 93 | 0.72939 |
eb391c2d8c9cf878c30d58ab8a32460b4c83a805 | 734 | // swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "SwiftyPoeditor",
platforms: [
.macOS(.v10_15)
],
products: [
.executable(name: "swifty-poeditor", targets: ["swifty-poeditor"]),
],
dependencies: [
.package(url: "https://github.com/yanagiba/swift-ast.git", .exact("0.19.9")),
.package(url: "https://github.com/vapor/console-kit.git", from: "4.0.0"),
.package(url: "https://github.com/swift-server/async-http-client.git", from: "1.0.0")
],
targets: [
.target(
name: "swifty-poeditor",
dependencies: ["SwiftAST+Tooling", "AsyncHTTPClient", "ConsoleKit"])
],
swiftLanguageVersions: [.v5]
)
| 29.36 | 93 | 0.591281 |
485db722c8fbd89a92825ffa7ce55c1d507d4da1 | 2,950 | //
// RespositoryTests.swift
// RespositoryTests
//
// Created by Fernando Moya de Rivas on 28/08/2019.
// Copyright © 2019 Fernando Moya de Rivas. All rights reserved.
//
import XCTest
import Domain
import Mockingjay
@testable import Repository
class RespositoryTests: XCTestCase {
let container = RepositoryContainer()
func test_fetchProperties() {
let dataStore = container.dataStore
let expectation = XCTestExpectation(description: "Fetching properties of a mock city")
dataStore.fetchProperties { (response) in
guard let properties = try? response.get() else {
return XCTFail()
}
XCTAssertFalse(properties.isEmpty)
expectation.fulfill()
}
wait(for: [expectation], timeout: 3)
}
func test_fetchProperty() {
let propertyId = "40903"
let dataStore = container.dataStore
let expectation = XCTestExpectation(description: "Fetching property 40903")
dataStore.fetchPropertyDetail(of: propertyId) { (response) in
guard let property = try? response.get() else {
return XCTFail()
}
XCTAssertEqual(property.id, propertyId)
expectation.fulfill()
}
wait(for: [expectation], timeout: 3)
}
func test_fetchProperties_forbidden() {
let dataStore = container.dataStore
stub(uri(HostelWorldEndpoint.properties(1530).url),
http(403))
let expectation = XCTestExpectation(description: "Mocking Forbidden response")
dataStore.fetchProperties { (response) in
switch response {
case .success:
XCTFail()
case .failure(let error):
XCTAssertEqual(error, .forbidden)
}
expectation.fulfill()
}
wait(for: [expectation], timeout: 3)
}
func test_fetchPropertyDetail_unknownError() {
let propertyId = "40903"
let dataStore = container.dataStore
let httpResponseCode = 506
stub(uri(HostelWorldEndpoint.propertyDetail(propertyId).url),
http(httpResponseCode))
let expectation = XCTestExpectation(description: "Mocking Forbidden response")
dataStore.fetchPropertyDetail(of: propertyId) { (response) in
switch response {
case .success:
XCTFail()
case .failure(let error):
if case .unknown(let message) = error {
XCTAssertTrue(message.contains("\(httpResponseCode)"))
} else {
XCTFail()
}
}
expectation.fulfill()
}
wait(for: [expectation], timeout: 3)
}
}
| 29.5 | 94 | 0.561356 |
48d6fa139eac0bd8eb2e2d4f6d303e4cf5028be6 | 3,424 | //
// Corona-Warn-App
//
// SAP SE and all other contributors
// copyright owners license this file to you under the Apache
// License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
import UIKit
/// The `WarnOthers` class behaves as a facade and encaplsulate all relevant logic whether to schedule or not to schedule warn others notifications about a positiv test result.
/// So you only need to pass the result into `evaluateNotificationState(testResult: TestResult)` and all scheduling is managed.
/// Notification scheduling - the app will inform the user 2 times to warn others.
/// WarnOthers always is related to one concrete test result, which always needs to be a positive one.
class WarnOthersReminder: WarnOthersRemindable {
// MARK: - Init
init(store: Store) {
self.store = store
self.hasPositiveTestResult = store.warnOthersHasActiveTestResult
}
// MARK: - Protocol WarnOthersRemindable
var hasPositiveTestResult: Bool {
get {
return store.warnOthersHasActiveTestResult
}
set {
store.warnOthersHasActiveTestResult = newValue
}
}
/// Notification timer in seconds for notification one
var notificationOneTimeInterval: TimeInterval {
get {
return store.warnOthersNotificationOneTimer
}
set {
store.warnOthersNotificationOneTimer = newValue
}
}
/// Notification timer in seconds for notification two
var notificationTwoTimeInterval: TimeInterval {
get {
return store.warnOthersNotificationTwoTimer
}
set {
store.warnOthersNotificationTwoTimer = newValue
}
}
/// This function takes a `TestResult` as parameter to evaluate, if possible notifications need to be scheduled for the warn others notification process.
func evaluateNotificationState(testResult: TestResult) {
// If incoming test restuls are others than positive, we don't deal with them
guard testResult == .positive, hasPositiveTestResult == false else { return }
// We are "clean" to go. So lock the door until result was removed
hasPositiveTestResult = true
scheduleNotifications()
}
func reset() {
cancelNotifications()
hasPositiveTestResult = false
Log.info("Warn others have been resetted")
}
/// In case the user has informed others about the positive result, this function should be called to reset possible pending 'warn others' notifications
func cancelNotifications() {
UNUserNotificationCenter.current().cancelWarnOthersNotification()
Log.info("Warn others: All notifications have been canceled")
}
// MARK: - Private
private let store: Store
private func scheduleNotifications() {
UNUserNotificationCenter.current().scheduleWarnOthersNotifications(
timeIntervalOne: TimeInterval(notificationOneTimeInterval),
timeIntervalTwo: TimeInterval(notificationTwoTimeInterval)
)
Log.info("Warn Others: New notifications have been scheduled: #1 \(store.warnOthersNotificationOneTimer)/ #2 \(store.warnOthersNotificationTwoTimer) seconds)")
}
}
| 33.242718 | 177 | 0.762266 |
c1d460fa61f2da1d9b80ad16ee096609ea2265d0 | 22,134 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_struct.swiftmodule -module-name resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -I %t -emit-module -emit-module-path=%t/resilient_class.swiftmodule -module-name resilient_class %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -enable-resilience -emit-silgen -parse-as-library -I %t %s | %FileCheck %s
import resilient_class
func doFoo(_ f: () -> ()) {
f()
}
public class Parent {
public init() {}
public func method() {}
public final func finalMethod() {}
public class func classMethod() {}
public final class func finalClassMethod() {}
}
public class GenericParent<A> {
let a: A
public init(a: A) {
self.a = a
}
public func method() {}
public final func finalMethod() {}
public class func classMethod() {}
public final class func finalClassMethod() {}
}
class Child : Parent {
// CHECK-LABEL: sil hidden @_T019partial_apply_super5ChildC6methodyyF : $@convention(method) (@guaranteed Child) -> ()
// CHECK: bb0([[SELF:%.*]] : $Child):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC6methodyyFTcTd : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super5ChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super5ChildC11classMethodyyFZ : $@convention(method) (@thick Child.Type) -> () {
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC11classMethodyyFZTcTd : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super5ChildC20callFinalSuperMethodyyF : $@convention(method) (@guaranteed Child) -> ()
// CHECK: bb0([[SELF:%.*]] : $Child):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $Child to $Parent
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC11finalMethodyyFTc : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> ()
// CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(thin) (@owned Parent) -> @owned @callee_owned () -> ()
// CHECK: apply [[DOFOO]]([[APPLIED_SELF]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super5ChildC20callFinalSuperMethodyyF'
func callFinalSuperMethod() {
doFoo(super.finalMethod)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super5ChildC25callFinalSuperClassMethodyyFZ : $@convention(method) (@thick Child.Type) -> ()
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super6ParentC16finalClassMethodyyFZTc : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> ()
// CHECK: [[APPLIED_SELF:%[0-9]+]] = apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(thin) (@thick Parent.Type) -> @owned @callee_owned () -> ()
// CHECK: apply [[DOFOO]]([[APPLIED_SELF]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
class func callFinalSuperClassMethod() {
doFoo(super.finalClassMethod)
}
}
class GenericChild<A> : GenericParent<A> {
override init(a: A) {
super.init(a: a)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super12GenericChildC6methodyyF : $@convention(method) <A> (@guaranteed GenericChild<A>) -> ()
// CHECK: bb0([[SELF:%.*]] : $GenericChild<A>):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GenericChild<A> to $GenericParent<A>
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super13GenericParentC6methodyyFTcTd : $@convention(thin) <τ_0_0> (@owned GenericParent<τ_0_0>) -> @owned @callee_owned () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(thin) <τ_0_0> (@owned GenericParent<τ_0_0>) -> @owned @callee_owned () -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super12GenericChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super12GenericChildC11classMethodyyFZ : $@convention(method) <A> (@thick GenericChild<A>.Type) -> ()
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChild<A>.Type to $@thick GenericParent<A>.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T019partial_apply_super13GenericParentC11classMethodyyFZTcTd : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> @owned @callee_owned () -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = apply %4<A>(%3) : $@convention(thin) <τ_0_0> (@thick GenericParent<τ_0_0>.Type) -> @owned @callee_owned () -> ()
// CHECK: apply %2(%5) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class ChildToFixedOutsideParent : OutsideParent {
// CHECK-LABEL: sil hidden @_T019partial_apply_super25ChildToFixedOutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $ChildToFixedOutsideParent):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $ChildToFixedOutsideParent to $OutsideParent
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $ChildToFixedOutsideParent, #OutsideParent.method!1 : (OutsideParent) -> () -> (), $@convention(method) (@guaranteed OutsideParent) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed OutsideParent) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super25ChildToFixedOutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super25ChildToFixedOutsideParentC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick ChildToFixedOutsideParent.Type to $@thick OutsideParent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick ChildToFixedOutsideParent.Type, #OutsideParent.classMethod!1 : (OutsideParent.Type) -> () -> (), $@convention(method) (@thick OutsideParent.Type) -> (){{.*}} // user: %5
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick OutsideParent.Type) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class ChildToResilientOutsideParent : ResilientOutsideParent {
// CHECK-LABEL: sil hidden @_T019partial_apply_super29ChildToResilientOutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $ChildToResilientOutsideParent):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $ChildToResilientOutsideParent to $ResilientOutsideParent
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $ChildToResilientOutsideParent, #ResilientOutsideParent.method!1 : (ResilientOutsideParent) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideParent) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed ResilientOutsideParent) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super29ChildToResilientOutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super29ChildToResilientOutsideParentC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick ChildToResilientOutsideParent.Type to $@thick ResilientOutsideParent.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick ChildToResilientOutsideParent.Type, #ResilientOutsideParent.classMethod!1 : (ResilientOutsideParent.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideParent.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick ResilientOutsideParent.Type) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GrandchildToFixedOutsideChild : OutsideChild {
// CHECK-LABEL: sil hidden @_T019partial_apply_super29GrandchildToFixedOutsideChildC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GrandchildToFixedOutsideChild):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GrandchildToFixedOutsideChild to $OutsideChild
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GrandchildToFixedOutsideChild, #OutsideChild.method!1 : (OutsideChild) -> () -> (), $@convention(method) (@guaranteed OutsideChild) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed OutsideChild) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super29GrandchildToFixedOutsideChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super29GrandchildToFixedOutsideChildC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GrandchildToFixedOutsideChild.Type to $@thick OutsideChild.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GrandchildToFixedOutsideChild.Type, #OutsideChild.classMethod!1 : (OutsideChild.Type) -> () -> (), $@convention(method) (@thick OutsideChild.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply %4(%3) : $@convention(method) (@thick OutsideChild.Type) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GrandchildToResilientOutsideChild : ResilientOutsideChild {
// CHECK-LABEL: sil hidden @_T019partial_apply_super33GrandchildToResilientOutsideChildC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GrandchildToResilientOutsideChild):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GrandchildToResilientOutsideChild to $ResilientOutsideChild
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GrandchildToResilientOutsideChild, #ResilientOutsideChild.method!1 : (ResilientOutsideChild) -> () -> (), $@convention(method) (@guaranteed ResilientOutsideChild) -> ()
// CHEC: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF_COPY]]) : $@convention(method) (@guaranteed ResilientOutsideChild) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super33GrandchildToResilientOutsideChildC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super33GrandchildToResilientOutsideChildC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GrandchildToResilientOutsideChild.Type to $@thick ResilientOutsideChild.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GrandchildToResilientOutsideChild.Type, #ResilientOutsideChild.classMethod!1 : (ResilientOutsideChild.Type) -> () -> (), $@convention(method) (@thick ResilientOutsideChild.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]([[CASTED_SELF]]) : $@convention(method) (@thick ResilientOutsideChild.Type) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GenericChildToFixedGenericOutsideParent<A> : GenericOutsideParent<A> {
// CHECK-LABEL: sil hidden @_T019partial_apply_super019GenericChildToFixedD13OutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GenericChildToFixedGenericOutsideParent<A>):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GenericChildToFixedGenericOutsideParent<A> to $GenericOutsideParent<A>
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GenericChildToFixedGenericOutsideParent<A>, #GenericOutsideParent.method!1 : <A> (GenericOutsideParent<A>) -> () -> (), $@convention(method) <τ_0_0> (@guaranteed GenericOutsideParent<τ_0_0>) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed GenericOutsideParent<τ_0_0>) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super019GenericChildToFixedD13OutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super019GenericChildToFixedD13OutsideParentC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChildToFixedGenericOutsideParent<A>.Type to $@thick GenericOutsideParent<A>.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChildToFixedGenericOutsideParent<A>.Type, #GenericOutsideParent.classMethod!1 : <A> (GenericOutsideParent<A>.Type) -> () -> (), $@convention(method) <τ_0_0> (@thick GenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@thick GenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
class GenericChildToResilientGenericOutsideParent<A> : ResilientGenericOutsideParent<A> {
// CHECK-LABEL: sil hidden @_T019partial_apply_super023GenericChildToResilientD13OutsideParentC6methodyyF
// CHECK: bb0([[SELF:%.*]] : $GenericChildToResilientGenericOutsideParent<A>):
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CASTED_SELF_COPY:%[0-9]+]] = upcast [[SELF_COPY]] : $GenericChildToResilientGenericOutsideParent<A> to $ResilientGenericOutsideParent<A>
// CHECK: [[BORROWED_CASTED_SELF_COPY:%.*]] = begin_borrow [[CASTED_SELF_COPY]]
// CHECK: [[DOWNCAST_BORROWED_CASTED_SELF_COPY:%.*]] = unchecked_ref_cast [[BORROWED_CASTED_SELF_COPY]]
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method [[DOWNCAST_BORROWED_CASTED_SELF_COPY]] : $GenericChildToResilientGenericOutsideParent<A>, #ResilientGenericOutsideParent.method!1 : <A> (ResilientGenericOutsideParent<A>) -> () -> (), $@convention(method) <τ_0_0> (@guaranteed ResilientGenericOutsideParent<τ_0_0>) -> ()
// CHECK: end_borrow [[BORROWED_CASTED_SELF_COPY]] from [[CASTED_SELF_COPY]]
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF_COPY]]) : $@convention(method) <τ_0_0> (@guaranteed ResilientGenericOutsideParent<τ_0_0>) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: } // end sil function '_T019partial_apply_super023GenericChildToResilientD13OutsideParentC6methodyyF'
override func method() {
doFoo(super.method)
}
// CHECK-LABEL: sil hidden @_T019partial_apply_super023GenericChildToResilientD13OutsideParentC11classMethodyyFZ
// CHECK: [[DOFOO:%[0-9]+]] = function_ref @_T019partial_apply_super5doFooyyycF : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
// CHECK: [[CASTED_SELF:%[0-9]+]] = upcast %0 : $@thick GenericChildToResilientGenericOutsideParent<A>.Type to $@thick ResilientGenericOutsideParent<A>.Type
// CHECK: [[SUPER_METHOD:%[0-9]+]] = super_method %0 : $@thick GenericChildToResilientGenericOutsideParent<A>.Type, #ResilientGenericOutsideParent.classMethod!1 : <A> (ResilientGenericOutsideParent<A>.Type) -> () -> (), $@convention(method) <τ_0_0> (@thick ResilientGenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: [[PARTIAL_APPLY:%[0-9]+]] = partial_apply [[SUPER_METHOD]]<A>([[CASTED_SELF]]) : $@convention(method) <τ_0_0> (@thick ResilientGenericOutsideParent<τ_0_0>.Type) -> ()
// CHECK: apply [[DOFOO]]([[PARTIAL_APPLY]]) : $@convention(thin) (@owned @callee_owned () -> ()) -> ()
override class func classMethod() {
doFoo(super.classMethod)
}
}
| 80.781022 | 325 | 0.684196 |
14b64edf0adaab3433eb022517a5c335d212fd03 | 1,112 | import UIKit
class CollectionViewCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: .zero)
setupProperties()
setupViewHierarchy()
setupLayoutConstraints()
setupReactiveBindings()
}
// MARK: Abstract
/// Sets up the properties of `self`. Called automatically on `init(frame:)`.
func setupProperties() {
// no-op by default
}
/// Sets up self views hierarchy and subviews in `self`. Called automatically on `init(frame:)`.
func setupViewHierarchy() {
// no-op by default
}
/// Sets up layout in `self`. Called automatically on `init(frame:)`.
func setupLayoutConstraints() {
// no-op by default
}
/// Sets up bindings in `self`. Called automatically on `init(frame:)`.
func setupReactiveBindings() {
// no-op by default
}
@available(*, unavailable, message: "Use init(frame:) instead")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CollectionViewCell: Reusable {}
| 26.47619 | 100 | 0.633094 |
d56c4e947db27825ae8bbc7d8a66bd1594dde26c | 3,618 | //
// PinView.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-10-28.
// Copyright © 2016 breadwallet LLC. All rights reserved.
//
import UIKit
enum PinViewStyle {
case create
case login
}
class PinView : UIView {
//MARK: - Public
var itemSize: CGFloat {
switch style {
case .create:
return 24.0
case .login:
return 16.0
}
}
var width: CGFloat {
return (itemSize + C.padding[1]) * CGFloat(length)
}
let shakeDuration: CFTimeInterval = 0.6
fileprivate var shakeCompletion: (() -> Void)?
init(style: PinViewStyle, length: Int) {
self.style = style
self.length = length
switch style {
case .create:
unFilled = (0...(length-1)).map { _ in Circle(color: .borderGray) }
case .login:
unFilled = (0...(length-1)).map { _ in Circle(color: .white) }
}
filled = (0...(length-1)).map { _ in Circle(color: .black) }
super.init(frame: CGRect())
setupSubviews()
}
func fill(_ number: Int) {
filled.enumerated().forEach { index, circle in
circle.isHidden = index > number-1
}
}
func shake(completion: (() -> Void)? = nil) {
shakeCompletion = completion
let translation = CAKeyframeAnimation(keyPath: "transform.translation.x");
translation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
translation.values = [-5, 5, -5, 5, -3, 3, -2, 2, 0]
let rotation = CAKeyframeAnimation(keyPath: "transform.rotation.y");
rotation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
rotation.values = [-5, 5, -5, 5, -3, 3, -2, 2, 0].map {
self.toRadian(value: $0)
}
let shakeGroup: CAAnimationGroup = CAAnimationGroup()
shakeGroup.animations = [translation, rotation]
shakeGroup.duration = shakeDuration
shakeGroup.delegate = self
self.layer.add(shakeGroup, forKey: "shakeIt")
}
//MARK: - Private
private let unFilled: [Circle]
private var filled: [Circle]
private let style: PinViewStyle
private let length: Int
private func toRadian(value: Int) -> CGFloat {
return CGFloat(Double(value) / 180.0 * .pi)
}
private func setupSubviews() {
addCircleContraints(unFilled)
addCircleContraints(filled)
filled.forEach { $0.isHidden = true }
}
private func addCircleContraints(_ circles: [Circle]) {
circles.enumerated().forEach { index, circle in
addSubview(circle)
let leadingConstraint: NSLayoutConstraint?
if index == 0 {
leadingConstraint = circle.constraint(.leading, toView: self, constant: 0.0)
} else {
leadingConstraint = NSLayoutConstraint(item: circle, attribute: .leading, relatedBy: .equal, toItem: circles[index - 1], attribute: .trailing, multiplier: 1.0, constant: 8.0)
}
circle.constrain([
circle.constraint(.width, constant: itemSize),
circle.constraint(.height, constant: itemSize),
circle.constraint(.centerY, toView: self, constant: nil),
leadingConstraint ])
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PinView : CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
shakeCompletion?()
}
}
| 31.46087 | 190 | 0.600884 |
67c297f5e60da50d5081d5d6da160d7520a8813c | 290 | //
// HUHttpMethods.swift
// HttpUtility
//
// Created by CodeCat15 on 1/22/21.
// Copyright © 2021 CodeCat15. All rights reserved.
//
import Foundation
public enum HUHttpMethods : String
{
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
| 16.111111 | 52 | 0.641379 |
e287ef92dde24bdb6e644e6860833a8e760262c5 | 1,347 | //
// AppDelegate.swift
// MVDV
//
// Created by YEONGJUNG KIM on 2021/12/29.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 36.405405 | 179 | 0.74536 |
fee361337daf0ce651b928eceb18a1f4a4e550a5 | 3,341 | //
// Validator.swift
// Cosmostation
//
// Created by yongjoo on 22/03/2019.
// Copyright © 2019 wannabit. All rights reserved.
//
import Foundation
public class Validator {
let UNBONDED = 0;
let UNBONDING = 1;
let BONDED = 2;
var operator_address: String = ""
var consensus_pubkey: String = ""
var jailed: Bool = false
var status: Int = -1;
var tokens: String = "";
var delegator_shares: String = "";
var bond_height: String = "";
var unbonding_height: String = "";
var unbonding_time: String = "";
var description: Description = Description.init();
var commission: Commission = Commission.init();
init(_ dictionary: [String: Any]) {
self.operator_address = dictionary["operator_address"] as? String ?? ""
self.consensus_pubkey = dictionary["operator_address"] as? String ?? ""
self.jailed = dictionary["jailed"] as? Bool ?? false
self.status = dictionary["status"] as? Int ?? -1
self.tokens = dictionary["tokens"] as? String ?? ""
self.delegator_shares = dictionary["delegator_shares"] as? String ?? ""
self.bond_height = dictionary["bond_height"] as? String ?? ""
self.unbonding_height = dictionary["unbonding_height"] as? String ?? ""
self.unbonding_time = dictionary["unbonding_time"] as? String ?? ""
self.description = Description.init(dictionary["description"] as! [String : Any])
self.commission = Commission.init(dictionary["commission"] as! [String : Any])
}
public class Description {
var moniker: String = ""
var identity: String = ""
var website: String = "";
var details = "";
init() {}
init(_ dictionary: [String: Any]) {
self.moniker = dictionary["moniker"] as? String ?? ""
self.identity = dictionary["identity"] as? String ?? ""
self.website = dictionary["website"] as? String ?? ""
self.details = dictionary["details"] as? String ?? ""
}
}
public class Commission {
var rate: String = ""
var max_rate: String = ""
var max_change_rate: String = "";
var update_time: String = "";
var commission_rates: CommissionRate = CommissionRate.init();
init() {}
init(_ dictionary: [String: Any]) {
self.rate = dictionary["rate"] as? String ?? ""
self.max_rate = dictionary["max_rate"] as? String ?? ""
self.max_change_rate = dictionary["max_change_rate"] as? String ?? ""
self.update_time = dictionary["update_time"] as? String ?? ""
if let commission_rates = dictionary["commission_rates"] as? [String : Any] {
self.commission_rates = CommissionRate.init(commission_rates)
}
}
}
public class CommissionRate {
var rate: String = ""
var max_rate: String = ""
var max_change_rate: String = "";
init() {}
init(_ dictionary: [String: Any]) {
self.rate = dictionary["rate"] as? String ?? ""
self.max_rate = dictionary["max_rate"] as? String ?? ""
self.max_change_rate = dictionary["max_change_rate"] as? String ?? ""
}
}
}
| 34.443299 | 89 | 0.57378 |
7a9830ebb5ace7799c8593fb163a0ea80c0c4f19 | 2,676 | import Foundation
import CommonCrypto
struct AES {
private let key: Data
private let iv: Data
init(key: Data, iv: Data) throws{
guard key.count == kCCKeySizeAES256 || key.count == kCCKeySizeAES128 else {
throw Error.badKeyLength
}
guard iv.count == kCCBlockSizeAES128 else {
throw Error.badInputVectorLength
}
self.key = key
self.iv = iv
}
enum Error: Swift.Error {
case keyGeneration(status: Int)
case cryptoFailed(status: CCCryptorStatus)
case badKeyLength
case badInputVectorLength
}
func encrypt(raw: Data) throws-> Data {
return try crypt(data: raw, option: CCOperation(kCCEncrypt))
}
func decrypt(raw: Data) throws-> Data {
return try crypt(data: raw, option: CCOperation(kCCDecrypt))
}
func crypt(data: Data, option: CCOperation) throws -> Data {
var outputBytes = [UInt8](repeating: 0, count: data.count + kCCBlockSizeAES128);
var outputLength = Int(0)
let status = data.withUnsafeBytes { dataBytes in
iv.withUnsafeBytes { ivBytes in
key.withUnsafeBytes { keyBytes in
CCCrypt(
option, // encrypt | decrypt
CCAlgorithm(kCCAlgorithmAES), // aes
CCOptions(ccNoPadding), // padding
keyBytes, // key
key.count, // 128 | 256
ivBytes, // iv
dataBytes, // raw input
data.count, // raw input length
&outputBytes, // output
outputBytes.count, // output length
&outputLength) // actual output size
}
}
}
guard status == kCCSuccess else {
print(status)
throw Error.cryptoFailed(status: status)
}
return Data(bytes: UnsafePointer<UInt8>(outputBytes), count: outputLength)
}
}
extension Data {
struct HexEncodingOptions: OptionSet {
let rawValue: Int
static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
}
func hexEncodedString(options: HexEncodingOptions = []) -> String {
let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
return map { String(format: format, $0) }.joined()
}
}
| 33.873418 | 89 | 0.50299 |
72b538a3c7e2b44c4c871d955914852250ddb9d9 | 2,874 | //
// InlineButtons.swift
// MyMonero
//
// Created by Paul Shapiro on 5/3/18.
// Copyright (c) 2014-2019, MyMonero.com
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
import UIKit
//
extension UICommonComponents
{
class InlineButton: UIButton
{
static let fixedHeight: CGFloat = UIFont.shouldStepDownLargerFontSizes ? 40 : 42
// TODO: style
enum InlineButtonType
{
case utility
}
var inlineButtonType: InlineButtonType
init(inlineButtonType: InlineButtonType)
{
self.inlineButtonType = inlineButtonType
super.init(frame: .zero)
self.setup()
}
func setup()
{
let font: UIFont = UIFont.shouldStepDownLargerFontSizes ? .middlingSemiboldSansSerif : .largeSemiboldSansSerif
var color: UIColor!
var backgroundColor: UIColor!
var cornerRadius: CGFloat!
let disabledColor = UIColor(rgb: 0x6B696B)
switch self.inlineButtonType
{
case .utility:
color = UIColor(rgb: 0xFCFBFC)
backgroundColor = UIColor(rgb: 0x383638)
cornerRadius = InlineButton.fixedHeight/2
break
}
self.layer.cornerRadius = cornerRadius
self.backgroundColor = backgroundColor
self.titleLabel!.font = font
self.setTitleColor(color, for: .normal)
self.setTitleColor(disabledColor, for: .disabled)
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
}
}
| 34.626506 | 113 | 0.743911 |
9c1584cea1251e1dc6aaca51fcb17f6697c22181 | 421 | //
// AppDelegate.swift
// Haptics
//
// Created by Rui Aureliano on 08/01/2020.
// Copyright © 2020 Rui Aureliano. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
}
| 21.05 | 142 | 0.752969 |
01bafe1f7dd77f3c16250e8e1ff5c22ed9e5d5b3 | 1,557 | import Foundation
import HexavilleFramework
public enum HexavilleAuthError: Error {
case unsupportedPlaform
case codeIsMissingInResponseParameters
case responseError(HTTPURLResponse, Data)
}
extension HexavilleAuthError: CustomStringConvertible {
public var description: String {
switch self {
case .responseError(let response, let body):
var str = ""
str += "\(response)"
str += "\n"
str += "\n"
str += String(data: body, encoding: .utf8) ?? "Unknown Error"
return str
default:
return "\(self)"
}
}
}
public enum CredentialProviderType {
case oauth2(OAuth2AuthorizationProvidable)
case oauth1(OAuth1AuthorizationProvidable)
}
public struct HexavilleAuth {
var providers: [CredentialProviderType] = []
public init() {}
public mutating func add(_ provider: OAuth1AuthorizationProvidable) {
self.providers.append(.oauth1(provider))
}
public mutating func add(_ provider: OAuth2AuthorizationProvidable) {
self.providers.append(.oauth2(provider))
}
}
extension ApplicationContext {
public func isAuthenticated() -> Bool {
return loginUser != nil
}
public var loginUser: LoginUser? {
get {
return memory[HexavilleAuth.AuthenticationMiddleware.sessionKey] as? LoginUser
}
set {
return memory[HexavilleAuth.AuthenticationMiddleware.sessionKey] = newValue
}
}
}
| 25.95 | 90 | 0.634554 |
bbc36f04ec1ab92b655fc001afb0ac765b17b14c | 536 | var episode = 220
var villain: String
switch episode {
case 1...3:
villain = "Emperor Palpatine"
case 4...6:
villain = "Darth Vader"
case 7...9:
villain = "Kylo Ren"
default:
villain = ""
}
print(villain)
/*
var year = 1943
switch year {
case 1701...1800:
print("18th century")
case 1801...1900:
print("19th century")
case 1901...2000:
print("20th century")
case 2001...2100:
print("21st century")
default:
print("You're a time traveler!")
}
// Prints: 20th century
*/ | 15.764706 | 36 | 0.597015 |
3a80bac0d6f90f0c83ac8b8ef19521f19aa35e01 | 5,379 | import MetalKit
import AVFoundation
//MARK: - GAME VIEW
//---------------------
// GAME VIEW
//---------------------
// Enum with the scenes
public enum SceneEnum: Int {
case Scene1
case Scene2
case Scene3
case Scene4
}
// View responsible for building the base of the Metal environment.
public class GameView: MTKView {
var commandQueue: MTLCommandQueue!
private var presentScene: Scene?
private var scenes = [Scene]()
private var currentScene = 0
var drumAudioPlayer: AVAudioPlayer!
var mainAudioPlayer: AVAudioPlayer!
override public init(frame: CGRect, device: MTLDevice?) {
super.init(frame: frame, device: device)
configureView()
guard let url_drum = Bundle.main.url(forResource: "Audio_Drum", withExtension: "mp3") else {
fatalError("Error on load resource")
}
drumAudioPlayer = try? AVAudioPlayer(contentsOf: url_drum)
drumAudioPlayer?.isMeteringEnabled = true
drumAudioPlayer?.play()
drumAudioPlayer?.numberOfLoops = -1
guard let url_main = Bundle.main.url(forResource: "Audio_Music", withExtension: "mp3") else {
fatalError("Error on load resource")
}
mainAudioPlayer = try? AVAudioPlayer(contentsOf: url_main)
mainAudioPlayer?.isMeteringEnabled = true
mainAudioPlayer?.play()
mainAudioPlayer?.numberOfLoops = -1
scenes.append(Scene_1(audioPlayer: drumAudioPlayer))
scenes.append(Scene_2(audioPlayer: drumAudioPlayer))
scenes.append(Scene_3(audioPlayer: drumAudioPlayer))
scenes.append(Scene_4(audioPlayer: drumAudioPlayer))
self.setPresentScene(scene: scenes[currentScene])
}
required public init(coder: NSCoder) {
super.init(coder: coder)
configureView()
}
//Make initial view settings
public func configureView() {
self.device = MTLCreateSystemDefaultDevice()
self.commandQueue = self.device!.makeCommandQueue()!
self.framebufferOnly = false
configureButtons()
}
//Create the view buttons
func configureButtons() {
let buttonLeft_Unpressed = NSImage(named: NSImage.Name(rawValue: "Image_Left_Unpressed"))!
let buttonLeft_Pressed = NSImage(named: NSImage.Name(rawValue: "Image_Left_Pressed"))!
let buttonLeft = NSButton(image: buttonLeft_Unpressed,
target: self, action: #selector(nextLeftScene))
buttonLeft.isTransparent = true
buttonLeft.frame = NSRect(origin: CGPoint(x: 0, y: 0),
size: NSSize(width: 60, height: 60))
buttonLeft.alternateImage = buttonLeft_Pressed
self.addSubview(buttonLeft)
let buttonRight_Unpressed = NSImage(named: NSImage.Name(rawValue: "Image_Right_Unpressed"))!
let buttonRight_Pressed = NSImage(named: NSImage.Name(rawValue: "Image_Right_Pressed"))!
let buttonRight = NSButton(image: buttonRight_Unpressed,
target: self, action: #selector(nextRightScene))
buttonRight.isTransparent = true
buttonRight.frame = NSRect(origin: CGPoint(x: self.bounds.width - 60,
y: 0),
size: NSSize(width: 60, height: 60))
buttonRight.alternateImage = buttonRight_Pressed
self.addSubview(buttonRight)
}
override public func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
presentScene?.render(commandQueue: commandQueue)
}
private func setPresentScene(scene: Scene) {
scene.setupSceneWith(view: self, device: device!)
self.presentScene = scene
}
//Send the mouse data for the uniform in present scene
public override func mouseDragged(with event: NSEvent) {
self.presentScene?.uniform.mouse += normalize(float3(
Float(event.deltaX/100),
Float(event.deltaY/100), 1.0))
}
//Send the mouse data for the uniform in present scene
public override func scrollWheel(with event: NSEvent) {
if let scene = presentScene {
if scene.uniform.axis.z < 0 && event.scrollingDeltaY < 0{
return
}
if scene.uniform.axis.z > 9 && event.scrollingDeltaY > 0{
return
}
self.presentScene?.uniform.axis += float3(0, 0, Float(event.scrollingDeltaY));
}
}
@objc
public func nextRightScene() {
if currentScene >= scenes.count - 1 {
currentScene = 0
}else {
currentScene += 1
}
self.setPresentScene(scene: scenes[currentScene])
}
@objc
public func nextLeftScene() {
if currentScene <= 0 {
currentScene = scenes.count - 1
}else {
currentScene -= 1
}
self.setPresentScene(scene: scenes[currentScene])
}
public func present(scene: SceneEnum) {
currentScene = scene.rawValue
self.setPresentScene(scene: scenes[scene.rawValue])
}
}
| 32.209581 | 101 | 0.593233 |
f4e330b20b3bc42d650eee005d3a431257137b8e | 4,221 | //
// MemoRepository.swift
// WithBook-Development
//
// Created by shintykt on 2020/05/04.
// Copyright © 2020 Takaya Shinto. All rights reserved.
//
import FirebaseFirestore
import FirebaseStorage
import RxFirebase
import RxSwift
protocol MemoCRUD {
func listenMemos(about book: Book) -> Observable<[Memo]>
func add(_ memo: Memo, about book: Book) -> Observable<Void>
func replace(_ memo: Memo, about book: Book) -> Observable<Void>
func remove(_ memo: Memo, about book: Book) -> Observable<Void>
}
struct MemoRepository {
private let bookRepository: BookReference
init(bookRepository: BookReference = BookRepository()) {
self.bookRepository = bookRepository
}
}
extension MemoRepository: MemoCRUD {
// メモを監視(Firestoreで更新がある度に呼び出し)
func listenMemos(about book: Book) -> Observable<[Memo]> {
return memosCollection(about: book)?
.order(by: "createdTime", descending: false)
.rx
.listen()
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.observeOn(ConcurrentDispatchQueueScheduler(qos: .background))
.map { snapshot -> [Memo] in
return snapshot.documents
.map { try? MemoEntity(from: $0) }
.compactMap { $0 }
.map {
return Memo(
id: $0.documentId,
createdTime: $0.createdTime.dateValue(),
updatedTime: $0.updatedTime?.dateValue(),
title: $0.title,
text: $0.text,
image: nil
)
}
} ?? .empty()
}
// メモを追加
func add(_ memo: Memo, about book: Book) -> Observable<Void> {
return Observable.create { observer in
let docData: [String: Any] = [
"createdTime": Timestamp(date: memo.createdTime),
"updatedTime": NSNull(),
"title": memo.title,
"text": memo.text ?? NSNull(),
"imageURL": NSNull()
]
// TODO: "imageURL"処理
self.memosCollection(about: book)?.document(memo.id).setData(docData) { error in
if let error = error { observer.onError(error); return }
observer.onNext(())
observer.onCompleted()
}
return Disposables.create()
}
}
// メモを更新
func replace(_ memo: Memo, about book: Book) -> Observable<Void> {
return Observable.create { observer in
let docData: [String: Any] = [
"createdTime": Timestamp(date: memo.createdTime),
"updatedTime": Timestamp(date: Date()),
"title": memo.title,
"text": memo.text ?? NSNull(),
"imageURL": NSNull()
]
// TODO: "imageURL"処理
self.memosCollection(about: book)?.document(memo.id).setData(docData) { error in
if let error = error { observer.onError(error); return }
observer.onNext(())
observer.onCompleted()
}
return Disposables.create()
}
}
// メモを削除
func remove(_ memo: Memo, about book: Book) -> Observable<Void> {
return Observable.create { observer in
// TODO: "imageURL"処理
self.memosCollection(about: book)?.document(memo.id).delete { error in
if let error = error { observer.onError(error); return }
observer.onNext(())
observer.onCompleted()
}
return Disposables.create()
}
}
}
private extension MemoRepository {
func memosCollection(about book: Book) -> CollectionReference? {
return bookRepository.booksCollection()?.document(book.id).collection("memos")
}
func memoImagesStorage(about book: Book) -> StorageReference? {
return bookRepository.bookImagesStorage()?.child(book.id).child("memoImages")
}
}
| 34.317073 | 92 | 0.534234 |
efc1cda41f8af7d9d4e8ed3c0d30b1675cb8c473 | 56 | import Foundation
class FDbAlgoAidItem:FDbAlgoItem
{
}
| 9.333333 | 32 | 0.821429 |
3a2ff81a34f20e46fd4bc1a6572957a75d6654cc | 3,419 | //
// BookDetailsPresenter.swift
// Library
//
// Created by Cosmin Stirbu on 2/23/17.
// MIT License
//
// Copyright (c) 2017 Fortech
//
// 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
protocol BookDetailsView: class {
func displayScreenTitle(title: String)
func display(id: String)
func display(isbn: String)
func display(title: String)
func display(author: String)
func display(pages: String)
func display(releaseDate: String)
func displayDeleteBookError(title: String, message: String)
func updateCancelButtonState(isEnabled enabled: Bool)
}
protocol BookDetailsPresenter {
var router: BookDetailsViewRouter { get }
func viewDidLoad()
func deleteButtonPressed()
}
class BookDetailsPresenterImplementation: BookDetailsPresenter {
fileprivate let book: Book
fileprivate let deleteBookUseCase: DeleteBookUseCase
let router: BookDetailsViewRouter
fileprivate weak var view: BookDetailsView?
init(view: BookDetailsView,
book: Book,
deleteBookUseCase: DeleteBookUseCase,
router: BookDetailsViewRouter) {
self.view = view
self.book = book
self.deleteBookUseCase = deleteBookUseCase
self.router = router
}
func viewDidLoad() {
view?.display(id: book.id)
view?.display(isbn: book.isbn)
view?.display(title: book.title)
view?.display(author: book.author)
view?.display(pages: "\(book.pages) pages")
view?.display(releaseDate: book.releaseDate?.relativeDescription() ?? "")
}
func deleteButtonPressed() {
view?.updateCancelButtonState(isEnabled: false)
deleteBookUseCase.delete(book: book) { (result) in
self.view?.updateCancelButtonState(isEnabled: true)
switch result {
case .success(_):
self.handleBookDeleted()
case let .failure(error):
self.handleBookDeleteError(error)
}
}
}
// MARK: - Private
fileprivate func handleBookDeleted() {
// Here we could use a similar approach like on AddBookViewController and call a delegate like we do when adding a book
// However we want to provide a different example - depending on the complexity of you particular case
// You can chose one way or the other
router.dismissView()
}
fileprivate func handleBookDeleteError(_ error: Error) {
// Here we could check the error code and display a localized error message
view?.displayDeleteBookError(title: "Error", message: error.localizedDescription)
}
}
| 34.19 | 121 | 0.750804 |
ddbb0f564756391925b0fd80ef307e9214def5e5 | 9,157 | //
// AKRefreshView.swift
// AKRefresh
//
// Created by liuchang on 2016/11/30.
// Copyright © 2016年 com.unknown. All rights reserved.
//
import UIKit
public enum AKRefreshViewStatus:Int {
case normal = 1
case willLoading = 2
case loading = 3
}
public protocol AKRefreshViewControl{
func refreshViewChangeUIWhenNormal(_ refreshView:AKRefreshViewType)
func refreshViewChangeUIWhenWillLoading(_ refreshView:AKRefreshViewType)
func refreshViewChangeUIWhenLoading(_ refreshView:AKRefreshViewType)
func refreshViewChangeUIWhenFinish(_ refreshView:AKRefreshViewType)
}
public protocol AKRefreshViewType{
// associatedtype baseView
var scrollView : UIScrollView?{get}
var scrollViewOriginalInsets : UIEdgeInsets {get}
var refreshAction : (()->())! {get set}
var status : AKRefreshViewStatus {get set}
var previousState : AKRefreshViewStatus {get}
var indicator:AKRefreshIndicator?{get set}
var progress : CGFloat {get}
func endRefresh(complete:((AKRefreshViewType)->())?)
func startRefresh()
/**
* 根据scrollView的属性计算出空间将要显示的位置
*
* @param scrollViewInsets scrollView 原始的 contentInsets
* @param offset scrollView 当前(滚动时)的 contentOffset
*
* @return 控件显示的百分比进度,如果控件直接处于屏幕外,返回-1,父类默认返回-1
*/
func progressWithScrollViewInsets(_ insets:UIEdgeInsets,offset:CGPoint) -> CGFloat
/**
* 控件将要显示的位置,由Header子类实现,Footer子类此方法无意义
*
* @return 控件刚加入 scrollView 时将要显示的位置,默认返回(0,0)
*/
func willShowAtPoint() -> CGPoint
}
open class AKRefreshView :UIControl,AKRefreshViewType,AKRefreshViewControl{
private var refreshComplete:((AKRefreshViewType)->())?
public var hideWhenComplate = false
public enum AnimationDuration:TimeInterval{
case none = 0
case normal = 0.25
case fast = 0.1
}
public enum KVOPath:String{
case scrollViewContentOffsetPath = "contentOffset"
case scrollViewContentSizePath = "contentSize"
}
private weak var pScrollView:UIScrollView?
private var pScrollViewOriginalInsets:UIEdgeInsets = .zero
private var pPreviousState:AKRefreshViewStatus = .normal
public var scrollView: UIScrollView?{
return self.pScrollView
}
public var scrollViewOriginalInsets: UIEdgeInsets{
return self.pScrollViewOriginalInsets
}
open var status: AKRefreshViewStatus = .normal{
didSet{
if (status == oldValue) {return}
self.pPreviousState = oldValue
self.onStateChange()
}
}
public var previousState: AKRefreshViewStatus{
return self.pPreviousState
}
public var refreshAction: (() -> ())!
public weak var indicator: AKRefreshIndicator?{
willSet{
if let newIndicator = newValue{
self.addSubview(newIndicator)
}
}
didSet{
if let oldIndicator = oldValue{
self.indicator?.progress = oldIndicator.progress
oldIndicator.removeFromSuperview()
}
}
}
public var progress: CGFloat{
return self.indicator?.progress ?? 0
}
public init(height:CGFloat, indicator:AKRefreshIndicator,action:@escaping (()->())) {
var frame = CGRect.zero
frame.size.height = height
super.init(frame: frame)
self.autoresizingMask = .flexibleWidth
if(indicator.superview != self){
self.addSubview(indicator)
}
self.indicator = indicator
self.refreshAction = action
self.backgroundColor = UIColor.clear
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
let offsetKeyPath = AKRefreshView.KVOPath.scrollViewContentOffsetPath.rawValue
self.superview?.removeObserver(self, forKeyPath: offsetKeyPath)
if let newView = newSuperview {
newView.addObserver(self, forKeyPath: offsetKeyPath, options: .new, context: nil)
self.frame.size.width = newView.frame.size.width
self.frame.origin = self.willShowAtPoint()
self.pScrollView = newView as? UIScrollView
self.pScrollView?.alwaysBounceVertical = true
self.pScrollViewOriginalInsets = self.pScrollView?.contentInset ?? .zero
}
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (self.status == .loading) {return}
if (AKRefreshView.KVOPath.scrollViewContentOffsetPath.rawValue == keyPath) {
if (!self.isUserInteractionEnabled
|| self.isHidden
|| self.alpha < 0.01) {
return
}
self.adjustState()
}else{
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
open func onStateChange(){
if (self.previousState != .loading) {
self.pScrollViewOriginalInsets = self.scrollView?.contentInset ?? .zero
}
if (self.status == .normal) {
if (self.previousState == .loading) {
self.indicator?.stopAnimation()
self.indicator?.progress = AKRefreshIndicator.ProgressInterval.min.rawValue
self.indicator?.isHidden = true
UIView.animate(withDuration: AKRefreshView.AnimationDuration.normal.rawValue, animations: {
self.refreshViewChangeUIWhenFinish(self)
}, completion: { (finished) in
self.indicator?.isHidden = false
self.refreshViewChangeUIWhenNormal(self)
self.refreshComplete?(self)
self.isHidden = self.hideWhenComplate
})
} else{
self.refreshViewChangeUIWhenNormal(self)
}
}else if(self.status == .willLoading){
self.refreshViewChangeUIWhenWillLoading(self)
}else if(self.status == .loading){
self.indicator?.isHidden = false
self.indicator?.progress = AKRefreshIndicator.ProgressInterval.max.rawValue
self.indicator?.startAnimation()
self.refreshViewChangeUIWhenLoading(self)
}
}
open func adjustState(){
if (self.window == nil) {return}
let progress = self.progressWithScrollViewInsets(self.scrollViewOriginalInsets, offset: self.scrollView?.contentOffset ?? .zero)
if (progress == -1) {
if self.indicator?.progress != 0 {
self.indicator?.progress = 0
}
return
}
if let scrollView = self.scrollView {
if (scrollView.isDragging){
//未松手
self.indicator?.progress = progress
let critical = AKRefreshIndicator.ProgressInterval.max.rawValue
if (progress >= critical && self.status == .normal) {
self.status = .willLoading
}else if(progress < critical && self.status == .willLoading){
self.status = .normal
}
}else{
//松手
if (self.status == .willLoading) {
self.status = .loading
}else if(self.status == .normal){
self.indicator?.progress = progress
}
}
}
}
open func endRefresh(complete:((AKRefreshViewType)->())? = nil) {
self.status = .normal
self.refreshComplete = complete
}
open func startRefresh() {
if let _ = self.window{
self.status = .loading
}else{
//还未在view上出现,延迟到drawRect中处理
self.status = .willLoading
}
}
open override func draw(_ rect: CGRect) {
super.draw(rect)
if (self.status == .willLoading) {
self.startRefresh()
}else{
self.status = .normal
}
}
open override func layoutSubviews() {
super.layoutSubviews()
if (self.status != .loading) {
let insets = self.scrollView?.contentInset ?? .zero
if self.scrollViewOriginalInsets != insets{
self.pScrollViewOriginalInsets = insets
self.adjustState()
}
}
}
open func progressWithScrollViewInsets(_ insets: UIEdgeInsets, offset: CGPoint) -> CGFloat {
return -1
}
open func willShowAtPoint() -> CGPoint {
return .zero
}
open func refreshViewChangeUIWhenNormal(_ refreshView: AKRefreshViewType) {
}
open func refreshViewChangeUIWhenWillLoading(_ refreshView: AKRefreshViewType) {
}
open func refreshViewChangeUIWhenLoading(_ refreshView: AKRefreshViewType) {
}
open func refreshViewChangeUIWhenFinish(_ refreshView: AKRefreshViewType) {
}
}
| 32.820789 | 156 | 0.611882 |
f5dd45d0c7a1cbd8261453e906e0c4eaa209da12 | 13,921 | //
// DrawerPage.swift
// MVVM
//
import UIKit
import RxSwift
import Action
class OverlayView: AbstractControlView {
public let tapGesture = UITapGestureRecognizer()
override func setupView() {
backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
addGestureRecognizer(tapGesture)
}
static func addToPage(_ page: UIViewController) -> OverlayView {
let overlayView = OverlayView()
page.view.addSubview(overlayView)
overlayView.autoPinEdgesToSuperviewEdges()
return overlayView
}
}
public enum DrawerLayout {
case under, over
}
public enum DrawerAnimation {
case slide, slideAndZoom
var duration: TimeInterval {
switch self {
case .slide: return 0.25
case .slideAndZoom: return 0.3
}
}
}
public enum DrawerWidth {
/// Fix drawer width
case fix(CGFloat)
/// Drawer width ratio compare to screen width
case ratio(CGFloat)
}
/// A navigation drawer page
public class DrawerPage: UIViewController, IDestroyable {
public private(set) var detailPage: UIViewController?
public private(set) var masterPage: UIViewController?
private let masterContentView = UIView()
private let detailContentView = UIView()
private let overlayView = OverlayView()
private lazy var tapAction: Action<Void, Void> = {
return Action() { .just(self.closeDrawer(true)) }
}()
public override var prefersStatusBarHidden: Bool {
if isOpen {
return masterPage?.prefersStatusBarHidden ?? false
}
return detailPage?.prefersStatusBarHidden ?? false
}
public override var preferredStatusBarStyle: UIStatusBarStyle {
if isOpen {
return masterPage?.preferredStatusBarStyle ?? .default
}
return detailPage?.preferredStatusBarStyle ?? .default
}
private var widthConstraint: NSLayoutConstraint?
/// Public properties for configurations
public private(set) var isOpen = false
/// Allow drawer to open or not
public var isEnabled = true
/*
Drawer widths:
- fix: set a fix width for drawer. For under layout, this should be the visible area
- ratio: set a ratio width compare to screen width
*/
public var drawerWidth: DrawerWidth = .fix(280) {
didSet { updateDrawerWidth() }
}
/*
Drawer animations:
- slide: slide from left (can be different with drawer layout)
- slideAndZoom: better with under layout, slide the detail page and zoom a bit
*/
public var drawerAnimation: DrawerAnimation = .slide
/*
Drawer layout:
- over: over the detail page
- under: udner the detail page
Animation will also depend on this to make correct animation senses
*/
public var drawerLayout: DrawerLayout = .over {
didSet { updateDrawerLayout() }
}
/// Background color for overlay view
public var overlayColor: UIColor = UIColor(r: 0, g: 0, b: 0, a: 0.7) {
didSet { updateOverlayColor() }
}
// destroyable interface
public var disposeBag: DisposeBag? = DisposeBag()
public init(withDetailPage detailPage: UIViewController? = nil, masterPage: UIViewController? = nil) {
self.detailPage = detailPage
self.masterPage = masterPage
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func destroy() {
overlayView.tapGesture.unbindAction()
detailPage?.removeFromParent()
masterPage?.removeFromParent()
(detailPage as? IDestroyable)?.destroy()
(masterPage as? IDestroyable)?.destroy()
}
public override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(detailContentView)
detailContentView.autoPinEdgesToSuperviewEdges()
overlayView.isHidden = true
overlayView.alpha = 0
detailContentView.addSubview(overlayView)
overlayView.autoPinEdgesToSuperviewEdges()
overlayView.tapGesture.bind(to: tapAction, input: ())
masterContentView.isHidden = true
view.addSubview(masterContentView)
masterContentView.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .trailing)
updateDrawerLayout()
if let detailPage = detailPage {
addChild(detailPage)
detailContentView.addSubview(detailPage.view)
detailPage.view.autoPinEdgesToSuperviewEdges()
detailPage.didMove(toParent: self)
detailContentView.sendSubviewToBack(detailPage.view)
}
if let masterPage = masterPage {
addChild(masterPage)
masterContentView.addSubview(masterPage.view)
masterPage.view.autoPinEdgesToSuperviewEdges()
masterPage.didMove(toParent: self)
}
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
detailPage?.beginAppearanceTransition(true, animated: animated)
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
detailPage?.endAppearanceTransition()
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
detailPage?.beginAppearanceTransition(false, animated: animated)
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
detailPage?.endAppearanceTransition()
}
public func replaceMasterPage(_ masterPage: UIViewController) {
(self.masterPage as? IDestroyable)?.destroy()
self.masterPage?.view.removeFromSuperview()
self.masterPage?.removeFromParent()
addChild(masterPage)
masterContentView.addSubview(masterPage.view)
masterPage.view.autoPinEdgesToSuperviewEdges()
masterPage.didMove(toParent: self)
self.masterPage = masterPage
}
public func replaceDetailPage(_ detailPage: UIViewController, animated: Bool = true) {
(self.detailPage as? IDestroyable)?.destroy()
self.detailPage?.view.removeFromSuperview()
self.detailPage?.removeFromParent()
addChild(detailPage)
detailContentView.addSubview(detailPage.view)
detailPage.view.autoPinEdgesToSuperviewEdges()
detailPage.didMove(toParent: self)
detailContentView.sendSubviewToBack(detailPage.view)
self.detailPage = detailPage
closeDrawer(animated)
}
public func toggleDrawer(_ animated: Bool = true) {
if isOpen {
closeDrawer(animated)
} else {
openDrawer(animated)
}
}
public func openDrawer(_ animated: Bool = true) {
if isOpen { return }
let duration: TimeInterval = animated ? drawerAnimation.duration : 0
overlayView.isHidden = false
masterContentView.isHidden = false
masterPage?.beginAppearanceTransition(true, animated: animated)
openDrawerAnimation(duration: duration) { _ in
self.masterPage?.endAppearanceTransition()
self.isOpen = !self.isOpen
self.setNeedsStatusBarAppearanceUpdate()
}
}
private func openDrawerAnimation(duration: TimeInterval, completion: @escaping ((Bool) -> ())) {
switch drawerAnimation {
case .slide:
switch drawerLayout {
case .over:
masterContentView.transform = CGAffineTransform(translationX: -masterContentView.frame.width, y: 0)
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
self.overlayView.alpha = 1
self.masterContentView.transform = .identity
}, completion: completion)
case .under:
masterContentView.transform = CGAffineTransform(translationX: -(masterContentView.frame.width / 3), y: 0)
detailContentView.transform = .identity
let translateX: CGFloat
switch drawerWidth {
case .fix(let width): translateX = width
case .ratio(let ratio): translateX = ratio * view.frame.width
}
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
self.overlayView.alpha = 1
self.masterContentView.transform = .identity
self.detailContentView.transform = CGAffineTransform(translationX: translateX, y: 0)
}, completion: completion)
}
case .slideAndZoom:
if drawerLayout == .over {
masterContentView.transform = CGAffineTransform(translationX: -masterContentView.frame.width, y: 0)
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
self.masterContentView.transform = .identity
})
}
detailContentView.transform = .identity
let scale: CGFloat = 0.8
let translateX: CGFloat
switch drawerWidth {
case .fix(let width): translateX = width
case .ratio(let ratio): translateX = ratio * view.frame.width
}
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
self.overlayView.alpha = 1
var transform = CGAffineTransform(translationX: translateX, y: 0)
transform = transform.concatenating(CGAffineTransform(scaleX: scale, y: scale))
self.detailContentView.transform = transform
}, completion: completion)
}
}
public func closeDrawer(_ animated: Bool = true) {
if !isOpen { return }
let duration: TimeInterval = animated ? drawerAnimation.duration : 0
masterPage?.beginAppearanceTransition(false, animated: animated)
closeDrawerAnimation(duration: duration) { (_) in
self.overlayView.isHidden = true
self.masterContentView.isHidden = true
self.masterPage?.endAppearanceTransition()
self.isOpen = !self.isOpen
self.setNeedsStatusBarAppearanceUpdate()
}
}
private func closeDrawerAnimation(duration: TimeInterval, completion: @escaping ((Bool) -> ())) {
switch drawerAnimation {
case .slide:
switch drawerLayout {
case .over:
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
self.overlayView.alpha = 0
self.masterContentView.transform = CGAffineTransform(translationX: -self.masterContentView.frame.width, y: 0)
}, completion: completion)
case .under:
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
self.overlayView.alpha = 0
self.masterContentView.transform = CGAffineTransform(translationX: -(self.masterContentView.frame.width / 3), y: 0)
self.detailContentView.transform = .identity
}, completion: completion)
}
case .slideAndZoom:
if drawerLayout == .over {
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
self.masterContentView.transform = CGAffineTransform(translationX: -self.masterContentView.frame.width, y: 0)
})
}
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: {
self.overlayView.alpha = 0
self.detailContentView.transform = .identity
}, completion: completion)
}
}
private func updateDrawerWidth() {
widthConstraint?.autoRemove()
switch drawerLayout {
case .over:
switch drawerWidth {
case .fix(let width):
widthConstraint = masterContentView.autoSetDimension(.width, toSize: width)
case .ratio(let ratio):
widthConstraint = masterContentView.autoMatch(.width, to: .width, of: view, withMultiplier: ratio)
}
default:
widthConstraint = masterContentView.autoMatch(.width, to: .width, of: view)
}
view.layoutIfNeeded()
}
private func updateDrawerLayout() {
detailContentView.transform = .identity
masterContentView.transform = .identity
masterContentView.isHidden = true
overlayView.isHidden = true
switch drawerLayout {
case .over:
view.bringSubviewToFront(masterContentView)
case .under:
view.sendSubviewToBack(masterContentView)
}
updateDrawerWidth()
updateOverlayColor()
}
private func updateOverlayColor() {
switch drawerLayout {
case .over:
overlayView.backgroundColor = overlayColor
case .under:
overlayView.backgroundColor = .clear
}
}
}
| 33.871046 | 135 | 0.604698 |
ed205a1c6686ff6d14d3262aa1d4cfd26838b9b7 | 244 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
protocol a {
typealias B : B
}
var P {
{
{
}
{
}
}
A.init( {
{
}
func d(
}
| 12.2 | 87 | 0.67623 |
8a629db4814f8bb001f67752f222dc2d48e23787 | 10,834 | import CoreGraphics
import Dispatch
import Foundation
precedencegroup Application {
associativity: left
}
precedencegroup ForwardComposition {
associativity: left
higherThan: Application
}
infix operator !!
infix operator ^^
infix operator ?=
infix operator >>>: ForwardComposition
infix operator |>: Application
prefix operator ^
extension String {
private var camelCaseComponents: [String] {
let components = self.components(separatedBy: .uppercaseLetters)
var currentPos = index(startIndex, offsetBy: components.first?.count ?? 0)
var result: [String] = components.first.map { [$0] } ?? []
for comp in components.dropFirst() {
result.append(String(self[currentPos]) + comp)
currentPos = index(currentPos, offsetBy: comp.count + 1)
}
return result
}
private var nameComponents: [String] {
components(separatedBy: CharacterSet(charactersIn: "_-: "))
.flatMap { $0.camelCaseComponents }
}
public func capitalizedFirst() -> String {
prefix(1).uppercased() + dropFirst()
}
public var snakeCase: String {
nameComponents
.map { $0.lowercased() }
.joined(separator: "_")
}
public var lowerCamelCase: String {
let comps = nameComponents
return (comps.first ?? "").lowercased() + comps.dropFirst().map { $0.capitalized }.joined()
}
public var upperCamelCase: String {
nameComponents.map { $0.capitalized }.joined()
}
@inlinable
public static func HEX<T: BinaryInteger>(_ num: T) -> String {
.init(num, radix: 0x10, uppercase: true)
}
}
extension Optional {
public static func !!(
v: Optional,
e: @autoclosure () -> Error
) throws -> Wrapped {
guard let unwrapped = v else { throw e() }
return unwrapped
}
public static func ^^ <T: Error>(v: Optional, e: T) -> Result<Wrapped, T> {
guard let unwrapped = v else { return .failure(e) }
return .success(unwrapped)
}
}
public protocol OptionalType {
associatedtype Wrapped
var optional: Wrapped? { get }
}
extension Optional: OptionalType {
public var optional: Wrapped? { self }
}
public func ?= <T>(v: inout T, val: T?) {
if let val = val {
v = val
}
}
extension Sequence where Iterator.Element: OptionalType {
public func unwrap() -> [Iterator.Element.Wrapped]? {
reduce([Element.Wrapped]?([])) { acc, e in
acc.flatMap { a in e.optional.map { a + [$0] } }
}
}
}
public struct Splitted<Collection: Swift.Collection>: Swift.Collection {
public func index(after i: Index) -> Index {
i.advanced(by: 1)
}
@inlinable
public subscript(position: Int) -> Collection.SubSequence {
_read {
let start = collection
.index(collection.startIndex, offsetBy: position * step)
let end = collection.index(start, offsetBy: step)
yield collection[start..<end]
}
}
public typealias Index = Int
public typealias Indicies = Range<Int>
public typealias SubSequence = Slice<Splitted<Collection>>
public typealias Element = Collection.SubSequence
public var startIndex: Int { 0 }
public var endIndex: Int {
precondition(step > 0)
return collection.count / step
}
public var step: Int
public var collection: Collection
@inlinable
public func makeIterator() -> Iterator {
.init(collection: collection, step: step)
}
public struct Iterator: IteratorProtocol {
private let collection: Collection
private let step: Int
private var idx: Collection.Index
public mutating func next() -> Element? {
guard idx < collection.endIndex else {
return nil
}
let current = idx
collection.formIndex(&idx, offsetBy: step)
return collection[current..<idx]
}
public init(collection: Collection, step: Int) {
precondition(step > 0)
self.collection = collection
self.step = step
idx = collection.startIndex
}
}
@inlinable
init(collection: Collection, step: Int) {
precondition(step > 0)
self.step = step
self.collection = collection
}
}
extension Collection where Index == Int {
public func splitBy(subSize: Int) -> Splitted<Self> {
Splitted(collection: self, step: subSize)
}
}
extension Array {
public func appendToAll<T>(a: T) -> [(T, Element)] {
map { (a, $0) }
}
public func concurrentMap<T>(_ transform: (Element) throws -> T) throws -> [T] {
var result = [T?](repeating: nil, count: count)
let lock = NSLock()
var barrier: Error?
DispatchQueue.concurrentPerform(iterations: count) { i in
guard lock.locked({ barrier == nil }) else { return }
do {
let val = try transform(self[i])
lock.locked { result[i] = val }
} catch {
lock.locked { barrier = error }
}
}
if let error = barrier {
throw error
}
return result.map { $0! }
}
public func concurrentMap<T>(_ transform: (Element) -> T) -> [T] {
[T](unsafeUninitializedCapacity: count) { buffer, finalCount in
let low = buffer.baseAddress!
finalCount = count
let bufferAccess = NSLock()
DispatchQueue.concurrentPerform(iterations: count) { i in
let val = transform(self[i])
bufferAccess.locked {
low.advanced(by: i).initialize(to: val)
}
}
}
}
public mutating func modifyLast(_ modifier: (inout Element) -> Void) {
guard var el = popLast() else { return }
modifier(&el)
append(el)
}
}
extension Array where Element == String {
public func appendFirstToLast(_ strings: [String], separator: String) -> [String] {
let mid: String
switch (last, strings.first) {
case let (last?, nil):
mid = last
case let (nil, first?):
mid = first
case let (last?, first?):
mid = last + separator + first
case (nil, nil):
return []
}
return dropLast() + [mid] + strings.dropFirst()
}
}
extension Sequence {
public func concurrentMap<T>(_ transform: @escaping (Element) -> T) -> [T] {
var result = [T?]()
let syncQueue = DispatchQueue(label: "sync_queue")
let workQueue = DispatchQueue(label: "work_queue", attributes: .concurrent)
for (i, e) in enumerated() {
syncQueue.async {
result.append(nil)
}
workQueue.async {
let val = transform(e)
syncQueue.sync {
result[i] = val
}
}
}
return workQueue.sync(flags: .barrier) {
syncQueue.sync {
result.map { $0! }
}
}
}
public func insertSeparator(_ separator: Element) -> JoinedSequence<[[Self.Element]]> {
map { [$0] }.joined(separator: [separator])
}
}
extension Collection {
@inlinable
public subscript(safe index: Index) -> Element? {
startIndex <= index && endIndex > index ? self[index] : nil
}
@inlinable
public var firstAndOnly: Element? {
guard let first = first, count == 1 else {
return nil
}
return first
}
}
extension Result {
@inlinable
public var value: Success? {
guard case let .success(s) = self else { return nil }
return s
}
public var isSucceed: Bool {
guard case .success = self else { return false }
return true
}
@inlinable
public init(optional: Success?, or error: @autoclosure () -> (Failure)) {
switch optional {
case let some?:
self = .success(some)
case nil:
self = .failure(error())
}
}
@inlinable
public func takeAction(onSuccess: (Success) -> Void, onFailure: (Failure) -> Void) {
switch self {
case let .success(val): onSuccess(val)
case let .failure(err): onFailure(err)
}
}
@inlinable
public func onSuccess(_ action: () -> Void) {
onSuccess { _ in action() }
}
@inlinable
public func onSuccess(_ action: (Success) -> Void) {
takeAction(onSuccess: action, onFailure: always(()))
}
@inlinable
public func onFailure(_ action: () -> Void) {
onFailure { _ in action() }
}
@inlinable
public func onFailure(_ action: (Error) -> Void) {
takeAction(onSuccess: always(()), onFailure: action)
}
}
public func partial<A1, A2, T>(_ f: @escaping (A1, A2) throws -> T, arg2: A2) -> (A1) throws -> T {
{ try f($0, arg2) }
}
@inlinable
public func always<T, U>(_ value: T) -> (U) -> T {
{ _ in value }
}
@inlinable
public func always<T, U1, U2>(_ value: T) -> (U1, U2) -> T {
{ _, _ in value }
}
@inlinable
public func always<T, U>(_ value: T) -> (inout U) -> T {
{ _ in value }
}
@inlinable
public func absurd<T>(_: Never) -> T {}
@inlinable
public func absurd<T, A>(_: A, _: Never) -> T {}
@inlinable
public func >>> <A, B, C>(
lhs: @escaping (A) -> B,
rhs: @escaping (B) -> C
) -> (A) -> C {
{ rhs(lhs($0)) }
}
@inlinable
public func |> <A, B>(
lhs: A,
rhs: (A) throws -> B
) rethrows -> B {
try rhs(lhs)
}
public func check(_ condition: Bool, _ error: Error) throws {
if !condition {
throw error
}
}
public func zip<T, U>(_ t: T?, _ u: U?) -> (T, U)? {
t.flatMap { t in u.map { u in (t, u) } }
}
public func zipLongest<T, U>(
_ t: T?, _ u: U?,
fillFirst: @autoclosure () -> T,
fillSecond: @autoclosure () -> U
) -> (T, U)? {
guard t != nil || u != nil else { return nil }
return (t ?? fillFirst(), u ?? fillSecond())
}
public func modified<T>(_ value: T, _ modifier: (inout T) -> Void) -> T {
var copy = value
modifier(©)
return copy
}
@inlinable
public func get<T, U>(_ kp: KeyPath<T, U>) -> (T) -> U {
{ $0[keyPath: kp] }
}
@inlinable
public func set<T, U>(_ kp: WritableKeyPath<T, U>) -> (inout T, U) -> Void {
{ $0[keyPath: kp] = $1 }
}
@inlinable
public prefix func ^ <T, U>(_ kp: KeyPath<T, U>) -> (T) -> U {
get(kp)
}
@inlinable
public prefix func ^ <T, U>(_ kp: WritableKeyPath<T, U>) -> (inout T, U) -> Void {
set(kp)
}
public func waitCallbackOnMT(_ operation: (@escaping () -> Void) -> Void) {
waitCallbackOnMT { completion in
operation {
completion(())
}
}
}
public func waitCallbackOnMT<T>(_ operation: (@escaping (T) -> Void) -> Void) -> T {
let semaphore = DispatchSemaphore(value: 0)
var result: T?
operation {
result = $0
semaphore.signal()
}
RunLoop.current.spin {
semaphore.wait(timeout: .now()) == .timedOut
}
return result!
}
extension RunLoop {
public func spin(while condition: () -> Bool) {
while condition() {
run(until: .init())
}
}
}
public func apply<T>(_ f: () -> T) -> T {
f()
}
extension CaseIterable where Self: RawRepresentable, RawValue: Hashable {
public static var rawValues: Set<AllCases.Element.RawValue> {
Set(allCases.map { $0.rawValue })
}
}
extension NSLock {
func locked<T>(_ block: () -> T) -> T {
lock()
defer { unlock() }
return block()
}
}
@inlinable
public func hex<T>(_ bytes: T) -> String {
withUnsafeBytes(of: bytes) {
$0.map(String.HEX).joined()
}
}
| 23.149573 | 99 | 0.616577 |
ac8bbe01b0918cdaa7b44debb9e8018eee635616 | 418 | //
// UIStackView+Chainable.swift
// Webtoon.clone
//
// Created by Stat.So on 2020/11/15.
//
import UIKit
extension Chain where Origin: UIStackView {
@discardableResult
func distribution(_ by: UIStackView.Distribution) -> Chain {
self.origin.distribution = by
return self
}
@discardableResult
func axis(_ by: NSLayoutConstraint.Axis) -> Chain {
self.origin.axis = by
return self
}
}
| 18.173913 | 62 | 0.688995 |
6a1db3c82723a392af973db96371b937a24a586d | 9,467 | // Copyright 2018-Present Shin Yamamoto. All rights reserved. MIT license.
import UIKit
/// An interface for implementing custom layout anchor objects.
@objc public protocol FloatingPanelLayoutAnchoring {
///
var referenceGuide: FloatingPanelLayoutReferenceGuide { get }
///
func layoutConstraints(_ fpc: FloatingPanelController, for position: FloatingPanelPosition) -> [NSLayoutConstraint]
}
/// An object that defines how to settles a panel with insets from an edge of a reference rectangle.
@objc public final class FloatingPanelLayoutAnchor: NSObject, FloatingPanelLayoutAnchoring /* , NSCopying */ {
/// Returns a layout anchor with the specified inset by an absolute value, edge and reference guide for a panel.
///
/// The inset is an amount to inset a panel from an edge of the reference guide. The edge refers to a panel
/// positioning.
@objc public init(absoluteInset: CGFloat, edge: FloatingPanelReferenceEdge, referenceGuide: FloatingPanelLayoutReferenceGuide) {
inset = absoluteInset
self.referenceGuide = referenceGuide
referenceEdge = edge
isAbsolute = true
}
/// Returns a layout anchor with the specified inset by a fractional value, edge and reference guide for a panel.
///
/// The inset is an amount to inset a panel from the edge of the specified reference guide. The value is
/// a floating-point number in the range 0.0 to 1.0, where 0.0 represents zero distance from the edge and
/// 1.0 represents a distance to the opposite edge.
@objc public init(fractionalInset: CGFloat, edge: FloatingPanelReferenceEdge, referenceGuide: FloatingPanelLayoutReferenceGuide) {
inset = fractionalInset
self.referenceGuide = referenceGuide
referenceEdge = edge
isAbsolute = false
}
let inset: CGFloat
let isAbsolute: Bool
/// The reference rectangle area for the inset.
@objc public let referenceGuide: FloatingPanelLayoutReferenceGuide
@objc let referenceEdge: FloatingPanelReferenceEdge
}
extension FloatingPanelLayoutAnchor {
public func layoutConstraints(_ vc: FloatingPanelController, for position: FloatingPanelPosition) -> [NSLayoutConstraint] {
let layoutGuide = referenceGuide.layoutGuide(vc: vc)
switch position {
case .top:
return layoutConstraints(layoutGuide, for: vc.surfaceView.bottomAnchor)
case .left:
return layoutConstraints(layoutGuide, for: vc.surfaceView.rightAnchor)
case .bottom:
return layoutConstraints(layoutGuide, for: vc.surfaceView.topAnchor)
case .right:
return layoutConstraints(layoutGuide, for: vc.surfaceView.leftAnchor)
}
}
private func layoutConstraints(_ layoutGuide: LayoutGuideProvider, for edgeAnchor: NSLayoutYAxisAnchor) -> [NSLayoutConstraint] {
switch referenceEdge {
case .top:
if isAbsolute {
return [edgeAnchor.constraint(equalTo: layoutGuide.topAnchor, constant: inset)]
}
let offsetAnchor = layoutGuide.topAnchor.anchorWithOffset(to: edgeAnchor)
return [offsetAnchor.constraint(equalTo: layoutGuide.heightAnchor, multiplier: inset)]
case .bottom:
if isAbsolute {
return [layoutGuide.bottomAnchor.constraint(equalTo: edgeAnchor, constant: inset)]
}
let offsetAnchor = edgeAnchor.anchorWithOffset(to: layoutGuide.bottomAnchor)
return [offsetAnchor.constraint(equalTo: layoutGuide.heightAnchor, multiplier: inset)]
default:
fatalError("Unsupported reference edges")
}
}
private func layoutConstraints(_ layoutGuide: LayoutGuideProvider, for edgeAnchor: NSLayoutXAxisAnchor) -> [NSLayoutConstraint] {
switch referenceEdge {
case .left:
if isAbsolute {
return [edgeAnchor.constraint(equalTo: layoutGuide.leftAnchor, constant: inset)]
}
let offsetAnchor = layoutGuide.leftAnchor.anchorWithOffset(to: edgeAnchor)
return [offsetAnchor.constraint(equalTo: layoutGuide.widthAnchor, multiplier: inset)]
case .right:
if isAbsolute {
return [layoutGuide.rightAnchor.constraint(equalTo: edgeAnchor, constant: inset)]
}
let offsetAnchor = edgeAnchor.anchorWithOffset(to: layoutGuide.rightAnchor)
return [offsetAnchor.constraint(equalTo: layoutGuide.widthAnchor, multiplier: inset)]
default:
fatalError("Unsupported reference edges")
}
}
}
/// An object that defines how to settles a panel with the intrinsic size for a content.
@objc public final class FloatingPanelIntrinsicLayoutAnchor: NSObject, FloatingPanelLayoutAnchoring /* , NSCopying */ {
/// Returns a layout anchor with the specified offset by an absolute value and reference guide for a panel.
///
/// The offset is an amount to offset a position of panel that displays the entire content from an edge of
/// the reference guide. The edge refers to a panel positioning.
@objc public init(absoluteOffset offset: CGFloat, referenceGuide: FloatingPanelLayoutReferenceGuide = .safeArea) {
self.offset = offset
self.referenceGuide = referenceGuide
isAbsolute = true
}
/// Returns a layout anchor with the specified offset by a fractional value and reference guide for a panel.
///
/// The offset value is a floating-point number in the range 0.0 to 1.0, where 0.0 represents the full content
/// is displayed and 0.5 represents the half of content is displayed.
@objc public init(fractionalOffset offset: CGFloat, referenceGuide: FloatingPanelLayoutReferenceGuide = .safeArea) {
self.offset = offset
self.referenceGuide = referenceGuide
isAbsolute = false
}
let offset: CGFloat
let isAbsolute: Bool
/// The reference rectangle area for the offset
@objc public let referenceGuide: FloatingPanelLayoutReferenceGuide
}
extension FloatingPanelIntrinsicLayoutAnchor {
public func layoutConstraints(_ vc: FloatingPanelController, for position: FloatingPanelPosition) -> [NSLayoutConstraint] {
let surfaceIntrinsicLength = position.mainDimension(vc.surfaceView.intrinsicContentSize)
let constant = isAbsolute ? surfaceIntrinsicLength - offset : surfaceIntrinsicLength * (1 - offset)
let layoutGuide = referenceGuide.layoutGuide(vc: vc)
switch position {
case .top:
return [vc.surfaceView.bottomAnchor.constraint(equalTo: layoutGuide.topAnchor, constant: constant)]
case .left:
return [vc.surfaceView.rightAnchor.constraint(equalTo: layoutGuide.leftAnchor, constant: constant)]
case .bottom:
return [vc.surfaceView.topAnchor.constraint(equalTo: layoutGuide.bottomAnchor, constant: -constant)]
case .right:
return [vc.surfaceView.leftAnchor.constraint(equalTo: layoutGuide.rightAnchor, constant: -constant)]
}
}
}
/// An object that defines how to settles a panel with a layout guide of a content view.
@objc public final class FloatingPanelAdaptiveLayoutAnchor: NSObject, FloatingPanelLayoutAnchoring /* , NSCopying */ {
/// Returns a layout anchor with the specified offset by an absolute value, layout guide to display content and reference guide for a panel.
///
/// The offset is an amount to offset a position of panel that displays the entire content of the specified guide from an edge of
/// the reference guide. The edge refers to a panel positioning.
@objc public init(absoluteOffset offset: CGFloat, contentLayout: UILayoutGuide, referenceGuide: FloatingPanelLayoutReferenceGuide = .safeArea) {
self.offset = offset
contentLayoutGuide = contentLayout
self.referenceGuide = referenceGuide
isAbsolute = true
}
/// Returns a layout anchor with the specified offset by a fractional value, layout guide to display content and reference guide for a panel.
///
/// The offset value is a floating-point number in the range 0.0 to 1.0, where 0.0 represents the full content
/// is displayed and 0.5 represents the half of content is displayed.
@objc public init(fractionalOffset offset: CGFloat, contentLayout: UILayoutGuide, referenceGuide: FloatingPanelLayoutReferenceGuide = .safeArea) {
self.offset = offset
contentLayoutGuide = contentLayout
self.referenceGuide = referenceGuide
isAbsolute = false
}
fileprivate let offset: CGFloat
fileprivate let isAbsolute: Bool
let contentLayoutGuide: UILayoutGuide
@objc public let referenceGuide: FloatingPanelLayoutReferenceGuide
}
extension FloatingPanelAdaptiveLayoutAnchor {
public func layoutConstraints(_ vc: FloatingPanelController, for position: FloatingPanelPosition) -> [NSLayoutConstraint] {
let layoutGuide = referenceGuide.layoutGuide(vc: vc)
let offsetAnchor: NSLayoutDimension
switch position {
case .top:
offsetAnchor = layoutGuide.topAnchor.anchorWithOffset(to: vc.surfaceView.bottomAnchor)
case .left:
offsetAnchor = layoutGuide.leftAnchor.anchorWithOffset(to: vc.surfaceView.rightAnchor)
case .bottom:
offsetAnchor = vc.surfaceView.topAnchor.anchorWithOffset(to: layoutGuide.bottomAnchor)
case .right:
offsetAnchor = vc.surfaceView.leftAnchor.anchorWithOffset(to: layoutGuide.rightAnchor)
}
if isAbsolute {
return [offsetAnchor.constraint(equalTo: position.mainDimensionAnchor(contentLayoutGuide), constant: -offset)]
} else {
return [offsetAnchor.constraint(equalTo: position.mainDimensionAnchor(contentLayoutGuide), multiplier: 1 - offset)]
}
}
}
extension FloatingPanelAdaptiveLayoutAnchor {
func distance(from dimension: CGFloat) -> CGFloat {
isAbsolute ? offset : dimension * offset
}
}
| 46.635468 | 148 | 0.755889 |
75495743f4ab1908aa00f6b2fbe4ac7e31f5b0ef | 624 | //
// CustomTableViewCell.swift
// Paramount
//
// Created by Yugasalabs-28 on 27/05/2019.
// Copyright © 2019 Yugasalabs. All rights reserved.
//
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet var menuLable: UILabel!
@IBOutlet var currencyLbl: UILabel!
@IBOutlet var countryCodeLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 22.285714 | 65 | 0.679487 |
48bb64e97017691bbed1fa6fda40170bf83a58fb | 10,635 | //
// FirestoreCoreHandler.swift
// FireStream
//
// Created by Pepe Becker on 2/10/20.
//
import RxSwift
import FirebaseFirestore
public class FirestoreCoreHandler: FirebaseCoreHandler {
public override func listChangeOn(_ path: Path) -> Observable<FireStreamEvent<ListData>> {
do {
let ref = try RefFirestore.collection(path)
return RxFirestore().on(ref).flatMap { change -> Maybe<FireStreamEvent<ListData>> in
let d = change.document
if d.exists {
let payload = ListData(d.documentID, d.data(with: .estimate))
let event = FireStreamEvent(payload, Self.typeForDocumentChange(change))
return Maybe.just(event)
}
return Maybe.empty()
}
} catch {
return Observable.error(error)
}
}
public override func deleteSendable(_ messagesPath: Path) -> Completable {
do {
let ref = try RefFirestore.document(messagesPath)
return RxFirestore().delete(ref)
} catch {
return Completable.error(error)
}
}
public override func send(_ messagesPath: Path, _ sendable: Sendable, _ newId: Consumer<String>?) -> Completable {
do {
let ref = try RefFirestore.collection(messagesPath)
return RxFirestore().add(ref, sendable.toData(), newId).asCompletable()
} catch {
return Completable.error(error)
}
}
public override func addUsers(_ path: Path, _ dataProvider: FireStreamUser.DataProvider, _ users: [FireStreamUser]) -> Completable {
return Single.create { emitter in
do {
let ref = try RefFirestore.collection(path)
let batch = RefFirestore.db().batch()
for u in users {
let docRef = ref.document(u.getId())
batch.setData(dataProvider.data(u), forDocument: docRef)
}
emitter(.success(batch))
} catch {
emitter(.error(error))
}
return Disposables.create()
}.flatMapCompletable(self.runBatch)
}
public override func updateUsers(_ path: Path, _ dataProvider: FireStreamUser.DataProvider, _ users: [FireStreamUser]) -> Completable {
return Single.create { emitter in
do {
let ref = try RefFirestore.collection(path)
let batch = RefFirestore.db().batch()
for u in users {
let docRef = ref.document(u.getId())
batch.updateData(dataProvider.data(u), forDocument: docRef)
}
emitter(.success(batch))
} catch {
emitter(.error(error))
}
return Disposables.create()
}.flatMapCompletable(self.runBatch)
}
public override func removeUsers(_ path: Path, _ users: [FireStreamUser]) -> Completable {
return Single.create { emitter in
do {
let ref = try RefFirestore.collection(path)
let batch = RefFirestore.db().batch()
for u in users {
let docRef = ref.document(u.getId())
batch.deleteDocument(docRef)
}
emitter(.success(batch))
} catch {
emitter(.error(error))
}
return Disposables.create()
}.flatMapCompletable(self.runBatch)
}
public override func loadMoreMessages(_ messagesPath: Path, _ fromDate: Date?, _ toDate: Date?, _ limit: Int?) -> Single<[Sendable]> {
return Single<Query>.create { emitter in
do {
var query = try RefFirestore.collection(messagesPath) as Query
query = query.order(by: Keys.Date, descending: false)
if let fromDate = fromDate {
query = query.whereField(Keys.Date, isGreaterThan: fromDate)
}
if let toDate = toDate {
query = query.whereField(Keys.Date, isLessThanOrEqualTo: toDate)
}
if let limit = limit {
if fromDate != nil {
query = query.limit(to: limit)
}
if toDate != nil {
query = query.limit(to: limit)
// TODO: fix this
// query = query.limitToLast(limit)
}
}
emitter(.success(query))
} catch {
emitter(.error(error))
}
return Disposables.create()
}.flatMap { RxFirestore().get($0) }.map { querySnapshot in
var sendables = [Sendable]()
if let querySnapshot = querySnapshot, !querySnapshot.isEmpty {
for c in querySnapshot.documentChanges {
let docSnapshot = c.document
// Add the message
if docSnapshot.exists && c.type == .added {
let sendable = self.sendableFromSnapshot(docSnapshot)
sendables.append(sendable)
}
}
}
return sendables
}
}
public override func dateOfLastSentMessage(_ messagesPath: Path) -> Single<Date> {
return Single<Query>.create { emitter in
do {
if let userId = Fire.stream().currentUserId() {
var query = try RefFirestore.collection(messagesPath) as Query
query = query.whereField(Keys.From, isEqualTo: userId)
query = query.order(by: Keys.Date, descending: true)
query = query.limit(to: 1)
emitter(.success(query))
} else {
emitter(.error(FireStreamError("userId is nil")))
}
} catch {
emitter(.error(error))
}
return Disposables.create()
}.flatMap { RxFirestore().get($0) }.map { querySnapshot -> Date in
if let querySnapshot = querySnapshot, !querySnapshot.isEmpty {
if querySnapshot.documentChanges.count > 0 {
if let change = querySnapshot.documentChanges.first, change.document.exists {
let sendable = self.sendableFromSnapshot(change.document)
sendable.setBody(change.document.data())
if let date = sendable.getDate() {
return date
}
}
}
}
return Date(timestamp: 0)
}
}
/**
* Start listening to the current message reference and pass the messages to the events
* @param newerThan only listen for messages after this date
* @return a events of message results
*/
public override func messagesOn(_ messagesPath: Path, _ newerThan: Date?, _ limit: Int?) -> Observable<FireStreamEvent<Sendable>> {
return Single<Query>.create { emitter in
do {
var query = try RefFirestore.collection(messagesPath) as Query
query = query.order(by: Keys.Date, descending: false)
if let newerThan = newerThan {
query = query.whereField(Keys.Date, isGreaterThan: newerThan)
}
if let limit = limit {
query = query.limit(to: limit)
}
emitter(.success(query))
} catch {
emitter(.error(error))
}
return Disposables.create()
}.asObservable().flatMap { query -> Observable<FireStreamEvent<Sendable>> in
return RxFirestore().on(query).flatMap { docChange -> Maybe<FireStreamEvent<Sendable>> in
let docSnapshot = docChange.document
if docSnapshot.exists {
let sendable = self.sendableFromSnapshot(docSnapshot)
let event = FireStreamEvent(sendable, Self.typeForDocumentChange(docChange))
return Maybe.just(event)
}
return Maybe.empty()
}
}
}
public override func timestamp() -> Any {
return FieldValue.serverTimestamp()
}
/**
* Firestore helper methods
*/
internal func sendableFromSnapshot(_ snapshot: DocumentSnapshot) -> Sendable {
let sendable = Sendable()
sendable.setId(snapshot.documentID)
if let from = snapshot.get(Keys.From) as? String {
sendable.setFrom(from)
}
if let timestamp = snapshot.get(Keys.Date, serverTimestampBehavior: .estimate) as? Date {
sendable.setDate(timestamp)
}
if let body = snapshot.get(Keys.Body) as? [String: Any] {
sendable.setBody(body)
}
if let type = snapshot.get(Keys.type) as? String {
sendable.setType(type)
}
return sendable
}
/**
* Run a Firestore updateBatch operation
* @param batch Firestore updateBatch
* @return completion
*/
internal func runBatch(_ batch: WriteBatch) -> Completable {
return Completable.create { emitter in
batch.commit(completion: { error in
if let error = error {
emitter(.error(error))
} else {
emitter(.completed)
}
})
return Disposables.create()
}
}
public class func typeForDocumentChange(_ change: DocumentChange) -> EventType {
switch change.type {
case .added:
return EventType.Added
case .removed:
return EventType.Removed
case .modified:
return EventType.Modified
default:
return EventType.None
}
}
public override func mute(_ path: Path, _ data: [String: Any]) -> Completable {
do {
let ref = try RefFirestore.document(path)
return RxFirestore().set(ref, data)
} catch {
return Completable.error(error)
}
}
public override func unmute(_ path: Path) -> Completable {
do {
let ref = try RefFirestore.document(path)
return RxFirestore().delete(ref)
} catch {
return Completable.error(error)
}
}
}
| 36.546392 | 139 | 0.530042 |
69ce0dbcbce4c618e94a3613229781f0712e3674 | 511 | //
// InterfaceSegregation.swift
// SOLID
//
// Created by Antonio Calvo on 11/03/2017.
// Copyright © 2017 Unagi Studio. All rights reserved.
//
import Foundation
protocol Shape3D: Shape {
var volumen: Double { get }
}
extension Shape3D {
var ratio: Double { return self.area / self.volumen }
}
struct Sphere: Shape3D {
let identifier: String
var radius: Double
var area: Double { return 4.0 * M_PI * pow(radius, 2) }
var volumen: Double { return (4.0 / 3.0) * M_PI * pow(radius, 3) }
}
| 19.653846 | 68 | 0.665362 |
20794cc19c8dd908536974a7e7961810d1a8cbd1 | 2,086 | //
// Placeholders.swift
// Placeholders
//
// Created by Олег on 13.04.17.
// Copyright © 2017 AnySuggestion. All rights reserved.
//
import Foundation
public struct PlaceholdersOptions : OptionSet {
public var rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static var infinite = PlaceholdersOptions(rawValue: 1 << 0)
public static var shuffle = PlaceholdersOptions(rawValue: 1 << 1)
}
final public class Placeholders<Element> {
public var iterator: AnyIterator<Element>
var timer: Timer?
var action: (Element) -> () = { _ in }
public init<Iterator : IteratorProtocol>(iterator: Iterator) where Iterator.Element == Element {
self.iterator = AnyIterator(iterator)
}
public convenience init(placeholders: [Element], options: PlaceholdersOptions = []) {
var finalPlaceholders = placeholders
if options.contains(.shuffle) { finalPlaceholders.shuffle() }
if options.contains(.infinite) {
self.init(iterator: finalPlaceholders.makeIterator().infinite())
} else {
self.init(iterator: finalPlaceholders.makeIterator())
}
}
deinit {
timer?.invalidate()
}
public func start(interval: TimeInterval, fireInitial: Bool, action: @escaping (Element) -> ()) {
self.action = action
let timer = Timer(timeInterval: interval,
target: self,
selector: #selector(act(timer:)),
userInfo: nil,
repeats: true)
RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
self.timer = timer
if fireInitial {
if let firstPlaceholder = iterator.next() {
action(firstPlaceholder)
}
}
}
@objc private func act(timer: Timer) {
if let nextPlaceholder = iterator.next() {
action(nextPlaceholder)
} else {
timer.invalidate()
}
}
}
| 28.575342 | 101 | 0.58581 |
713b8a88c525b8d2e73ec20ec18d9b4554efc42b | 15,843 | // ParameterEncodingTests.swift
//
// Copyright (c) 2014–2015 Alamofire (http://alamofire.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
import XCTest
class AlamofireURLParameterEncodingTestCase: XCTestCase {
let encoding: ParameterEncoding = .URL
var URLRequest: NSURLRequest!
override func setUp() {
super.setUp()
let URL = NSURL(string: "http://example.com/")!
self.URLRequest = NSURLRequest(URL: URL)
}
// MARK: -
func testURLParameterEncodeNilParameters() {
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: nil)
XCTAssertNil(URLRequest.URL.query?, "query should be nil")
}
func testURLParameterEncodeOneStringKeyStringValueParameter() {
let parameters = ["foo": "bar"]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "foo=bar", "query is incorrect")
}
func testURLParameterEncodeOneStringKeyStringValueParameterAppendedToQuery() {
var mutableURLRequest = self.URLRequest.mutableCopy() as NSMutableURLRequest
let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false)!
URLComponents.query = "baz=qux"
mutableURLRequest.URL = URLComponents.URL
let parameters = ["foo": "bar"]
let (URLRequest, error) = self.encoding.encode(mutableURLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "baz=qux&foo=bar", "query is incorrect")
}
func testURLParameterEncodeTwoStringKeyStringValueParameters() {
let parameters = ["foo": "bar", "baz": "qux"]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "baz=qux&foo=bar", "query is incorrect")
}
func testURLParameterEncodeStringKeyIntegerValueParameter() {
let parameters = ["foo": 1]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "foo=1", "query is incorrect")
}
func testURLParameterEncodeStringKeyDoubleValueParameter() {
let parameters = ["foo": 1.1]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "foo=1.1", "query is incorrect")
}
func testURLParameterEncodeStringKeyBoolValueParameter() {
let parameters = ["foo": true]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "foo=1", "query is incorrect")
}
func testURLParameterEncodeStringKeyArrayValueParameter() {
let parameters = ["foo": ["a", 1, true]]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "foo%5B%5D=a&foo%5B%5D=1&foo%5B%5D=1", "query is incorrect")
}
func testURLParameterEncodeStringKeyDictionaryValueParameter() {
let parameters = ["foo": ["bar": 1]]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "foo%5Bbar%5D=1", "query is incorrect")
}
func testURLParameterEncodeStringKeyNestedDictionaryValueParameter() {
let parameters = ["foo": ["bar": ["baz": 1]]]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "foo%5Bbar%5D%5Bbaz%5D=1", "query is incorrect")
}
func testURLParameterEncodeStringKeyNestedDictionaryArrayValueParameter() {
let parameters = ["foo": ["bar": ["baz": ["a", 1, true]]]]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "foo%5Bbar%5D%5Bbaz%5D%5B%5D=a&foo%5Bbar%5D%5Bbaz%5D%5B%5D=1&foo%5Bbar%5D%5Bbaz%5D%5B%5D=1", "query is incorrect")
}
func testURLParameterEncodeStringWithAmpersandKeyStringWithAmpersandValueParameter() {
let parameters = ["foo&bar": "baz&qux", "foobar": "bazqux"]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "foo%26bar=baz%26qux&foobar=bazqux", "query is incorrect")
}
func testURLParameterEncodeStringWithQuestionMarkKeyStringWithQuestionMarkValueParameter() {
let parameters = ["?foo?": "?bar?"]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "%3Ffoo%3F=%3Fbar%3F", "query is incorrect")
}
func testURLParameterEncodeStringWithSpaceKeyStringWithSpaceValueParameter() {
let parameters = [" foo ": " bar "]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "%20foo%20=%20bar%20", "query is incorrect")
}
func testURLParameterEncodeStringWithPlusKeyStringWithPlusValueParameter() {
let parameters = ["+foo+": "+bar+"]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "%2Bfoo%2B=%2Bbar%2B", "query is incorrect")
}
func testURLParameterEncodeStringKeyAllowedCharactersStringValueParameter() {
let parameters = ["allowed": " =\"#%/<>?@\\^`{}[]|&"]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "allowed=%20%3D%22%23%25%2F%3C%3E%3F%40%5C%5E%60%7B%7D%5B%5D%7C%26", "query is incorrect")
}
func testURLParameterEncodeStringKeyPercentEncodedStringValueParameter() {
let parameters = ["percent": "%25"]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "percent=%2525", "query is incorrect")
}
func testURLParameterEncodeStringKeyNonLatinStringValueParameter() {
let parameters = [
"french": "français",
"japanese": "日本語",
"arabic": "العربية",
"emoji": "😃"
]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "arabic=%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9&emoji=%F0%9F%98%83&french=fran%C3%A7ais&japanese=%E6%97%A5%E6%9C%AC%E8%AA%9E", "query is incorrect")
}
func testURLParameterEncodeStringForRequestWithPrecomposedQuery() {
let URL = NSURL(string: "http://example.com/movies?hd=[1]")!
let parameters = ["page": "0"]
let (URLRequest, error) = self.encoding.encode(NSURLRequest(URL: URL), parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "hd=%5B1%5D&page=0", "query is incorrect")
}
func testURLParameterEncodeStringWithPlusKeyStringWithPlusValueParameterForRequestWithPrecomposedQuery() {
let URL = NSURL(string: "http://example.com/movie?hd=[1]")!
let parameters = ["+foo+": "+bar+"]
let (URLRequest, error) = self.encoding.encode(NSURLRequest(URL: URL), parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "hd=%5B1%5D&%2Bfoo%2B=%2Bbar%2B", "query is incorrect")
}
func testURLParameterEncodeGETParametersInURL() {
var mutableURLRequest = self.URLRequest.mutableCopy() as NSMutableURLRequest
mutableURLRequest.HTTPMethod = Method.GET.rawValue
let parameters = ["foo": 1, "bar": 2]
let (URLRequest, error) = self.encoding.encode(mutableURLRequest, parameters: parameters)
XCTAssertEqual(URLRequest.URL.query!, "bar=2&foo=1", "query is incorrect")
XCTAssertNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should be nil")
XCTAssertNil(URLRequest.HTTPBody, "HTTPBody should be nil")
}
func testURLParameterEncodePOSTParametersInHTTPBody() {
var mutableURLRequest = self.URLRequest.mutableCopy() as NSMutableURLRequest
mutableURLRequest.HTTPMethod = Method.POST.rawValue
let parameters = ["foo": 1, "bar": 2]
let (URLRequest, error) = self.encoding.encode(mutableURLRequest, parameters: parameters)
XCTAssertEqual(NSString(data: URLRequest.HTTPBody!, encoding: NSUTF8StringEncoding)!, "bar=2&foo=1", "HTTPBody is incorrect")
XCTAssertEqual(URLRequest.valueForHTTPHeaderField("Content-Type")!, "application/x-www-form-urlencoded", "Content-Type should be application/x-www-form-urlencoded")
XCTAssertNotNil(URLRequest.HTTPBody, "HTTPBody should not be nil")
}
}
class AlamofireJSONParameterEncodingTestCase: XCTestCase {
let encoding: ParameterEncoding = .JSON
var URLRequest: NSURLRequest!
override func setUp() {
super.setUp()
let URL = NSURL(string: "http://example.com/")!
self.URLRequest = NSURLRequest(URL: URL)
}
// MARK: -
func testJSONParameterEncodeNilParameters() {
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: nil)
XCTAssertNil(error, "error should be nil")
XCTAssertNil(URLRequest.URL.query?, "query should be nil")
XCTAssertNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should be nil")
XCTAssertNil(URLRequest.HTTPBody, "HTTPBody should be nil")
}
func testJSONParameterEncodeComplexParameters() {
let parameters = [
"foo": "bar",
"baz": ["a", 1, true],
"qux": ["a": 1,
"b": [2, 2],
"c": [3, 3, 3]
]
]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertNil(error, "error should be nil")
XCTAssertNil(URLRequest.URL.query?, "query should be nil")
XCTAssertNotNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should not be nil")
XCTAssert(URLRequest.valueForHTTPHeaderField("Content-Type")!.hasPrefix("application/json"), "Content-Type should be application/json")
XCTAssertNotNil(URLRequest.HTTPBody, "HTTPBody should not be nil")
let JSON = NSJSONSerialization.JSONObjectWithData(URLRequest.HTTPBody!, options: .AllowFragments, error: nil) as NSObject!
XCTAssertNotNil(JSON, "HTTPBody JSON is invalid")
XCTAssertEqual(JSON as NSObject, parameters as NSObject, "HTTPBody JSON does not equal parameters")
}
}
class AlamofirePropertyListParameterEncodingTestCase: XCTestCase {
let encoding: ParameterEncoding = .PropertyList(.XMLFormat_v1_0, 0)
var URLRequest: NSURLRequest!
override func setUp() {
super.setUp()
let URL = NSURL(string: "http://example.com/")!
self.URLRequest = NSURLRequest(URL: URL)
}
// MARK: -
func testPropertyListParameterEncodeNilParameters() {
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: nil)
XCTAssertNil(error, "error should be nil")
XCTAssertNil(URLRequest.URL.query?, "query should be nil")
XCTAssertNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should be nil")
XCTAssertNil(URLRequest.HTTPBody, "HTTPBody should be nil")
}
func testPropertyListParameterEncodeComplexParameters() {
let parameters = [
"foo": "bar",
"baz": ["a", 1, true],
"qux": ["a": 1,
"b": [2, 2],
"c": [3, 3, 3]
]
]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertNil(error, "error should be nil")
XCTAssertNil(URLRequest.URL.query?, "query should be nil")
XCTAssertNotNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should not be nil")
XCTAssert(URLRequest.valueForHTTPHeaderField("Content-Type")!.hasPrefix("application/x-plist"), "Content-Type should be application/x-plist")
XCTAssertNotNil(URLRequest.HTTPBody, "HTTPBody should not be nil")
let plist = NSPropertyListSerialization.propertyListWithData(URLRequest.HTTPBody!, options: 0, format: nil, error: nil) as NSObject
XCTAssertNotNil(plist, "HTTPBody JSON is invalid")
XCTAssertEqual(plist as NSObject, parameters as NSObject, "HTTPBody plist does not equal parameters")
}
func testPropertyListParameterEncodeDateAndDataParameters() {
let date: NSDate = NSDate()
let data: NSData = "data".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let parameters = [
"date": date,
"data": data
]
let (URLRequest, error) = self.encoding.encode(self.URLRequest, parameters: parameters)
XCTAssertNil(error, "error should be nil")
XCTAssertNil(URLRequest.URL.query?, "query should be nil")
XCTAssertNotNil(URLRequest.valueForHTTPHeaderField("Content-Type"), "Content-Type should not be nil")
XCTAssert(URLRequest.valueForHTTPHeaderField("Content-Type")!.hasPrefix("application/x-plist"), "Content-Type should be application/x-plist")
XCTAssertNotNil(URLRequest.HTTPBody, "HTTPBody should not be nil")
let plist = NSPropertyListSerialization.propertyListWithData(URLRequest.HTTPBody!, options: 0, format: nil, error: nil) as NSObject!
XCTAssertNotNil(plist, "HTTPBody JSON is invalid")
XCTAssert(plist.valueForKey("date") is NSDate, "date is not NSDate")
XCTAssert(plist.valueForKey("data") is NSData, "data is not NSData")
}
}
class AlamofireCustomParameterEncodingTestCase: XCTestCase {
func testCustomParameterEncode() {
let encodingClosure: (URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?) = { (URLRequest, parameters) in
let mutableURLRequest = URLRequest.URLRequest.mutableCopy() as NSMutableURLRequest
mutableURLRequest.setValue("Xcode", forHTTPHeaderField: "User-Agent")
return (mutableURLRequest, nil)
}
let encoding: ParameterEncoding = .Custom(encodingClosure)
let URL = NSURL(string: "http://example.com")!
let URLRequest = NSURLRequest(URL: URL)
let parameters: [String: AnyObject] = [:]
XCTAssertEqual(encoding.encode(URLRequest, parameters: parameters).0, encodingClosure(URLRequest, parameters).0, "URLRequest should be equal")
}
}
| 45.008523 | 197 | 0.685792 |
bbfd130b0408e17562f148ef8fa6920a258902e5 | 948 | import Foundation
public enum TransactionStatus: Int, Codable { case new, relayed, invalid }
public class Transaction {
public var uid: String
public var dataHash: Data
public var version: Int
public var lockTime: Int
public var timestamp: Int
public var order: Int
public var blockHash: Data? = nil
public var isMine: Bool = false
public var isOutgoing: Bool = false
public var status: TransactionStatus = .relayed
public var segWit: Bool = false
public var conflictingTxHash: Data? = nil
public var transactionInfoJson: Data = Data()
public var rawTransaction: String? = nil
public init(version: Int = 0, lockTime: Int = 0, timestamp: Int? = nil) {
self.version = version
self.lockTime = lockTime
self.timestamp = timestamp ?? Int(Date().timeIntervalSince1970)
self.order = 0
self.dataHash = Data()
self.uid = UUID().uuidString
}
}
| 32.689655 | 77 | 0.670886 |
e999b5fa2cdc366068840ec2450f1a7c2263fce2 | 3,111 | @testable import Layout
import Wrappers
import XCTest
final class PaddingLayoutCase: XCTestCase {
func test_inset_leading() {
var traits = LayoutTraits(proposedSize: CGSize(width: 200, height: 200))
var localSut = SimpleCompliantLayout
.init { rect in
XCTAssertTrue(rect == CGRect(x: 10, y: 0, width: 100, height: 100))
}
.frame(width: 100, height: 100, alignment: .topLeading)
.padding(.leading, 10)
.background(
SimpleCompliantLayout { rect in
XCTAssertTrue(rect == CGRect(x: 0, y: 0, width: 110, height: 100))
}
)
localSut.build(&traits)
localSut.layout(in: traits.rect(at: .zero), using: &traits)
}
func test_inset_trailing() {
var traits = LayoutTraits(proposedSize: CGSize(width: 200, height: 200))
var localSut = SimpleCompliantLayout
.init { rect in
XCTAssertTrue(rect == CGRect(x: 0, y: 0, width: 100, height: 100))
}
.frame(width: 100, height: 100, alignment: .topLeading)
.padding(.trailing, 10)
.background(
SimpleCompliantLayout { rect in
XCTAssertTrue(rect == CGRect(x: 0, y: 0, width: 110, height: 100))
}
)
localSut.build(&traits)
localSut.layout(in: traits.rect(at: .zero), using: &traits)
}
func test_inset_top() {
var traits = LayoutTraits(proposedSize: CGSize(width: 200, height: 200))
var localSut = SimpleCompliantLayout
.init { rect in
XCTAssertTrue(rect == CGRect(x: 0, y: 10, width: 100, height: 100))
}
.frame(width: 100, height: 100, alignment: .topLeading)
.padding(.top, 10)
.background(
SimpleCompliantLayout { rect in
XCTAssertTrue(rect == CGRect(x: 0, y: 0, width: 100, height: 110))
}
)
localSut.build(&traits)
localSut.layout(in: traits.rect(at: .zero), using: &traits)
}
func test_inset_bottom() {
var traits = LayoutTraits(proposedSize: CGSize(width: 200, height: 200))
var localSut = SimpleCompliantLayout
.init { rect in
XCTAssertTrue(rect == CGRect(x: 0, y: 0, width: 100, height: 100))
}
.frame(width: 100, height: 100, alignment: .topLeading)
.padding(.bottom, 10)
.background(
SimpleCompliantLayout { rect in
XCTAssertTrue(rect == CGRect(x: 0, y: 0, width: 100, height: 110))
}
)
localSut.build(&traits)
localSut.layout(in: traits.rect(at: .zero), using: &traits)
}
func test_inset_all() {
var traits = LayoutTraits(proposedSize: CGSize(width: 200, height: 200))
var localSut = SimpleCompliantLayout
.init { rect in
XCTAssertTrue(rect == CGRect(x: 10, y: 10, width: 100, height: 100))
}
.frame(width: 100, height: 100, alignment: .topLeading)
.padding(10)
.background(
SimpleCompliantLayout { rect in
XCTAssertTrue(rect == CGRect(x: 0, y: 0, width: 120, height: 120))
}
)
localSut.build(&traits)
localSut.layout(in: traits.rect(at: .zero), using: &traits)
}
// TODO: Check negative insets behavior.
}
| 30.203883 | 76 | 0.616843 |
3a0dcd5a6c53e710b58c1571dcbff9b81aedb302 | 7,867 | //
// RileyLinkDevicesTableViewDataSource.swift
// RileyLinkKitUI
//
// Copyright © 2018 Pete Schwamb. All rights reserved.
//
import UIKit
import CoreBluetooth
import RileyLinkBLEKit
import RileyLinkKit
public class RileyLinkDevicesTableViewDataSource: NSObject {
public let rileyLinkPumpManager: RileyLinkPumpManager
public let devicesSectionIndex: Int
public var tableView: UITableView! {
didSet {
tableView.register(RileyLinkDeviceTableViewCell.self, forCellReuseIdentifier: RileyLinkDeviceTableViewCell.className)
tableView.register(RileyLinkDevicesHeaderView.self, forHeaderFooterViewReuseIdentifier: RileyLinkDevicesHeaderView.className)
// Register for manager notifications
NotificationCenter.default.addObserver(self, selector: #selector(reloadDevices), name: .ManagerDevicesDidChange, object: rileyLinkPumpManager.rileyLinkDeviceProvider)
// Register for device notifications
for name in [.DeviceConnectionStateDidChange, .DeviceRSSIDidChange, .DeviceNameDidChange] as [Notification.Name] {
NotificationCenter.default.addObserver(self, selector: #selector(deviceDidUpdate(_:)), name: name, object: nil)
}
reloadDevices()
}
}
public init(rileyLinkPumpManager: RileyLinkPumpManager, devicesSectionIndex: Int) {
self.rileyLinkPumpManager = rileyLinkPumpManager
self.devicesSectionIndex = devicesSectionIndex
super.init()
}
// MARK: -
lazy var decimalFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
return formatter
}()
public var isScanningEnabled: Bool = false {
didSet {
rileyLinkPumpManager.rileyLinkConnectionManager?.setScanningEnabled(isScanningEnabled)
if isScanningEnabled {
rssiFetchTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(updateRSSI), userInfo: nil, repeats: true)
updateRSSI()
} else {
rssiFetchTimer = nil
}
}
}
private(set) public var devices: [RileyLinkDevice] = [] {
didSet {
// Assume only appends are possible when count changes for algorithmic simplicity
guard oldValue.count < devices.count else {
tableView.reloadSections(IndexSet(integer: devicesSectionIndex), with: .fade)
return
}
tableView.beginUpdates()
let insertedPaths = (oldValue.count..<devices.count).map { (index) -> IndexPath in
return IndexPath(row: index, section: devicesSectionIndex)
}
tableView.insertRows(at: insertedPaths, with: .automatic)
tableView.endUpdates()
}
}
/// Returns an adjusted peripheral state reflecting the user's auto-connect preference.
/// Peripherals connected to the system will show as disconnected if the user hasn't designated them
///
/// - Parameter device: The peripheral
/// - Returns: The adjusted connection state
private func preferenceStateForDevice(_ device: RileyLinkDevice) -> CBPeripheralState? {
guard let connectionManager = rileyLinkPumpManager.rileyLinkConnectionManager else {
return nil
}
let isAutoConnectDevice = connectionManager.shouldConnect(to: device.peripheralIdentifier.uuidString)
var state = device.peripheralState
switch state {
case .disconnected, .disconnecting:
break
case .connecting, .connected:
if !isAutoConnectDevice {
state = .disconnected
}
}
return state
}
private var deviceRSSI: [UUID: Int] = [:]
private var rssiFetchTimer: Timer? {
willSet {
rssiFetchTimer?.invalidate()
}
}
@objc private func reloadDevices() {
rileyLinkPumpManager.rileyLinkDeviceProvider.getDevices { (devices) in
DispatchQueue.main.async {
self.devices = devices
}
}
}
@objc private func deviceDidUpdate(_ note: Notification) {
DispatchQueue.main.async {
if let device = note.object as? RileyLinkDevice, let index = self.devices.index(where: { $0 === device }) {
if let rssi = note.userInfo?[RileyLinkDevice.notificationRSSIKey] as? Int {
self.deviceRSSI[device.peripheralIdentifier] = rssi
}
if let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: self.devicesSectionIndex)) as? RileyLinkDeviceTableViewCell {
cell.configureCellWithName(
device.name,
signal: self.decimalFormatter.decibleString(from: self.deviceRSSI[device.peripheralIdentifier]),
peripheralState: self.preferenceStateForDevice(device)
)
}
}
}
}
@objc public func updateRSSI() {
for device in devices {
device.readRSSI()
}
}
@objc private func deviceConnectionChanged(_ connectSwitch: UISwitch) {
let switchOrigin = connectSwitch.convert(CGPoint.zero, to: tableView)
if let indexPath = tableView.indexPathForRow(at: switchOrigin), indexPath.section == devicesSectionIndex
{
let device = devices[indexPath.row]
if connectSwitch.isOn {
rileyLinkPumpManager.connectToRileyLink(device)
} else {
rileyLinkPumpManager.disconnectFromRileyLink(device)
}
}
}
}
extension RileyLinkDevicesTableViewDataSource: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return devices.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let deviceCell = tableView.dequeueReusableCell(withIdentifier: RileyLinkDeviceTableViewCell.className) as! RileyLinkDeviceTableViewCell
let device = devices[indexPath.row]
deviceCell.configureCellWithName(
device.name,
signal: decimalFormatter.decibleString(from: deviceRSSI[device.peripheralIdentifier]),
peripheralState: self.preferenceStateForDevice(device)
)
deviceCell.connectSwitch?.addTarget(self, action: #selector(deviceConnectionChanged(_:)), for: .valueChanged)
return deviceCell
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return LocalizedString("Devices", comment: "The title of the devices table section in RileyLink settings")
}
}
extension RileyLinkDevicesTableViewDataSource: UITableViewDelegate {
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableView.dequeueReusableHeaderFooterView(withIdentifier: RileyLinkDevicesHeaderView.className)
}
public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return 55
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
}
| 36.934272 | 178 | 0.665057 |
4866b6d1aad4be047369ac668c72ec3ab012e13b | 42 | import Octoseer
try app(.detect()).run()
| 10.5 | 24 | 0.690476 |
206d60dd204f63366ce272caa45eed3a1ce100d8 | 898 | //
// View+OptionalAlignment.swift
// CommerceHQ-iOS
//
// Created by Sergey Kazakov on 17.03.2021.
//
import SwiftUI
extension View {
@ViewBuilder
@inlinable func alignmentGuide(_ alignment: HorizontalAlignment,
isActive: Bool,
computeValue: @escaping (ViewDimensions) -> CGFloat) -> some View {
if isActive {
alignmentGuide(alignment, computeValue: computeValue)
} else {
self
}
}
@ViewBuilder
@inlinable func alignmentGuide(_ alignment: VerticalAlignment,
isActive: Bool,
computeValue: @escaping (ViewDimensions) -> CGFloat) -> some View {
if isActive {
alignmentGuide(alignment, computeValue: computeValue)
} else {
self
}
}
}
| 26.411765 | 102 | 0.535635 |
79256b42ddf5df00705cfe2f830065011686a7fa | 716 | //
// YIL.swift
// Demo
//
// Created by apple on 2017/12/8.
// Copyright © 2017年 apple. All rights reserved.
//
import Foundation
import UIKit
public final class YIL<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
public protocol YILCompatible {
associatedtype CompatibleType
var yil: CompatibleType { get }
}
public extension YILCompatible {
public var yil: YIL<Self> {
get { return YIL(self) }
}
}
extension UICollectionViewCell: YILCompatible{}
extension UIViewController: YILCompatible{}
extension UIImage: YILCompatible{}
extension UIView: YILCompatible{}
extension UIColor: YILCompatible{}
extension NSObject: YILCompatible{}
| 20.457143 | 49 | 0.706704 |
b9fd59426e4a59500718cc2cd49ffaef16178c30 | 39,000 | open class Routes {
public let staticFilesPath: String
public var routes: [Route] = []
public lazy var fallback: Responder = FileResponder(path: self.staticFilesPath)
public init(staticFilesPath: String) {
self.staticFilesPath = staticFilesPath
}
}
extension Routes {
public func compose(_ path: String, middleware: [Middleware] = [], router representable: RouterRepresentable) {
let router = representable.router
let middleware = middleware + router.middleware
for route in router.routes {
for (method, responder) in route.actions {
add(method: method, path: path + route.path, middleware: middleware, responder: responder)
}
}
}
}
extension Routes {
public func fallback(middleware: [Middleware] = [], respond: @escaping Respond) {
fallback(middleware: middleware, responder: BasicResponder(respond))
}
public func fallback(middleware: [Middleware] = [], responder: Responder) {
fallback = middleware.chain(to: responder)
}
}
extension Routes {
public func get(
_ path: String = "",
middleware: [Middleware] = [],
respond: @escaping Respond) {
get(path, middleware: middleware, responder: BasicResponder(respond))
}
public func get(
_ path: String = "",
middleware: [Middleware] = [],
responder: Responder) {
add(method: .get, path: path, middleware: middleware, responder: responder)
}
public func get<
A: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A) throws -> Response) {
add(method: .get, path: path, middleware: middleware, respond: respond)
}
public func get<
A: PathParameterConvertible,
B: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B) throws -> Response) {
add(method: .get, path: path, middleware: middleware, respond: respond)
}
public func get<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C) throws -> Response) {
add(method: .get, path: path, middleware: middleware, respond: respond)
}
public func get<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C, D) throws -> Response) {
add(method: .get, path: path, middleware: middleware, respond: respond)
}
public func get<
T: MapInitializable
>(
_ path: String = "",
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, T) throws -> Response) {
add(method: .get, path: path, middleware: middleware, respond: respond)
}
public func get<
A: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, T) throws -> Response) {
add(method: .get, path: path, middleware: middleware, respond: respond)
}
public func get<
A: PathParameterConvertible,
B: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, T) throws -> Response) {
add(method: .get, path: path, middleware: middleware, respond: respond)
}
public func get<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, T) throws -> Response) {
add(method: .get, path: path, middleware: middleware, respond: respond)
}
public func get<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, D, T) throws -> Response) {
add(method: .get, path: path, middleware: middleware, respond: respond)
}
}
extension Routes {
public func head(
_ path: String = "",
middleware: [Middleware] = [],
respond: @escaping Respond) {
head(path, middleware: middleware, responder: BasicResponder(respond))
}
public func head(
_ path: String = "",
middleware: [Middleware] = [],
responder: Responder) {
add(method: .head, path: path, middleware: middleware, responder: responder)
}
public func head<
A: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A) throws -> Response) {
add(method: .head, path: path, middleware: middleware, respond: respond)
}
public func head<
A: PathParameterConvertible,
B: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B) throws -> Response) {
add(method: .head, path: path, middleware: middleware, respond: respond)
}
public func head<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C) throws -> Response) {
add(method: .head, path: path, middleware: middleware, respond: respond)
}
public func head<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C, D) throws -> Response) {
add(method: .head, path: path, middleware: middleware, respond: respond)
}
public func head<
T: MapInitializable
>(
_ path: String = "",
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, T) throws -> Response) {
add(method: .head, path: path, middleware: middleware, respond: respond)
}
public func head<
A: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, T) throws -> Response) {
add(method: .head, path: path, middleware: middleware, respond: respond)
}
public func head<
A: PathParameterConvertible,
B: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, T) throws -> Response) {
add(method: .head, path: path, middleware: middleware, respond: respond)
}
public func head<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, T) throws -> Response) {
add(method: .head, path: path, middleware: middleware, respond: respond)
}
public func head<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, D, T) throws -> Response) {
add(method: .head, path: path, middleware: middleware, respond: respond)
}
}
extension Routes {
public func post(
_ path: String = "",
middleware: [Middleware] = [],
respond: @escaping Respond) {
post(path, middleware: middleware, responder: BasicResponder(respond))
}
public func post(
_ path: String = "",
middleware: [Middleware] = [],
responder: Responder) {
add(method: .post, path: path, middleware: middleware, responder: responder)
}
public func post<
A: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A) throws -> Response) {
add(method: .post, path: path, middleware: middleware, respond: respond)
}
public func post<
A: PathParameterConvertible,
B: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B) throws -> Response) {
add(method: .post, path: path, middleware: middleware, respond: respond)
}
public func post<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C) throws -> Response) {
add(method: .post, path: path, middleware: middleware, respond: respond)
}
public func post<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C, D) throws -> Response) {
add(method: .post, path: path, middleware: middleware, respond: respond)
}
public func post<
T: MapInitializable
>(
_ path: String = "",
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, T) throws -> Response) {
add(method: .post, path: path, middleware: middleware, respond: respond)
}
public func post<
A: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, T) throws -> Response) {
add(method: .post, path: path, middleware: middleware, respond: respond)
}
public func post<
A: PathParameterConvertible,
B: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, T) throws -> Response) {
add(method: .post, path: path, middleware: middleware, respond: respond)
}
public func post<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, T) throws -> Response) {
add(method: .post, path: path, middleware: middleware, respond: respond)
}
public func post<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, D, T) throws -> Response) {
add(method: .post, path: path, middleware: middleware, respond: respond)
}
}
extension Routes {
public func put(
_ path: String = "",
middleware: [Middleware] = [],
respond: @escaping Respond) {
put(path, middleware: middleware, responder: BasicResponder(respond))
}
public func put(
_ path: String = "",
middleware: [Middleware] = [],
responder: Responder) {
add(method: .put, path: path, middleware: middleware, responder: responder)
}
public func put<
A: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A) throws -> Response) {
add(method: .put, path: path, middleware: middleware, respond: respond)
}
public func put<
A: PathParameterConvertible,
B: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B) throws -> Response) {
add(method: .put, path: path, middleware: middleware, respond: respond)
}
public func put<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible
>(
_ path: String = "",
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C) throws -> Response) {
add(method: .put, path: path, middleware: middleware, respond: respond)
}
public func put<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C, D) throws -> Response) {
add(method: .put, path: path, middleware: middleware, respond: respond)
}
public func put<
T: MapInitializable
>(
_ path: String = "",
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, T) throws -> Response) {
add(method: .put, path: path, middleware: middleware, respond: respond)
}
public func put<
A: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, T) throws -> Response) {
add(method: .put, path: path, middleware: middleware, respond: respond)
}
public func put<
A: PathParameterConvertible,
B: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, T) throws -> Response) {
add(method: .put, path: path, middleware: middleware, respond: respond)
}
public func put<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, T) throws -> Response) {
add(method: .put, path: path, middleware: middleware, respond: respond)
}
public func put<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, D, T) throws -> Response) {
add(method: .put, path: path, middleware: middleware, respond: respond)
}
}
extension Routes {
public func patch(
_ path: String = "",
middleware: [Middleware] = [],
respond: @escaping Respond) {
patch(path, middleware: middleware, responder: BasicResponder(respond))
}
public func patch(
_ path: String = "",
middleware: [Middleware] = [],
responder: Responder) {
add(method: .patch, path: path, middleware: middleware, responder: responder)
}
public func patch<
A: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A) throws -> Response) {
add(method: .patch, path: path, middleware: middleware, respond: respond)
}
public func patch<
A: PathParameterConvertible,
B: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B) throws -> Response) {
add(method: .patch, path: path, middleware: middleware, respond: respond)
}
public func patch<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C) throws -> Response) {
add(method: .patch, path: path, middleware: middleware, respond: respond)
}
public func patch<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C, D) throws -> Response) {
add(method: .patch, path: path, middleware: middleware, respond: respond)
}
public func patch<
T: MapInitializable
>(
_ path: String = "",
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, T) throws -> Response) {
add(method: .patch, path: path, middleware: middleware, respond: respond)
}
public func patch<
A: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, T) throws -> Response) {
add(method: .patch, path: path, middleware: middleware, respond: respond)
}
public func patch<
A: PathParameterConvertible,
B: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, T) throws -> Response) {
add(method: .patch, path: path, middleware: middleware, respond: respond)
}
public func patch<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, T) throws -> Response) {
add(method: .patch, path: path, middleware: middleware, respond: respond)
}
public func patch<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, D, T) throws -> Response) {
add(method: .patch, path: path, middleware: middleware, respond: respond)
}
}
extension Routes {
public func delete(
_ path: String = "",
middleware: [Middleware] = [],
respond: @escaping Respond) {
delete(path, middleware: middleware, responder: BasicResponder(respond))
}
public func delete(
_ path: String = "",
middleware: [Middleware] = [],
responder: Responder) {
add(method: .delete, path: path, middleware: middleware, responder: responder)
}
public func delete<
A: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A) throws -> Response) {
add(method: .delete, path: path, middleware: middleware, respond: respond)
}
public func delete<
A: PathParameterConvertible,
B: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B) throws -> Response) {
add(method: .delete, path: path, middleware: middleware, respond: respond)
}
public func delete<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C) throws -> Response) {
add(method: .delete, path: path, middleware: middleware, respond: respond)
}
public func delete<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C, D) throws -> Response) {
add(method: .delete, path: path, middleware: middleware, respond: respond)
}
public func delete<
T: MapInitializable
>(
_ path: String = "",
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, T) throws -> Response) {
add(method: .delete, path: path, middleware: middleware, respond: respond)
}
public func delete<
A: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, T) throws -> Response) {
add(method: .delete, path: path, middleware: middleware, respond: respond)
}
public func delete<
A: PathParameterConvertible,
B: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, T) throws -> Response) {
add(method: .delete, path: path, middleware: middleware, respond: respond)
}
public func delete<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, T) throws -> Response) {
add(method: .delete, path: path, middleware: middleware, respond: respond)
}
public func delete<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, D, T) throws -> Response) {
add(method: .delete, path: path, middleware: middleware, respond: respond)
}
}
extension Routes {
public func options(
_ path: String = "",
middleware: [Middleware] = [],
respond: @escaping Respond) {
options(path, middleware: middleware, responder: BasicResponder(respond))
}
public func options(
_ path: String = "",
middleware: [Middleware] = [],
responder: Responder) {
add(method: .options, path: path, middleware: middleware, responder: responder)
}
public func options<
A: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A) throws -> Response) {
add(method: .options, path: path, middleware: middleware, respond: respond)
}
public func options<
A: PathParameterConvertible,
B: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B) throws -> Response) {
add(method: .options, path: path, middleware: middleware, respond: respond)
}
public func options<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C) throws -> Response) {
add(method: .options, path: path, middleware: middleware, respond: respond)
}
public func options<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible
>(
_ path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C, D) throws -> Response) {
add(method: .options, path: path, middleware: middleware, respond: respond)
}
public func options<
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, T) throws -> Response) {
add(method: .options, path: path, middleware: middleware, respond: respond)
}
public func options<
A: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, T) throws -> Response) {
add(method: .options, path: path, middleware: middleware, respond: respond)
}
public func options<
A: PathParameterConvertible,
B: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, T) throws -> Response) {
add(method: .options, path: path, middleware: middleware, respond: respond)
}
public func options<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, T) throws -> Response) {
add(method: .options, path: path, middleware: middleware, respond: respond)
}
public func options<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible,
T: MapInitializable
>(
_ path: String,
middleware: [Middleware] = [],
content: T.Type = T.self,
respond: @escaping (Request, A, B, C, D, T) throws -> Response) {
add(method: .options, path: path, middleware: middleware, respond: respond)
}
}
extension Routes {
public func add(methods: Set<Request.Method>, path: String = "", middleware: [Middleware] = [], responder: Responder) {
for method in methods {
add(method: method, path: path, middleware: middleware, responder: responder)
}
}
public func add(methods: Set<Request.Method>, path: String = "", middleware: [Middleware] = [], respond: @escaping Respond) {
add(methods: methods, path: path, middleware: middleware, responder: BasicResponder(respond))
}
}
extension Routes {
public func add<
A: PathParameterConvertible
>(
method: Request.Method,
path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A) throws -> Response) {
let keys = parseParameterKeys(path: path, count: 1)
let responder = BasicResponder { request in
let parameters = try self.parseParameters(
keys: keys,
pathParameters: request.pathParameters
)
let a = try A(pathParameter: parameters[0])
return try respond(request, a)
}
add(method: method, path: path, middleware: middleware, responder: responder)
}
public func add<
A: PathParameterConvertible,
B: PathParameterConvertible
>(
method: Request.Method,
path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B) throws -> Response) {
let keys = parseParameterKeys(path: path, count: 2)
let responder = BasicResponder { request in
let parameters = try self.parseParameters(
keys: keys,
pathParameters: request.pathParameters
)
let a = try A(pathParameter: parameters[0])
let b = try B(pathParameter: parameters[1])
return try respond(request, a, b)
}
add(method: method, path: path, middleware: middleware, responder: responder)
}
public func add<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible
>(
method: Request.Method,
path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C) throws -> Response) {
let keys = parseParameterKeys(path: path, count: 3)
let responder = BasicResponder { request in
let parameters = try self.parseParameters(
keys: keys,
pathParameters: request.pathParameters
)
let a = try A(pathParameter: parameters[0])
let b = try B(pathParameter: parameters[1])
let c = try C(pathParameter: parameters[2])
return try respond(request, a, b, c)
}
add(method: method, path: path, middleware: middleware, responder: responder)
}
public func add<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible
>(
method: Request.Method,
path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C, D) throws -> Response) {
let keys = parseParameterKeys(path: path, count: 4)
let responder = BasicResponder { request in
let parameters = try self.parseParameters(
keys: keys,
pathParameters: request.pathParameters
)
let a = try A(pathParameter: parameters[0])
let b = try B(pathParameter: parameters[1])
let c = try C(pathParameter: parameters[2])
let d = try D(pathParameter: parameters[3])
return try respond(request, a, b, c, d)
}
add(method: method, path: path, middleware: middleware, responder: responder)
}
public func add<
T: MapInitializable
>(
method: Request.Method,
path: String = "",
middleware: [Middleware] = [],
respond: @escaping (_ request: Request, _ content: T) throws -> Response) {
let contentMapper = ContentMapperMiddleware(mappingTo: T.self)
let responder = BasicResponder { request in
guard let content = request.storage[T.contentMapperKey] as? T else {
throw HTTPError.badRequest
}
return try respond(request, content)
}
add(method: method, path: path, middleware: [contentMapper] + middleware, responder: responder)
}
public func add<
A: PathParameterConvertible,
T: MapInitializable
>(
method: Request.Method,
path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, T) throws -> Response) {
let keys = parseParameterKeys(path: path, count: 1)
let contentMapper = ContentMapperMiddleware(mappingTo: T.self)
let responder = BasicResponder { request in
let parameters = try self.parseParameters(
keys: keys,
pathParameters: request.pathParameters
)
let a = try A(pathParameter: parameters[0])
guard let content = request.storage[T.contentMapperKey] as? T else {
throw HTTPError.badRequest
}
return try respond(request, a, content)
}
add(method: method, path: path, middleware: [contentMapper] + middleware, responder: responder)
}
public func add<
A: PathParameterConvertible,
B: PathParameterConvertible,
T: MapInitializable
>(
method: Request.Method,
path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, T) throws -> Response) {
let keys = parseParameterKeys(path: path, count: 2)
let contentMapper = ContentMapperMiddleware(mappingTo: T.self)
let responder = BasicResponder { request in
let parameters = try self.parseParameters(
keys: keys,
pathParameters: request.pathParameters
)
let a = try A(pathParameter: parameters[0])
let b = try B(pathParameter: parameters[1])
guard let content = request.storage[T.contentMapperKey] as? T else {
throw HTTPError.badRequest
}
return try respond(request, a, b, content)
}
add(method: method, path: path, middleware: [contentMapper] + middleware, responder: responder)
}
public func add<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
T: MapInitializable
>(
method: Request.Method,
path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C, T) throws -> Response) {
let keys = parseParameterKeys(path: path, count: 3)
let contentMapper = ContentMapperMiddleware(mappingTo: T.self)
let responder = BasicResponder { request in
let parameters = try self.parseParameters(
keys: keys,
pathParameters: request.pathParameters
)
let a = try A(pathParameter: parameters[0])
let b = try B(pathParameter: parameters[1])
let c = try C(pathParameter: parameters[2])
guard let content = request.storage[T.contentMapperKey] as? T else {
throw HTTPError.badRequest
}
return try respond(request, a, b, c, content)
}
add(method: method, path: path, middleware: [contentMapper] + middleware, responder: responder)
}
public func add<
A: PathParameterConvertible,
B: PathParameterConvertible,
C: PathParameterConvertible,
D: PathParameterConvertible,
T: MapInitializable
>(
method: Request.Method,
path: String,
middleware: [Middleware] = [],
respond: @escaping (Request, A, B, C, D, T) throws -> Response) {
let keys = parseParameterKeys(path: path, count: 4)
let contentMapper = ContentMapperMiddleware(mappingTo: T.self)
let responder = BasicResponder { request in
let parameters = try self.parseParameters(
keys: keys,
pathParameters: request.pathParameters
)
let a = try A(pathParameter: parameters[0])
let b = try B(pathParameter: parameters[1])
let c = try C(pathParameter: parameters[2])
let d = try D(pathParameter: parameters[3])
guard let content = request.storage[T.contentMapperKey] as? T else {
throw HTTPError.badRequest
}
return try respond(request, a, b, c, d, content)
}
add(method: method, path: path, middleware: [contentMapper] + middleware, responder: responder)
}
private func parseParameters(keys: [String], pathParameters: [String: String]) throws -> [String] {
guard keys.count == pathParameters.count else {
throw HTTPError.internalServerError
}
return keys.flatMap({ pathParameters[$0] })
}
// Todo: if there are repeated identifiers call malformedRoute
private func parseParameterKeys(path: String, count: Int) -> [String] {
let keys = path.unicodeScalars
.split(separator: "/")
.filter { $0.first == ":" }
.map { $0.dropFirst() }
.map(String.init)
if keys.count != count {
fatalError("Invalid route \"\(path)\". The number of path parameters doesn't match the number of strong typed parameters in the route.")
}
if Set(keys).count != count {
fatalError("Invalid route \"\(path)\". Path parameter names should be distinct.")
}
return keys
}
}
extension Routes {
public func fallback(_ path: String, middleware: [Middleware] = [], respond: @escaping Respond) {
fallback(path, middleware: middleware, responder: BasicResponder(respond))
}
public func add(method: Request.Method, path: String = "", middleware: [Middleware] = [], respond: @escaping Respond) {
add(method: method, path: path, middleware: middleware, responder: BasicResponder(respond))
}
}
extension Routes {
public func fallback(_ path: String, middleware: [Middleware] = [], responder: Responder) {
let fallback = middleware.chain(to: responder)
let routePath = path
if let route = route(for: routePath) {
route.fallback = fallback
} else {
let route = Route(path: routePath, fallback: fallback)
routes.append(route)
}
}
public func add(method: Request.Method, path: String = "", middleware: [Middleware] = [], responder: Responder) {
let action = middleware.chain(to: responder)
let routePath = path
if let route = route(for: routePath) {
route.addAction(method: method, action: action)
} else {
let route = Route(path: routePath, actions: [method: action], fallback: self.fallback)
routes.append(route)
}
}
private func route(for path: String) -> Route? {
for route in routes where route.path == path {
return route
}
return nil
}
}
| 32.967033 | 148 | 0.585487 |
c175f436642bb0d06a23ed8aac719220e204f537 | 617 | //
// Movie.swift
// MovieAppSwift
//
// Created by don't touch me on 6/15/16.
// Copyright © 2016 trvl, LLC. All rights reserved.
//
import Foundation
class Movie {
var adult: Bool = false
var overview: String = ""
var releaseDate: String = ""
var muviId: Int = 0
var originalTitle: String = ""
var originalLanguage: String = ""
var backdropPath: String = ""
var popularity: Double = 0
var voteCount: Int = 0
var video: Bool = true
var voteAverage: Double = 0
var title: String = ""
var posterPath: String = ""
}
| 17.628571 | 52 | 0.573744 |
9b9e445c066a60c57e14b64d6a2641b7eb159b08 | 624 | //
// HistoryCoordinatorTestCase.swift
// DeFi BrowserTests
//
// Created by Daniel Lima on 01/09/21.
//
import Foundation
import XCTest
@testable import DeFi_Browser
class HistoryCoordinatorTestCase: XCTestCase {
var sut: HistoryCoordinator!
override func setUp() {
super.setUp()
sut = HistoryCoordinator(databaseService: FakeDatabaseService())
}
override func tearDown() {
sut = nil
super.tearDown()
}
func testViewControllerType() {
XCTAssertTrue(sut.rootViewController.viewControllers.first is HistoryViewController)
}
}
| 19.5 | 92 | 0.668269 |
5dc9583fcac3c12c4825d175592a9d7dd21a49eb | 1,347 | //
// RootPaneUIRepresentable.swift
//
// Created by Hans Seiffert on 05.12.20.
//
// ---
// MIT License
//
// Copyright © 2020 Hans Seiffert
//
// 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
//
import UIKit
import QAMenu
public protocol RootPaneUIRepresentable: PaneUIKitRepresentable {
func scrollToTop()
}
| 37.416667 | 82 | 0.747587 |
d9369347145bf02eaac988cccda10929a7a4f714 | 6,339 | //
// SCLLimitAppListController.swift
// SwiftStudy
//
// Created by 王贵彬 on 2020/3/17.
// Copyright © 2020 mac. All rights reserved.
//
import Foundation
import UIKit
import SwiftyJSON
import MJRefresh
struct AppListItem {
var applicationId: String!
var slug: String!
var name: String!
var releaseDate: String!
var version: String!
var description: String!
var categoryId: Int = 0
var categoryName: String!
var iconUrl: String!
var itunesUrl: String!
var starCurrent: String!
var starOverall: String!
var ratingOverall: String!
var downloads: String!
var currentPrice: String!
var lastPrice: String!
var priceTrend: String!
var expireDatetime: String!
var releaseNotes: String!
var updateDate: String!
var fileSize: String!
var ipa: String!
var shares: String!
var favorites: String!
mutating func updateWithData(json:JSON) -> AppListItem {
self.applicationId = json["applicationId"].stringValue
self.slug = json["slug"].stringValue
self.name = json["name"].stringValue
self.releaseDate = json["releaseDate"].stringValue
self.version = json["version"].stringValue
self.description = json["description"].stringValue
self.categoryId = json["categoryId"].intValue
self.categoryName = json["categoryName"].stringValue
self.iconUrl = json["iconUrl"].stringValue
self.itunesUrl = json["itunesUrl"].stringValue
self.starCurrent = json["starCurrent"].stringValue
self.starOverall = json["starOverall"].stringValue
self.ratingOverall = json["ratingOverall"].stringValue
self.downloads = json["downloads"].stringValue
self.currentPrice = json["currentPrice"].stringValue
self.lastPrice = json["lastPrice"].stringValue
self.priceTrend = json["priceTrend"].stringValue
self.expireDatetime = json["expireDatetime"].stringValue
self.releaseNotes = json["releaseNotes"].stringValue
self.updateDate = json["updateDate"].stringValue
self.fileSize = json["fileSize"].stringValue
self.ipa = json["ipa"].stringValue
self.shares = json["shares"].stringValue
self.favorites = json["favorites"].stringValue
return self
}
}
public enum AppListType {
case limit
case sales
case free
case detail
}
class SCLLimitAppListController : SCLBaseViewController {
var page : Int = 1
var type : AppListType = .limit
var dataList : [AppListItem] = []
lazy var tableView:UITableView = {
let tab:UITableView = UITableView(frame: self.view.bounds, style: .plain)
tab.delegate = self
tab.dataSource = self
tab.rowHeight = UITableView.automaticDimension
tab.estimatedRowHeight = 80
tab.register(UINib(nibName:"SCLAppListItemCell", bundle: nil), forCellReuseIdentifier: "SCLAppListItemCell")
self.view.addSubview(tab)
return tab
}()
init(type:AppListType) {
self.type = type
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
self.view.backgroundColor = .white
switch type {
case .limit:
self.navigationItem.title = "限免应用"
case .sales:
self.navigationItem.title = "降价应用"
case .free:
self.navigationItem.title = "免费应用"
case .detail:
self.navigationItem.title = "应用详情"
}
if #available(iOS 11.0, *){
self.tableView.contentInsetAdjustmentBehavior = .never
}else{
self.automaticallyAdjustsScrollViewInsets = false;
}
self.tableView.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(0)
make.leading.trailing.equalTo(self.view)
make.bottom.equalToSuperview().offset(bottomHeight)
}
self.getDataRequest()
self.setUpRefresh()
}
func setUpRefresh(){
self.tableView.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: { [unowned self] in
self.page += 1
self.getDataRequest()
})
}
//获取数据
func getDataRequest() {
var req : APPRequest
switch type {
case .limit:
req = .limitList(page)
case .sales:
req = .salesList(page)
case .free:
req = .freeList(page)
case .detail:
self.tableView.mj_footer?.endRefreshingWithNoMoreData()
self.tableView.reloadData()
return;
}
Network.request(req, success: { (json) in
let dataArr = json["applications"].arrayValue
for json in dataArr {
var item = AppListItem()
item = item.updateWithData(json: json)
self.dataList.append(item)
}
self.tableView.mj_footer?.endRefreshing()
self.tableView.reloadData()
}, error: { (statusCode) in
sclLog("错误状态码: \(statusCode)")
}) { (error) in
sclLog("报错信息: \(error.errorDescription ?? "呵呵")")
}
}
}
extension SCLLimitAppListController : UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:SCLAppListItemCell = tableView.dequeueReusableCell(withIdentifier: "SCLAppListItemCell") as! SCLAppListItemCell
cell.isList = !(type==AppListType.detail)
cell.refreshData(item: dataList[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if type == .detail {
return
}
let vc:SCLLimitAppListController = SCLLimitAppListController(type: .detail)
vc.dataList = [dataList[indexPath.row]]
self.navigationController?.pushViewController(vc, animated: true)
}
}
| 31.695 | 128 | 0.619972 |
f9f3f52217e159444ca1706ef3b208d09cc297ef | 1,906 | /***************************************************************************************************
* eye.swift
*
* This file provides functionality for obtaining an identity matrix.
*
* Author: Philip Erickson
* Creation Date: 1 May 2016
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2016 Philip Erickson
**************************************************************************************************/
// TODO: remove the optional column... maybe a vector wants an eye function?
/// Create a matrix with ones on the main diagonal and zeros elsewhere.
///
/// - Parameters:
/// - rows: number of rows; or edge length in square matrix if columns is nil
/// - columns: number of columns; if nil, return square identity matrix
/// - Returns: identity matrix of specified size
public func eye(_ rows: Int, _ columns: Int? = nil) -> Matrix<Double>
{
let cols = columns ?? rows
precondition(rows > 0 && cols > 0, "Invalid matrix dimensions: \([rows, cols])")
var M = zeros(rows, cols)
for d in 0..<rows
{
M[d,d] = 1
}
return M
}
public func eye(_ size: [Int]) -> Matrix<Double>
{
precondition(size.count == 2, "Matrix size must be 2 dimensional")
return eye(size[0], size[1])
}
/// Return the scalar multiplicative identity.
///
/// - Returns: the scalar 1
public func eye() -> Double
{
return 1.0
} | 33.438596 | 101 | 0.605981 |
e506837312a508bd5a8e1c4aa8bff604b02239d5 | 3,196 | //
// SystemKeyboardButton.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-10-05.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Foundation
import SwiftUI
/**
This view mimics the buttons that are used in an iOS system
keyboard. It wraps the provided content and applies a style.
Note that this view only mimics the look of a system button
for the provided `content` and `style`. It does not add any
gestures or actions. If you do apply gestures or wrap it in
a `Button`, change the `style` according to press state etc.
If you want to create a more complete and functional button,
`SystemKeyboardActionButton` will create a fully functional
and contextually correct button for the provided `action`.
*/
public struct SystemKeyboardButton<Content: View>: View {
/**
Create a system keyboard button.
- Parameters:
- content: The content to present in the button.
- style: The style to apply to the button
*/
public init(
content: Content,
style: SystemKeyboardButtonStyle) {
self.content = content
self.style = style
}
private let content: Content
private let style: SystemKeyboardButtonStyle
public var body: some View {
content.systemKeyboardButtonStyle(style)
.accessibility(addTraits: .isButton)
}
}
struct SystemKeyboardButton_Previews: PreviewProvider {
static let appearance = StandardKeyboardAppearance(
context: .preview)
static func previewButton<Content: View>(for content: Content, style: SystemKeyboardButtonStyle) -> some View {
SystemKeyboardButton(
content: content
.padding(.horizontal, 80)
.padding(.vertical, 20),
style: style)
}
static var previewImage: some View {
Image("photo-forest", bundle: .module)
.resizable()
.aspectRatio(contentMode: .fill)
.edgesIgnoringSafeArea(.all)
}
static var previewStack: some View {
ScrollView {
VStack(spacing: 20) {
previewButton(for: Text("hello"), style: .preview1)
previewButton(for: Text("HELLO"), style: .preview2)
previewButton(for: SystemKeyboardButtonText(text: "🚀", action: .character("")), style: .preview1)
previewButton(for: Image.keyboardGlobe, style: .preview2)
previewButton(for: Text("input"), style: appearance.systemKeyboardButtonStyle(for: .character(""), isPressed: false))
previewButton(for: Text("input pressed"), style: appearance.systemKeyboardButtonStyle(for: .character(""), isPressed: true))
previewButton(for: Text("control"), style: appearance.systemKeyboardButtonStyle(for: .backspace, isPressed: false))
previewButton(for: Text("control pressed"), style: appearance.systemKeyboardButtonStyle(for: .backspace, isPressed: true))
}.padding(.top, 40)
}
}
static var previews: some View {
ZStack {
previewImage
previewStack
}
}
}
| 34 | 140 | 0.640175 |
4bd98fd7f726a64d6355929043f4f49470364781 | 999 | import TSCBasic
public let devEntrypointSHA256 = ByteString([
0xB1, 0x75, 0x6E, 0xC8, 0x39, 0x45, 0xE2, 0x06, 0x00, 0xDD, 0x2E, 0x4D, 0x67, 0xD4, 0xD6, 0xCE,
0x35, 0x62, 0xA0, 0x3D, 0x9F, 0x63, 0x6E, 0x63, 0xAD, 0x79, 0xF2, 0x2D, 0x9D, 0x3C, 0x5C, 0x0A
])
public let bundleEntrypointSHA256 = ByteString([
0x2B, 0xD2, 0xB5, 0x0C, 0x08, 0xFB, 0x5A, 0x8D, 0x55, 0xC4, 0x4B, 0x3A, 0x51, 0x63, 0x80, 0x1F,
0xB9, 0x15, 0x50, 0xD2, 0xB6, 0x12, 0xC3, 0xDE, 0x3A, 0x7D, 0xEB, 0xB0, 0x1F, 0x40, 0x06, 0x3F
])
public let testEntrypointSHA256 = ByteString([
0xCE, 0x38, 0xCE, 0x55, 0x05, 0x45, 0x93, 0x75, 0xE6, 0xCD, 0xCE, 0x1C, 0xA6, 0x67, 0x14, 0x16,
0xBB, 0xAE, 0xF3, 0xFC, 0xFB, 0x86, 0xCB, 0x98, 0x1A, 0x66, 0x5C, 0xC7, 0x6C, 0x3B, 0x81, 0xF4
])
public let staticArchiveHash = ByteString([
0x7A, 0x27, 0x1A, 0x64, 0x7A, 0xEB, 0xE1, 0x94, 0x24, 0xE6, 0x4A, 0x98, 0x14, 0x5F, 0xC3, 0xA7,
0xB5, 0x6B, 0x81, 0x51, 0x75, 0xA0, 0x8E, 0xF4, 0x8D, 0x48, 0xC9, 0x9A, 0x60, 0x25, 0x24, 0x2F,
])
| 45.409091 | 97 | 0.680681 |
0aae5d9c8fc1cf3b08855af2308e76c82e7f2d2d | 4,382 | /**
* Splash
* Copyright (c) John Sundell 2018
* MIT license - see LICENSE.md
*/
#if os(macOS)
import Cocoa
#endif
#if os(iOS)
import UIKit
#endif
/// Output format to use to generate an NSAttributedString from the
/// highlighted code. A `Theme` is used to determine what fonts and
/// colors to use for the various tokens.
public struct AttributedStringOutputFormat: OutputFormat {
public var theme: Theme
public init(theme: Theme) {
self.theme = theme
}
public func makeBuilder() -> Builder {
return Builder(theme: theme)
}
}
public extension AttributedStringOutputFormat {
struct Builder: OutputBuilder {
private let theme: Theme
private lazy var font = loadFont()
private var string = NSMutableAttributedString()
fileprivate init(theme: Theme) {
self.theme = theme
}
public mutating func addToken(_ token: String, ofType type: TokenType) {
let color = theme.tokenColors[type] ?? Color(red: 1, green: 1, blue: 1)
string.append(token, font: font, color: color)
}
public mutating func addPlainText(_ text: String) {
string.append(text, font: font, color: theme.plainTextColor)
}
public mutating func addWhitespace(_ whitespace: String) {
let color = Color(red: 1, green: 1, blue: 1)
string.append(whitespace, font: font, color: color)
}
public func build() -> NSAttributedString {
return NSAttributedString(attributedString: string)
}
#if os(macOS)
private mutating func loadFont() -> NSFont {
let size = CGFloat(theme.font.size)
switch theme.font.resource {
case .system:
return .defaultFont(ofSize: size)
case .path(let path):
guard let font = NSFont.loaded(from: path, size: size) else {
return .defaultFont(ofSize: size)
}
return font
}
}
#endif
#if os(iOS)
private mutating func loadFont() -> UIFont {
let size = CGFloat(theme.font.size)
return .defaultFont(ofSize: size)
}
#endif
}
}
#if os(macOS)
private extension NSMutableAttributedString {
func append(_ string: String, font: NSFont, color: Color) {
let color = NSColor(
red: CGFloat(color.red),
green: CGFloat(color.green),
blue: CGFloat(color.blue),
alpha: CGFloat(color.alpha)
)
let attributedString = NSAttributedString(string: string, attributes: [
.foregroundColor: color,
.font: font
])
append(attributedString)
}
}
private extension NSFont {
static func loaded(from path: String, size: CGFloat) -> NSFont? {
let url = CFURLCreateWithFileSystemPath(
kCFAllocatorDefault,
path as CFString,
.cfurlposixPathStyle,
false
)
guard let font = url.flatMap(CGDataProvider.init).flatMap(CGFont.init) else {
return nil
}
return CTFontCreateWithGraphicsFont(font, size, nil, nil)
}
static func defaultFont(ofSize size: CGFloat) -> NSFont {
guard let courier = loaded(from: "/Library/Fonts/Courier New.ttf", size: size) else {
return .systemFont(ofSize: size)
}
return courier
}
}
#endif
#if os(iOS)
private extension NSMutableAttributedString {
func append(_ string: String, font: UIFont, color: Color) {
let color = UIColor(
red: CGFloat(color.red),
green: CGFloat(color.green),
blue: CGFloat(color.blue),
alpha: CGFloat(color.alpha)
)
let attributedString = NSAttributedString(string: string, attributes: [
.foregroundColor: color,
.font: font
])
append(attributedString)
}
}
private extension UIFont {
static func defaultFont(ofSize size: CGFloat) -> UIFont {
guard let menlo = UIFont(name: "Menlo-Regular", size: size) else {
return .systemFont(ofSize: size)
}
return menlo
}
}
#endif
| 26.883436 | 93 | 0.574852 |
0e5eb6b8bad3ea1c10eb4526ee2dfcfc9d4d97d9 | 239 | //
// Double+.swift
// CleanArchitecture
//
// Created by Tuan Truong on 9/6/18.
// Copyright © 2018 Framgia. All rights reserved.
//
extension Double {
var currency: String {
return String(format: "$%.02f", self)
}
}
| 17.071429 | 50 | 0.615063 |
6934d85e08bc6bf7c55c2a1322b8d9ff9f25aa2a | 2,285 | import UIKit
import DateToolsSwift
open class DayViewController: UIViewController, EventDataSource, DayViewDelegate {
public lazy var dayView: DayView = DayView()
public var dataSource: EventDataSource? {
get {
return dayView.dataSource
}
set(value) {
dayView.dataSource = value
}
}
public var delegate: DayViewDelegate? {
get {
return dayView.delegate
}
set(value) {
dayView.delegate = value
}
}
public var calendar = Calendar.autoupdatingCurrent {
didSet {
dayView.calendar = calendar
}
}
open override func loadView() {
view = dayView
}
override open func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = []
view.tintColor = UIColor.red
dataSource = self
delegate = self
dayView.reloadData()
let sizeClass = traitCollection.horizontalSizeClass
configureDayViewLayoutForHorizontalSizeClass(sizeClass)
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
dayView.scrollToFirstEventIfNeeded()
}
open override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
configureDayViewLayoutForHorizontalSizeClass(newCollection.horizontalSizeClass)
}
func configureDayViewLayoutForHorizontalSizeClass(_ sizeClass: UIUserInterfaceSizeClass) {
dayView.transitionToHorizontalSizeClass(sizeClass)
}
open func reloadData() {
dayView.reloadData()
}
open func updateStyle(_ newStyle: CalendarStyle) {
dayView.updateStyle(newStyle)
}
open func eventsForDate(_ date: Date) -> [EventDescriptor] {
return [Event]()
}
// MARK: DayViewDelegate
open func dayViewDidSelectEventView(_ eventView: EventView) {
}
open func dayViewDidLongPressEventView(_ eventView: EventView) {
}
open func dayViewDidTapTimeline(dayView: DayView) {
}
open func dayView(dayView: DayView, willMoveTo date: Date) {
}
open func dayView(dayView: DayView, didMoveTo date: Date) {
}
open func dayView(dayView: DayView, didLongPressTimelineAt date: Date) {
}
open func dayView(dayView: DayView, didUpdate event: EventDescriptor) {
}
}
| 24.052632 | 131 | 0.724289 |
71a5383fa7cf67cac746ba929d9364f8806dfc53 | 3,093 | //
// S3+Put.swift
// S3
//
// Created by Ondrej Rafaj on 01/12/2016.
// Copyright © 2016 manGoweb UK Ltd. All rights reserved.
//
import Foundation
import Vapor
// Helper S3 extension for uploading files by their URL/path
extension S3 {
// MARK: Upload
/// Upload file to S3
public func put(file: File.Upload, headers: HTTPHeaders) throws -> EventLoopFuture<File.Response> {
let builder = urlBuilder()
let url = try builder.url(file: file)
var awsheaders: HTTPHeaders = headers
awsheaders.replaceOrAdd(name: "content-type", value: file.mime.description)
awsheaders.replaceOrAdd(name: "x-amz-acl", value: file.access.rawValue)
let headers = try signer.headers(for: .PUT, urlString: url, headers: awsheaders, payload: Payload.bytes(file.data))
return self.client.put(URI(string: url.absoluteString), headers: headers) { req in
var buffer = ByteBufferAllocator().buffer(capacity: file.data.count)
buffer.writeBytes(file.data)
req.body = buffer
}.flatMapThrowing { response -> File.Response in
try self.check(response)
let res = File.Response(data: file.data, bucket: file.bucket ?? self.defaultBucket, path: file.path, access: file.access, mime: file.mime)
return res
}
}
/// Upload file to S3
public func put(file: File.Upload) throws -> EventLoopFuture<File.Response> {
return try put(file: file, headers: [:])
}
/// Upload file by it's URL to S3
public func put(file url: URL, destination: String, access: AccessControlList = .privateAccess) throws -> EventLoopFuture<File.Response> {
let data: Data = try Data(contentsOf: url)
let file = File.Upload(data: data, bucket: nil, destination: destination, access: access, mime: mimeType(forFileAtUrl: url))
return try put(file: file)
}
/// Upload file by it's path to S3
public func put(file path: String, destination: String, access: AccessControlList = .privateAccess) throws -> EventLoopFuture<File.Response> {
let url: URL = URL(fileURLWithPath: path)
return try put(file: url, destination: destination, bucket: nil, access: access)
}
/// Upload file by it's URL to S3, full set
public func put(file url: URL, destination: String, bucket: String?, access: AccessControlList = .privateAccess) throws -> EventLoopFuture<File.Response> {
let data: Data = try Data(contentsOf: url)
let file = File.Upload(data: data, bucket: bucket, destination: destination, access: access, mime: mimeType(forFileAtUrl: url))
return try put(file: file)
}
/// Upload file by it's path to S3, full set
public func put(file path: String, destination: String, bucket: String?, access: AccessControlList = .privateAccess) throws -> EventLoopFuture<File.Response> {
let url: URL = URL(fileURLWithPath: path)
return try put(file: url, destination: destination, bucket: bucket, access: access)
}
}
| 44.185714 | 163 | 0.658907 |
d64eedb04f8e62b943515672487ac9ad0e938b80 | 645 | //
// SearchCellViewModel.swift
// FinalProject
//
// Created by PCI0007 on 9/21/20.
// Copyright © 2020 MBA0176. All rights reserved.
//
import Foundation
final class SearchCellViewModel {
private(set) var trackName: String
private(set) var artistName: String
private(set) var artworkUrl600: String
private(set) var primaryGenreName: String
init(trackName: String, artistName: String, artworkUrl600: String, primaryGenreName: String) {
self.trackName = trackName
self.artistName = artistName
self.artworkUrl600 = artworkUrl600
self.primaryGenreName = primaryGenreName
}
}
| 25.8 | 98 | 0.702326 |
ab0b26d535ce9f7a2c7409969e3001a28b91eb3c | 1,014 | // swift-tools-version:4.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "InterviewUIComponent",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "InterviewUIComponent",
targets: ["InterviewUIComponent"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/CoderMJLee/MJRefresh.git", .upToNextMinor(from: "3.7.0")),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "InterviewUIComponent",
dependencies: ["MJRefresh"]),
],
)
| 39 | 117 | 0.662722 |
5da3695b169b9bac11760302d5a26baecd7379b2 | 2,373 |
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
@available(iOS 13.0, *)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
@available(iOS 13.0, *)
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
@available(iOS 13.0, *)
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
@available(iOS 13.0, *)
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
@available(iOS 13.0, *)
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
@available(iOS 13.0, *)
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 44.773585 | 147 | 0.703751 |
23b8fae135cdc4fefb9bb4c4511c373af27a663f | 21,989 | //
// TMBarView.swift
// Tabman
//
// Created by Merrick Sapsford on 01/08/2018.
// Copyright © 2019 UI At Six. All rights reserved.
//
import UIKit
import Pageboy
// swiftlint:disable file_length
private struct TMBarViewDefaults {
static let animationDuration: TimeInterval = 0.25
static let spacing: CGFloat = 8.0
}
/// `TMBarView` is the default Tabman implementation of `TMBar`. A `UIView` that contains a `TMBarLayout` which displays
/// a collection of `TMBarButton`, and also a `TMBarIndicator`. The types of these three components are defined by constraints
/// in the `TMBarView` type definition.
open class TMBarView<Layout: TMBarLayout, Button: TMBarButton, Indicator: TMBarIndicator>: UIView, TMTransitionStyleable, TMBarLayoutParent {
// MARK: Types
public typealias BarButtonCustomization = (Button) -> Void
public enum ScrollMode: Int {
case interactive
case swipe
case none
}
// MARK: Properties
internal let rootContentStack = UIStackView()
internal let scrollViewContainer = EdgeFadedView()
internal let scrollView = GestureScrollView()
internal private(set) var layoutGrid: TMBarViewLayoutGrid!
private let scrollHandler: TMBarViewScrollHandler
private var rootContainerTop: NSLayoutConstraint!
private var rootContainerBottom: NSLayoutConstraint!
private var indicatorLayoutHandler: TMBarIndicatorLayoutHandler?
private var indicatedPosition: CGFloat?
private lazy var contentInsetGuides = TMBarViewContentInsetGuides(for: self)
private var accessoryViews = [AccessoryLocation: UIView]()
// MARK: Components
/// `TMBarLayout` that dictates display and behavior of bar buttons and other bar view components.
public private(set) lazy var layout = Layout()
/// Collection of `TMBarButton` objects that directly map to the `TMBarItem`s provided by the `dataSource`.
public let buttons = TMBarButtonCollection<Button>()
/// `TMBarIndicator` that is used to indicate the current bar index state.
public let indicator = Indicator()
/// Background view that appears behind all content in the bar view.
///
/// Note: Default style is `.blur(style: .extraLight)`.
public let backgroundView = TMBarBackgroundView(style: .blur(style: .extraLight))
/// Items that are displayed in the bar.
public private(set) var items: [TMBarItemable]?
/// Object that acts as a data source to the BarView.
public weak var dataSource: TMBarDataSource?
/// Object that acts as a delegate to the BarView.
///
/// By default this is set to the `TabmanViewController` the bar is added to.
public weak var delegate: TMBarDelegate?
// MARK: Accessory Views
/// View to display on the left (or leading) edge of the bar.
///
/// This view is within the scroll view and is subject to scroll off-screen
/// with bar contents.
open var leftAccessoryView: UIView? {
didSet {
setAccessoryView(leftAccessoryView, at: .leading)
}
}
/// View to display on the left (or leading) edge of the bar.
///
/// This view is not part of the scrollable bar contents and will be visible at all times.
open var leftPinnedAccessoryView: UIView? {
didSet {
setAccessoryView(leftPinnedAccessoryView, at: .leadingPinned)
}
}
/// View to display on the right (or trailing) edge of the bar.
///
/// This view is within the scroll view and is subject to scroll off-screen
/// with bar contents.
open var rightAccessoryView: UIView? {
didSet {
setAccessoryView(rightAccessoryView, at: .trailing)
}
}
/// View to display on the right (or trailing) edge of the bar.
///
/// This view is not part of the scrollable bar contents and will be visible at all times.
open var rightPinnedAccessoryView: UIView? {
didSet {
setAccessoryView(rightPinnedAccessoryView, at: .trailingPinned)
}
}
// MARK: Customization
/// Transition style for updating bar view components such as scroll view.
internal var transitionStyle: TMTransitionStyle = .progressive
/// The type of scrolling interaction to allow.
///
/// Options:
/// - `.interactive`: The bar contents can be scrolled interactively.
/// - `.swipe`: The bar contents can be scrolled through with swipe gestures.
/// - `.none`: The bar contents can't be scrolled at all.
public var scrollMode: ScrollMode {
set {
scrollView.scrollMode = GestureScrollView.ScrollMode(rawValue: newValue.rawValue)!
} get {
return ScrollMode(rawValue: scrollView.scrollMode.rawValue)!
}
}
/// Whether to fade the leading and trailing edges of the bar content to an alpha of 0.
public var fadesContentEdges: Bool {
set {
scrollViewContainer.showFade = newValue
} get {
return scrollViewContainer.showFade
}
}
/// Spacing between components in the bar, such as between the layout and accessory views.
///
/// Defaults to `8.0`.
public var spacing: CGFloat {
set {
layoutGrid.horizontalSpacing = newValue
} get {
return layoutGrid.horizontalSpacing
}
}
// MARK: TMBarLayoutParent
var contentInset: UIEdgeInsets = .zero {
didSet {
updateScrollViewContentInset()
}
}
var alignment: TMBarLayout.Alignment = .leading {
didSet {
updateScrollViewContentInset()
}
}
// MARK: Init
public required init() {
self.scrollHandler = TMBarViewScrollHandler(for: scrollView)
super.init(frame: .zero)
buttons.interactionHandler = self
scrollHandler.delegate = self
scrollView.gestureDelegate = self
layout(in: self)
NotificationCenter.default.addObserver(self,
selector: #selector(itemNeedsUpdate(_:)),
name: TMBarItemableNeedsUpdateNotification,
object: nil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("BarView does not support Interface Builder")
}
// MARK: Layout
open override func layoutSubviews() {
super.layoutSubviews()
UIView.performWithoutAnimation {
reloadIndicatorPosition()
updateEdgeFades(for: scrollView)
}
}
private func layout(in view: UIView) {
layoutRootViews(in: view)
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollViewContainer.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
scrollView.leadingAnchor.constraint(equalTo: scrollViewContainer.leadingAnchor),
scrollView.topAnchor.constraint(equalTo: scrollViewContainer.topAnchor),
scrollView.trailingAnchor.constraint(equalTo: scrollViewContainer.trailingAnchor),
scrollView.bottomAnchor.constraint(equalTo: scrollViewContainer.bottomAnchor)
])
rootContentStack.addArrangedSubview(scrollViewContainer)
// Set up grid - stack views that content views are added to.
self.layoutGrid = TMBarViewLayoutGrid(with: layout.view)
layoutGrid.horizontalSpacing = TMBarViewDefaults.spacing
scrollView.addSubview(layoutGrid)
layoutGrid.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
layoutGrid.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
layoutGrid.topAnchor.constraint(equalTo: scrollView.topAnchor),
layoutGrid.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
layoutGrid.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
layoutGrid.heightAnchor.constraint(equalTo: rootContentStack.heightAnchor)
])
layout.layout(parent: self, insetGuides: contentInsetGuides)
self.indicatorLayoutHandler = container(for: indicator).layoutHandler
}
private func layoutRootViews(in view: UIView) {
var constraints = [NSLayoutConstraint]()
view.addSubview(backgroundView)
backgroundView.translatesAutoresizingMaskIntoConstraints = false
constraints.append(contentsOf: [
backgroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
backgroundView.topAnchor.constraint(equalTo: view.topAnchor),
backgroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
backgroundView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
rootContentStack.axis = .horizontal
view.addSubview(rootContentStack)
rootContentStack.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11, *) {
constraints.append(contentsOf: [
rootContentStack.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
rootContentStack.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor)
])
} else {
constraints.append(contentsOf: [
rootContentStack.leadingAnchor.constraint(equalTo: view.leadingAnchor),
rootContentStack.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
}
self.rootContainerTop = rootContentStack.topAnchor.constraint(equalTo: view.topAnchor)
self.rootContainerBottom = view.bottomAnchor.constraint(equalTo: rootContentStack.bottomAnchor)
constraints.append(contentsOf: [rootContainerTop, rootContainerBottom])
NSLayoutConstraint.activate(constraints)
}
private func updateScrollViewContentInset() {
let alignmentInset: CGFloat
switch alignment {
case .leading:
alignmentInset = 0.0
case .center:
let buttonWidth = (buttons.all.first?.bounds.size.width ?? 0.0) / 2.0
var width = bounds.size.width / 2
if #available(iOS 11, *) {
width -= safeAreaInsets.left
}
alignmentInset = width - buttonWidth
case .trailing:
let buttonWidth = (buttons.all.first?.bounds.size.width ?? 0.0)
var width = bounds.size.width
if #available(iOS 11, *) {
width -= safeAreaInsets.left
}
alignmentInset = width - buttonWidth
}
let sanitizedContentInset = UIEdgeInsets(top: 0.0, left: alignmentInset + contentInset.left, bottom: 0.0, right: contentInset.right)
scrollView.contentInset = sanitizedContentInset
scrollView.contentOffset.x -= sanitizedContentInset.left
rootContainerTop.constant = contentInset.top
rootContainerBottom.constant = contentInset.bottom
}
// MARK: Notifications
@objc private func itemNeedsUpdate(_ notification: Notification) {
guard let item = notification.object as? TMBarItemable else {
return
}
guard let button = buttons.all.filter({ $0.item === item }).first else {
return
}
UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveEaseIn, animations: {
button.populate(for: item)
self.reloadIndicatorPosition()
}, completion: nil)
}
}
// MARK: - Bar
extension TMBarView: TMBar {
public func reloadData(at indexes: ClosedRange<Int>,
context: TMBarReloadContext) {
guard let dataSource = self.dataSource else {
return
}
var items = self.items ?? [TMBarItemable]()
switch context {
case .full, .insertion:
if context == .full && buttons.all.count > 0 { // remove existing buttons
layout.remove(buttons: buttons.all)
buttons.all.removeAll()
}
var newButtons = [Button]()
for index in indexes.lowerBound ... indexes.upperBound {
let item = dataSource.barItem(for: self, at: index)
items.insert(item, at: index)
let button = Button(for: item, intrinsicSuperview: self)
button.populate(for: item)
button.update(for: .unselected)
newButtons.append(button)
}
buttons.all.insert(contentsOf: newButtons, at: indexes.lowerBound)
layout.insert(buttons: newButtons, at: indexes.lowerBound)
case .deletion:
var buttonsToRemove = [Button]()
for index in indexes.lowerBound ... indexes.upperBound {
let button = buttons.all[index]
buttonsToRemove.append(button)
items.remove(at: index)
}
layout.remove(buttons: buttonsToRemove)
}
self.items = items
UIView.performWithoutAnimation {
layoutIfNeeded()
updateScrollViewContentInset()
reloadIndicatorPosition()
}
}
public func update(for position: CGFloat,
capacity: Int,
direction: TMBarUpdateDirection,
animation: TMAnimation) {
self.indicatedPosition = position
layoutIfNeeded()
let handler = TMBarViewUpdateHandler(for: self,
at: position,
capacity: capacity,
direction: direction,
expectedAnimation: animation)
// Update indicator
handler.update(component: indicator) { (context) in
self.indicatorLayoutHandler?.update(for: context.focusRect.rect(isProgressive: self.indicator.isProgressive,
overscrollBehavior: self.indicator.overscrollBehavior)) // Update indicator layout
self.indicator.superview?.layoutIfNeeded()
}
// Update buttons
handler.update(component: buttons) { (context) in
self.buttons.stateController.update(for: context.position,
direction: context.direction)
}
// Update bar view
handler.update(component: self) { (context) in
let pinnedAccessoryWidth = (self.accessoryView(at: .leadingPinned)?.bounds.size.width ?? 0.0) + (self.accessoryView(at: .trailingPinned)?.bounds.size.width ?? 0.0)
var maxOffsetX = (self.scrollView.contentSize.width - (self.bounds.size.width - pinnedAccessoryWidth)) + self.scrollView.contentInset.right // maximum possible x offset
let minOffsetX = -self.scrollView.contentInset.left
if #available(iOS 11, *) {
maxOffsetX += self.safeAreaInsets.right
}
// Aim to use a focus origin that centers the button in the bar.
// If the minimum viable x offset is greater than the center of the bar however, use that.
let focusRectCenterX = context.focusRect.origin.x + (context.focusRect.size.width / 2)
let barCenterX = (self.bounds.size.width / 2) - focusRectCenterX
let centeredFocusOrigin = CGPoint(x: -barCenterX, y: 0.0)
// Create offset and sanitize for bounds.
var contentOffset = centeredFocusOrigin
contentOffset.x = max(minOffsetX, min(contentOffset.x, maxOffsetX))
// Calculate how far the scroll view leading content inset is actually off 'center' as a delta.
// As the target for this update is to center the focusRect in the bar, we have to append
// this delta to the offset otherwise the inset could be ignored.
let actualCenterX = ((self.bounds.size.width - (self.buttons.all.first?.bounds.size.width ?? 0.0 )) / 2)
let offCenterDelta = self.scrollView.contentInset.left - actualCenterX
if offCenterDelta > 0.0 {
contentOffset.x -= offCenterDelta
}
self.scrollView.contentOffset = contentOffset
}
}
// MARK: Updating
func updateEdgeFades(for scrollView: UIScrollView) {
guard scrollView.contentSize.width > scrollView.bounds.size.width else {
scrollViewContainer.leadingFade = 0.0
scrollViewContainer.trailingFade = 0.0
return
}
let contentSizeRatio = ((scrollView.contentSize.width - scrollView.bounds.size.width) / 2)
let leadingOffsetRatio = max(0.0, min(1.0, (scrollView.contentOffset.x / contentSizeRatio)))
let trailingOffsetRatio = max(0.0, min(1.0, ((scrollView.contentSize.width - scrollView.bounds.size.width) - scrollView.contentOffset.x) / contentSizeRatio))
scrollViewContainer.leadingFade = leadingOffsetRatio
scrollViewContainer.trailingFade = trailingOffsetRatio
}
}
// MARK: - Indicator
extension TMBarView {
/// Create a container for an indicator to be displayed in. Will also add the container to the view hierarchy.
///
/// - Parameter indicator: Indicator to create container for.
/// - Returns: Indicator container.
private func container(for indicator: Indicator) -> TMBarIndicatorContainer<Indicator> {
let container = TMBarIndicatorContainer(for: indicator)
switch indicator.displayMode {
case .top:
layoutGrid.addTopSubview(container)
case .bottom:
layoutGrid.addBottomSubview(container)
case .fill:
scrollView.insertSubview(container, at: 0)
container.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
container.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
container.topAnchor.constraint(equalTo: scrollView.topAnchor),
container.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
container.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor)
])
}
return container
}
private func reloadIndicatorPosition() {
guard let indicatedPosition = self.indicatedPosition else {
return
}
update(for: indicatedPosition,
capacity: buttons.all.count,
direction: .none,
animation: TMAnimation(isEnabled: true,
duration: TMBarViewDefaults.animationDuration))
}
}
// MARK: - Interaction
extension TMBarView: TMBarButtonInteractionHandler, GestureScrollViewGestureDelegate {
func barButtonInteraction(controller: TMBarButtonInteractionController,
didHandlePressOf button: TMBarButton,
at index: Int) {
delegate?.bar(self, didRequestScrollTo: index)
}
func scrollView(_ scrollView: GestureScrollView,
didReceiveSwipeTo direction: UISwipeGestureRecognizer.Direction) {
let index = Int(indicatedPosition ?? 0)
switch direction {
case .right, .down:
delegate?.bar(self, didRequestScrollTo: max(0, index - 1))
case .left, .up:
delegate?.bar(self, didRequestScrollTo: min(buttons.all.count - 1, index + 1))
default:
fatalError()
}
}
}
// MARK: - Accessory View Management
private extension TMBarView {
enum AccessoryLocation: String {
case leading
case leadingPinned
case trailing
case trailingPinned
}
func setAccessoryView(_ view: UIView?,
at location: AccessoryLocation) {
cleanUpOldAccessoryView(at: location)
addAccessoryView(view, at: location)
}
private func accessoryView(at location: AccessoryLocation) -> UIView? {
return accessoryViews[location]
}
private func cleanUpOldAccessoryView(at location: AccessoryLocation) {
let view = accessoryView(at: location)
view?.removeFromSuperview()
accessoryViews[location] = nil
}
private func addAccessoryView(_ view: UIView?, at location: AccessoryLocation) {
guard let view = view else {
return
}
accessoryViews[location] = view
switch location {
case .leading:
layoutGrid.addLeadingSubview(view)
case .leadingPinned:
rootContentStack.insertArrangedSubview(view, at: 0)
case .trailing:
layoutGrid.addTrailingSubview(view)
case .trailingPinned:
rootContentStack.insertArrangedSubview(view, at: rootContentStack.arrangedSubviews.count)
}
reloadIndicatorPosition()
}
}
extension TMBarView: TMBarViewScrollHandlerDelegate {
func barViewScrollHandler(_ handler: TMBarViewScrollHandler,
didReceiveUpdated contentOffset: CGPoint,
from scrollView: UIScrollView) {
updateEdgeFades(for: scrollView)
}
}
| 39.477558 | 180 | 0.622766 |
1e5f73b7ecce654be846888d374bd70a65ac0381 | 756 | import XCTest
import LICustomActionSheet
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 26.068966 | 111 | 0.60582 |
87b4f34ea79ae700d98d2bea6631aef94bf33ce8 | 1,046 | // swift-tools-version:5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "ArgumentMagics",
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "ArgumentMagics",
targets: ["ArgumentMagics"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.target(
name: "ArgumentMagics",
dependencies: []),
.testTarget(
name: "ArgumentMagicsTests",
dependencies: ["ArgumentMagics"]),
]
)
| 36.068966 | 117 | 0.630019 |
4898f9bcf4b17e1d165e2450fe9b31f31eef3633 | 2,302 | //
// ViewController.swift
// MustacheDemoOSX
//
// Created by Gwendal Roué on 11/02/2015.
// Copyright (c) 2015 Gwendal Roué. All rights reserved.
//
import Cocoa
import Mustache
class ViewController: NSViewController {
@IBOutlet var templateTextView: NSTextView!
@IBOutlet var JSONTextView: NSTextView!
@IBOutlet var renderingTextView: NSTextView!
@IBOutlet var model: Model!
let font = NSFont(name: "Menlo", size: 12)
override func viewDidLoad() {
super.viewDidLoad()
templateTextView.isAutomaticQuoteSubstitutionEnabled = false
templateTextView.textStorage?.font = font
JSONTextView.isAutomaticQuoteSubstitutionEnabled = false
JSONTextView.textStorage?.font = font
}
@IBAction func render(_ sender: Any?) {
do {
let template = try Template(string: model.templateString)
// Play with those goodies in your templates:
// They are documented at https://github.com/groue/GRMustache.swift/blob/master/Guides/goodies.md
let percentFormatter = NumberFormatter()
percentFormatter.numberStyle = .percent
template.register(percentFormatter, forKey: "percent")
template.register(StandardLibrary.each, forKey: "each")
template.register(StandardLibrary.zip, forKey: "zip")
template.register(StandardLibrary.Localizer(), forKey: "localize")
template.register(StandardLibrary.HTMLEscape, forKey: "HTMLEscape")
template.register(StandardLibrary.URLEscape, forKey: "URLEscape")
template.register(StandardLibrary.javascriptEscape, forKey: "javascriptEscape")
let data = model.JSONString.data(using: .utf8)!
let JSONObject = try JSONSerialization.jsonObject(with: data, options: [])
let string = try template.render(Box(JSONObject as? NSObject))
present(renderingString: string)
}
catch let error as NSError {
present(renderingString: "\(error.domain): \(error.localizedDescription)")
}
}
func present(renderingString string: String) {
self.renderingTextView.string = string
self.renderingTextView.textStorage?.font = font
}
}
| 37.737705 | 109 | 0.661599 |
38ac36a17764aae0c56c56503331d4779be778ef | 785 | //
// RoundedButton.swift
// quick-draw-ios
//
// Created by Betül Çalık on 30.01.2022.
//
import UIKit
class RoundedButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
updateLayerProperties()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
titleLabel?.font = Fonts.loraRegular
}
func updateLayerProperties() {
layer.masksToBounds = false
layer.cornerRadius = 20
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 2, height: 2)
layer.shouldRasterize = true
layer.shadowRadius = 5
layer.shadowOpacity = 0.6
}
}
| 21.216216 | 59 | 0.6 |
5de0a20e92ad6547b06e80f791d8e265e534eb03 | 2,112 | /*
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Note:
* You may assume that all inputs are consist of lowercase letters a-z.
* All inputs are guaranteed to be non-empty strings.
*/
class Trie {
class TrieNode<Key: Hashable> {
var key: Key?
weak var parent: TrieNode?
var children: [Key: TrieNode] = [:]
var isTerminating = false
init(key: Key?, parent: TrieNode?) {
self.key = key
self.parent = parent
}
}
typealias Node = TrieNode<Character>
private let root = Node(key: nil, parent: nil)
/** Initialize your data structure here. */
init() {}
/** Inserts a word into the trie. */
func insert(_ word: String) {
var current = root
for c in word {
if current.children[c] == nil {
current.children[c] = Node(key: c, parent: current)
}
current = current.children[c]!
}
current.isTerminating = true
}
/** Returns if the word is in the trie. */
func search(_ word: String) -> Bool {
var current = root
for c in word {
guard let child = current.children[c] else {
return false
}
current = child
}
return current.isTerminating
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func startsWith(_ prefix: String) -> Bool {
var current = root
for c in prefix {
guard let child = current.children[c] else { return false }
current = child
}
return true
}
}
/**
* Your Trie object will be instantiated and called as such:
* let obj = Trie()
* obj.insert(word)
* let ret_2: Bool = obj.search(word)
* let ret_3: Bool = obj.startsWith(prefix)
*/
| 23.730337 | 86 | 0.566761 |
14ca0b15f6ef1994b2b887a01e45d0843b7e77f3 | 2,006 |
import UIKit
final class Observable<T> {
init(_ value: T) {
self.value = value
}
var value: T {
didSet {
changeHandlers.forEach({ $0.handler(value) })
}
}
typealias ChangeHandler = ((T) -> Void)
private var changeHandlers: [(identifier: Int, handler: ChangeHandler)] = []
/**
Adds observer to the value.
- parameter initial: The handler is run immediately with initial value.
- parameter handler: The handler to execute when value changes.
- returns: Identifier of the observer.
*/
@discardableResult func observe(initial: Bool = false, handler: @escaping ChangeHandler) -> Int {
let identifier = UUID().uuidString.hashValue
changeHandlers.append((identifier, handler))
guard initial else { return identifier }
handler(value)
return identifier
}
/**
Removes observer to the value.
- parameter observer: The observer to remove.
*/
func removeObserver(_ observer: Int) {
changeHandlers = changeHandlers.filter({ $0.identifier != observer })
}
}
final class Pantry {
let jams = Observable([Jam(flavour: .apple)])
func add(jam: Jam) {
jams.value.append(jam)
}
}
struct Jam {
enum Flavour: String {
case apple, orange
}
let flavour: Flavour
init(flavour: Flavour) {
self.flavour = flavour
}
}
let pantry = Pantry()
print("Adding count and contents observers.")
let observer = pantry.jams.observe { (jams) in
print("Pantry now has \(jams.count) jars of jam.")
}
pantry.jams.observe(initial: true) { (jams) in
let contents = jams.map({ $0.flavour.rawValue }).joined(separator: ", ")
print("Jams in pantry: \(contents)")
}
print("Adding jam to pantry.")
pantry.add(jam: Jam(flavour: .orange))
print("Removing count observer.")
pantry.jams.removeObserver(observer)
print("Adding jam to pantry.")
pantry.add(jam: Jam(flavour: .apple))
| 26.051948 | 101 | 0.628614 |
019f8107b0a97f734fe8bd72719f08614e39337a | 4,041 | //
// SelectLocationViewController.swift
// FBLA2017
//
// Created by Luke Mann on 4/10/17.
// Copyright © 2017 Luke Mann. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import NVActivityIndicatorView
//This class is used to pick a location for the Uplaod View Controller
protocol SelectLocationProtocol {
func recieveLocation(latitude: String, longitude: String, addressString: String)
}
class SelectLocationViewController: UIViewController {
@IBOutlet weak var address: UILabel!
@IBOutlet weak var mapView: MKMapView!
var geoCoder: CLGeocoder!
var locationManager: CLLocationManager!
var previousAddress: String!
@IBOutlet weak var setLocationButton: UIButton!
var delgate: SelectLocationProtocol?
var activitiyIndicator: NVActivityIndicatorView?
override func viewDidLoad() {
super.viewDidLoad()
setLocationButton.layer.cornerRadius = setLocationButton.frame.height / 2
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.delegate = self
locationManager.requestLocation()
geoCoder = CLGeocoder()
self.mapView.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
activitiyIndicator = ActivityIndicatorLoader.startActivityIndicator(view: self.view)
}
}
//MARK: - Location Manager Delegate
extension SelectLocationViewController:CLLocationManagerDelegate {
func geoCode(location: CLLocation!) {
// geoCoder.cancelGeocode()
geoCoder.reverseGeocodeLocation(location, completionHandler: { (data, _) -> Void in
guard let placeMarks = data as [CLPlacemark]! else {
return
}
let loc: CLPlacemark = placeMarks[0]
let addressDict: [NSString:NSObject] = loc.addressDictionary as! [NSString: NSObject]
let addrList = addressDict["FormattedAddressLines"] as! [String]
if addrList.count > 1 {
let address: String? = addrList[1]
self.address.text = address
self.previousAddress = address
self.activitiyIndicator?.stopAnimating()
} else {
if !addrList.isEmpty {
let address: String? = addrList[0]
self.address.text = address
self.previousAddress = address
self.activitiyIndicator?.stopAnimating()
} else {
let address="Unknown Location"
self.address.text = address
self.previousAddress = address
self.activitiyIndicator?.stopAnimating()
}
}
})
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.first!
self.mapView.centerCoordinate = location.coordinate
let reg = MKCoordinateRegionMakeWithDistance(location.coordinate, 5, 5)
self.mapView.setRegion(reg, animated: true)
geoCode(location: location)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}
//MARK:- Map View Delegate
extension SelectLocationViewController:MKMapViewDelegate {
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let location = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude)
geoCode(location: location)
}
@IBAction func setLocationButtonPressed(_ sender: UIButton) {
let latitudeText: String = "\(mapView.centerCoordinate.latitude)"
let longitudeText: String = "\(mapView.centerCoordinate.longitude)"
self.delgate?.recieveLocation(latitude: latitudeText, longitude:longitudeText, addressString: self.address.text!)
dismiss(animated: true, completion: nil)
}
}
| 33.957983 | 125 | 0.669141 |
019e8cb65a8e115be3c8d6ee5a5b6c15c41e4d0c | 785 | //
// Networking+Extensions.swift
// NovastoneCodeTest
//
// Created by Anderson Gralha on 23/08/20.
// Copyright © 2020 Anderson Gralha. All rights reserved.
//
import UIKit
import Alamofire
extension NetworkingController {
struct TestRequest1: NetworkProtocol {
var url: String = "https://www.google.com"
var headers: HTTPHeaders? = nil
var httpMethod: HTTPMethod = .get
var parameters: Parameters? = nil
var encoding: ParameterEncoding = URLEncoding.default
}
struct TestRequest2: NetworkProtocol {
var url: String = ""
var headers: HTTPHeaders? = nil
var httpMethod: HTTPMethod = .get
var parameters: Parameters? = nil
var encoding: ParameterEncoding = URLEncoding.default
}
}
| 26.166667 | 61 | 0.666242 |
33d5caca3ff1704bcb368066eb8aa5d89daa8627 | 1,952 | import MixboxUiTestsFoundation
import MixboxTestsFoundation
class OrMatcherTests: BaseLogicMatcherTests {
func test___match___matches___if_at_least_one_of_nested_matchers_matches() {
assertMatches(
matcher: OrMatcher([AlwaysTrueMatcher()])
)
assertMatches(
matcher: OrMatcher([AlwaysFalseMatcher(), AlwaysTrueMatcher()])
)
assertMatches(
matcher: OrMatcher([AlwaysTrueMatcher(), AlwaysFalseMatcher()])
)
}
func test___match___mismatches___if_all_nested_matchers_mismatches() {
assertMismatches(
matcher: OrMatcher([AlwaysFalseMatcher()])
)
}
func test___match___mismatches___if_there_are_no_nested_matchers() {
assertMismatches(
matcher: OrMatcher([])
)
}
func test___match___mismatches_with_percentageOfMatching_equal_to_maximum_of_percentageOfMatching_of_nested_matchers() {
let point10Matcher: Matcher<Int> = AndMatcher(
Array(repeating: AlwaysTrueMatcher(), count: 1)
+ Array(repeating: AlwaysFalseMatcher(), count: 9)
)
let point25Matcher: Matcher<Int> = AndMatcher(
Array(repeating: AlwaysTrueMatcher(), count: 1)
+ Array(repeating: AlwaysFalseMatcher(), count: 3)
)
assertMismatches(
matcher: OrMatcher([point10Matcher, point25Matcher]),
percentageOfMatching: 0.25
)
assertMismatches(
matcher: OrMatcher([point25Matcher, point10Matcher]),
percentageOfMatching: 0.25
)
}
func test___description___is_correct() {
assertDescriptionIsCorrect(
matcher: OrMatcher([AlwaysFalseMatcher()]),
description:
"""
Любое из [
Всегда ложно
]
"""
)
}
}
| 30.5 | 124 | 0.604508 |
3a3258f45c9be3551bf128482dbdf149a3a5063a | 1,837 | //
// AppDelegate.swift
// AudioPlayerTest
//
// Created by pk on 2017/10/11.
// Copyright © 2017年 pk. 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) {
// 不在跑步页面才需要关闭
if AudioManager.shared.audioPlayScene != .run {
AudioManager.shared.openBackgroundAudioAutoPlay = false
}
}
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) {
AudioManager.shared.openBackgroundAudioAutoPlay = true
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 36.74 | 285 | 0.733261 |
673ddf73ce7f96a8770487347b1ef658b068276f | 2,264 | //
// ChatListViewController.swift
// tdlib-ios
//
// Created by Anton Glezman on 29/09/2019.
// Copyright © 2019 Anton Glezman. All rights reserved.
//
import UIKit
final class ChatListViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
private let authService = ServiceLayer.instance.authService
private let chatListService = ServiceLayer.instance.chatListService
override func viewDidLoad() {
super.viewDidLoad()
chatListService.delegate = self
try? chatListService.getChatList(limit: 30)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard
segue.identifier == "ShowChat",
let vc = segue.destination as? ConversationViewController,
let chat = sender as? ChatInfo
else {
return
}
vc.chat = chat
}
@IBAction func close(_ sender: Any) {
authService.logout()
ApplicationController.showAuth()
}
}
extension ChatListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chatListService.chatList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChatCell", for: indexPath)
let chatOrder = chatListService.chatList[indexPath.row]
guard let chat = chatListService.chats[chatOrder.chatId] else { preconditionFailure() }
cell.textLabel?.text = chat.title
cell.detailTextLabel?.text = chat.lastMessage?.text
return cell
}
}
extension ChatListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let chatOrder = chatListService.chatList[indexPath.row]
guard let chat = chatListService.chats[chatOrder.chatId] else { preconditionFailure() }
performSegue(withIdentifier: "ShowChat", sender: chat)
}
}
extension ChatListViewController: ChatListServiceDelegate {
func chatListUpdated() {
tableView.reloadData()
}
}
| 29.025641 | 100 | 0.678004 |
f9b9d2a59cd462e96ccb996a19335fc84c2d9263 | 10,897 | // ActionButton.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 ActionButton
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public typealias ActionButtonAction = (ActionButton) -> Void
open class ActionButton: NSObject {
/// The action the button should perform when tapped
open var action: ActionButtonAction?
/// The button's background color : set default color and selected color
open var backgroundColor: UIColor = UIColor(red: 238.0/255.0, green: 130.0/255.0, blue: 34.0/255.0, alpha:1.0) {
willSet {
floatButton.backgroundColor = newValue
backgroundColorSelected = newValue
}
}
/// The button's background color : set default color
open var backgroundColorSelected: UIColor = UIColor(red: 238.0/255.0, green: 130.0/255.0, blue: 34.0/255.0, alpha:1.0)
/// Indicates if the buttons is active (showing its items)
fileprivate(set) open var active: Bool = false
/// An array of items that the button will present
internal var items: [ActionButtonItem]? {
willSet {
for abi in self.items! {
abi.view.removeFromSuperview()
}
}
didSet {
placeButtonItems()
showActive(true)
}
}
/// The button that will be presented to the user
fileprivate var floatButton: UIButton!
/// View that will hold the placement of the button's actions
fileprivate var contentView: UIView!
/// View where the *floatButton* will be displayed
fileprivate var parentView: UIView!
/// Blur effect that will be presented when the button is active
fileprivate var blurVisualEffect: UIVisualEffectView!
// Distance between each item action
fileprivate let itemOffset = -55
/// the float button's radius
fileprivate let floatButtonRadius = 50
public init(attachedToView view: UIView, items: [ActionButtonItem]?) {
super.init()
self.parentView = view
self.items = items
let bounds = self.parentView.bounds
self.floatButton = UIButton(type: .custom)
self.floatButton.layer.cornerRadius = CGFloat(floatButtonRadius / 2)
self.floatButton.layer.shadowOpacity = 1
self.floatButton.layer.shadowRadius = 2
self.floatButton.layer.shadowOffset = CGSize(width: 1, height: 1)
self.floatButton.layer.shadowColor = UIColor.gray.cgColor
self.floatButton.setTitle("+", for: UIControl.State())
self.floatButton.setImage(nil, for: UIControl.State())
self.floatButton.backgroundColor = self.backgroundColor
self.floatButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 35)
self.floatButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
self.floatButton.isUserInteractionEnabled = true
self.floatButton.translatesAutoresizingMaskIntoConstraints = false
self.floatButton.addTarget(self, action: #selector(ActionButton.buttonTapped(_:)), for: .touchUpInside)
self.floatButton.addTarget(self, action: #selector(ActionButton.buttonTouchDown(_:)), for: .touchDown)
self.parentView.addSubview(self.floatButton)
self.contentView = UIView(frame: bounds)
self.blurVisualEffect = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
self.blurVisualEffect.frame = self.contentView.frame
self.contentView.addSubview(self.blurVisualEffect)
let tap = UITapGestureRecognizer(target: self, action: #selector(ActionButton.backgroundTapped(_:)))
self.contentView.addGestureRecognizer(tap)
self.installConstraints()
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Set Methods
open func setTitle(_ title: String?, forState state: UIControl.State) {
floatButton.setImage(nil, for: state)
floatButton.setTitle(title, for: state)
floatButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
}
open func setImage(_ image: UIImage?, forState state: UIControl.State) {
setTitle(nil, forState: state)
floatButton.setImage(image, for: state)
floatButton.adjustsImageWhenHighlighted = false
floatButton.contentEdgeInsets = UIEdgeInsets.zero
}
//MARK: - Auto Layout Methods
/**
Install all the necessary constraints for the button. By the default the button will be placed at 15pts from the bottom and the 15pts from the right of its *parentView*
*/
fileprivate func installConstraints() {
let views: [String: UIView] = ["floatButton":self.floatButton, "parentView":self.parentView]
let width = NSLayoutConstraint.constraints(withVisualFormat: "H:[floatButton(\(floatButtonRadius))]", options: NSLayoutConstraint.FormatOptions.alignAllCenterX, metrics: nil, views: views)
let height = NSLayoutConstraint.constraints(withVisualFormat: "V:[floatButton(\(floatButtonRadius))]", options: NSLayoutConstraint.FormatOptions.alignAllCenterX, metrics: nil, views: views)
self.floatButton.addConstraints(width)
self.floatButton.addConstraints(height)
let trailingSpacing = NSLayoutConstraint.constraints(withVisualFormat: "V:[floatButton]-15-|", options: NSLayoutConstraint.FormatOptions.alignAllCenterX, metrics: nil, views: views)
let bottomSpacing = NSLayoutConstraint.constraints(withVisualFormat: "H:[floatButton]-15-|", options: NSLayoutConstraint.FormatOptions.alignAllCenterX, metrics: nil, views: views)
self.parentView.addConstraints(trailingSpacing)
self.parentView.addConstraints(bottomSpacing)
}
//MARK: - Button Actions Methods
@objc func buttonTapped(_ sender: UIControl) {
animatePressingWithScale(1.0)
if let unwrappedAction = self.action {
unwrappedAction(self)
}
}
@objc func buttonTouchDown(_ sender: UIButton) {
animatePressingWithScale(0.9)
}
//MARK: - Gesture Recognizer Methods
@objc func backgroundTapped(_ gesture: UIGestureRecognizer) {
if self.active {
self.toggle()
}
}
//MARK: - Custom Methods
/**
Presents or hides all the ActionButton's actions
*/
open func toggleMenu() {
self.placeButtonItems()
self.toggle()
}
//MARK: - Action Button Items Placement
/**
Defines the position of all the ActionButton's actions
*/
fileprivate func placeButtonItems() {
if let optionalItems = self.items {
for item in optionalItems {
item.view.center = CGPoint(x: self.floatButton.center.x - 83, y: self.floatButton.center.y)
item.view.removeFromSuperview()
self.contentView.addSubview(item.view)
}
}
}
//MARK - Float Menu Methods
/**
Presents or hides all the ActionButton's actions and changes the *active* state
*/
fileprivate func toggle() {
self.animateMenu()
self.showBlur()
self.active = !self.active
self.floatButton.backgroundColor = self.active ? backgroundColorSelected : backgroundColor
self.floatButton.isSelected = self.active
}
fileprivate func animateMenu() {
let rotation = self.active ? 0 : CGFloat(Double.pi)
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: UIView.AnimationOptions.allowAnimatedContent, animations: {
if self.floatButton.imageView?.image == nil {
self.floatButton.transform = CGAffineTransform(rotationAngle: rotation)
}
self.showActive(false)
}, completion: {completed in
if self.active == false {
self.hideBlur()
}
})
}
fileprivate func showActive(_ active: Bool) {
if self.active == active {
self.contentView.alpha = 1.0
if let optionalItems = self.items {
for (index, item) in optionalItems.enumerated() {
let offset = index + 1
let translation = self.itemOffset * offset
item.view.transform = CGAffineTransform(translationX: 0, y: CGFloat(translation))
item.view.alpha = 1
}
}
} else {
self.contentView.alpha = 0.0
if let optionalItems = self.items {
for item in optionalItems {
item.view.transform = CGAffineTransform(translationX: 0, y: 0)
item.view.alpha = 0
}
}
}
}
fileprivate func showBlur() {
self.parentView.insertSubview(self.contentView, belowSubview: self.floatButton)
}
fileprivate func hideBlur() {
self.contentView.removeFromSuperview()
}
/**
Animates the button pressing, by the default this method just scales the button down when it's pressed and returns to its normal size when the button is no longer pressed
- parameter scale: how much the button should be scaled
*/
fileprivate func animatePressingWithScale(_ scale: CGFloat) {
UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.1, options: UIView.AnimationOptions.allowAnimatedContent, animations: {
self.floatButton.transform = CGAffineTransform(scaleX: scale, y: scale)
}, completion: nil)
}
}
| 40.812734 | 197 | 0.654951 |
5bdc70b13e9c9b3c3bc722923c4d7020efc484c9 | 4,223 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator.
// DO NOT EDIT.
import SotoCore
/// Error enum for DeviceFarm
public struct DeviceFarmErrorType: AWSErrorType {
enum Code: String {
case argumentException = "ArgumentException"
case cannotDeleteException = "CannotDeleteException"
case idempotencyException = "IdempotencyException"
case internalServiceException = "InternalServiceException"
case invalidOperationException = "InvalidOperationException"
case limitExceededException = "LimitExceededException"
case notEligibleException = "NotEligibleException"
case notFoundException = "NotFoundException"
case serviceAccountException = "ServiceAccountException"
case tagOperationException = "TagOperationException"
case tagPolicyException = "TagPolicyException"
case tooManyTagsException = "TooManyTagsException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize DeviceFarm
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// An invalid argument was specified.
public static var argumentException: Self { .init(.argumentException) }
/// The requested object could not be deleted.
public static var cannotDeleteException: Self { .init(.cannotDeleteException) }
/// An entity with the same name already exists.
public static var idempotencyException: Self { .init(.idempotencyException) }
/// An internal exception was raised in the service. Contact [email protected] if you see this error.
public static var internalServiceException: Self { .init(.internalServiceException) }
/// There was an error with the update request, or you do not have sufficient permissions to update this VPC endpoint configuration.
public static var invalidOperationException: Self { .init(.invalidOperationException) }
/// A limit was exceeded.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// Exception gets thrown when a user is not eligible to perform the specified transaction.
public static var notEligibleException: Self { .init(.notEligibleException) }
/// The specified entity was not found.
public static var notFoundException: Self { .init(.notFoundException) }
/// There was a problem with the service account.
public static var serviceAccountException: Self { .init(.serviceAccountException) }
/// The operation was not successful. Try again.
public static var tagOperationException: Self { .init(.tagOperationException) }
/// The request doesn't comply with the AWS Identity and Access Management (IAM) tag policy. Correct your request and then retry it.
public static var tagPolicyException: Self { .init(.tagPolicyException) }
/// The list of tags on the repository is over the limit. The maximum number of tags that can be applied to a repository is 50.
public static var tooManyTagsException: Self { .init(.tooManyTagsException) }
}
extension DeviceFarmErrorType: Equatable {
public static func == (lhs: DeviceFarmErrorType, rhs: DeviceFarmErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension DeviceFarmErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 45.902174 | 136 | 0.699029 |
1c3ff865367749a74a3aed3367b665aa6ab1a7c9 | 898 | //
// DZMRMBaseView.swift
// DZMeBookRead
//
// Created by 邓泽淼 on 2017/5/11.
// Copyright © 2017年 DZM. All rights reserved.
//
import UIKit
class DZMRMBaseView: UIControl {
/// 菜单
weak var readMenu:DZMReadMenu!
/// 初始化方法
convenience init(readMenu:DZMReadMenu) {
self.init(frame:CGRect.zero,readMenu:readMenu)
}
/// 初始化方法
init(frame:CGRect,readMenu:DZMReadMenu) {
self.readMenu = readMenu
super.init(frame: frame)
addSubviews()
}
/// 初始化方法
override init(frame: CGRect) {
super.init(frame: frame)
addSubviews()
}
/// 添加子控件
func addSubviews() {
backgroundColor = DZMMenuUIColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 17.96 | 59 | 0.553452 |
75cc27b9df3fe05b81deb3afe62ed27efe316e85 | 727 | import Turf
import CoreLocation
@_spi(Experimental) public struct OverviewViewportStateOptions: Equatable {
public var geometry: Geometry
public var padding: UIEdgeInsets
public var bearing: CLLocationDirection
public var pitch: CGFloat
public var animationDuration: TimeInterval
public init(geometry: GeometryConvertible,
padding: UIEdgeInsets = .zero,
bearing: CLLocationDirection = 0,
pitch: CGFloat = 0,
animationDuration: TimeInterval = 1) {
self.geometry = geometry.geometry
self.padding = padding
self.bearing = bearing
self.pitch = pitch
self.animationDuration = animationDuration
}
}
| 31.608696 | 75 | 0.668501 |
48c4dc5a9d9f05d71c2eb2e56793af8fc2717cb1 | 750 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "ApolloDeveloperKit",
platforms: [.iOS(.v9), .macOS(.v10_10)],
products: [
.library(
name: "ApolloDeveloperKit",
targets: ["ApolloDeveloperKit"])
],
dependencies: [
.package(name: "Apollo", url: "https://github.com/apollographql/apollo-ios.git", "0.34.0"..<"1.0.0")
],
targets: [
.target(
name: "ApolloDeveloperKit",
dependencies: ["Apollo"],
resources: [.copy("Assets")]),
.testTarget(
name: "ApolloDeveloperKitTests",
dependencies: ["ApolloDeveloperKit"],
exclude: ["ApolloDeveloperKitTests.swift"])
]
)
| 27.777778 | 108 | 0.561333 |
2fe5039af2b2d09ac5614e490ec0602024621831 | 10,657 | //
// Dip
//
// Copyright (c) 2015 Olivier Halligon <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
///A key used to store definitons in a container.
public struct DefinitionKey: Hashable, CustomStringConvertible {
public let type: Any.Type
public let typeOfArguments: Any.Type
public private(set) var tag: DependencyContainer.Tag?
init(type: Any.Type, typeOfArguments: Any.Type, tag: DependencyContainer.Tag? = nil) {
self.type = type
self.typeOfArguments = typeOfArguments
self.tag = tag
}
public var hashValue: Int {
return "\(type)-\(typeOfArguments)-\(tag.desc)".hashValue
}
public var description: String {
return "type: \(type), arguments: \(typeOfArguments), tag: \(tag.desc)"
}
func tagged(with tag: DependencyContainer.Tag?) -> DefinitionKey {
var tagged = self
tagged.tag = tag
return tagged
}
/// Check two definition keys on equality by comparing their `type`, `factoryType` and `tag` properties.
public static func ==(lhs: DefinitionKey, rhs: DefinitionKey) -> Bool {
return
lhs.type == rhs.type &&
lhs.typeOfArguments == rhs.typeOfArguments &&
lhs.tag == rhs.tag
}
}
///Dummy protocol to store definitions for different types in collection
public protocol DefinitionType: class { }
/**
`Definition<T, U>` describes how instances of type `T` should be created when this type is resolved by the `DependencyContainer`.
- `T` is the type of the instance to resolve
- `U` is the type of runtime arguments accepted by factory that will create an instance of T.
For example `Definition<Service, String>` is the type of definition that will create an instance of type `Service` using factory that accepts `String` argument.
*/
public final class Definition<T, U>: DefinitionType {
public typealias F = (U) throws -> T
//MARK: - _Definition
weak var container: DependencyContainer?
let factory: F
let scope: ComponentScope
var weakFactory: ((Any) throws -> Any)!
var resolveProperties: ((DependencyContainer, Any) throws -> ())?
init(scope: ComponentScope, factory: @escaping F) {
self.factory = factory
self.scope = scope
}
/**
Set the block that will be used to resolve dependencies of the instance.
This block will be called before `resolve(tag:)` returns.
- parameter block: The block to resolve property dependencies of the instance.
- returns: modified definition
- note: To resolve circular dependencies at least one of them should use this block
to resolve its dependencies. Otherwise the application will enter an infinite loop and crash.
- note: You can call this method several times on the same definition.
Container will call all provided blocks in the same order.
**Example**
```swift
container.register { ClientImp(service: try container.resolve() as Service) as Client }
container.register { ServiceImp() as Service }
.resolvingProperties { container, service in
service.client = try container.resolve() as Client
}
```
*/
@discardableResult public func resolvingProperties(_ block: @escaping (DependencyContainer, T) throws -> ()) -> Definition {
if let oldBlock = self.resolveProperties {
self.resolveProperties = {
try oldBlock($0, $1 as! T)
try block($0, $1 as! T)
}
}
else {
self.resolveProperties = { try block($0, $1 as! T) }
}
return self
}
/// Calls `resolveDependencies` block if it was set.
func resolveProperties(of instance: Any, container: DependencyContainer) throws {
guard let resolvedInstance = instance as? T else { return }
if let forwardsTo = forwardsTo {
try forwardsTo.resolveProperties(of: resolvedInstance, container: container)
}
if let resolveProperties = self.resolveProperties {
try resolveProperties(container, resolvedInstance)
}
}
//MARK: - AutoWiringDefinition
var autoWiringFactory: ((DependencyContainer, DependencyContainer.Tag?) throws -> Any)?
var numberOfArguments: Int = 0
//MARK: - TypeForwardingDefinition
/// Types that can be resolved using this definition.
private(set) var implementingTypes: [Any.Type] = [(T?).self, (T!).self]
/// Return `true` if type can be resolved using this definition
func doesImplements(type aType: Any.Type) -> Bool {
return implementingTypes.contains(where: { $0 == aType })
}
//MARK: - _TypeForwardingDefinition
/// Adds type as being able to be resolved using this definition
func _implements(type aType: Any.Type) {
_implements(types: [aType])
}
/// Adds types as being able to be resolved using this definition
func _implements(types aTypes: [Any.Type]) {
implementingTypes.append(contentsOf: aTypes.filter({ !doesImplements(type: $0) }))
}
/// Definition to which resolution will be forwarded to
weak var forwardsTo: _TypeForwardingDefinition? {
didSet {
//both definitions (self and forwardsTo) can resolve
//each other types and each other implementing types
//this relationship can be used to reuse previously resolved instances
if let forwardsTo = forwardsTo {
_implements(type: forwardsTo.type)
_implements(types: forwardsTo.implementingTypes)
//definitions for types that can be resolved by `forwardsTo` definition
//can also be used to resolve self type and it's implementing types
//this way container properly reuses previosly resolved instances
//when there are several forwarded definitions
//see testThatItReusesInstanceResolvedByTypeForwarding)
for definition in forwardsTo.forwardsFrom {
definition._implements(type: type)
definition._implements(types: implementingTypes)
}
//forwardsTo can be used to resolve self type and it's implementing types
forwardsTo._implements(type: type)
forwardsTo._implements(types: implementingTypes)
forwardsTo.forwardsFrom.append(self)
}
}
}
/// Definitions that will forward resolution to this definition
var forwardsFrom: [_TypeForwardingDefinition] = []
}
//MARK: - _Definition
protocol _Definition: DefinitionType, AutoWiringDefinition, TypeForwardingDefinition {
var type: Any.Type { get }
var scope: ComponentScope { get }
var weakFactory: ((Any) throws -> Any)! { get }
func resolveProperties(of instance: Any, container: DependencyContainer) throws
var container: DependencyContainer? { get set }
}
//MARK: - Type Forwarding
protocol _TypeForwardingDefinition: TypeForwardingDefinition, _Definition {
weak var forwardsTo: _TypeForwardingDefinition? { get }
var forwardsFrom: [_TypeForwardingDefinition] { get set }
func _implements(type aType: Any.Type)
func _implements(types aTypes: [Any.Type])
}
extension Definition: _TypeForwardingDefinition {
var type: Any.Type {
return T.self
}
}
extension Definition: CustomStringConvertible {
public var description: String {
return "type: \(T.self), factory: \(F.self), scope: \(scope)"
}
}
//MARK: - Definition Builder
/// Internal class used to build definition
class DefinitionBuilder<T, U> {
typealias F = (U) throws -> T
var scope: ComponentScope!
var factory: F!
var numberOfArguments: Int = 0
var autoWiringFactory: ((DependencyContainer, DependencyContainer.Tag?) throws -> T)?
var forwardsTo: _Definition?
init(configure: (DefinitionBuilder) -> ()) {
configure(self)
}
func build() -> Definition<T, U> {
let factory = self.factory!
let definition = Definition<T, U>(scope: scope, factory: factory)
definition.numberOfArguments = numberOfArguments
definition.autoWiringFactory = autoWiringFactory
definition.weakFactory = { try factory($0 as! U) }
definition.forwardsTo = forwardsTo as? _TypeForwardingDefinition
return definition
}
}
//MARK: - KeyDefinitionPair
typealias KeyDefinitionPair = (key: DefinitionKey, definition: _Definition)
/// Definitions are matched if they are registered for the same tag and thier factories accept the same number of runtime arguments.
private func ~=(lhs: KeyDefinitionPair, rhs: KeyDefinitionPair) -> Bool {
guard lhs.key.type == rhs.key.type else { return false }
guard lhs.key.tag == rhs.key.tag else { return false }
guard lhs.definition.numberOfArguments == rhs.definition.numberOfArguments else { return false }
return true
}
/// Returns key-defintion pairs with definitions able to resolve that type (directly or via type forwarding)
/// and which tag matches provided key's tag or is nil if strictByTag is false.
/// In the end filters defintions by type of runtime arguments.
func filter(definitions _definitions: [KeyDefinitionPair], byKey key: DefinitionKey, strictByTag: Bool = false, byTypeOfArguments: Bool = false) -> [KeyDefinitionPair] {
let definitions = _definitions
.filter({ $0.key.type == key.type || $0.definition.doesImplements(type: key.type) })
.filter({ $0.key.tag == key.tag || (!strictByTag && $0.key.tag == nil) })
if byTypeOfArguments {
return definitions.filter({ $0.key.typeOfArguments == key.typeOfArguments })
}
else {
return definitions
}
}
/// Orders key-definition pairs putting first definitions registered for provided tag.
func order(definitions _definitions: [KeyDefinitionPair], byTag tag: DependencyContainer.Tag?) -> [KeyDefinitionPair] {
return
_definitions.filter({ $0.key.tag == tag }) +
_definitions.filter({ $0.key.tag != tag })
}
| 36.496575 | 169 | 0.710519 |
167fa9848381b2ab1b16f52d42363e4e99278eba | 424 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
let:{func a<T:a
let a{}0{
| 38.545455 | 79 | 0.745283 |
1470cbbd7ab36ccbbcc8240fa4766b070ced123d | 445 | //
// Created by Pierluigi Cifani on 12/02/2017.
//
import BSWInterfaceKit
class ClassicProfileViewControllerTests: BSWSnapshotTest {
func testSampleLayout() {
let viewModel = ClassicProfileViewModel.buffon()
let detailVC = ClassicProfileViewController(viewModel: viewModel)
let navController = UINavigationController(rootViewController: detailVC)
waitABitAndVerify(viewController: navController)
}
}
| 27.8125 | 80 | 0.750562 |
876cc9bdf0198c8d21ad33073bd530258805128f | 2,291 | //
// SceneDelegate.swift
// Examples
//
// Created by Igor Vedeneev on 6/24/21.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.226415 | 147 | 0.712789 |
e94407d4fe6b31984d83130b5b08fd8b1384b117 | 1,540 | //
// GTPart.swift
// Gym Tracker
//
// Created by Marco Boschi on 13/08/2018.
// Copyright © 2018 Marco Boschi. All rights reserved.
//
//
import Foundation
import CoreData
@objc(GTPart)
public class GTPart: GTDataObject, WorkoutLevel {
static private let workoutKey = "workout"
static private let orderKey = "order"
@NSManaged final private(set) var workout: GTWorkout?
@NSManaged final public var order: Int32
/// Make the exercise a part of the given workout.
///
/// Unless when passing `nil`, don't call this method directly but rather call `add(parts:_)` on the workout.
func set(workout w: GTWorkout?) {
let old = self.workout
self.workout = w
old?.recalculatePartsOrder()
}
public var parentLevel: CompositeWorkoutLevel? {
fatalError("Abstract property not implemented")
}
// MARK: - iOS/watchOS interface
override var wcObject: WCObject? {
guard let obj = super.wcObject else {
return nil
}
if let w = workout?.recordID.wcRepresentation {
obj[Self.workoutKey] = w
}
obj[Self.orderKey] = order
return obj
}
override func mergeUpdatesFrom(_ src: WCObject, inDataManager dataManager: DataManager) -> Bool {
guard super.mergeUpdatesFrom(src, inDataManager: dataManager) else {
return false
}
guard let order = src[Self.orderKey] as? Int32 else {
return false
}
self.workout = CDRecordID(wcRepresentation: src[Self.workoutKey] as? [String])?.getObject(fromDataManager: dataManager) as? GTWorkout
self.order = order
return true
}
}
| 22.985075 | 135 | 0.705195 |
2f1d2b2874154f40c75f1b574ac78c35850342e7 | 704 | import Foundation
typealias Version = Float
typealias Percentage = Float
struct MarketShare {
let version: Version
let percentage: Percentage
init?(versionString: String, shareString: String) {
guard
let versionStart = versionString.range(of: "iOS ")?.upperBound,
let version = Version(versionString[versionStart...]),
let share = Percentage(shareString)
else {
return nil
}
self.version = version
self.percentage = share
}
init?(csvRow fields: [String]) {
guard fields.count == 2 else { return nil }
self.init(versionString: fields[0], shareString: fields[1])
}
}
| 23.466667 | 75 | 0.610795 |
b9b47fcc7b7ddd81433f1f7dcb7cc0b35467ceb3 | 244 | //
// Weather+CoreDataClass.swift
// WeatherApp
//
// Created by Michil Khodulov on 13.11.2017.
// Copyright © 2017 Michil Khodulov. All rights reserved.
//
//
import Foundation
import CoreData
public class Weather: NSManagedObject {
}
| 14.352941 | 58 | 0.717213 |
110728d7d88ac0d574af1b617839ebe4b9ec191e | 7,725 | //
// NewContactViewModel.swift
// Contacts App
//
// Created by Anderson Gralha on 19/12/18.
// Copyright © 2018 andersongralha. All rights reserved.
//
import UIKit
import CoreData
class NewContactViewModel {
// MARK: - Properties
var selectedContact: Contact?
// Set the isUpdating contact false if adding a new contact
var isUpdating = true
// MARK: - Init
init() {
}
// MARK: - Public Functions
func setupNewContact() {
selectedContact = Contact()
selectedContact?.id = Database.shared.getNewPrimaryKey()
isUpdating = false
}
func isLastItem(_ indexPath: IndexPath) -> Bool {
switch indexPath.section {
case EnumContactDataSection.phone.rawValue:
return indexPath.row >= selectedContact?.phones.count ?? 0
case EnumContactDataSection.email.rawValue:
return indexPath.row >= selectedContact?.emails.count ?? 0
case EnumContactDataSection.address.rawValue:
return indexPath.row >= selectedContact?.addresses.count ?? 0
default:
return false
}
}
func isValidContact(success:() -> Void, error: (String) -> Void) {
if selectedContact?.phones.count == 0 {
error("Contact should have at least one phone number. ")
} else if selectedContact?.emails.count == 0 {
error("Contact should have at least one email. ")
} else {
success()
}
}
func addRow(for indexPath: IndexPath, update: Bool? = false) {
guard let contact = selectedContact else {
return
}
switch indexPath.section {
case EnumContactDataSection.phone.rawValue:
let phone = Phone()
if update ?? false {
Database.shared.updateContact(contact: contact,
phone: phone,
index: contact.phones.count)
} else {
contact.phones.append(phone)
}
case EnumContactDataSection.email.rawValue:
let email = Email()
if update ?? false {
Database.shared.updateContact(contact: contact,
email: email,
index: contact.emails.count)
} else {
contact.emails.append(email)
}
case EnumContactDataSection.address.rawValue:
let address = Address()
if update ?? false {
Database.shared.updateContact(contact: contact,
address: address,
index: contact.addresses.count)
} else {
contact.addresses.append(address)
}
default:
break
}
}
func removeItem(for indexPath: IndexPath) {
guard let contact = selectedContact else {
return
}
switch indexPath.section {
case EnumContactDataSection.phone.rawValue:
if isUpdating {
Database.shared.updateContact(contact: contact,
phone: true,
index: indexPath.row,
remove: true)
} else {
contact.phones.remove(at: indexPath.row)
}
case EnumContactDataSection.email.rawValue:
if isUpdating {
Database.shared.updateContact(contact: contact,
email: true,
index: indexPath.row,
remove: true)
} else {
selectedContact?.emails.remove(at: indexPath.row)
}
case EnumContactDataSection.address.rawValue:
if isUpdating {
Database.shared.updateContact(contact: contact,
address: true,
index: indexPath.row,
remove: true)
} else {
selectedContact?.addresses.remove(at: indexPath.row)
}
default:
break
}
}
func addContact(success: () -> Void, failure: (String) -> Void) {
if let contact = selectedContact {
Database.shared.addContact(
contact: contact,
success: {
success()
}, failure: { error in
failure(error)
})
} else {
failure("Failed to add contact. Error 11.")
}
}
// MARK: - Update Contact Functions
func setFirstName(_ value: String) {
guard let contact = selectedContact else {
return
}
if isUpdating {
Database.shared.updateContact(contact: contact,
firstName: value)
} else {
contact.firstName = value
}
}
func setLastName(_ value: String) {
guard let contact = selectedContact else {
return
}
if isUpdating {
Database.shared.updateContact(contact: contact,
lastName: value)
} else {
contact.lastName = value
}
}
func setBirthDate(_ value: Date) {
guard let contact = selectedContact else {
return
}
if isUpdating {
Database.shared.updateContact(contact: contact,
birthDate: value)
} else {
contact.dateOfBirth = value
}
}
func setPhone(_ value: String, forIndex: Int) {
guard let contact = selectedContact else {
return
}
if isUpdating {
let phone = Phone()
phone.phone = value
Database.shared.updateContact(contact: contact,
phone: phone,
index: forIndex)
} else {
contact.phones[forIndex].phone = value
}
}
func setEmail(_ value: String, forIndex: Int) {
guard let contact = selectedContact else {
return
}
if isUpdating {
let email = Email()
email.email = value
Database.shared.updateContact(contact: contact,
email: email,
index: forIndex)
} else {
contact.emails[forIndex].email = value
}
}
func setAddress(_ value: String, forIndex: Int) {
guard let contact = selectedContact else {
return
}
if isUpdating {
let address = Address()
address.address = value
Database.shared.updateContact(contact: contact,
address: address,
index: forIndex)
} else {
contact.addresses[forIndex].address = value
}
}
}
| 31.149194 | 77 | 0.458252 |
892ef1696977fb5788b749f123fb838ee1ad9427 | 3,798 | //
// TipsViewController.swift
// Dyscope
//
// Created by Shreeniket Bendre on 9/5/20.
// Copyright © 2020 Shreeniket Bendre. All rights reserved.
//
import UIKit
import youtube_ios_player_helper
class TipsViewController: UIViewController, YTPlayerViewDelegate{
@IBOutlet weak var playerView: YTPlayerView!
@IBOutlet weak var textView: UITextView!
var str = "After being exposed to the virus that causes COVID-19, it can take as few as two and as many as 14 days for symptoms to develop. Cases range from mild to critical. The average timeline from the first symptom to recovery is about 17 days, but some cases are fatal. Here's what it looks like to develop COVID-19, day by day."
var id = "OOJqHPfG7pA"
override func viewDidLoad() {
super.viewDidLoad()
playerView.delegate = self
setup(id, str)
// Do any additional setup after loading the view.
}
func setup(_ id: String, _ text: String){
textView.text = text
playerView.load(withVideoId: "\(id)", playerVars: ["playsinline":1])
}
func playerViewDidBecomeReady(_ playerView: YTPlayerView) {
playerView.playVideo()
}
@IBAction func b1(_ sender: Any){
playerView.stopVideo()
str = "After being exposed to the virus that causes COVID-19, it can take as few as two and as many as 14 days for symptoms to develop. Cases range from mild to critical. The average timeline from the first symptom to recovery is about 17 days, but some cases are fatal. Here's what it looks like to develop COVID-19, day by day."
id = "OOJqHPfG7pA"
setup(id, str)
}
@IBAction func b2(_ sender: Any){
playerView.stopVideo()
str = "As doctors, authorities and employers advise self-quarantine if you exhibit any symptoms of Coronavirus, here's a quick guide to implementing a self-isolation routine in your life. There are 6 basic things that you need to be mindful of, when under quarantine. These include limited contact even with family, and maintaining hygiene regarding clothing, bed linen, and utensils."
id = "VwVHCa81YeI"
setup(id, str)
}
@IBAction func b3(_ sender: Any){
playerView.stopVideo()
str = "In this simple face mask sewing video, it illustrates how to cut and sew a face mask step by step no sewing machine needed. Using the plate helped me create a simple and quick pattern. You can make a face mask at home from fabric or similar materials."
id = "uRfhuRNua_E"
setup(id, str)
}
@IBAction func b4(_ sender: Any){
playerView.stopVideo()
str = "Proper hand hygiene is the most important thing you can do to prevent the spread of germs and to protect yourself and others from illnesses. When not done carefully, germs on the fingertips, palms and thumbs, and between fingers, are often missed. This video demonstrates the World Health Organization (WHO) technique for hand-washing. Watch the video to be sure you are washing your hands thoroughly."
id = "IisgnbMfKvI"
setup(id, str)
}
@IBAction func b5(_ sender: Any){
playerView.stopVideo()
str = "This video will be demonstrating and diagnosing different types of cough. It is is provided for educational purposes only."
id = "XEDg1NnOpmc"
setup(id, str)
}
@IBAction func b6(_ sender: Any){
playerView.stopVideo()
str = "A fabric mask can act as a barrier to prevent the spread of the virus. However, it must be used correctly and always combined with other measures to protect yourself and everyone else. Here is how to wear a fabric mask safely."
id = "9Tv2BVN_WTk"
setup(id, str)
}
}
| 46.888889 | 417 | 0.687204 |
16b9d0a0e510e472f3431e9421c5aeb6ae9268be | 3,010 | //
// SecureDataStore.swift
// Split
//
// Created by Natalia Stele on 19/01/2018.
//
import Foundation
class SecureDataStore {
enum Asset: String {
case accessToken = "user_auth_token"
}
private let metricsManager = DefaultMetricsManager.shared
private var token: String?
static let shared: SecureDataStore = {
let instance = SecureDataStore()
return instance
}()
// MARK: - save access token
func setToken(token: String) {
if let token = getToken() {
Logger.d(token)
removeToken()
}
self.token = token
guard let valueData = token.data(using: String.Encoding.utf8) else {
Logger.e("Error saving text to Keychain")
return
}
let queryAdd: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: Asset.accessToken.rawValue,
kSecValueData as String: valueData,
kSecAttrAccessible as String: kSecAttrAccessibleAlways
]
let resultCode = SecItemAdd(queryAdd as CFDictionary, nil)
if resultCode != noErr {
Logger.e("Error saving to Keychain: \(resultCode).")
} else {
Logger.d("Saved to keychain successfully.")
}
}
// MARK: - retrieve access token
func getToken() -> String? {
if let token = self.token {
return token
}
metricsManager.count(delta: 1, for: Metrics.Counter.getApiKeyFromSecureStorage)
var query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: Asset.accessToken.rawValue
]
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanTrue
// Search for the keychain items
var result: AnyObject?
var lastResultCode: OSStatus = noErr
lastResultCode = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
if lastResultCode == noErr, let dic = result as? [String: Any],
let data = dic[kSecValueData as String] as? Data {
if let token = String(data: data, encoding: .utf8) {
return token
}
}
return nil
}
// MARK: - delete access token
func removeToken() {
let queryDelete: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: Asset.accessToken.rawValue
]
let resultCodeDelete = SecItemDelete(queryDelete as CFDictionary)
if resultCodeDelete != noErr {
Logger.e("Error deleting from Keychain: \(resultCodeDelete)")
} else {
Logger.d("Removed successfully from the keychain")
}
}
}
| 24.876033 | 87 | 0.600332 |
e5e64799a6faab25b506bfd44bb1daea8d675e43 | 2,760 | //
// NewsDetailViewController+StateRestoration.swift
// DailyFeed
//
// Created by Sumit Paul on 31/01/17.
//
import UIKit
extension NewsDetailViewController {
// MARK: - UIStateRestoring Delegate Methods
override func encodeRestorableState(with coder: NSCoder) {
if let newsImage = newsImageView.image {
coder.encode(UIImageJPEGRepresentation(newsImage, 1.0), forKey:"newsImage")
}
if let title = newsTitleLabel.text {
coder.encode(title, forKey: "title")
}
if let contentText = contentTextView.text {
coder.encode(contentText, forKey: "contentText")
}
if let newsAuthor = newsAuthorLabel.text {
coder.encode(newsAuthor, forKey: "newsAuthor")
}
if let publishedDate = receivedNewsItem?.publishedAt {
coder.encode(publishedDate, forKey: "publishedDate")
}
if let url = self.articleStringURL {
coder.encode(url, forKey: "newsURL")
}
if let newsSourceImage = newsSourceImageView.image {
coder.encode(UIImagePNGRepresentation(newsSourceImage), forKey: "newsSourceImage")
}
super.encodeRestorableState(with: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
if let newsImageData = coder.decodeObject(forKey: "newsImage") as? Data {
newsImageView.image = UIImage(data: newsImageData)
}
if let title = coder.decodeObject(forKey: "title") as? String {
newsTitleLabel.text = title
}
if let contentText = coder.decodeObject(forKey: "contentText") as? String {
contentTextView.text = contentText
}
if let newsAuthorText = coder.decodeObject(forKey: "newsAuthor") as? String {
newsAuthorLabel.text = newsAuthorText
}
if let publishedAtDate = coder.decodeObject(forKey: "publishedDate") as? String {
guard let publishedDate = publishedAtDate.dateFromTimestamp?.relativelyFormatted(short: false) else {
return swipeLeftButton.setTitle("Read More...", for: .normal)
}
swipeLeftButton.setTitle("\(publishedDate) • Read More...", for: .normal)
}
if let urlString = coder.decodeObject(forKey: "newsURL") as? String {
articleStringURL = urlString
}
if let newsSourceImageData = coder.decodeObject(forKey: "newsSourceImage") as? Data {
newsSourceImageView.image = UIImage(data: newsSourceImageData)
}
super.decodeRestorableState(with: coder)
}
}
| 34.074074 | 113 | 0.606884 |
0e258663e09a9aa062798a77aa675dc51e9ebd32 | 1,571 | //
// DetailViewModel.swift
// NasaImage
//
// Created by Wilhelm Thieme on 12/08/2021.
//
import UIKit
protocol DetailViewModel: AnyObject {
var didLoadImage: (() -> Void)? { get set }
func backButtonPressed()
func startLoadImage()
var image: UIImage? { get }
var title: String { get }
var explanation: String { get }
var information: String { get }
}
class DetailViewModelImpl: BaseViewModel, DetailViewModel {
var didLoadImage: (() -> Void)?
var asset: NasaAsset?
var image: UIImage?
var title: String { return asset?.title ?? NSLocalizedString("noTitle", comment: "") }
var explanation: String { return asset?.explanation ?? NSLocalizedString("noDescription", comment: "") }
var information: String {
return NSLocalizedString("infoTemplate", comment: "")
.replacingOccurrences(of: "%0", with: asset?.location ?? NSLocalizedString("unknown", comment: ""))
.replacingOccurrences(of: "%1", with: asset?.photographer ?? NSLocalizedString("unknown", comment: ""))
}
init(_ image: NasaAsset? = nil) {
asset = image
}
func backButtonPressed() {
coordinatior.back()
}
func startLoadImage() {
guard let asset = asset else { return }
_ = apiService.getImage(asset.id, size: .large) { [self] result in
switch result {
case .success(let newImage): image = newImage
case .failure(_): image = UIImage(named: "DefaultImage")
}
didLoadImage?()
}
}
}
| 30.803922 | 115 | 0.612349 |
7258bf12a7d4a514da3a92198b1104ff8beca3ee | 250 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class C<T where f:A{
let a{
var b
class A{
protocol c:b
func a
func a<T where f:a | 22.727273 | 87 | 0.748 |
d56a1f77284e597f1d40bf701190fe20a7c2812b | 2,903 | //
// GameStatisticsManager.swift
// PP2
//
// Created by Alexey Goryunov on 5/29/19.
// Copyright © 2019 Alexey Goryunov. All rights reserved.
//
import UIKit
class GameStatisticsManager: NSObject {
let dataStorageManager: DataStorageManagerProtocol
init(withDataStorageManager manager: DataStorageManagerProtocol) {
self.dataStorageManager = manager
}
func resetData() {
dataStorageManager.resetData()
}
func getStatisticsTrend() -> GameStatisticsTrend? {
let trend = GameStatisticsTrend()
let lastTwoSteps = dataStorageManager.getLastTwoSteps()
if lastTwoSteps.count == 0 {
return nil
}
let lastStep = lastTwoSteps.last!
let prevStep = lastTwoSteps.first!
trend.preysNumber = lastStep.preyCount
trend.predatorsNumber = lastStep.predatorCount
trend.lastTurnDuration = lastStep.turnDuration
trend.currentTotalCount = trend.preysNumber + trend.predatorsNumber
trend.stepNumber = lastStep.turnNumber
if lastStep.turnNumber != prevStep.turnNumber {
trend.preysTrend = self.calculateTrend(fromPreviousValue: Double(prevStep.preyCount), andCurrentValue: Double(lastStep.preyCount))
trend.predatorsTrend = self.calculateTrend(fromPreviousValue: Double(prevStep.predatorCount), andCurrentValue: Double(lastStep.predatorCount))
trend.currentTotalTrend = self.calculateTrend(fromPreviousValue: Double(prevStep.totalCreaturesCount()), andCurrentValue: Double(lastStep.totalCreaturesCount()))
}
LogManager.shared.log("Predators: Previous: \(prevStep.predatorCount); Last: \(lastStep.predatorCount); Trend: \(trend.predatorsTrend)")
LogManager.shared.log("Preys: Previous: \(prevStep.preyCount); Last: \(lastStep.preyCount); Trend: \(trend.preysTrend)")
return trend
}
func storeNewStatistics(_ newStatistics: GameStatistics!) {
if let statistics = newStatistics {
dataStorageManager.storeGameStatistics(statistics)
}
}
class func captureGameStatistics(_ creatures: Array<Creature>, _ stepNumber: Int, _ duration: TimeInterval) -> GameStatistics {
let statistic = GameStatistics()
for creature in creatures {
if creature.type == CreatureType.prey {
statistic.preyCount += 1
}
else if creature.type == CreatureType.predator {
statistic.predatorCount += 1
}
}
statistic.turnNumber = stepNumber
statistic.turnDuration = Double(duration)
return statistic
}
// MARK: Private
private func calculateTrend(fromPreviousValue prevVal: Double, andCurrentValue currentVal: Double) -> Double {
if prevVal == 0.0 {
return currentVal
}
return currentVal / prevVal
}
}
| 34.975904 | 173 | 0.676197 |
5d3cf23ed13896fee6293e38030b3dbeb01688dd | 13,465 | //
// AAChartModel.swift
// AAChartKit-Swift
//
// Created by An An on 17/4/19.
// Copyright © 2017年 An An . All rights reserved.
//*************** ...... SOURCE CODE ...... ***************
//***...................................................***
//*** https://github.com/AAChartModel/AAChartKit ***
//*** https://github.com/AAChartModel/AAChartKit-Swift ***
//***...................................................***
//*************** ...... SOURCE CODE ...... ***************
/*
* -------------------------------------------------------------------------------
*
* 🌕 🌖 🌗 🌘 ❀❀❀ WARM TIPS!!! ❀❀❀ 🌑 🌒 🌓 🌔
*
* Please contact me on GitHub,if there are any problems encountered in use.
* GitHub Issues : https://github.com/AAChartModel/AAChartKit-Swift/issues
* -------------------------------------------------------------------------------
* And if you want to contribute for this project, please contact me as well
* GitHub : https://github.com/AAChartModel
* StackOverflow : https://stackoverflow.com/users/7842508/codeforu
* JianShu : http://www.jianshu.com/u/f1e6753d4254
* SegmentFault : https://segmentfault.com/u/huanghunbieguan
*
* -------------------------------------------------------------------------------
*/
enum AAChartAnimationType:String {
case EaseInQuad = "easeInQuad"
case EaseOutQuad = "easeOutQuad"
case EaseInOutQuad = "easeInOutQuad"
case EaseInCubic = "easeInCubic"
case EaseOutCubic = "easeOutCubic"
case EaseInOutCubic = "easeInOutCubic"
case EaseInQuart = "easeInQuart"
case EaseOutQuart = "easeOutQuart"
case EaseInOutQuart = "easeInOutQuart"
case EaseInQuint = "easeInQuint"
case EaseOutQuint = "easeOutQuint"
case EaseInOutQuint = "easeInOutQuint"
case EaseInSine = "easeInSine"
case EaseOutSine = "easeOutSine"
case EaseInOutSine = "easeInOutSine"
case EaseInExpo = "easeInExpo"
case EaseOutExpo = "easeOutExpo"
case EaseInOutExpo = "easeInOutExpo"
case EaseInCirc = "easeInCirc"
case EaseOutCirc = "easeOutCirc"
case EaseInOutCirc = "easeInOutCirc"
case EaseOutBounce = "easeOutBounce"
case EaseInBack = "easeInBack"
case EaseOutBack = "easeOutBack"
case EaseInOutBack = "easeInOutBack"
case Elastic = "elastic"
case SwingFromTo = "swingFromTo"
case SwingFrom = "swingFrom"
case SwingTo = "swingTo"
case Bounce = "bounce"
case BouncePast = "bouncePast"
case EaseFromTo = "easeFromTo"
case EaseFrom = "easeFrom"
case EaseTo = "easeTo"
}
enum AAChartType:String {
case Column = "column"
case Bar = "bar"
case Area = "area"
case AreaSpline = "areaspline"
case Line = "line"
case Spline = "spline"
case Scatter = "scatter"
case Pie = "pie"
case Bubble = "bubble"
case Pyramid = "pyramid"
case Funnel = "funnel"
case Columnrange = "columnrange"
case Arearange = "arearange"
case Areasplinerange = "areasplinerange"
case Boxplot = "boxplot"
case Waterfall = "waterfall"
case Polygon = "polygon"
}
enum AAChartSubtitleAlignType:String {
case Left = "left"
case Center = "center"
case Right = "right"
}
enum AAChartZoomType:String {
case None = "none"
case X = "x"
case Y = "y"
case XY = "xy"
}
enum AAChartStackingType:String {
case False = ""
case Normal = "normal"
case Percent = "percent"
}
enum AAChartSymbolType:String {
case Circle = "circle"
case Square = "square"
case Diamond = "diamond"
case Triangle = "triangle"
case Triangle_down = "triangle-down"
}
enum AAChartSymbolStyleType:String {
case Normal = "normal"
case InnerBlank = "innerBlank"
case BorderBlank = "borderBlank"
}
enum AAchartLegendlLayoutType:String {
case Horizontal = "horizontal"
case Vertical = "vertical"
}
enum AAChartLegendAlignType:String {
case Left = "left"
case Center = "center"
case Right = "right"
}
enum AAChartLegendVerticalAlignType:String {
case Top = "top"
case Middle = "middle"
case Bottom = "bottom"
}
enum AALineDashSyleType:String {
case Solid = "Solid"
case ShortDash = "ShortDash"
case ShortDot = "ShortDot"
case ShortDashDot = "ShortDashDot"
case ShortDashDotDot = "ShortDashDotDot"
case Dot = "Dot"
case Dash = "Dash"
case LongDash = "LongDash"
case DashDot = "DashDot"
case LongDashDot = "LongDashDot"
case LongDashDotDot = "LongDashDotDot"
}
public class AAChartModel:AASerializable {
private var animationType:String? //动画类型
private var animationDuration:Int? //动画时间
private var title:String? //标题内容
private var subtitle:String? //副标题内容
private var chartType:String? //图表类型
private var stacking:String? //堆积样式
private var symbol:String? //折线曲线连接点的类型:"circle", "square", "diamond", "triangle","triangle-down",默认是"circle"
private var symbolStyle:String? //折线或者曲线的连接点是否为空心的
private var zoomType:String? //缩放类型 AAChartZoomTypeX表示可沿着 x 轴进行手势缩放
private var inverted:Bool? //x 轴是否翻转(垂直)
private var xAxisReversed:Bool? //x 轴翻转
private var yAxisReversed:Bool? //y 轴翻转
private var gradientColorEnable:Bool? //是否要为渐变色
private var polar:Bool? //是否极化图形(变为雷达图)
private var marginLeft:Float?
private var marginRight:Float?
private var dataLabelEnabled:Bool? //是否显示数据
private var xAxisLabelsEnabled:Bool? //x轴是否显示数据
private var categories:Array<Any>? //x轴是否显示数据
private var xAxisGridLineWidth:Float? //x轴网格线的宽度
private var xAxisVisible:Bool? //x轴是否显示
private var yAxisVisible:Bool? //y轴是否显示
private var yAxisLabelsEnabled:Bool? //y轴是否显示数据
private var yAxisTitle:String? //y轴标题
private var yAxisLineWidth:Float? //y轴轴线的宽度
private var yAxisGridLineWidth:Float? //y轴网格线的宽度
private var tooltipEnabled:Bool? //是否显示浮动提示框(默认显示)
private var tooltipValueSuffix:String? //浮动提示框单位后缀
private var tooltipCrosshairs:Bool? //是否显示准星线(默认显示)
private var colorsTheme:Array<Any>? //图表主题颜色数组
private var series:Array<Dictionary<String, Any>>? //图表的数据数组
private var legendEnabled:Bool? //是否显示图例
private var legendLayout:String? //图例数据项的布局。布局类型: "horizontal" 或 "vertical" 即水平布局和垂直布局 默认是:horizontal.
private var legendAlign:String? //设定图例在图表区中的水平对齐方式,合法值有left,center 和 right。
private var legendVerticalAlign:String? //设定图例在图表区中的垂直对齐方式,合法值有 top,middle 和 bottom。垂直位置可以通过 y 选项做进一步设定。
private var backgroundColor:String? //图表背景色
private var borderRadius:Int? //柱状图长条图头部圆角半径(可用于设置头部的形状,仅对条形图,柱状图有效)
private var markerRadius:Int? //折线连接点的半径长度
func animationType(_ prop: AAChartAnimationType) -> AAChartModel {
self.animationType = prop.rawValue
return self
}
func animationDuration(_ prop: Int) -> AAChartModel {
self.animationDuration = prop
return self
}
func title(_ prop: String) -> AAChartModel {
self.title = prop
return self
}
func subtitle(_ prop: String) -> AAChartModel {
self.subtitle = prop
return self
}
func chartType(_ prop: AAChartType) -> AAChartModel {
self.chartType = prop.rawValue
return self
}
func stacking(_ prop: AAChartStackingType) -> AAChartModel {
self.stacking = prop.rawValue
return self
}
func symbol(_ prop: AAChartSymbolType) -> AAChartModel {
self.symbol = prop.rawValue
return self
}
func zoomType(_ prop: AAChartZoomType) -> AAChartModel {
self.zoomType = prop.rawValue
return self
}
func inverted(_ prop: Bool) -> AAChartModel {
self.inverted = prop
return self
}
func symbolStyle(_ prop: AAChartSymbolStyleType) -> AAChartModel {
self.symbolStyle = prop.rawValue
return self
}
func xAxisReversed(_ prop: Bool) -> AAChartModel {
self.xAxisReversed = prop
return self
}
func yAxisReversed(_ prop: Bool) -> AAChartModel {
self.yAxisReversed = prop
return self
}
func tooltipEnabled(_ prop:Bool) -> AAChartModel {
self.tooltipEnabled = prop
return self
}
func tooltipValueSuffix(_ prop:String) -> AAChartModel {
self.tooltipValueSuffix = prop
return self
}
func tooltipCrosshairs(_ prop: Bool) -> AAChartModel {
self.tooltipCrosshairs = prop
return self
}
func gradientColorEnable(_ prop: Bool) -> AAChartModel {
self.gradientColorEnable = prop
return self
}
func polar(_ prop: Bool) -> AAChartModel {
self.polar = prop
return self
}
func marginLeft(_ prop: Float) -> AAChartModel {
self.marginLeft = prop
return self
}
func marginRight(_ prop: Float) -> AAChartModel {
self.marginRight = prop
return self
}
func dataLabelEnabled(_ prop: Bool) -> AAChartModel {
self.dataLabelEnabled = prop
return self
}
func xAxisLabelsEnabled(_ prop: Bool) -> AAChartModel {
self.xAxisLabelsEnabled = prop
return self
}
func categories(_ prop: Array<Any>) -> AAChartModel {
self.categories = prop
return self
}
func xAxisGridLineWidth(_ prop: Float) -> AAChartModel {
self.xAxisGridLineWidth = prop
return self
}
func xAxisVisible(_ prop: Bool) -> AAChartModel {
self.xAxisVisible = prop
return self
}
func yAxisVisible(_ prop: Bool) -> AAChartModel {
self.yAxisVisible = prop
return self
}
func yAxisLabelsEnabled(_ prop: Bool) -> AAChartModel {
self.yAxisLabelsEnabled = prop
return self
}
func yAxisTitle(_ prop: String) -> AAChartModel {
self.yAxisTitle = prop
return self
}
func yAxisGridLineWidth(_ prop: Float) -> AAChartModel {
self.yAxisGridLineWidth = prop
return self
}
func colorsTheme(_ prop: Array<Any>) -> AAChartModel {
self.colorsTheme = prop
return self
}
func series(_ prop: Array<Dictionary<String, Any>>) -> AAChartModel {
self.series = prop
return self
}
func legendEnabled(_ prop: Bool) -> AAChartModel {
self.legendEnabled = prop
return self
}
func legendLayout(_ prop: AAchartLegendlLayoutType) -> AAChartModel {
self.legendLayout = prop.rawValue
return self
}
func legendAlign(_ prop: AAChartLegendAlignType) -> AAChartModel {
self.legendAlign = prop.rawValue
return self
}
func legendVerticalAlign(_ prop: AAChartLegendVerticalAlignType) -> AAChartModel {
self.legendAlign = prop.rawValue
return self
}
func backgroundColor(_ prop: String) -> AAChartModel {
self.backgroundColor = prop
return self
}
func borderRadius(_ prop: Int) -> AAChartModel {
self.borderRadius = prop
return self
}
func markerRadius(_ prop: Int) -> AAChartModel {
self.markerRadius = prop
return self
}
public init() {
self.backgroundColor = "#ffffff"
// self.animationType = AAChartAnimationType.EaseInOutQuart.rawValue
self.animationDuration = 800//以毫秒为单位
self.chartType = AAChartType.Column.rawValue
self.inverted = false
self.stacking = AAChartStackingType.False.rawValue
self.xAxisReversed = false
self.yAxisReversed = false
self.zoomType = AAChartZoomType.None.rawValue//默认禁用手势缩放
self.colorsTheme = ["#9b43b4","#ef476f","#ffd066","#04d69f","#25547c",]
self.gradientColorEnable = false
self.polar = false
self.dataLabelEnabled = true
self.tooltipEnabled = true
self.tooltipCrosshairs = true
self.xAxisLabelsEnabled = true
// self.xAxisGridLineWidth = 1
self.xAxisVisible = true // X 轴默认可见
self.yAxisVisible = true // Y 轴默认可见
self.yAxisLabelsEnabled = true
self.yAxisLineWidth = 0
self.yAxisGridLineWidth = 0.6
self.legendEnabled = true
self.legendLayout = AAchartLegendlLayoutType.Horizontal.rawValue
self.legendAlign = AAChartLegendAlignType.Center.rawValue
self.legendVerticalAlign = AAChartLegendVerticalAlignType.Bottom.rawValue
self.borderRadius = 0//柱状图长条图头部圆角半径(可用于设置头部的形状,仅对条形图,柱状图有效,设置为1000时,柱形图或者条形图头部为楔形)
self.markerRadius = 5//折线连接点的半径长度,设置默认值为0,这样就相当于不显示了
}
}
| 32.367788 | 126 | 0.592499 |
675a858803fc60a52b683bfdc6f0cfb922fe4111 | 1,932 | //
// SearchSettingsViewController.swift
// GithubDemo
//
// Created by Rajjwal Rawal on 3/5/17.
// Copyright © 2017 codepath. All rights reserved.
//
import UIKit
protocol SettingsPresentingViewControllerDelegate: class {
func didSaveSettings(settings: Int)
func didCancelSettings()
}
class SearchSettingsViewController: UIViewController {
weak var delegate: SettingsPresentingViewControllerDelegate?
@IBOutlet weak var minStarsSlider: UISlider!
@IBOutlet weak var minStarsLabel: UILabel!
var minStars: Int!
var copyMinStars: Int!
override func viewDidLoad() {
super.viewDidLoad()
minStarsLabel.text = "\(minStars!)"
copyMinStars = minStars
minStarsSlider.value = Float(minStars!)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onSliderChanged(_ sender: UISlider) {
copyMinStars = Int(sender.value)
minStarsLabel.text = "\(copyMinStars!)"
print(copyMinStars)
}
@IBAction func onSavePressed(_ sender: UIBarButtonItem) {
self.minStars = copyMinStars
self.delegate?.didSaveSettings(settings: copyMinStars!)
dismiss(animated: true, completion: nil)
}
@IBAction func onCancelPressed(_ sender: UIBarButtonItem) {
self.delegate?.didCancelSettings()
dismiss(animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 27.6 | 103 | 0.679607 |
561042790e42c747d8be6a2ee7dc487918a08826 | 3,330 | //
// EnumListUnboxTests.swift
// EnumListProject
//
// Created by Bartosz Polaczyk on 12/08/2017.
// Copyright © 2017 Bartosz Polaczyk. All rights reserved.
//
import XCTest
import EnumList
import Unbox
class EnumListUnboxTests: XCTestCase {
private enum SubjectString: EnumListStringRaw<SubjectString.Values>, RawRepresentable, UnboxableEnum{
struct Values:StringEnumValues {
typealias Element = SubjectString
static var allRaws:Set<String> = []
}
case caseNo1 = "case1"
case caseNo2 = "case2"
}
private enum SubjectInt: EnumListIntRaw<SubjectInt.Values>, RawRepresentable, UnboxableEnum{
struct Values:IntEnumValues {
typealias Element = SubjectInt
static var allRaws:Set<Int> = []
}
case caseNo1 = 1
case caseNo2 = 200
}
func testUnboxingDoesNotBreakListingAllsEnums() throws {
// Arrange
let dictionary:[String:Any] = ["data":"case1"]
let a = Unboxer(dictionary:dictionary)
let _:SubjectString = try a.unbox(key: "data")
// Act
SubjectString.Values.initialize()
let all = SubjectString.Values.all
// Assert
XCTAssertEqual(all, [.caseNo1, .caseNo2])
}
func testUnboxingStringFindsEnum() throws {
// Arrange
let dictionary:[String:Any] = ["data":"case1"]
// Act
let a = Unboxer(dictionary:dictionary)
let unboxed:SubjectString = try a.unbox(key: "data")
// Assert
XCTAssertEqual(unboxed, .caseNo1)
}
func testUnboxingStringFailsForIntValueInDict() throws {
// Arrange
let dictionary:[String:Any] = ["data":1]
// Act
let a = Unboxer(dictionary:dictionary)
let unboxed:SubjectString? = try? a.unbox(key: "data")
// Assert
XCTAssertNil(unboxed)
}
func testUnboxingIntEnumSucceeds() throws {
// Arrange
let dictionary:[String:Any] = ["data":1]
// Act
let a = Unboxer(dictionary:dictionary)
let unboxed:SubjectInt = try a.unbox(key: "data")
// Assert
XCTAssertEqual(unboxed, .caseNo1)
}
func testUnboxingSecondIntEnumSucceeds() throws {
// Arrange
let dictionary:[String:Any] = ["data":200]
// Act
let a = Unboxer(dictionary:dictionary)
let unboxed:SubjectInt = try a.unbox(key: "data")
// Assert
XCTAssertEqual(unboxed, .caseNo2)
}
func testUnboxingIntEnumFromUnknownValueFails() throws {
// Arrange
let dictionary:[String:Any] = ["data":-1]
// Act
let a = Unboxer(dictionary:dictionary)
let unboxed:SubjectInt? = try? a.unbox(key: "data")
// Assert
XCTAssertNil(unboxed)
}
func testUnboxingIntEnumFromStringFails() throws {
// Arrange
let dictionary:[String:Any] = ["data":"1"]
// Act
let a = Unboxer(dictionary:dictionary)
let unboxed:SubjectInt? = try? a.unbox(key: "data")
// Assert
XCTAssertNil(unboxed)
}
}
| 26.854839 | 105 | 0.568168 |
9cb1ffa0462c3fe12dba72aa195a886ca0a9a03a | 6,255 | //
// UserInfo.swift
// mckuai
//
// Created by 陈强 on 15/5/8.
// Copyright (c) 2015年 XingfuQiu. All rights reserved.
//
protocol ExitProtocol {
/**
注销用户
:returns: Void
*/
func userExitProtocol() -> Void
}
import Foundation
import UIKit
class UserInfo: UIViewController, UIAlertViewDelegate, CityProtocol {
var manager = AFHTTPRequestOperationManager()
var cityList: cityListViewController!
var Delegate: ExitProtocol?
@IBOutlet weak var headImg_view: UIView!
@IBOutlet weak var userName_view: UIView!
@IBOutlet weak var passWord_view: UIView!
@IBOutlet weak var addr_view: UIView!
@IBOutlet weak var headImg: UIImageView!
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var addr: UILabel!
var image:UIImageView!
var user:JSON?{
didSet{
if let u = user{
userName.text = u["nike"].stringValue
addr.text = u["addr"].stringValue
image = UIImageView(frame: CGRectMake(self.view.frame.size.width-80-25, 44+22+8+12, 80, 80))
image.sd_setImageWithURL(NSURL(string: u["headImg"].stringValue))
image.layer.masksToBounds=true;
image.layer.cornerRadius = image.frame.size.width/2
self.view.addSubview(image)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.headImg.hidden = true
loadData(true)
var toHeadImg = UITapGestureRecognizer(target: self, action: "toHeadImgFunction")
self.headImg_view.addGestureRecognizer(toHeadImg)
var toUserName = UITapGestureRecognizer(target: self, action: "toUserNameFunction")
self.userName_view.addGestureRecognizer(toUserName)
var toPassWord = UITapGestureRecognizer(target: self, action: "toPassWordFunction")
self.passWord_view.addGestureRecognizer(toPassWord)
var toAddr = UITapGestureRecognizer(target: self, action: "toAddrFunction")
self.addr_view.addGestureRecognizer(toAddr)
}
func toHeadImgFunction() {
MobClick.event("userSetPage", attributes: ["type":"headImg"])
Avatar.changeAvatar(self.navigationController!,url:user!["headImg"].stringValue)
}
func toUserNameFunction() {
MobClick.event("userSetPage", attributes: ["type":"userName"])
Nickname.changeNickname(self.navigationController!,uname:user!["nike"].stringValue)
}
func toPassWordFunction() {
MobClick.event("userSetPage", attributes: ["type":"passWord"])
if user!["userType"].stringValue == "qq"{
MCUtils.showCustomHUD("QQ用户不能修改密码", aType: .Warning)
return
}
Profile_Password.changePass(self.navigationController!)
}
func toAddrFunction() {
MobClick.event("userSetPage", attributes: ["type":"addr"])
cityList = cityListViewController()
cityList.hidesBottomBarWhenPushed = true
cityList.Delegate = self
self.navigationController?.pushViewController(cityList, animated: true)
}
func onSelectCity(selectedCity: String) {
//保存到本地
Defaults[D_USER_ADDR] = selectedCity
self.addr.text = selectedCity
}
override func viewDidAppear(animated: Bool) {
self.navigationController?.navigationBar.lt_reset()
self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor(hexString: MCUtils.COLOR_NavBG))
loadData(false)
}
func loadData(showHUD: Bool){
var uid = appUserIdSave
// uid = 3
if uid == 0 {
self.navigationController?.popViewControllerAnimated(false)
}
let params = [
"userId":String(uid)
]
manager.POST(getUser_url,
parameters: params,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
self.user = json["dataObject"]
}else{
MCUtils.showCustomHUD("个人信息获取失败", aType: .Error)
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
MCUtils.showCustomHUD("个人信息获取失败", aType: .Error)
})
}
@IBAction func exit(){
MobClick.event("userSetPage", attributes: ["type":"exit"])
UIAlertView(title: "提示", message: "你确定要注销吗?", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定").show()
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 1 {
// Defaults.remove(D_USER_ID)
// appUserIdSave = 0
// isLoginout = true
// println("用户已退出!")
self.Delegate?.userExitProtocol()
self.navigationController?.popToRootViewControllerAnimated(true)
// self.tabBarController?.selectedIndex = 1
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
class func showUserInfoView(ctl:UINavigationController?,aDelegate: ExitProtocol?){
var userInfo = UIStoryboard(name: "UserInfo", bundle: nil).instantiateViewControllerWithIdentifier("userInfo") as! UserInfo
userInfo.Delegate = aDelegate
if (ctl != nil) {
ctl?.pushViewController(userInfo, animated: true)
} else {
MCUtils.mainNav?.pushViewController(userInfo, animated: true)
}
}
override func viewWillAppear(animated: Bool) {
self.tabBarController?.tabBar.hidden = true
MobClick.beginLogPageView("userInfoSet")
}
override func viewWillDisappear(animated: Bool) {
self.tabBarController?.tabBar.hidden = false
MobClick.endLogPageView("userInfoSet")
}
} | 33.095238 | 131 | 0.611031 |
2128e6f6283847451995f349d1323fc097838180 | 4,463 | // Copyright 2018-2021 Amazon.com, Inc. or its affiliates. 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.
// A copy of the License is located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file 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.
//
// AWSClientInvocationTraceContext.swift
// SmokeAWSHttp
//
import Foundation
import Logging
import SmokeHTTPClient
import AsyncHTTPClient
import NIOHTTP1
private let xAmzRequestId = "x-amz-request-id"
private let xAmzRequestIdAlt = "x-amzn-RequestId"
private let xAmzId2 = "x-amz-id-2"
/**
A type conforming to the `InvocationTraceContext` protocol, sutiable for AWS clients. This implementation will log the input to and output from the outgoing request,
along with x-amz-request-id and x-amz-id-2" headers if present.
*/
public struct AWSClientInvocationTraceContext: InvocationTraceContext {
public typealias OutwardsRequestContext = String
public init() {
}
public func handleOutwardsRequestStart(method: HTTPMethod, uri: String, logger: Logger, internalRequestId: String,
headers: inout HTTPHeaders, bodyData: Data) -> String {
logger.info("Starting outgoing \(method) request to endpoint '\(uri)'.")
logger.debug("Outgoing request body: \(bodyData.debugString)")
return ""
}
public func handleOutwardsRequestSuccess(outwardsRequestContext: String?, logger: Logger, internalRequestId: String,
response: HTTPClient.Response, bodyData: Data?) {
let logLine = getLogLine(successfullyCompletedRequest: true, response: response, bodyData: bodyData, error: nil)
logger.info("\(logLine)")
if let bodyData = bodyData {
logger.debug("Outgoing response body: \(bodyData.debugString)")
}
}
public func handleOutwardsRequestFailure(outwardsRequestContext: String?, logger: Logger, internalRequestId: String,
response: HTTPClient.Response?, bodyData: Data?, error: Error) {
let logLine = getLogLine(successfullyCompletedRequest: false, response: response, bodyData: bodyData, error: error)
// log at error if this is a server error
if let response = response, response.status.code >= 500 && response.status.code < 600 {
logger.error("\(logLine)")
} else {
logger.info("\(logLine)")
}
if let bodyData = bodyData {
logger.debug("Outgoing response body: \(bodyData.debugString)")
}
}
private func getLogLine(successfullyCompletedRequest: Bool, response: HTTPClient.Response?, bodyData: Data?,
error: Error?) -> String {
var logElements: [String] = []
let completionString = successfullyCompletedRequest ? "Successfully" : "Unsuccessfully"
logElements.append("\(completionString) completed outgoing request.")
if let errorUnwrapped = error {
logElements.append("Error occurred: \(errorUnwrapped).")
}
if let code = response?.status.code {
logElements.append("Returned status code: \(code)")
}
// check the variants of request id
if let requestIds = response?.headers[xAmzRequestId], !requestIds.isEmpty {
logElements.append("Returned \(xAmzRequestId) header '\(requestIds.joined(separator: ","))'")
} else if let requestIds = response?.headers[xAmzRequestIdAlt], !requestIds.isEmpty {
logElements.append("Returned \(xAmzRequestId) header '\(requestIds.joined(separator: ","))'")
}
if let id2s = response?.headers[xAmzId2], !id2s.isEmpty {
logElements.append("Returned \(xAmzId2) header '\(id2s.joined(separator: ","))'")
}
if let bodyData = bodyData {
logElements.append("Returned body with size \(bodyData.count)")
}
return logElements.joined(separator: " ")
}
}
| 42.504762 | 167 | 0.642841 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.