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
|
---|---|---|---|---|---|
e978a9b04afb9a9cb58e95577a8f26561e451a9d | 494 | //
// PixabayPhoto.swift
// PixabayImageBrowser
//
// Created by Landon Epps on 4/22/19.
// Copyright © 2019 Landon Epps. All rights reserved.
//
import UIKit
class PixabayPhoto {
let id: Int
let thumbnailURL: URL
let largeImageURL: URL
var thumbnailImage: UIImage?
var largeImage: UIImage?
init(id: Int, thumbnailURL: URL, largeImageURL: URL) {
self.id = id
self.thumbnailURL = thumbnailURL
self.largeImageURL = largeImageURL
}
}
| 20.583333 | 58 | 0.657895 |
dbff74f6a1f454377ab43e89ae8dc5593ff4de7a | 936 | //
// FilterBox.swift
// Tripfinger
//
// Created by Preben Ludviksen on 28/10/15.
// Copyright © 2015 Preben Ludviksen. All rights reserved.
//
import Foundation
protocol FilterBoxDelegate: class {
func filterClick()
}
class FilterBox: UIView {
@IBOutlet weak var filterControls: UIView!
@IBOutlet weak var regionNameLabel: UILabel!
@IBOutlet weak var categoryLabel: UILabel!
var delegate: FilterBoxDelegate!
override func awakeFromNib() {
filterControls.layer.borderColor = UIColor.darkGrayColor().CGColor
filterControls.layer.borderWidth = 0.5;
let singleTap = UITapGestureRecognizer(target: self, action: #selector(filterClick))
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
filterControls.addGestureRecognizer(singleTap)
filterControls.userInteractionEnabled = true
}
func filterClick() {
delegate.filterClick()
}
} | 23.4 | 88 | 0.725427 |
bb952a997664719e512fa14ab61dcdbfe8c159ed | 5,234 | //
// GEAlertViewController.swift
// GraphicEditKit
//
// Created by yulong mei on 2021/5/31.
//
import UIKit
class GEAlertAction: NSObject {
enum GEAlertActionStyle {
case cancel, confirm, delete
}
var title: String?
var style: GEAlertActionStyle = .confirm
typealias GEAlertHandle = (GEAlertAction) -> Void
var handle: GEAlertHandle?
init(title: String, style: GEAlertActionStyle, handle: GEAlertHandle? = nil) {
self.title = title
self.style = style
self.handle = handle
}
@objc func action() {
self.handle?(self)
}
}
class GEAlertViewController: UIViewController {
var alertStyle: GEAlertStyle = .Text
var alertTitle: String?
var alertMessage: String?
var actions: [GEAlertAction] = []
convenience init(title: String, message: String, style: GEAlertStyle) {
self.init()
alertTitle = title
alertMessage = message
alertStyle = style
modalPresentationStyle = .overFullScreen
modalTransitionStyle = .crossDissolve
}
override func viewDidLoad() {
super.viewDidLoad()
self.loadSubview()
self.layoutSubview()
}
private func loadSubview() {
self.view.backgroundColor = GEBGAlphaColor3
self.view.addSubview(bgView)
bgView.addSubview(titleLabel)
bgView.addSubview(contentView)
contentView.addSubview(messageLabel)
contentView.addSubview(textView)
}
private func layoutSubview() {
let width = 304 * UIScreen.main.bounds.width / 375
bgView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.width.equalTo(width)
}
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(16)
make.width.lessThanOrEqualTo(width - 66)
make.centerX.equalToSuperview()
}
contentView.snp.makeConstraints { (make) in
make.left.equalTo(32)
make.right.equalTo(-32)
make.top.equalTo(titleLabel.snp.bottom).offset(16)
make.bottom.lessThanOrEqualTo(-16).priority(.low)
}
titleLabel.text = alertTitle
if alertStyle == .Text {
textView.isHidden = true
messageLabel.isHidden = false
messageLabel.text = alertMessage
messageLabel.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}else {
textView.isHidden = false
messageLabel.isHidden = true
textView.text = alertMessage
textView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
self.addActions()
}
private func addActions() {
let allWidth: CGFloat = 304 * UIScreen.main.bounds.width / 375
let count = actions.count
let allButtonsWidth: CGFloat = allWidth - 32 - CGFloat((count - 1) * 8)
let buttonWidth = allButtonsWidth / CGFloat(count)
var x: CGFloat = 16
for action in actions {
let button = GEButton()
button.action = action
button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
button.setTitle(action.title, for: .normal)
button.layer.masksToBounds = true
button.layer.cornerRadius = 16
bgView.addSubview(button)
button.snp.makeConstraints { (make) in
make.top.equalTo(contentView.snp.bottom).offset(16)
make.left.equalTo(x)
make.width.equalTo(buttonWidth)
make.bottom.lessThanOrEqualTo(bgView.snp.bottom).offset(-16)
}
x += buttonWidth + 8
}
}
@objc func buttonAction(_ sender: UIButton) {
guard let button = sender as? GEButton else { return }
self.dismiss(animated: true) {
button.action?.action()
}
}
deinit {
debugPrint("deinit \(type(of: self))")
}
private lazy var bgView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.layer.masksToBounds = true
view.layer.cornerRadius = 16
return view
}()
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 16, weight: .medium)
label.numberOfLines = 0
return label
}()
private lazy var contentView: UIView = {
let view = UIView()
view.backgroundColor = .white
return view
}()
private lazy var messageLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.textColor = .black
label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
label.numberOfLines = 0
return label
}()
private lazy var textView: UITextView = {
let view = UITextView()
return view
}()
enum GEAlertStyle {
case Text, TextView
}
}
| 29.240223 | 92 | 0.583493 |
2f302a0568e2a406190d071e83fd5d05fbb9f57e | 1,919 | // --------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the ""Software""), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// --------------------------------------------------------------------------
import Foundation
struct VirtualParam {
var name: String
var type: String
var defaultValue: String
var path: String
init(from param: VirtualParameter) {
self.name = param.name
var path = param.targetProperty.name
if let groupBy = param.groupedBy?.name {
path = "\(groupBy).\(path)"
}
self.path = path
let optional = !param.required
let swiftType = param.schema!.swiftType()
self.type = optional ? "\(swiftType)?" : swiftType
self.defaultValue = param.required ? "" : " = nil"
}
}
| 39.979167 | 79 | 0.645128 |
3856f83f40990ff2b624da8598181424db140bd0 | 2,420 | /// Copyright (c) 2020 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import Fluent
import Vapor
final class Question: Model, Content {
static let schema = "questions"
@ID(key: .id)
var id: UUID?
@Field(key: "content")
var content: String
@Field(key: "answered")
var answered: Bool
@Field(key: "asked_from")
var askedFrom: UUID
@Timestamp(key: "created_at", on: .create)
var createdAt: Date?
init() { }
init(id: UUID? = nil, content: String, askedFrom: UUID) {
self.id = id
self.content = content
self.answered = false
self.askedFrom = askedFrom
}
}
| 38.412698 | 83 | 0.731405 |
382464b4eb7784db86eeb5150949c73341f682d3 | 2,749 | //
// SceneDelegate.swift
// Drawing
//
// Created by misono on 2019/12/16.
// Copyright © 2019 misono. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.292308 | 147 | 0.705347 |
9b6701b555ec2f32ccb34e083e0a079ca1404980 | 1,212 | //
// LogTypeLabel.swift
// StumpExample
//
// Created by Leone Parise Vieira da Silva on 06/05/17.
// Copyright © 2017 com.leoneparise. All rights reserved.
//
import UIKit
@IBDesignable
public class LogLevelLabel: UILabel {
public var level:LogLevel? {
didSet {
self.text = level?.stringValue.uppercased()
self.backgroundColor = level?.color
setNeedsLayout()
}
}
public convenience init(level:LogLevel) {
self.init(frame: CGRect.zero)
self.level = level
}
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.clipsToBounds = true
self.layer.cornerRadius = 3
self.font = UIFont.systemFont(ofSize: 9, weight: UIFont.Weight(rawValue: 500))
self.textColor = .white
self.backgroundColor = .darkGray
self.textAlignment = .center
}
public override func prepareForInterfaceBuilder() {
commonInit()
self.level = .info
}
}
| 24.24 | 86 | 0.603135 |
3a65cb6c9a1b46a854086946a4575a2152860e6f | 254 | //
// PosterCell.swift
// FlixApp
//
// Created by Isaac Samuel on 9/24/18.
// Copyright © 2018 Isaac Samuel. All rights reserved.
//
import UIKit
class PosterCell: UICollectionViewCell {
@IBOutlet weak var posterImageView: UIImageView!
}
| 16.933333 | 55 | 0.69685 |
56fa52abcaf31dfbf0fd52864dad3bf8fe06ff3f | 683 | //
// LumiHeaderTexField.swift
// LumiCoreApp
//
// Copyright © 2020 LUMI WALLET LTD. All rights reserved.
//
import SwiftUI
struct LumiHeaderTexField: View {
let header: String
@Binding var input: String
let placeholder: String
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(header)
.lumiTextStyle(.title)
HStack {
TextField(placeholder, text: $input)
.lumiTextStyle(.title)
.disableAutocorrection(true)
}
}
.underlined()
.padding(EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16))
}
}
| 21.34375 | 74 | 0.559297 |
1c72f8fb5a3c67560c3ffb7fd218a3cf393fa88e | 215 | //
// MoyaResult.swift
// BeanCounty
//
// Created by Max Desiatov on 02/04/2020.
// Copyright © 2020 Digital Signal Limited. All rights reserved.
//
import Moya
typealias MoyaResult<T> = Result<T, MoyaError>
| 17.916667 | 65 | 0.702326 |
5007d468c3526e0a73128aa1880b04df2da6e0d3 | 8,563 | import XCTest
import Cuckoo
@testable import EthereumKit
class EncryptionHandshakeTests: XCTestCase {
private var myKey: ECKey!
private var ephemeralKey: ECKey!
private var remoteKeyPoint: ECPoint!
private var remoteEphemeralKeyPoint: ECPoint!
private var mockCrypto: MockICryptoUtils!
private var mockRandom: MockIRandomHelper!
private var mockFactory: MockIFactory!
private var authMessage: AuthMessage!
private var authAckMessage: AuthAckMessage!
private var nonce = Data(repeating: 0, count: 32)
private var remoteNonce = Data(repeating: 1, count: 32)
private var junkData = Data(repeating: 2, count: 102)
private var sharedSecret = Data(repeating: 3, count: 32)
private var ephemeralSharedSecret = Data(repeating: 4, count: 32)
private var signature = Data(repeating: 5, count: 32)
private var authECIESMessage = ECIESEncryptedMessage(prefixBytes: Data(), ephemeralPublicKey: Data(), initialVector: Data(), cipher: Data(), checksum: Data())
private var encodedAuthECIESMessage: Data!
private var encodedAuthAckMessage: Data!
private var encryptionHandshake: EncryptionHandshake!
override func setUp() {
super.setUp()
myKey = RandomHelper.shared.randomKey()
ephemeralKey = RandomHelper.shared.randomKey()
remoteKeyPoint = RandomHelper.shared.randomKey().publicKeyPoint
remoteEphemeralKeyPoint = RandomHelper.shared.randomKey().publicKeyPoint
encodedAuthECIESMessage = authECIESMessage.encoded()
authMessage = AuthMessage(signature: signature, publicKeyPoint: myKey.publicKeyPoint, nonce: nonce)
encodedAuthAckMessage = RLP.encode([remoteEphemeralKeyPoint.x + remoteEphemeralKeyPoint.y, remoteNonce, 4])
authAckMessage = try! AuthAckMessage(data: encodedAuthAckMessage)
mockCrypto = MockICryptoUtils()
mockRandom = MockIRandomHelper()
mockFactory = MockIFactory()
stub(mockRandom) { mock in
when(mock.randomKey()).thenReturn(ephemeralKey)
when(mock.randomBytes(length: equal(to: 32))).thenReturn(nonce)
when(mock.randomBytes(length: equal(to: Range<Int>(uncheckedBounds: (lower: 100, upper: 300))))).thenReturn(junkData)
}
stub(mockCrypto) { mock in
when(mock.ecdhAgree(myKey: equal(to: myKey), remotePublicKeyPoint: equal(to: remoteKeyPoint))).thenReturn(sharedSecret)
when(mock.ecdhAgree(myKey: equal(to: ephemeralKey), remotePublicKeyPoint: equal(to: remoteEphemeralKeyPoint))).thenReturn(ephemeralSharedSecret)
when(mock.ellipticSign(_: equal(to: sharedSecret.xor(with: nonce)), key: equal(to: ephemeralKey))).thenReturn(signature)
when(mock.eciesEncrypt(remotePublicKey: equal(to: remoteKeyPoint), message: equal(to: authMessage.encoded() + junkData))).thenReturn(authECIESMessage)
when(mock.eciesDecrypt(privateKey: equal(to: myKey.privateKey), message: any())).thenReturn(encodedAuthAckMessage)
}
stub(mockFactory) { mock in
when(mock.authMessage(signature: equal(to: signature), publicKeyPoint: equal(to: myKey.publicKeyPoint), nonce: equal(to: nonce))).thenReturn(authMessage)
when(mock.authAckMessage(data: any())).thenReturn(authAckMessage)
}
encryptionHandshake = EncryptionHandshake(myKey: myKey, publicKeyPoint: remoteKeyPoint, crypto: mockCrypto, randomHelper: mockRandom, factory: mockFactory)
verify(mockRandom).randomKey()
verify(mockRandom).randomBytes(length: equal(to: 32))
}
override func tearDown() {
myKey = nil
ephemeralKey = nil
remoteKeyPoint = nil
remoteEphemeralKeyPoint = nil
encryptionHandshake = nil
mockCrypto = nil
mockRandom = nil
mockFactory = nil
authMessage = nil
authAckMessage = nil
super.tearDown()
}
func testCreateAuthMessage() {
let authMessagePacket: Data!
do {
authMessagePacket = try encryptionHandshake.createAuthMessage()
} catch {
XCTFail("Unexpected error: \(error)")
return
}
verify(mockCrypto).ecdhAgree(myKey: equal(to: myKey), remotePublicKeyPoint: equal(to: remoteKeyPoint))
verify(mockCrypto).ellipticSign(_: equal(to: sharedSecret.xor(with: nonce)), key: equal(to: ephemeralKey))
verify(mockRandom).randomBytes(length: equal(to: Range<Int>(uncheckedBounds: (lower: 100, upper: 300))))
verify(mockCrypto).eciesEncrypt(remotePublicKey: equal(to: remoteKeyPoint), message: equal(to: authMessage.encoded() + junkData))
verify(mockFactory).authMessage(signature: equal(to: signature), publicKeyPoint: equal(to: myKey.publicKeyPoint), nonce: equal(to: nonce))
verifyNoMoreInteractions(mockCrypto)
verifyNoMoreInteractions(mockFactory)
XCTAssertEqual(authMessagePacket, encodedAuthECIESMessage)
}
func testExtractSecrets() {
let noncesHash = Data(repeating: 7, count: 32)
let sharedSecret = Data(repeating: 8, count: 32)
let aes = Data(repeating: 9, count: 32)
let mac = Data(repeating: 10, count: 32)
let token = Data(repeating: 11, count: 32)
let egressMac = KeccakDigest()
let ingressMac = KeccakDigest()
let eciesMessage = ECIESEncryptedMessage(prefixBytes: Data(), ephemeralPublicKey: Data(), initialVector: Data(), cipher: Data(), checksum: Data())
stub(mockCrypto) { mock in
when(mock.sha3(_: equal(to: remoteNonce + nonce))).thenReturn(noncesHash)
when(mock.sha3(_: equal(to: ephemeralSharedSecret + noncesHash))).thenReturn(sharedSecret)
when(mock.sha3(_: equal(to: ephemeralSharedSecret + sharedSecret))).thenReturn(aes)
when(mock.sha3(_: equal(to: ephemeralSharedSecret + aes))).thenReturn(mac)
when(mock.sha3(_: equal(to: sharedSecret))).thenReturn(token)
}
stub(mockFactory) { mock in
when(mock.keccakDigest()).thenReturn(egressMac, ingressMac)
}
let secrets: Secrets!
do {
secrets = try encryptionHandshake.extractSecrets(from: eciesMessage)
} catch {
XCTFail("Unexpected error: \(error)")
return
}
verify(mockCrypto).eciesDecrypt(privateKey: equal(to: myKey.privateKey), message: equal(to: eciesMessage))
verify(mockCrypto).ecdhAgree(myKey: equal(to: ephemeralKey), remotePublicKeyPoint: equal(to: remoteEphemeralKeyPoint))
verify(mockCrypto).sha3(_: equal(to: remoteNonce + nonce))
verify(mockCrypto).sha3(_: equal(to: ephemeralSharedSecret + noncesHash))
verify(mockCrypto).sha3(_: equal(to: ephemeralSharedSecret + sharedSecret))
verify(mockCrypto).sha3(_: equal(to: ephemeralSharedSecret + aes))
verify(mockCrypto).sha3(_: equal(to: sharedSecret))
verify(mockFactory).authAckMessage(data: equal(to: encodedAuthAckMessage))
verify(mockFactory, times(2)).keccakDigest()
verifyNoMoreInteractions(mockCrypto)
verifyNoMoreInteractions(mockFactory)
XCTAssertEqual(secrets.egressMac, egressMac)
XCTAssertEqual(secrets.ingressMac, ingressMac)
XCTAssertEqual(secrets.aes, aes)
XCTAssertEqual(secrets.mac, mac)
XCTAssertEqual(secrets.token, token)
XCTAssertEqual(secrets.egressMac.digest(), keccakDigest(updatedWith: [mac.xor(with: remoteNonce), Data()]))
XCTAssertEqual(secrets.ingressMac.digest(), keccakDigest(updatedWith: [mac.xor(with: nonce), Data()]))
}
func testExtractSecrets_NonDecodableMessage() {
let eciesMessage = ECIESEncryptedMessage(prefixBytes: Data(), ephemeralPublicKey: Data(), initialVector: Data(), cipher: Data(), checksum: Data())
stub(mockFactory) { mock in
when(mock.authAckMessage(data: any())).thenThrow(MessageDecodeError.notEnoughFields)
}
do {
_ = try encryptionHandshake.extractSecrets(from: eciesMessage)
XCTFail("Expecting error")
} catch let error as MessageDecodeError {
XCTAssertEqual(error, MessageDecodeError.notEnoughFields)
} catch {
XCTFail("Unexpected error: \(error)")
}
}
private func keccakDigest(updatedWith: [Data]) -> Data {
let digest = KeccakDigest()
for data in updatedWith {
digest.update(with: data)
}
return digest.digest()
}
}
| 46.037634 | 165 | 0.682238 |
bb221ab453c50fafc8ed59808d2b1800a8030bf5 | 1,461 | //
// Copyright 2020-2020 Tim Schmelter
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
import SwiftFoundationExtensions
public final class Graph<Element> {
public let id: UUID
public let value: Element
public private(set) var connectionsMap: [AnyHashable: Graph<Element>]
public var connections: Set<Graph<Element>> {
Set(Array(connectionsMap.values))
}
public init(_ value: Element) {
self.id = UUID()
self.value = value
self.connectionsMap = [AnyHashable: Graph<Element>]()
}
public func add(_ connection: Graph<Element>, for key: AnyHashable = UUID()) {
connectionsMap[key] = connection
}
}
extension Graph: Equatable {
public static func == (lhs: Graph<Element>, rhs: Graph<Element>) -> Bool {
lhs.id == rhs.id
}
}
extension Graph: Hashable {
public func hash(into hasher: inout Hasher) {
id.hash(into: &hasher)
}
}
extension Graph where Element: Equatable {
/// Evaluates equality for the values of two graph nodes, and their immediate connections
public func shallowCompareValues(_ other: Graph<Element>) -> Bool {
guard value == other.value else {
return false
}
let connectionValues = connections.map { $0.value }
let otherConnectionValues = other.connections.map { $0.value }
return connectionValues.elementsEqualIgnoringOrder(otherConnectionValues)
}
}
| 26.563636 | 93 | 0.661875 |
f7e014d16b24d5f2fb024e7462d217f043681aeb | 4,929 | //
// ShowMenuOptionVC.swift
// Riot
//
// Created by Vuong Le on 2/20/19.
// Copyright © 2019 matrix.org. All rights reserved.
//
import UIKit
internal enum CKMenuRoomCellType {
case unMute
case mute
case removeFromFavourite
case addToFavourite
case setting
case leave
// title
func title() -> String {
switch self {
case .unMute:
return "Turn on room notification"
case .mute:
return "Turn off room notification"
case .removeFromFavourite:
return "Remove from favourite"
case .addToFavourite:
return "Add to favourite"
case .setting:
return "Setting"
case .leave:
return "Leave"
}
}
// icon
func icon() -> String {
switch self {
case .unMute:
return "ic_room_bell_on"
case .mute:
return "ic_room_bell_off"
case .removeFromFavourite:
return "ic_room_unfavourite"
case .addToFavourite:
return "ic_room_favourite"
case .setting:
return "ic_room_settings"
case .leave:
return "ic_leave_room"
}
}
}
// MARK: - CKRoomMenuViewController
final class CKMenuRoomViewController: UIViewController {
// MARK: - OUTLET
@IBOutlet weak var tableView: UITableView!
// MARK: - PROPERTY
internal var datasourceTableView: [CKMenuRoomCellType] = []
internal var callBackCKRecentListVC: ((_ result: CKMenuRoomCellType) -> Void)?
internal var mute: CKMenuRoomCellType = .unMute
internal var favourite: CKMenuRoomCellType = .removeFromFavourite
private let disposeBag = DisposeBag()
// MARK: - OVERRIDE
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.estimatedRowHeight = 50
self.tableView.separatorStyle = .singleLine
self.tableView.bounces = false
tableView.register(
UINib.init(nibName: "CKAlertSettingRoomCell", bundle: nil),
forCellReuseIdentifier: "CKAlertSettingRoomCell")
bindingTheme()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
datasourceTableView = [mute, favourite, .setting, .leave]
self.tableView.reloadData()
}
// MARK: - PRIVATE
private func bindingTheme() {
// Binding navigation bar color
themeService.attrsStream.subscribe(onNext: { [weak self] (theme) in
self?.tableView.reloadData()
}).disposed(by: disposeBag)
themeService.rx
.bind({ $0.primaryBgColor }, to: view.rx.backgroundColor, tableView.rx.backgroundColor)
.disposed(by: disposeBag)
}
// MARK: - PUBLIC
}
extension CKMenuRoomViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datasourceTableView.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "CKAlertSettingRoomCell", for: indexPath)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let data = datasourceTableView[indexPath.row]
if let cell = cell as? CKAlertSettingRoomCell {
cell.imgCell.image = UIImage.init(named: data.icon())?.withRenderingMode(.alwaysTemplate)
cell.lblTitle.text = data.title()
cell.lblTitle.textColor = themeService.attrs.primaryTextColor
cell.imgCell.tintColor = themeService.attrs.primaryTextColor
cell.backgroundColor = themeService.attrs.primaryBgColor
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView(frame: CGRect.zero)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let data = datasourceTableView[indexPath.row]
switch data {
case .unMute:
self.callBackCKRecentListVC?(.unMute)
case .mute:
self.callBackCKRecentListVC?(.mute)
case .removeFromFavourite:
self.callBackCKRecentListVC?(.removeFromFavourite)
case .addToFavourite:
self.callBackCKRecentListVC?(.addToFavourite)
case .setting:
self.callBackCKRecentListVC?(.setting)
case .leave:
self.callBackCKRecentListVC?(.leave)
}
tableView.reloadData()
}
}
| 30.054878 | 112 | 0.633597 |
088245f7cca69f52ed3b7770e08b8b28b7bc5543 | 1,306 | //
// CGPoint+VectorType.swift
// ALTutorialVC
//
// Created by Ali Germiyanoglu on 04/11/2017.
// Copyright © 2017 aeg. All rights reserved.
//
import Foundation
internal protocol VectorType {
associatedtype Element
var xElement: Element { get }
var yElement: Element { get }
static func buildFrom(x: Element, y: Element) -> Self
init<T: VectorType>(fromVector: T) where T.Element == Element
}
internal func -<T: VectorType>(lhs: T, rhs: T) -> T where T.Element == CGFloat {
return T.buildFrom(x: lhs.xElement - rhs.xElement, y: lhs.yElement - rhs.yElement)
}
internal func /<T: VectorType>(lhs: T, rhs: T.Element) -> T where T.Element == CGFloat {
return T.buildFrom(x: lhs.xElement / rhs, y: lhs.yElement / rhs)
}
internal func *<T: VectorType>(lhs: T, rhs: T.Element) -> T where T.Element == CGFloat {
return T.buildFrom(x: lhs.xElement * rhs, y: lhs.yElement * rhs)
}
extension CGPoint: VectorType {
static internal func buildFrom(x: CGFloat, y: CGFloat) -> CGPoint {
return CGPoint(x: x, y: y)
}
var xElement: CGFloat { return x }
var yElement: CGFloat { return y }
init<T: VectorType>(fromVector: T) where T.Element == CGFloat {
self.init(x: fromVector.xElement, y: fromVector.yElement)
}
}
| 27.787234 | 88 | 0.650842 |
6112500e684a0bfa795df56d429a7f6701545b78 | 1,078 | import Foundation
public extension MTKNoteGroup {
public func transpose(_ direction: MTKTranspositionDirection, by interval: MTKInterval) {
for (i, _) in notes.enumerated() {
notes[i].transpose(direction, by: interval)
}
}
public func octavate(_ direction: MTKTranspositionDirection, octaves: Int = 1) {
for (i, _) in notes.enumerated() {
notes[i].octavate(direction, octaves: octaves)
}
}
public func invert(_ direction: MTKTranspositionDirection, times: Int = 1) {
guard notes.count > 0 else {
return
}
guard times > 0 else {
return
}
for _ in 0..<times {
switch direction {
case .up:
var note = notes.removeFirst()
note.octavate(.up)
notes.append(note)
case .down:
var note = notes.removeLast()
note.octavate(.down)
notes.insert(note, at: 0)
}
}
}
}
| 27.641026 | 93 | 0.512987 |
225449099d3bf7c92b2e8c1a0abeb45fa229155c | 419 | import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
IOSSecurit
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
| 27.933333 | 87 | 0.789976 |
230af9fd6e8d5c938d28cf9d9a631ef19752e30c | 3,611 | // RUN: %target-swift-frontend -emit-sil %s -target x86_64-apple-macosx10.50 -verify
// RUN: %target-swift-frontend -emit-silgen %s -target x86_64-apple-macosx10.50 | FileCheck %s
// REQUIRES: OS=macosx
// CHECK-LABEL: sil{{.+}}@main{{.*}} {
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 53
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 8
// CHECK: [[FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10.53.8, iOS 7.1, *) {
}
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_br [[TRUE]]
// Since we are compiling for an unmentioned platform (OS X), we check against the minimum
// deployment target, which is 10.50
if #available(iOS 7.1, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10.52, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 52
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(macOS 10.52, *) {
}
// CHECK: [[MAJOR:%.*]] = integer_literal $Builtin.Word, 10
// CHECK: [[MINOR:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[PATCH:%.*]] = integer_literal $Builtin.Word, 0
// CHECK: [[QUERY_FUNC:%.*]] = function_ref @_TFs26_stdlib_isOSVersionAtLeastFTBwBwBw_Bi1_ : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
// CHECK: [[QUERY_RESULT:%.*]] = apply [[QUERY_FUNC]]([[MAJOR]], [[MINOR]], [[PATCH]]) : $@convention(thin) (Builtin.Word, Builtin.Word, Builtin.Word) -> Builtin.Int1
if #available(OSX 10, *) {
}
// CHECK: }
func doThing() {}
func testUnreachableVersionAvailable(condition: Bool) {
if #available(OSX 10.0, *) {
doThing() // no-warning
return
} else {
doThing() // FIXME-warning {{will never be executed}}
}
if true {
doThing() // no-warning
}
if false { // expected-note {{condition always evaluates to false}}
doThing() // expected-warning {{will never be executed}}
}
}
func testUnreachablePlatformAvailable(condition: Bool) {
if #available(iOS 7.1, *) {
doThing() // no-warning
return
} else {
doThing() // no-warning
}
if true {
doThing() // no-warning
}
if false { // expected-note {{condition always evaluates to false}}
doThing() // expected-warning {{will never be executed}}
}
}
func testUnreachablePlatformAvailableGuard() {
guard #available(iOS 7.1, *) else {
doThing() // no-warning
return
}
doThing() // no-warning
}
| 39.25 | 170 | 0.655774 |
dd91a2010d21d190538a2d8e5efb9fbfda94313d | 6,746 | //
// PXReviewConfirmConfiguration.swift
// MercadoPagoSDK
//
// Created by Juan sebastian Sanzone on 6/8/18.
// Copyright © 2018 MercadoPago. All rights reserved.
//
import Foundation
/**
This object declares custom preferences (customizations) for "Review and Confirm" screen.
*/
@objcMembers open class PXReviewConfirmConfiguration: NSObject {
private static let DEFAULT_AMOUNT_TITLE = "Precio Unitario: ".localized
private static let DEFAULT_QUANTITY_TITLE = "Cantidad: ".localized
private var itemsEnabled: Bool = true
private var topCustomView: UIView?
private var bottomCustomView: UIView?
// For only 1 PM Scenario. (Internal)
private var changePaymentMethodsEnabled: Bool = true
/// :nodoc:
override init() {}
// MARK: Init.
/**
- parameter itemsEnabled: Determinate if items view should be display or not.
- parameter topView: Optional custom top view.
- parameter bottomView: Optional custom bottom view.
*/
public init(itemsEnabled: Bool, topView: UIView? = nil, bottomView: UIView? = nil) {
self.itemsEnabled = itemsEnabled
self.topCustomView = topView
self.bottomCustomView = bottomView
}
// MARK: To deprecate post v4. SP integration.
internal var summaryTitles: [SummaryType: String] {
get {
return [SummaryType.PRODUCT: "Producto".localized,
SummaryType.ARREARS: "Mora".localized,
SummaryType.CHARGE: "Cargos".localized,
SummaryType.DISCOUNT: String(format: "discount".localized, 2),
SummaryType.TAXES: "Impuestos".localized,
SummaryType.SHIPPING: "Envío".localized]
}
}
internal var details: [SummaryType: SummaryDetail] = [SummaryType: SummaryDetail]()
}
// MARK: - Internal Getters.
extension PXReviewConfirmConfiguration {
internal func hasItemsEnabled() -> Bool {
return itemsEnabled
}
internal func getTopCustomView() -> UIView? {
return self.topCustomView
}
internal func getBottomCustomView() -> UIView? {
return self.bottomCustomView
}
}
/** :nodoc: */
// Payment method.
// MARK: To deprecate post v4. SP integration.
internal extension PXReviewConfirmConfiguration {
func isChangeMethodOptionEnabled() -> Bool {
return changePaymentMethodsEnabled
}
func disableChangeMethodOption() {
changePaymentMethodsEnabled = false
}
}
/** :nodoc: */
// Amount.
// MARK: To deprecate post v4. SP integration.
internal extension PXReviewConfirmConfiguration {
func shouldShowAmountTitle() -> Bool {
return true
}
func getAmountTitle() -> String {
return PXReviewConfirmConfiguration.DEFAULT_AMOUNT_TITLE
}
}
/** :nodoc: */
// Collector icon.
// MARK: To deprecate post v4. SP integration.
internal extension PXReviewConfirmConfiguration {
func getCollectorIcon() -> UIImage? {
return nil
}
}
/** :nodoc: */
// Quantity row.
// MARK: To deprecate post v4. SP integration.
internal extension PXReviewConfirmConfiguration {
func shouldShowQuantityRow() -> Bool {
return true
}
func getQuantityLabel() -> String {
return PXReviewConfirmConfiguration.DEFAULT_QUANTITY_TITLE
}
}
/** :nodoc: */
// Disclaimer text.
// MARK: To deprecate post v4. SP integration.
internal extension PXReviewConfirmConfiguration {
func getDisclaimerText() -> String? {
return nil
}
func getDisclaimerTextColor() -> UIColor {
return ThemeManager.shared.noTaxAndDiscountLabelTintColor()
}
}
/** :nodoc: */
// Summary.
// MARK: To deprecate post v4. SP integration.
internal extension PXReviewConfirmConfiguration {
// Not in Android.
func addSummaryProductDetail(amount: Double) {
self.addDetail(detail: SummaryItemDetail(amount: amount), type: SummaryType.PRODUCT)
}
func addSummaryDiscountDetail(amount: Double) {
self.addDetail(detail: SummaryItemDetail(amount: amount), type: SummaryType.DISCOUNT)
}
func addSummaryTaxesDetail(amount: Double) {
self.addDetail(detail: SummaryItemDetail(amount: amount), type: SummaryType.TAXES)
}
func addSummaryShippingDetail(amount: Double) {
self.addDetail(detail: SummaryItemDetail(amount: amount), type: SummaryType.SHIPPING)
}
func addSummaryArrearsDetail(amount: Double) {
self.addDetail(detail: SummaryItemDetail(amount: amount), type: SummaryType.ARREARS)
}
func setSummaryProductTitle(productTitle: String) {
self.updateTitle(type: SummaryType.PRODUCT, title: productTitle)
}
private func updateTitle(type: SummaryType, title: String) {
if self.details[type] != nil {
self.details[type]?.title = title
} else {
self.details[type] = SummaryDetail(title: title, detail: nil)
}
if type == SummaryType.DISCOUNT {
self.details[type]?.titleColor = UIColor.mpGreenishTeal()
self.details[type]?.amountColor = UIColor.mpGreenishTeal()
}
}
private func getOneWordDescription(oneWordDescription: String) -> String {
if oneWordDescription.count <= 0 {
return ""
}
if let firstWord = oneWordDescription.components(separatedBy: " ").first {
return firstWord
} else {
return oneWordDescription
}
}
private func addDetail(detail: SummaryItemDetail, type: SummaryType) {
if self.details[type] != nil {
self.details[type]?.details.append(detail)
} else {
guard let title = self.summaryTitles[type] else {
self.details[type] = SummaryDetail(title: "", detail: detail)
return
}
self.details[type] = SummaryDetail(title: title, detail: detail)
}
if type == SummaryType.DISCOUNT {
self.details[type]?.titleColor = UIColor.mpGreenishTeal()
self.details[type]?.amountColor = UIColor.mpGreenishTeal()
}
}
func getSummaryTotalAmount() -> Double {
var totalAmount = 0.0
guard let productDetail = details[SummaryType.PRODUCT] else {
return 0.0
}
if productDetail.getTotalAmount() <= 0 {
return 0.0
}
for summaryType in details.keys {
if let detailAmount = details[summaryType]?.getTotalAmount() {
if summaryType == SummaryType.DISCOUNT {
totalAmount -= detailAmount
} else {
totalAmount += detailAmount
}
}
}
return totalAmount
}
}
| 30.803653 | 93 | 0.643641 |
4623a3be474c66516500d0bfce0cbb00bb518111 | 1,189 | //
// keyChainToolTestVC.swift
// XPUtilExample
//
// Created by jamalping on 2019/3/24.
// Copyright © 2019年 xyj. All rights reserved.
//
import UIKit
final class User: Codable, CustomStringConvertible {
var name = "jamal"
var age = 22
public var description: String {
return "\(self.name)" + "\(self.age)"
}
}
extension User: TypeSafeKeychainValue {
func data() -> Data? {
return try? JSONEncoder().encode(self)
}
static func value(data: Data) -> User? {
guard let model: User = try? JSONDecoder().decode(User.self, from: data) else {
return nil
}
return model
}
}
class keyChainToolTestVC: UIViewController {
let num = "num"
override func viewDidLoad() {
super.viewDidLoad()
title = "keyChainToolTest"
save()
get()
}
func save(key: String = "num") {
KeychainTool.set(User(), forKey: key)
}
func get(key: String = "num") {
guard let value: User = KeychainTool.value(forKey: key) else {
return
}
print(value.description)
}
}
| 19.816667 | 87 | 0.550883 |
877fd9f1b4ce59a8df4ff525e30db49761d74083 | 303 | //
// Constants.swift
// FlickrViewer
//
// Created by Chi on 3/4/18.
// Copyright © 2018 cammy. All rights reserved.
//
import Foundation
struct Contants {
static var navigationBarColor = "#EA827F"
static var navigationBarTintColor = "#FFFFFF"
static var selectionColor = "#EB4B98"
}
| 18.9375 | 49 | 0.686469 |
3af87891f50c8ba592ca3932033a6ef20bbfc68f | 600 | //
// AMGFormField.swift
//
// Created by Abel Gancsos on 3/7/18.
// Copyright © 2018 Abel Gancsos. All rights reserved.
//
import Foundation
import Cocoa
enum FORM_FIELD_TYPE : NSInteger {
case TEXT_FIELD = 100;
case PASSWORD = 101;
case POPUP = 102;
case TEXTAREA = 103;
case SWITCH = 104;
case DEFAULT = 105;
}
class AMGFormField {
var type : FORM_FIELD_TYPE = FORM_FIELD_TYPE.DEFAULT;
var label : String = "";
var value : [Any] = [];
var options : [Any] = [];
var editable : Bool = false;
public init(){
}
}
| 18.75 | 61 | 0.59 |
8fd428be5ca65f65e6b2fd756342f30df3c7966d | 415 | import UIKit
class AKDaysTableViewCell: UITableViewCell {
// MARK: Outlets
@IBOutlet weak var mainContainer: UIView!
@IBOutlet weak var title: UILabel!
// MARK: UITableViewCell Overriding
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| 24.411765 | 65 | 0.674699 |
ef5a0bc456fd967b8385f7dd66438122a72c29d9 | 2,548 | import Foundation
import azureSwiftRuntime
public protocol WebAppsStopContinuousWebJobSlot {
var headerParameters: [String: String] { get set }
var resourceGroupName : String { get set }
var name : String { get set }
var webJobName : String { get set }
var slot : String { get set }
var subscriptionId : String { get set }
var apiVersion : String { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (Error?) -> Void) -> Void;
}
extension Commands.WebApps {
// StopContinuousWebJobSlot stop a continuous web job for an app, or a deployment slot.
internal class StopContinuousWebJobSlotCommand : BaseCommand, WebAppsStopContinuousWebJobSlot {
public var resourceGroupName : String
public var name : String
public var webJobName : String
public var slot : String
public var subscriptionId : String
public var apiVersion = "2016-08-01"
public init(resourceGroupName: String, name: String, webJobName: String, slot: String, subscriptionId: String) {
self.resourceGroupName = resourceGroupName
self.name = name
self.webJobName = webJobName
self.slot = slot
self.subscriptionId = subscriptionId
super.init()
self.method = "Post"
self.isLongRunningOperation = false
self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/slots/{slot}/continuouswebjobs/{webJobName}/stop"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName)
self.pathParameters["{name}"] = String(describing: self.name)
self.pathParameters["{webJobName}"] = String(describing: self.webJobName)
self.pathParameters["{slot}"] = String(describing: self.slot)
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
self.queryParameters["api-version"] = String(describing: self.apiVersion)
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (Error?) -> Void) -> Void {
client.executeAsync(command: self) {
(error) in
completionHandler(error)
}
}
}
}
| 44.701754 | 179 | 0.63854 |
6128e68b5ce0bdd135e0a6a8b54ee240927a4d2b | 984 | //
// TableViewCell.swift
// ZCycleView
//
// Created by mengqingzheng on 2017/11/29.
// Copyright © 2017年 MQZHot. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
lazy var cycleView: ZCycleView = ZCycleView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(cycleView)
cycleView.setUrlsGroup(["http://chatm-icon.oss-cn-beijing.aliyuncs.com/pic/pic_20171101181927887.jpg", "http://chatm-icon.oss-cn-beijing.aliyuncs.com/pic/pic_20171114171645011.jpg", "http://chatm-icon.oss-cn-beijing.aliyuncs.com/pic/pic_20171114172009707.png"])
cycleView.timeInterval = 3
}
override func layoutSubviews() {
super.layoutSubviews()
cycleView.frame = bounds
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 31.741935 | 269 | 0.698171 |
64f56406dd01af8def157f12737585240ec9dd09 | 2,570 | //
// Color.swift
// Sage
//
// Copyright 2016-2017 Nikolai Vazquez
//
// 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.
//
/// A chess color.
public enum Color: String, CustomStringConvertible {
public var hashValue: Int {
switch self {
case .white:
return 0
case .black:
return 1
}
}
#if swift(>=3)
/// White chess color.
case white
/// Black chess color.
case black
/// White color regardless of Swift version.
public static let _white = Color.white
/// Black color regardless of Swift version.
internal static let _black = Color.black
/// An array of all colors.
public static let all: [Color] = [.white, .black]
#else
/// White chess color.
case White
/// Black chess color.
case Black
/// White color regardless of Swift version.
internal static let _white = Color.White
/// Black color regardless of Swift version.
internal static let _black = Color.Black
/// An array of all colors.
public static let all: [Color] = [.White, .Black]
#endif
/// Whether the color is white or not.
public var isWhite: Bool {
return self == ._white
}
/// Whether the color is black or not.
public var isBlack: Bool {
return self == ._black
}
/// A textual representation of `self`.
public var description: String {
return rawValue
}
/// The lowercase character for the color. `White` is "w", `Black` is "b".
public var character: Character {
return self.isWhite ? "w" : "b"
}
/// Create a color from a character of any case.
public init?(character: Character) {
switch character {
case "W", "w": self = ._white
case "B", "b": self = ._black
default: return nil
}
}
/// Returns the inverse of `self`.
public func inverse() -> Color {
return self.isWhite ? ._black : ._white
}
/// Inverts the color of `self`.
public mutating func invert() {
self = inverse()
}
}
| 23.796296 | 78 | 0.624125 |
ddd541370b0039e11656d3fbf734785bfa9ea8b5 | 1,705 | //
// Copyright (c) topmind GmbH and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
//
import CoreData
@testable import CoreDataMind
import XCTest
class CoreDataStackTests: XCTestCase {
var stack: CoreDataStack?
lazy var modelUrl: URL? = {
Bundle(for: CoreDataTests.self).url(forResource: "Model", withExtension: "momd")
}()
// MARK: - SETUP
override func setUp() {
super.setUp()
let expect = expectation(description: "store init")
stack = CoreDataStack(type: .memory, model: CoreDataTests.model) {
switch $0 {
case .success:
expect.fulfill()
case let .failure(error):
XCTFail(error.localizedDescription)
}
}
waitForExpectations(timeout: 5, handler: { _ in })
}
override func tearDown() {
super.tearDown()
stack = nil
}
// MARK: - TESTS
func testSQliteStackSetup() {
if let url = modelUrl {
let expect = expectation(description: "store init")
stack = CoreDataStack(type: .sqlite, modelUrl: url) { _ in
expect.fulfill()
}
waitForExpectations(timeout: 5, handler: { _ in })
}
XCTAssertNotNil(stack?.persistentStoreCoordinator)
_ = try? FileManager.default.removeItem(at: stack!.storeURL!)
}
func testMemoryStackSetup() {
if let url = modelUrl {
let expect = expectation(description: "store init")
stack = CoreDataStack(type: .memory, modelUrl: url) { _ in
expect.fulfill()
}
waitForExpectations(timeout: 5, handler: { _ in })
}
XCTAssertNotNil(stack?.persistentStoreCoordinator)
}
func testDefaultContextShouldHaveMainQueueConcurrencyType() {
XCTAssertTrue(stack?.mainContext.concurrencyType == .mainQueueConcurrencyType)
}
}
| 25.833333 | 84 | 0.708504 |
72691f370dc020a4882f10d08d61205bc6e77c92 | 11,715 | //
// WatchlistViewController.swift
// App
//
// Created by Hong on 26/5/17.
// Copyright © 2017 Pointwelve. All rights reserved.
//
import Domain
import FirebaseCrashlytics
import RxCocoa
import RxDataSources
import RxSwift
import SwiftReorder
import SwipeCellKit
import UIKit
final class WatchlistViewController: UIViewController, DefaultViewControllerType, ScreenNameable {
fileprivate enum Metric {
static let rowHeight: CGFloat = 70.0
}
typealias ViewModel = WatchlistViewModel
var disposeBag = DisposeBag()
var viewModel: WatchlistViewModel!
var deleteIndexPathSubject = PublishSubject<IndexPath>()
var fromIndexToIndexSubject = PublishSubject<(IndexPath, IndexPath)>()
private lazy var loadStateView: LoadStateView = {
let view = LoadStateView()
view.translatesAutoresizingMaskIntoConstraints = false
view.isHidden = true
return view
}()
private let tableViewDataTrigger = BehaviorSubject<Void?>(value: nil)
fileprivate lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.rowHeight = Metric.rowHeight
tableView.registerCell(of: WatchlistTableViewCell.self, with: WatchlistTableViewCell.identifier)
return tableView
}()
private lazy var addWatchlistBarButton: UIBarButtonItem = {
let addWatchlistBarButton = UIBarButtonItem(image:
Image.plusIcon.resource, style: .plain, target: self, action: nil)
addWatchlistBarButton.tintColor = Color.tealish
return addWatchlistBarButton
}()
private var loadingIndicator: LoadingIndicator = {
let view = LoadingIndicator()
view.translatesAutoresizingMaskIntoConstraints = false
view.isHidden = true
return view
}()
fileprivate var dataSource: RxTableViewSectionedReloadDataSource<WatchlistListData>?
var screenNameAccessibilityId: AccessibilityIdentifier {
return .watchlistTitle
}
func layout() {
update(screenName: "watchlist.title".localized())
let addButton = addWatchlistBarButton
addButton.setAccessibility(id: .watchlistAddButton)
navigationItem.rightBarButtonItem = addButton
[tableView, loadStateView].forEach(view.addSubview)
NSLayoutConstraint.activate([
loadStateView.topAnchor.constraint(equalTo: view.topAnchor),
loadStateView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
loadStateView.leftAnchor.constraint(equalTo: view.leftAnchor),
loadStateView.rightAnchor.constraint(equalTo: view.rightAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
tableView.rightAnchor.constraint(equalTo: view.rightAnchor)
])
registerForPreviewing(with: self, sourceView: tableView)
}
func bind() {
tableView.reorder.delegate = self
// Ended dragging
let didEndDragging = tableView.rx
.didEndDragging
.filter { !$0 }
.void()
// Ended decelerating
let didEndDecelerating = tableView.rx
.didEndDecelerating
.asObservable()
// Get latest visible rows while either event triggers
let visibleCellRows = Observable.merge(didEndDragging, didEndDecelerating)
.map { [weak self] _ in
self?.tableView.indexPathsForVisibleRows?.compactMap { $0.row }
}.asDriver(onErrorJustReturn: nil)
.filterNil()
.distinctUntilChanged {
let firstSet = Set($0)
let secondSet = Set($1)
return firstSet == secondSet
}
//
let didDragToTop = didEndDecelerating.map { [weak self] in
self?.tableView.indexPathsForVisibleRows?.compactMap { $0.row }
}
.asDriver(onErrorJustReturn: nil)
.filterNil()
.withLatestFrom(visibleCellRows) { ($0, $1) }
.filter { $0.0 == $0.1 }
.map { $0.0 }
func displayCellDriver() -> Driver<[Int]> {
return tableView.rx.willDisplayCell.asObservable()
.filter { (_, indexPath) -> Bool in
indexPath.row == self.tableView.indexPathsForVisibleRows?.last?.row
}
.take(1)
.map { _ in self.tableView.indexPathsForVisibleRows?.compactMap { $0.row } ?? [] }
.asDriver(onErrorJustReturn: [])
}
// Manaul Triggering from view appear, delete action
let manualTrigger = tableViewDataTrigger
.filterNil()
.asDriver(onErrorJustReturn: ())
.flatMap { displayCellDriver() }
let mergedVisibleCells = Driver.merge(didDragToTop, visibleCellRows, manualTrigger).debounce(.milliseconds(500))
let addWatchlistButtonObservable = addWatchlistBarButton.rx.tap.asObservable()
let viewDisappeared = rx.viewWillDisappear
.void()
.asDriver(onErrorJustReturn: ())
let cellSelected = tableView.rx.modelSelected(MutableBox<CurrencyPair>.self)
.asObservable()
let output = viewModel.transform(input:
.init(addWatchlistButtonObservable: addWatchlistButtonObservable,
watchlistDeleteObservable: deleteIndexPathSubject.asObservable(),
visibleCellRows: mergedVisibleCells,
viewDisappeared: viewDisappeared,
cellSelected: cellSelected,
fromIndexToIndexObservable: fromIndexToIndexSubject.asObservable()))
let dataSource = RxTableViewSectionedReloadDataSource<WatchlistListData>(configureCell: { _, tv, indexPath, item -> UITableViewCell in
if let spacer = tv.reorder.spacerCell(for: indexPath) {
return spacer
}
let cell = tv.dequeueReusableCell(withIdentifier: WatchlistTableViewCell.identifier, for: indexPath)
guard let priceCell = cell as? WatchlistTableViewCell else {
return UITableViewCell()
}
_ = priceCell.bind(input: WatchlistCellViewModel.Input(currencyPair: item,
streamPrice: output.streamPrice,
historicalPriceAPI: output.historicalPriceAPI))
priceCell.delegate = self
ThemeProvider.current
.drive(onNext: { theme in
if indexPath.row % 2 == 0 {
theme.cellOne.apply(to: priceCell)
} else {
theme.cellTwo.apply(to: priceCell)
}
})
.disposed(by: self.disposeBag)
return priceCell
})
self.dataSource = dataSource
output.currencyPairs
.drive(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
output.loadStateViewModel.output
.isContentHidden
.drive(tableView.rx.isHidden)
.disposed(by: disposeBag)
output.addWatchlistDriver
.drive()
.disposed(by: disposeBag)
output.reloadTriggerDriver
.drive(onNext: { [weak self] _ in
self?.tableViewDataTrigger.on(.next(()))
})
.disposed(by: disposeBag)
output.updateWatchlistDriver
.drive(onNext: { [weak self] _ in
self?.tableViewDataTrigger.on(.next(()))
})
.disposed(by: disposeBag)
loadStateView.bind(state: output.loadStateViewModel)
ThemeProvider.current
.drive(onNext: { [weak self] theme in
guard let `self` = self else {
return
}
theme.tableView.apply(to: self.tableView)
theme.view.apply(to: self.view)
})
.disposed(by: disposeBag)
output.unsubscribeSocket
.drive()
.disposed(by: disposeBag)
output.cellSelected
.drive()
.disposed(by: disposeBag)
output.reloadTableViewOnErrorSignal
.emit(onNext: { [weak self] _ in
self?.tableView.reloadData()
})
.disposed(by: disposeBag)
let isHidden = output.isLoading
.map { !$0 }
let loadingIndicatorInput = LoadingIndicatorViewModel.Input(isHidden: isHidden,
state: output.loadingIndicatorState)
_ = loadingIndicator.bind(input: loadingIndicatorInput)
}
}
extension WatchlistViewController: SwipeTableViewCellDelegate {
func tableView(_ tableView: UITableView,
editActionsForRowAt indexPath: IndexPath,
for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
guard orientation == .right else { return nil }
let deleteAction = SwipeAction(style: .destructive,
title: nil) { [weak self] _, indexPath in
self?.deleteIndexPathSubject.onNext(indexPath)
}
deleteAction.image = Image.deleteIcon.resource
deleteAction.hidesWhenSelected = true
return [deleteAction]
}
}
extension WatchlistViewController: TableViewReorderDelegate {
func tableView(_ tableView: UITableView,
reorderRowAt sourceIndexPath: IndexPath,
to destinationIndexPath: IndexPath) {}
func tableViewDidFinishReordering(_ tableView: UITableView,
from initialSourceIndexPath: IndexPath,
to finalDestinationIndexPath: IndexPath) {
guard initialSourceIndexPath != finalDestinationIndexPath else { return }
fromIndexToIndexSubject.onNext((initialSourceIndexPath, finalDestinationIndexPath))
}
}
extension WatchlistViewController: UIViewControllerPreviewingDelegate {
private func getWatchlistDetailViewController(currencyPair: CurrencyPair) -> UIViewController? {
let navigator = WatchlistDetailNavigator(state: .init(parent: viewModel.navigator))
navigator.currencyPair = currencyPair
let viewController = WatchlistDetailViewController(viewModel: .init(navigator: navigator))
viewController.currencyPair = currencyPair
let navigationController = BaseNavigationController(rootViewController: viewController)
Style.NavigationBar.noHairline.apply(to: navigationController.navigationBar)
navigationController.setNavigationBarHidden(true, animated: false)
return navigationController
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing,
commit viewControllerToCommit: UIViewController) {
guard let baseNavController = viewControllerToCommit as? BaseNavigationController,
let viewController = baseNavController.viewControllers.first as? WatchlistDetailViewController else {
return
}
viewModel.navigator.showWatchlistDetail(viewController.currencyPair)
var metadata = viewController.currencyPair.analyticsMetadata
metadata.updateValue("3D Touch", forKey: "Navigation Method")
AnalyticsProvider.log(event: "Show Currency Pair Detail", metadata: metadata)
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing,
viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location),
let cell = tableView.cellForRow(at: indexPath),
let currencyPair = dataSource?[indexPath].value else { return nil }
let viewController = getWatchlistDetailViewController(currencyPair: currencyPair)
previewingContext.sourceRect = cell.frame
return viewController
}
}
| 36.381988 | 140 | 0.664703 |
6ae8dd6a762842d6707d7c2e5fb96cdd4b7b502b | 2,192 | //
// PlayerViewController.swift
// SpotPlayer
//
// Created by Pete Smith on 01/05/2016.
// Copyright © 2016 Pete Smith. All rights reserved.
//
import UIKit
import Kingfisher
import SPBZoomTransition
class DetailViewController: UIViewController {
// Constants
private struct InternalConstants {
static let CellHeight: CGFloat = 60
}
// MARK: - IBOutlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var table: UITableView!
// MARK: - Properties (public)
var image: UIImage?
// MARK: - Properties (private)
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
imageView.image = image
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Setup
// MARK: - Navigation
@IBAction func backButtonPressed(_ sender: UIButton) {
}
}
typealias TableDelegate = DetailViewController
extension TableDelegate: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return InternalConstants.CellHeight
}
}
typealias TableDatasource = DetailViewController
extension TableDatasource: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifiers.TableCell, for: indexPath)
return cell
}
}
typealias ZoomDestinationDelegate = DetailViewController
extension ZoomDestinationDelegate: ZoomAnimatorDestinationDelegate {
func destinationFrame() -> CGRect {
return CGRect(x: 0, y: 30.0, width: view.bounds.width, height: view.bounds.width)
}
}
| 25.195402 | 113 | 0.67792 |
7a8f3f9973860f0c35e689a37187646e180910b6 | 2,340 | //
// Date+WJKAddition.swift
// weiBo
//
// Created by 王靖凯 on 2016/11/30.
// Copyright © 2016年 王靖凯. All rights reserved.
//
import UIKit
private let dateFromat = DateFormatter()
private let calendar = Calendar.current
extension Date {
static func dateFromSinaFormat(sinaDateString: String) -> Date {
dateFromat.locale = Locale(identifier: "en")
dateFromat.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
return dateFromat.date(from: sinaDateString)!
}
struct todayData {
var weekday: String?
var monthAndYear: String?
var day: String?
}
static func today() -> todayData {
var date = todayData()
let today = Date()
let weekdays = [nil, "星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", nil]
let day = calendar.component(Calendar.Component.weekday, from: today)
date.weekday = weekdays[day]
dateFromat.dateFormat = "MM/yyyy"
dateFromat.locale = Locale(identifier: "en")
date.monthAndYear = dateFromat.string(from: today)
dateFromat.dateFormat = "d"
date.day = dateFromat.string(from: today)
return date
}
public func requiredTimeString() -> String {
if calendar.isDateInToday(self) {
let secends = -Int(timeIntervalSinceNow)
if secends < 60 {
return "刚刚"
} else if secends < 3600 {
return "\(secends / 60)分钟前"
} else {
return "\(secends / 3600)小时前"
}
} else if calendar.isDateInYesterday(self) {
dateFromat.locale = Locale(identifier: "en")
dateFromat.dateFormat = "昨天 HH:mm"
return "\(dateFromat.string(from: self))"
} else {
let thisYear = calendar.component(.year, from: Date())
let hisYear = calendar.component(.year, from: self)
if thisYear == hisYear {
dateFromat.dateFormat = "MM-dd HH: mm"
dateFromat.locale = Locale(identifier: "en")
return "\(dateFromat.string(from: self))"
} else {
dateFromat.dateFormat = "yyyy-MM-dd HH: mm"
dateFromat.locale = Locale(identifier: "en")
return "\(dateFromat.string(from: self))"
}
}
}
}
| 31.621622 | 82 | 0.56453 |
79aa52e01158c4fc9157aa8bc962c08fa59aa11b | 6,695 | //
// Deprecated.swift
// https://github.com/denandreychuk/EasySwiftLayout
//
// This code is distributed under the terms and conditions of the MIT license.
// Copyright (c) 2019-2020 Denis Andreychuk
//
// 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
@available(*, deprecated, message: "`ESL2DimensionalInsets` deprecated and replaced with `ESLSizeInsets`")
typealias ESL2DimensionalInsets = CGSize
@available(*, deprecated, message: "`ESLOffset` deprecated and replaced with `UIOffset`")
public struct ESLOffset {
public let x: CGFloat
public let y: CGFloat
public static let zero = ESLOffset(x: 0, y: 0)
public init(x: CGFloat, y: CGFloat) {
self.x = x
self.y = y
}
}
// MARK: - Pin Methods
public extension UIView {
@available(*, deprecated, renamed: "pinEdgesToSuperview(ofGroup:usingRelation:withInset:priority:)")
func pinHorizontalEdgesToSuperview(withInset inset: CGFloat = .zero) {
pinEdgesToSuperview(ofGroup: .horizontal, withInset: inset)
}
@available(*, deprecated, renamed: "pinEdgesToSuperview(ofGroup:usingRelation:withInset:priority:)")
func pinVerticalEdgesToSuperview(withInset inset: CGFloat = .zero) {
pinEdgesToSuperview(ofGroup: .vertical, withInset: inset)
}
}
// MARK: - Size Methods
public extension UIView {
@available(*, deprecated, renamed: "width(match:withInset:usingRelation:priority:)")
@discardableResult
func width(
to anotherView: UIView,
withInset inset: CGFloat = .zero,
usingRelation relation: NSLayoutConstraint.Relation = .equal,
priority: UILayoutPriority = .required
) -> Self {
width(match: anotherView, withInset: inset, usingRelation: relation, priority: priority)
}
@available(*, deprecated, renamed: "height(match:withInset:usingRelation:priority:)")
@discardableResult
func height(
to anotherView: UIView,
withInset inset: CGFloat = .zero,
usingRelation relation: NSLayoutConstraint.Relation = .equal,
priority: UILayoutPriority = .required
) -> Self {
height(match: anotherView, withInset: inset, usingRelation: relation, priority: priority)
}
@available(*, deprecated, renamed: "size(match:withInsets:usingRelation:priority:)")
@discardableResult
func size(
to anotherView: UIView,
withInsets insets: ESLSizeInsets = .zero,
usingRelation relation: NSLayoutConstraint.Relation = .equal,
priority: UILayoutPriority = .required
) -> Self {
size(match: anotherView, withInsets: insets, usingRelation: relation, priority: priority)
}
@available(*, deprecated, renamed: "size(match:withInset:usingRelation:priority:)")
@discardableResult
func size(
to anotherView: UIView,
withInset inset: CGFloat = .zero,
usingRelation relation: NSLayoutConstraint.Relation = .equal,
priority: UILayoutPriority = .required
) -> Self {
size(match: anotherView, withInset: inset, usingRelation: relation, priority: priority)
}
@available(*, deprecated, renamed: "width(_:usingRelation:priority:)")
@discardableResult
func width(
_ relation: NSLayoutConstraint.Relation, to width: CGFloat,
priority: UILayoutPriority = .required
) -> Self {
self.width(width, usingRelation: relation, priority: priority)
return self
}
@available(*, deprecated, renamed: "height(_:usingRelation:priority:)")
@discardableResult
func height(
_ relation: NSLayoutConstraint.Relation, to height: CGFloat,
priority: UILayoutPriority = .required
) -> Self {
self.height(height, usingRelation: relation, priority: priority)
return self
}
@available(*, deprecated, renamed: "size(_:usingRelation:priority:)")
@discardableResult
func size(_ relation: NSLayoutConstraint.Relation, to size: CGSize, priority: UILayoutPriority = .required) -> Self {
self.size(size, usingRelation: relation, priority: priority)
}
@available(*, deprecated, renamed: "size(toSquareWithSide:usingRelation:priority:)")
@discardableResult
func size(
_ relation: NSLayoutConstraint.Relation,
toSquareWithSide side: CGFloat,
priority: UILayoutPriority = .required
) -> Self {
size(toSquareWithSide: side, usingRelation: relation, priority: priority)
return self
}
}
// MARK: - Center Methods
public extension UIView {
@available(*, deprecated, renamed: "centerInSuperview(axis:withOffset:priority:)")
@discardableResult
func centerInSuperview(
_ axis: ESLAxis,
withOffset offset: CGFloat = .zero,
priority: UILayoutPriority = .required
) -> Self {
centerInSuperview(axis: axis)
}
@available(*, deprecated)
@discardableResult
func centerInView(
_ anotherView: UIView,
withOffset offset: ESLOffset,
priority: UILayoutPriority = .required
) -> Self {
centerInView(anotherView, axis: .horizontal, withOffset: offset.x, priority: priority)
centerInView(anotherView, axis: .vertical, withOffset: offset.y, priority: priority)
return self
}
@available(*, deprecated)
@discardableResult
func centerInSuperview(withOffset offset: ESLOffset, priority: UILayoutPriority = .required) -> Self {
guard let superview = superview else { return self }
centerInView(superview, withOffset: offset, priority: priority)
return self
}
}
| 36.98895 | 121 | 0.688275 |
bb9e56054545b5406f6b2cded57b92efd5d991cb | 2,753 | //
// Service3ViewController.swift
// Swimediator_Example
import Foundation
import Swimediator
class Service3ViewController: BaseViewController {
let from: String
let to: String
lazy var fromLabel: UILabel = {
let label = UILabel()
return label
}()
lazy var toLabel: UILabel = {
let label = UILabel()
return label
}()
init(from: String, to: String) {
self.from = from
self.to = to
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
fromLabel.text = "from: " + from
toLabel.text = "to: " + to
view.addSubview(fromLabel)
view.addSubview(toLabel)
fromLabel.snp.makeConstraints { (make) in
make.center.equalToSuperview()
}
toLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(fromLabel)
make.top.equalTo(fromLabel.snp.bottom).offset(10)
}
}
override func injector1Action() {
let vc = MediatorManager.getObject(aProtocol: Service1Protocol.self)
self.navigationController?.pushViewController(vc as! UIViewController, animated: true)
}
override func injector2Action() {
let vc = MediatorManager.getObject(aProtocol: Service2Protocol.self, arg1: "Service2ToService3")
self.navigationController?.pushViewController(vc as! UIViewController, animated: true)
}
override func injector3Action() {
let vc = MediatorManager.getObject(aProtocol: Service3Protocol.self, arg1: "service3", arg2: "service3")
self.navigationController?.pushViewController(vc as! UIViewController, animated: true)
}
override func router1Action() {
let obj = try? MediatorManager.routerURL(route: "swi://service1")
guard let vc = obj as? UIViewController else {
return
}
self.navigationController?.pushViewController(vc, animated: true)
}
override func router2Action() {
let obj = try? MediatorManager.routerURL(route: "swi://service2/router_Service2ToService3")
guard let vc = obj as? UIViewController else {
return
}
self.navigationController?.pushViewController(vc, animated: true)
}
override func router3Action() {
let obj = try? MediatorManager.routerURL(route: "swi://service3?from=router_Service3&to=router_Service3")
guard let vc = obj as? UIViewController else {
return
}
self.navigationController?.pushViewController(vc, animated: true)
}
}
| 31.643678 | 113 | 0.636033 |
8fcb2b557bf3664fe2b1cc92b2758fd2975080d7 | 832 | //
// LikesByTableViewCell.swift
// BaseProject
//
// Created by MN on 13/04/2018.
// Copyright © 2018 Wave. All rights reserved.
//
import UIKit
class LikesByTableViewCell: UITableViewCell {
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var profileImageTop: UIImageView!
var userID: String!
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
}
var profileButtonAction: ((String) -> Void)?
@IBAction func profileButtonTApped(sender: UIButton!){
profileButtonAction?(self.userID)
}
}
| 22.486486 | 65 | 0.671875 |
eddb9309c79d0fc3099abf7a3e5262457b1d03ca | 12,696 | import UIKit
import MiniApp
class SettingsTableViewController: UITableViewController {
@IBOutlet weak var endPointSegmentedControl: UISegmentedControl!
@IBOutlet weak var textFieldAppID: UITextField!
@IBOutlet weak var textFieldSubKey: UITextField!
@IBOutlet weak var invalidHostAppIdLabel: UILabel!
@IBOutlet weak var invalidSubscriptionKeyLabel: UILabel!
weak var configUpdateDelegate: SettingsDelegate?
let predefinedKeys: [String] = ["RAS_PROJECT_IDENTIFIER", "RAS_SUBSCRIPTION_KEY", ""]
let localizedErrorTitle = MASDKLocale.localize("miniapp.sdk.ios.error.title")
enum SectionHeader: Int {
case RAS = 1
case profile = 2
case previewMode = 0
}
enum TestMode: Int, CaseIterable {
case HOSTED,
PREVIEW
func stringValue() -> String {
switch self {
case .HOSTED:
return MASDKLocale.localize("miniapp.sdk.ios.mode.publishing")
case .PREVIEW:
return MASDKLocale.localize("miniapp.sdk.ios.mode.previewing")
}
}
func isPreviewMode() -> Bool {
switch self {
case .HOSTED:
return false
case .PREVIEW:
return true
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.textFieldAppID.delegate = self
self.textFieldSubKey.delegate = self
addTapGesture()
addBuildVersionLabel()
self.tableView.separatorStyle = .singleLine
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
resetFields()
toggleSaveButton()
}
func resetFields() {
self.invalidHostAppIdLabel.isHidden = true
self.invalidSubscriptionKeyLabel.isHidden = true
configure(field: self.textFieldAppID, for: .projectId)
configure(field: self.textFieldSubKey, for: .subscriptionKey)
configureMode()
}
@IBAction func actionResetConfig(_ sender: Any) {
resetFields()
self.dismiss(animated: true, completion: nil)
}
@IBAction func actionSaveConfig() {
if isValueEntered(text: self.textFieldAppID.text, key: .projectId) && isValueEntered(text: self.textFieldSubKey.text, key: .subscriptionKey) {
if self.textFieldAppID.text!.isValidUUID() {
let selectedMode = TestMode(rawValue: self.endPointSegmentedControl.selectedSegmentIndex)
let isPreview = selectedMode?.isPreviewMode() ?? true
fetchAppList(withConfig:
createConfig(
projectId: self.textFieldAppID.text!,
subscriptionKey: self.textFieldSubKey.text!,
loadPreviewVersions: isPreview
)
)
}
displayInvalidValueErrorMessage(forKey: .projectId)
}
}
/// Fetch the mini app list for a given Host app ID and subscription key.
/// Reload Mini App list only when successful response is received
/// If error received with 200 as status code but there is no mini apps published in the platform, so we show a different error message
func fetchAppList(withConfig: MiniAppSdkConfig) {
showProgressIndicator(silently: false) {
MiniApp.shared(with: withConfig).list { (result) in
DispatchQueue.main.async {
self.refreshControl?.endRefreshing()
}
switch result {
case .success(let responseData):
DispatchQueue.main.async {
self.dismissProgressIndicator()
self.saveCustomConfiguration(responseData: responseData)
}
case .failure(let error):
let errorInfo = error as NSError
if errorInfo.code != 200 {
print(error.localizedDescription)
self.displayAlert(
title: MASDKLocale.localize("miniapp.sdk.ios.error.title"),
message: MASDKLocale.localize("miniapp.sdk.ios.error.message.list"),
dismissController: true)
} else {
DispatchQueue.main.async {
self.displayAlert(
title: MASDKLocale.localize("Information"),
message: MASDKLocale.localize("miniapp.sdk.ios.error.message.no_miniapp_found"), dismissController: true) { _ in
self.saveCustomConfiguration(responseData: nil)
self.dismiss(animated: true, completion: nil)
}
}
}
}
}
}
}
func saveCustomConfiguration(responseData: [MiniAppInfo]?) {
self.save(field: self.textFieldAppID, for: .projectId)
self.save(field: self.textFieldSubKey, for: .subscriptionKey)
self.saveMode()
self.displayAlert(title: MASDKLocale.localize("miniapp.sdk.ios.param.save_title"),
message: MASDKLocale.localize("miniapp.sdk.ios.param.save_text"),
autoDismiss: true) { _ in
self.dismiss(animated: true, completion: nil)
guard let miniAppList = responseData else {
self.configUpdateDelegate?.didSettingsUpdated(controller: self, updated: nil)
return
}
self.configUpdateDelegate?.didSettingsUpdated(controller: self, updated: miniAppList)
}
}
func createConfig(projectId: String, subscriptionKey: String, loadPreviewVersions: Bool) -> MiniAppSdkConfig {
return MiniAppSdkConfig(
rasProjectId: projectId,
subscriptionKey: subscriptionKey,
hostAppVersion: Bundle.main.infoDictionary?[Config.Key.version.rawValue] as? String,
isPreviewMode: loadPreviewVersions)
}
/// Adding Tap gesture to dismiss the Keyboard
func addTapGesture() {
let tapGesture = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:)))
tapGesture.cancelsTouchesInView = false
view.addGestureRecognizer(tapGesture)
}
func configure(field: UITextField?, for key: Config.Key) {
field?.placeholder = Bundle.main.infoDictionary?[key.rawValue] as? String
field?.text = getTextFieldValue(key: key, placeholderText: field?.placeholder)
}
func configureMode() {
self.endPointSegmentedControl.removeAllSegments()
TestMode.allCases.forEach { configure(mode: $0) }
let defaultMode = (Bundle.main.infoDictionary?[Config.Key.isPreviewMode.rawValue] as? Bool ?? true).intValue
if let index = Config.userDefaults?.value(forKey: Config.Key.isPreviewMode.rawValue) {
self.endPointSegmentedControl.selectedSegmentIndex = (index as? Bool)?.intValue ?? defaultMode
} else {
self.endPointSegmentedControl.selectedSegmentIndex = defaultMode
}
}
func configure(mode: TestMode) {
self.endPointSegmentedControl.insertSegment(withTitle: mode.stringValue(), at: mode.rawValue, animated: false)
}
func getTextFieldValue(key: Config.Key, placeholderText: String?) -> String? {
guard let value = Config.userDefaults?.string(forKey: key.rawValue) else {
return placeholderText
}
return value
}
func toggleSaveButton() {
if !self.textFieldAppID.text!.isValidUUID() || self.textFieldSubKey.text!.isEmpty {
self.navigationItem.rightBarButtonItem?.isEnabled = false
return
}
self.navigationItem.rightBarButtonItem?.isEnabled = true
}
func save(field: UITextField?, for key: Config.Key) {
if let textField = field {
Config.userDefaults?.set(textField.text, forKey: key.rawValue)
} else {
Config.userDefaults?.removeObject(forKey: key.rawValue)
}
}
func saveMode() {
let selectedMode = self.endPointSegmentedControl.selectedSegmentIndex
Config.userDefaults?.set(selectedMode.boolValue, forKey: Config.Key.isPreviewMode.rawValue)
}
func isValueEntered(text: String?, key: Config.Key) -> Bool {
guard let textFieldValue = text, !textFieldValue.isEmpty else {
displayNoValueFoundErrorMessage(forKey: key)
return false
}
return true
}
func displayInvalidValueErrorMessage(forKey: Config.Key) {
switch forKey {
case .projectId:
displayAlert(title: localizedErrorTitle,
message: MASDKLocale.localize("miniapp.sdk.ios.error.message.incorrect_appid"),
autoDismiss: true)
case .subscriptionKey:
displayAlert(title: localizedErrorTitle,
message: MASDKLocale.localize("miniapp.sdk.ios.error.message.incorrect_subscription_key"),
autoDismiss: false)
default:
break
}
}
func displayNoValueFoundErrorMessage(forKey: Config.Key) {
switch forKey {
case .projectId:
displayAlert(title: localizedErrorTitle,
message: MASDKLocale.localize("miniapp.sdk.ios.error.message.empty_appid_key"),
autoDismiss: true)
case .subscriptionKey:
displayAlert(title: localizedErrorTitle,
message: MASDKLocale.localize("miniapp.sdk.ios.error.message.empty_subscription_key"),
autoDismiss: false)
default:
break
}
}
public func textFieldShouldClear(_ textField: UITextField) -> Bool {
if textField.tag == 100 {
self.invalidHostAppIdLabel.isHidden = true
} else {
self.invalidSubscriptionKeyLabel.isHidden = true
}
self.navigationItem.rightBarButtonItem?.isEnabled = false
return true
}
public override func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let textFieldValue = (textField.text! as NSString).replacingCharacters(in: range, with: string)
validateTextFields(textField: textField, and: textFieldValue)
if textFieldValue.isEmpty {
self.navigationItem.rightBarButtonItem?.isEnabled = false
return true
}
if textField.tag == 100 {
self.navigationItem.rightBarButtonItem?.isEnabled = textFieldValue.isValidUUID()
return true
}
if self.textFieldAppID.text!.isValidUUID() {
self.navigationItem.rightBarButtonItem?.isEnabled = true
return true
}
self.navigationItem.rightBarButtonItem?.isEnabled = false
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
validateTextFields(textField: textField, and: textField.text ?? "")
}
func validateTextFields(textField: UITextField, and value: String) {
if textField.tag == 100 {
self.invalidHostAppIdLabel.isHidden = value.isValidUUID()
return
}
self.invalidSubscriptionKeyLabel.isHidden = !value.isEmpty
}
func addBuildVersionLabel() {
self.navigationItem.prompt = getBuildVersionText()
}
func getBuildVersionText() -> String {
var versionText = ""
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
versionText.append("Build Version: \(version) - ")
}
if let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
versionText.append("(\(build))")
}
return versionText
}
}
protocol SettingsDelegate: AnyObject {
func didSettingsUpdated(controller: SettingsTableViewController, updated miniAppList: [MiniAppInfo]?)
}
extension SettingsTableViewController {
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case SectionHeader.previewMode.rawValue:
return "Preview Mode"
case SectionHeader.profile.rawValue:
return ""
case SectionHeader.RAS.rawValue:
return "RAS"
default:
return nil
}
}
}
| 39.551402 | 150 | 0.612398 |
e9929ece48ebb07ee2bf86c69898d0651cf25f21 | 1,141 | //
// VGSCheckoutSDKRequestResult.swift
// VGSCheckoutSDK
import Foundation
/// Checkout addtional info in `VGSCheckoutRequestResult`.
public protocol VGSCheckoutInfo {}
/// Basic Checkout addtional info.
internal protocol VGSCheckoutBasicExtraData {}
/// Response enum cases for SDK requests.
@frozen public enum VGSCheckoutRequestResult {
/**
Success response case
- Parameters:
- code: response status code.
- data: response **data** object.
- response: URLResponse object represents a URL load response.
- info: `VGSCheckoutInfo?`, addtional info in `VGSCheckoutRequestResult`.
*/
case success(_ code: Int, _ data: Data?, _ response: URLResponse?, _ info: VGSCheckoutInfo? = nil)
/**
Failed response case
- Parameters:
- code: response status code.
- data: response **Data** object.
- response: `URLResponse` object represents a URL load response.
- error: `Error` object.
- info: `VGSCheckoutInfo?`, addtional info in `VGSCheckoutRequestResult`.
*/
case failure(_ code: Int, _ data: Data?, _ response: URLResponse?, _ error: Error?, _ info: VGSCheckoutInfo? = nil)
}
| 30.026316 | 117 | 0.708151 |
01c4e98357f33d80cd745104a8567fb2d2054206 | 1,451 | // BigUInteger+ExpressibleBy.swift
//
// This source file is part of the Swift Math open source project.
//
// Copyright (c) 2022 Logan Richards and the Swift Math project authors.
// Licensed under MIT
//
// See https://github.com/Logarithm-1/NumberTheory/blob/main/LICENSE for license information
extension BigUInteger: ExpressibleByIntegerLiteral {
public typealias IntegerLiteralType = UInt
/// Allows ``BigInteger`` to be expressed by an integer. For example:
///
/// let x: BigInteger = 5
///
/// `x` would be an BigInteger with a value of `5`
public init(integerLiteral value: UInt) {
self.init(value)
}
}
extension BigUInteger: ExpressibleByStringLiteral {
/// A `BigUInteger` from a decimal number represented by a string literal of arbitrary length.
/// - Requires the string to only contain decimal digits
public init(stringLiteral value: StringLiteralType) {
self.init(value, radix: 10)!
}
/// A `BigUInteger` from a Extended Grapheme Cluster.
/// - Requires the string to only contain decimal digits
public init(extendedGraphemeClusterLiteral value: String) {
self = BigUInteger(value, radix: 10)!
}
/// A `BigUInteger` from a Unicode Scalar
/// - Requires the Scalar to represent a decimal digit.
public init(unicodeScalarLiteral value: UnicodeScalar) {
self = BigUInteger(String(value), radix: 10)!
}
}
| 34.547619 | 98 | 0.686423 |
50c12fc72f3b3b3e0834bda197627feee1c9e799 | 3,578 | //
// CardPartTitleDescriptionViewTests.swift
// CardParts_Tests
//
// Created by Kier, Tom on 12/8/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import XCTest
import RxSwift
import RxCocoa
@testable import CardParts
class CardPartTitleDescriptionViewTests: 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 testLeftTitle() {
let cell = CardPartTitleDescriptionView()
XCTAssertEqual(cell.leftTitleFont, CardParts.theme.leftTitleFont)
XCTAssertEqual(cell.leftTitleLabel.font, CardParts.theme.leftTitleFont)
XCTAssertEqual(cell.leftTitleColor, CardParts.theme.leftTitleColor)
XCTAssertEqual(cell.leftTitleLabel.textColor, CardParts.theme.leftTitleColor)
cell.leftTitleFont = UIFont.boldSystemFont(ofSize: 20)
XCTAssertEqual(cell.leftTitleLabel.font, UIFont.boldSystemFont(ofSize: 20))
cell.leftTitleColor = UIColor.red
XCTAssertEqual(cell.leftTitleLabel.textColor, UIColor.red)
}
func testLeftDescription() {
let cell = CardPartTitleDescriptionView()
XCTAssertEqual(cell.leftDescriptionFont, CardParts.theme.leftDescriptionFont)
XCTAssertEqual(cell.leftDescriptionLabel.font, CardParts.theme.leftDescriptionFont)
XCTAssertEqual(cell.leftDescriptionColor, CardParts.theme.leftDescriptionColor)
XCTAssertEqual(cell.leftDescriptionLabel.textColor, CardParts.theme.leftDescriptionColor)
cell.leftDescriptionFont = UIFont.boldSystemFont(ofSize: 20)
XCTAssertEqual(cell.leftDescriptionLabel.font, UIFont.boldSystemFont(ofSize: 20))
cell.leftDescriptionColor = UIColor.red
XCTAssertEqual(cell.leftDescriptionLabel.textColor, UIColor.red)
}
func testRightTitle() {
let cell = CardPartTitleDescriptionView()
XCTAssertEqual(cell.rightTitleFont, CardParts.theme.rightTitleFont)
XCTAssertEqual(cell.rightTitleLabel.font, CardParts.theme.rightTitleFont)
XCTAssertEqual(cell.rightTitleColor, CardParts.theme.rightTitleColor)
XCTAssertEqual(cell.rightTitleLabel.textColor, CardParts.theme.rightTitleColor)
cell.rightTitleFont = UIFont.boldSystemFont(ofSize: 20)
XCTAssertEqual(cell.rightTitleLabel.font, UIFont.boldSystemFont(ofSize: 20))
cell.rightTitleColor = UIColor.red
XCTAssertEqual(cell.rightTitleLabel.textColor, UIColor.red)
}
func testRightDescription() {
let cell = CardPartTitleDescriptionView()
XCTAssertEqual(cell.rightDescriptionFont, CardParts.theme.rightDescriptionFont)
XCTAssertEqual(cell.rightDescriptionLabel.font, CardParts.theme.rightDescriptionFont)
XCTAssertEqual(cell.rightDescriptionColor, CardParts.theme.rightDescriptionColor)
XCTAssertEqual(cell.rightDescriptionLabel.textColor, CardParts.theme.rightDescriptionColor)
cell.rightDescriptionFont = UIFont.boldSystemFont(ofSize: 20)
XCTAssertEqual(cell.rightDescriptionLabel.font, UIFont.boldSystemFont(ofSize: 20))
cell.rightDescriptionColor = UIColor.red
XCTAssertEqual(cell.rightDescriptionLabel.textColor, UIColor.red)
}
}
| 40.659091 | 111 | 0.72275 |
e939dab7bbbd1d49a41162ef6ef8498705f3304e | 444 | //
// AppDelegate.swift
// SwiftyPicker
//
// Created by Fabian Canas on 9/14/15.
// Copyright © 2015 Fabián Cañas. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
}
| 20.181818 | 151 | 0.720721 |
e267ffc3920a1a88eaaa96e08438e86d3c5fa8e0 | 3,896 | //
// AppDelegate.swift
// iOS Example
//
// Created by Xuan Jie Chew on 09/08/2019.
// Copyright (c) 2019 Parousya. All rights reserved.
//
import UIKit
import ParousyaSAASSDK
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Start ParousyaSAASSDK on launch if user is still logged in.
// This is required for beacon events even when the app is terminated.
let userDefaults = UserDefaults.standard
if let userId = userDefaults.object(forKey: ParousyaSAASSampleClientConstants.userIdKey) as? String,
let value = userDefaults.object(forKey: ParousyaSAASSampleClientConstants.userTypeKey) as? Int,
let userType = PRSPersonType(rawValue: value) {
ParousyaSAASSDK.start(appKey: ParousyaSAASSampleClientConstants.appKey, appSecret: ParousyaSAASSampleClientConstants.appSecret, personGenericId: userId, personType: userType, isDebug: true, onSuccess: {
}) { error in
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Pass the data object to ParousyaSAASSDK.
ParousyaSAASSDK.registerPushToken(token: deviceToken, onSuccess: {
}) { error in
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let payload = userInfo as NSDictionary
// Parousya remote notifications will include a dictionary under the "parousya" key.
// Pass the entire payload to ParousyaSAASSDK to handle if "parousya" key is found.
if let _ = payload["parousya"] as? [String:Any] {
ParousyaSAASSDK.processPushPayload(payload, onHandled: {
completionHandler(.newData)
}) {
completionHandler(.noData)
}
return
}
// Handle your own push notifications here
// Call completionHandler after you are done
completionHandler(.noData)
}
}
| 43.775281 | 285 | 0.755133 |
6a2ef698c6f334833c9d4318d9a0f2123c68dbc1 | 5,922 | //
// TwitterManagerTests.swift
// CriticalMapsTests
//
// Created by Leonard Thomas on 1/28/19.
//
@testable import CriticalMaps
import XCTest
class TwitterManagerTests: XCTestCase {
func getSetup() -> (twitterManager: TwitterManager, networkLayer: MockNetworkLayer) {
let networkLayer = MockNetworkLayer()
let twitterManger = TwitterManager(networkLayer: networkLayer, request: TwitterRequest())
return (twitterManger, networkLayer)
}
func testUpdateMessagesCallback() {
let setup = getSetup()
let exp = expectation(description: "Update Tweets callback called")
var cachedTweets: [Tweet]!
let fakeResponse = TwitterApiResponse.TestData.fakeResponse
setup.networkLayer.mockResponse = fakeResponse
setup.twitterManager.updateContentStateCallback = { contentState in
// iterating through the elements is more stable as the order of the elements may be different
switch contentState {
case let .results(tweets):
cachedTweets = tweets
XCTAssertEqual(tweets.count, Tweet.TestData.fakeTweets.count)
for tweet in tweets {
XCTAssert(fakeResponse.statuses.contains(tweet))
}
exp.fulfill()
default:
XCTFail("contentState is not a result")
}
}
setup.twitterManager.loadTweets()
wait(for: [exp], timeout: 1)
XCTAssertEqual(fakeResponse.statuses.count, cachedTweets.count)
for tweet in cachedTweets {
XCTAssert(fakeResponse.statuses.contains(tweet))
}
}
func testLoadTweetsCompletionOnSuccess() {
let setup = getSetup()
let exp = expectation(description: "Update Tweets callback called")
setup.networkLayer.mockResponse = TwitterApiResponse.TestData.fakeResponse
setup.twitterManager.loadTweets { _ in
exp.fulfill()
}
wait(for: [exp], timeout: 1)
XCTAssertEqual(setup.networkLayer.numberOfGetCalled, 1)
}
func testLoadTweetsCompletionOnFailure() {
let setup = getSetup()
let exp = expectation(description: "Update Tweets callback called")
setup.networkLayer.mockResponse = nil
setup.twitterManager.loadTweets { _ in
exp.fulfill()
}
wait(for: [exp], timeout: 1)
XCTAssertEqual(setup.networkLayer.numberOfGetCalled, 1)
}
func testLoadTweetsCompletionOnSuccessShouldProduceContentState() {
// given
let setup = getSetup()
let tweetCallbackExpectation = expectation(description: "Update Tweets callback called")
let contentStateExpectation = expectation(description: "ContentStateCallback succeded")
setup.networkLayer.mockResponse = TwitterApiResponse.TestData.fakeResponse
var contentStateCallback: ContentState<[Tweet]>?
// when
setup.twitterManager.updateContentStateCallback = { state in
contentStateCallback = state
contentStateExpectation.fulfill()
}
setup.twitterManager.loadTweets { _ in
tweetCallbackExpectation.fulfill()
}
// then
wait(for: [tweetCallbackExpectation, contentStateExpectation], timeout: 1)
XCTAssertNotNil(contentStateCallback)
}
func testLoadTweetsCompletionOnSuccessShouldProduceResultContentState() {
// given
let setup = getSetup()
let tweetCallbackExpectation = expectation(description: "Update Tweets callback called")
let contentStateExpectation = expectation(description: "ContentStateCallback succeded")
setup.networkLayer.mockResponse = TwitterApiResponse.TestData.fakeResponse
var contentStateCallback: ContentState<[Tweet]>?
// when
setup.twitterManager.updateContentStateCallback = { state in
contentStateCallback = state
contentStateExpectation.fulfill()
}
setup.twitterManager.loadTweets { _ in
tweetCallbackExpectation.fulfill()
}
// then
wait(for: [tweetCallbackExpectation, contentStateExpectation], timeout: 1)
switch contentStateCallback! {
case .results:
break // means success
default:
XCTFail()
}
}
func testLoadTweetsCompletionOnSuccessShouldProduceErrorContentState() {
// given
let setup = getSetup()
let tweetCallbackExpectation = expectation(description: "Update Tweets callback called")
let contentStateExpectation = expectation(description: "ContentStateCallback succeded")
setup.networkLayer.mockResponse = nil
var contentStateCallback: ContentState<[Tweet]>?
// when
setup.twitterManager.updateContentStateCallback = { state in
contentStateCallback = state
contentStateExpectation.fulfill()
}
setup.twitterManager.loadTweets { _ in
tweetCallbackExpectation.fulfill()
}
// then
wait(for: [tweetCallbackExpectation, contentStateExpectation], timeout: 1)
switch contentStateCallback! {
case .error:
break // means success
default:
XCTFail()
}
}
}
private extension TwitterApiResponse {
enum TestData {
static let fakeResponse = TwitterApiResponse(statuses: Tweet.TestData.fakeTweets)
}
}
private extension Tweet {
enum TestData {
static let fakeTweets: [Tweet] = [
Tweet(text: "Hello World", createdAt: Date(), user: TwitterUser(name: "Test", screenName: "Foo", profileImageUrl: "haa"), id: "12345"),
Tweet(text: "Test Test", createdAt: Date(), user: TwitterUser(name: "Hello World", screenName: "Bar", profileImageUrl: "differentURL"), id: "67890"),
]
}
}
| 36.782609 | 161 | 0.653327 |
ddc44928f372aeafa4410cf4266fce6a550cdb1f | 1,709 | //
// SwiftBTC_Tests
//
// Created by Otto Suess on 28.02.18.
// Copyright © 2018 Zap. All rights reserved.
//
@testable import SwiftBTC
import XCTest
final class LegacyBitcoinAddressTests: XCTestCase {
func testAddressTypes() {
let tests: [(String, LegacyBitcoinAddress.AddressType, Network)] = [
("17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem", .pubkeyHash, .mainnet),
("3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX", .scriptHash, .mainnet),
("5Hwgr3u458GLafKBgxtssHSPqJnYoGrSzgQsPwLFhLNYskDPyyA", .privateKey, .mainnet),
("mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn", .pubkeyHash, .testnet),
("2MzQwSSnBHWHqSAqtTVQ6v47XtaisrJa1Vc", .scriptHash, .testnet),
("92Pg46rUhgTT7romnV7iGW6W1gbGdeezqdbJCzShkCsYNzyyNcc", .privateKey, .testnet),
("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", .pubkeyHash, .mainnet),
("1111111111111111111114oLvT2", .pubkeyHash, .mainnet),
("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j", .pubkeyHash, .mainnet),
("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", .pubkeyHash, .mainnet)
]
for (input, type, network) in tests {
let address = LegacyBitcoinAddress(string: input)
XCTAssertEqual(address?.type, type)
XCTAssertEqual(address?.network, network)
}
}
func testInvalidAddresses() {
let invalid = [
"1badbadbadbadbadbadbadbadbadbadbad",
"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X",
"1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
"1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i"
]
for input in invalid {
XCTAssertNil(LegacyBitcoinAddress(string: input))
}
}
}
| 37.152174 | 91 | 0.656524 |
1c7b9ab84ca111e887cc5b93b1da4b5d27d5bf76 | 6,066 | //
// EventNameFormatter.swift
// AnalyticsCenter
//
// Created by Anton Kaliuzhnyi on 18.05.2021.
//
import Foundation
open class EventNameFormatter: AnalyticsEventNameFormatter {
public enum Format {
case camelCase
case capitalizedCamelCase
case snakeCase
case capitalizedSnakeCase
case upperSnakeCase
case kebabCase
case capitalizedKebabCase
case upperKebabCase
case sentence
case capitalized
case lowercased
case uppercased
}
public let format: Format
public init(format: Format) {
self.format = format
}
open func format(_ name: String) -> String {
let words = words(from: name)
var result = ""
switch format {
case .camelCase:
for (i, w) in words.enumerated() {
if i == 0 {
result = w.lowercased()
} else {
result += capitalizeFirstLetter(w)
}
}
case .capitalizedCamelCase:
for w in words {
result += capitalizeFirstLetter(w)
}
case .snakeCase:
for (i, w) in words.enumerated() {
if i == 0 {
result = w.lowercased()
} else {
result += "_" + w.lowercased()
}
}
case .capitalizedSnakeCase:
for (i, w) in words.enumerated() {
if i == 0 {
result = capitalizeFirstLetter(w)
} else {
result += "_" + capitalizeFirstLetter(w)
}
}
case .upperSnakeCase:
for (i, w) in words.enumerated() {
if i == 0 {
result = w.uppercased()
} else {
result += "_" + w.uppercased()
}
}
case .kebabCase:
for (i, w) in words.enumerated() {
if i == 0 {
result = w.lowercased()
} else {
result += "-" + w.lowercased()
}
}
case .capitalizedKebabCase:
for (i, w) in words.enumerated() {
if i == 0 {
result = capitalizeFirstLetter(w)
} else {
result += "-" + capitalizeFirstLetter(w)
}
}
case .upperKebabCase:
for (i, w) in words.enumerated() {
if i == 0 {
result = w.uppercased()
} else {
result += "-" + w.uppercased()
}
}
case .sentence:
for (i, w) in words.enumerated() {
if i == 0 {
result = capitalizeFirstLetter(w)
} else {
result += " " + w.lowercased()
}
}
case .capitalized:
for (i, w) in words.enumerated() {
if i == 0 {
result = capitalizeFirstLetter(w)
} else {
result += " " + capitalizeFirstLetter(w)
}
}
case .lowercased:
for (i, w) in words.enumerated() {
if i == 0 {
result = w.lowercased()
} else {
result += " " + w.lowercased()
}
}
case .uppercased:
for (i, w) in words.enumerated() {
if i == 0 {
result = w.uppercased()
} else {
result += " " + w.uppercased()
}
}
}
return result
}
private func words(from string: String) -> [String] {
let stringTrimmed = string.trimmingCharacters(in: .whitespacesAndNewlines)
var words: [String] = []
if stringTrimmed.contains("_"),
let snakeCaseRange = stringTrimmed.range(of: #"^\S+(_\S+)*$"#, options: .regularExpression) { // #"^\w+(_\w+)*$"#
words = String(stringTrimmed[snakeCaseRange])
.replacingOccurrences(of: #"[_\W]+"#, with: "_", options: .regularExpression)
.components(separatedBy: "_")
.compactMap { $0.isEmpty ? nil : $0 }
} else if stringTrimmed.contains(" ") {
words = stringTrimmed
.replacingOccurrences(of: #"[_\W]+"#, with: " ", options: .regularExpression)
.components(separatedBy: " ")
.compactMap { $0.isEmpty ? nil : $0 }
} else if !splitByUppercasedLetters(stringTrimmed).isEmpty {
let splitByNonWordCharacters = splitByNonWordCharacters(stringTrimmed)
var splitWords: [String] = []
for word in splitByNonWordCharacters {
splitWords.append(contentsOf: splitByUppercasedLetters(word))
}
words = splitWords
} else {
print("else")
words.append(stringTrimmed)
}
return words
}
private func splitByNonWordCharacters(_ s: String) -> [String] {
return s
.replacingOccurrences(of: #"\W+"#, with: " ", options: .regularExpression)
.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: " ")
}
private func splitByUppercasedLetters(_ s: String) -> [String] {
let regex = try! NSRegularExpression(pattern: "([a-z]*)([A-Z])")
let range = NSRange(s.startIndex..., in: s)
return regex
.stringByReplacingMatches(in: s, range: range, withTemplate: "$1 $2")
.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: " ")
}
private func capitalizeFirstLetter(_ string: String) -> String {
return string.prefix(1).capitalized + string.dropFirst().lowercased()
}
}
| 33.32967 | 125 | 0.465711 |
1c3ca170dee423ba4c619c6a504737e04e634d89 | 5,820 | //
// SwiftPriorityQueue.swift
// SwiftPriorityQueue
//
// Copyright (c) 2015 David Kopec
//
// 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.
// This code was inspired by Section 2.4 of Algorithms by Sedgewick & Wayne, 4th Edition
#if !swift(>=3.0)
typealias IteratorProtocol = GeneratorType
typealias Sequence = SequenceType
typealias Collection = CollectionType
#endif
/// A PriorityQueue takes objects to be pushed of any type that implements Comparable.
/// It will pop the objects in the order that they would be sorted. A pop() or a push()
/// can be accomplished in O(lg n) time. It can be specified whether the objects should
/// be popped in ascending or descending order (Max Priority Queue or Min Priority Queue)
/// at the time of initialization.
public struct PriorityQueue<T: Comparable> {
private var heap = [T]()
private let ordered: (T, T) -> Bool
public init(ascending: Bool = false, startingValues: [T] = []) {
if ascending {
ordered = { $0 > $1 }
} else {
ordered = { $0 < $1 }
}
// Based on "Heap construction" from Sedgewick p 323
heap = startingValues
var i = heap.count/2 - 1
while i >= 0 {
sink(i)
i -= 1
}
}
/// How many elements the Priority Queue stores
public var count: Int { return heap.count }
/// true if and only if the Priority Queue is empty
public var isEmpty: Bool { return heap.isEmpty }
/// Add a new element onto the Priority Queue. O(lg n)
///
/// - parameter element: The element to be inserted into the Priority Queue.
public mutating func push(element: T) {
heap.append(element)
swim(heap.count - 1)
}
/// Remove and return the element with the highest priority (or lowest if ascending). O(lg n)
///
/// - returns: The element with the highest priority in the Priority Queue, or nil if the PriorityQueue is empty.
public mutating func pop() -> T? {
if heap.isEmpty { return nil }
if heap.count == 1 { return heap.removeFirst() } // added for Swift 2 compatibility
// so as not to call swap() with two instances of the same location
swap(&heap[0], &heap[heap.count - 1])
let temp = heap.removeLast()
sink(0)
return temp
}
/// Get a look at the current highest priority item, without removing it. O(1)
///
/// - returns: The element with the highest priority in the PriorityQueue, or nil if the PriorityQueue is empty.
public func peek() -> T? {
return heap.first
}
/// Eliminate all of the elements from the Priority Queue.
public mutating func clear() {
#if swift(>=3.0)
heap.removeAll(keepingCapacity: false)
#else
heap.removeAll(keepCapacity: false)
#endif
}
// Based on example from Sedgewick p 316
private mutating func sink(index: Int) {
var index = index
while 2 * index + 1 < heap.count {
var j = 2 * index + 1
if j < (heap.count - 1) && ordered(heap[j], heap[j + 1]) { j += 1 }
if !ordered(heap[index], heap[j]) { break }
swap(&heap[index], &heap[j])
index = j
}
}
// Based on example from Sedgewick p 316
private mutating func swim(index: Int) {
var index = index
while index > 0 && ordered(heap[(index - 1) / 2], heap[index]) {
swap(&heap[(index - 1) / 2], &heap[index])
index = (index - 1) / 2
}
}
}
// MARK: - GeneratorType
extension PriorityQueue: IteratorProtocol {
public typealias Element = T
mutating public func next() -> Element? { return pop() }
}
// MARK: - SequenceType
extension PriorityQueue: Sequence {
public typealias Iterator = PriorityQueue
public func makeIterator() -> Iterator { return self }
}
// MARK: - CollectionType
extension PriorityQueue: Collection {
public typealias Index = Int
public var startIndex: Int { return heap.startIndex }
public var endIndex: Int { return heap.endIndex }
public subscript(i: Int) -> T { return heap[i] }
#if swift(>=3.0)
public func index(after i: PriorityQueue.Index) -> PriorityQueue.Index {
return heap.index(after: i)
}
#endif
}
// MARK: - CustomStringConvertible, CustomDebugStringConvertible
extension PriorityQueue: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String { return heap.description }
public var debugDescription: String { return heap.debugDescription }
}
| 34.850299 | 117 | 0.632818 |
d53598ea0d7f39290c02ca3600e4a41b212446c1 | 2,486 | import TCP
import Dispatch
/// Helper that keeps track of a connection counter for an `Address`
fileprivate final class RemoteAddress {
let address: TCPAddress
var count = 0
init(address: TCPAddress) {
self.address = address
}
}
/// Validates peers against a set of rules before further processing the peer
///
/// Used to harden a TCP Server against Denial of Service and other attacks.
public final class PeerValidator {
public typealias Input = TCPClient
/// Limits the amount of connections per IP address to prevent certain Denial of Service attacks
public var maxConnectionsPerIP: Int
/// The external connection counter
fileprivate var remotes = [RemoteAddress]()
/// Creates a new
public init(maxConnectionsPerIP: Int) {
self.maxConnectionsPerIP = maxConnectionsPerIP
}
/// Validates incoming clients
public func willAccept(client: TCPClient) -> Bool {
// Accept must always set the address
guard let currentRemoteAddress = client.socket.address else {
return false
}
var currentRemote: RemoteAddress? = nil
// Looks for currently open connections from this address
for remote in self.remotes where remote.address == currentRemoteAddress {
// If there is one, ensure there aren't too many
guard remote.count < self.maxConnectionsPerIP else {
return false
}
currentRemote = remote
}
// If the remote address doesn't have connections open
if currentRemote == nil {
currentRemote = RemoteAddress(address: currentRemoteAddress)
}
// Cleans up be decreasing the counter
client.willClose = {
defer {
// Prevent memory leak
client.willClose = {}
}
guard let currentRemote = currentRemote else {
return
}
currentRemote.count -= 1
// Return if there are still connections open
guard currentRemote.count <= 0 else {
return
}
// Otherwise, remove the remote address
if let index = self.remotes.index(where: { $0.address == currentRemoteAddress }) {
self.remotes.remove(at: index)
}
}
return true
}
}
| 30.317073 | 100 | 0.589702 |
fec976ff2296d458219a5e8c6cc74792f8fb6b5f | 3,164 | //
// OperableArray.swift
// Ballcap
//
// Created by 1amageek on 2019/04/05.
// Copyright © 2019 Stamp Inc. All rights reserved.
//
import FirebaseFirestore
public enum OperableArray<Element: Codable>: Codable, ExpressibleByArrayLiteral, RawRepresentable {
case value([Element])
case arrayRemove([Element])
case arrayUnion([Element])
public typealias RawValue = [Element]
public typealias ArrayLiteralElement = Element
public init?(rawValue: [Element]) {
self = .value(rawValue)
}
public var rawValue: [Element] {
switch self {
case .value(let value): return value
default: fatalError()
}
}
public init(arrayLiteral elements: Element...) {
self = .value(elements)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let value = try container.decode([Element].self)
self = .value(value)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .value(let value): try container.encode(value)
case .arrayRemove(let value): try container.encode(FieldValue.arrayRemove(value))
case .arrayUnion(let value): try container.encode(FieldValue.arrayUnion(value))
}
}
}
extension OperableArray: Equatable where Element: Equatable {
public static func == (lhs: OperableArray<Element>, rhs: OperableArray<Element>) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension OperableArray: Collection {
public var startIndex: Int {
return 0
}
public var endIndex: Int {
switch self {
case .value(let value): return value.count
case .arrayRemove(let value): return value.count
case .arrayUnion(let value): return value.count
}
}
public func index(after i: Int) -> Int {
return i + 1
}
public var isEmpty: Bool {
switch self {
case .value(let value): return value.isEmpty
case .arrayRemove(let value): return value.isEmpty
case .arrayUnion(let value): return value.isEmpty
}
}
public var count: Int {
switch self {
case .value(let value): return value.count
case .arrayRemove(let value): return value.count
case .arrayUnion(let value): return value.count
}
}
public var first: Element? {
switch self {
case .value(let value): return value.first
case .arrayRemove(let value): return value.first
case .arrayUnion(let value): return value.first
}
}
public var last: Element? {
switch self {
case .value(let value): return value.last
case .arrayRemove(let value): return value.last
case .arrayUnion(let value): return value.last
}
}
public subscript(index: Int) -> Element {
switch self {
case .value(let value): return value[index]
case .arrayRemove(let value): return value[index]
case .arrayUnion(let value): return value[index]
}
}
}
| 27.275862 | 99 | 0.626422 |
f7a0b9b17874a4887fe70f0d21c6f8f3110963f9 | 690 | //
// TutorialDetailView.swift
// Cyf3r
//
// Created by Amogh Mantri on 4/22/20.
// Copyright © 2020 Amogh Mantri. All rights reserved.
//
import SwiftUI
struct TutorialDetailView: View {
var cryptid: Crypt
var body: some View {
ScrollView {
VStack {
Text(cryptid.name).font(.title).bold()
.foregroundColor(Color("Orange"))
cryptid.image
.resizable()
.aspectRatio(contentMode: .fit)
.padding()
Text(cryptid.description)
.padding()
Spacer()
Text("Source: Cyptography Website")
}
}
}
}
| 20.294118 | 55 | 0.511594 |
22e3d8e46e523afe612584f03487cc19db4ea6f4 | 743 | //
// LSFoundationExtensions.swift
// SightCallAlpha
//
// Created by Jason Jobe on 3/19/21.
//
import Foundation
public extension Data {
func hexEncodedString() -> String {
return map { String(format: "%02hhx", $0) }.joined()
}
}
public extension URL {
func queryValueForKey(_ key: String) -> String? {
guard let components = NSURLComponents(url: self, resolvingAgainstBaseURL: false) else {
return nil
}
return components.queryItems?
.filter { $0.name == key }
.first?.value
// guard let queryItems = components.queryItems else { return nil }
// return queryItems.filter {
// $0.name == key
// }.first?.value
}
}
| 23.21875 | 96 | 0.58681 |
fce70e71dc764a8b04993a0541603bdf07321d17 | 1,294 | //
// SelfTestingSelfMonitoringViewController.swift
// CoronaContact
//
import Reusable
import UIKit
final class SelfTestingSelfMonitoringViewController: UIViewController, StoryboardBased, ViewModelBased, FlashableScrollIndicators {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var instructionsView: InstructionsView!
var viewModel: SelfTestingSelfMonitoringViewModel?
override func viewDidLoad() {
super.viewDidLoad()
viewModel?.onViewDidLoad()
setupUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
flashScrollIndicators()
}
override func didMove(toParent parent: UIViewController?) {
super.didMove(toParent: parent)
if parent == nil {
viewModel?.viewClosed()
}
}
private func setupUI() {
instructionsView.instructions = [
.init(index: 1, text: "self_testing_self_monitoring_recommendation_1".localized),
.init(index: 2, text: "self_testing_self_monitoring_recommendation_2".localized),
.init(index: 3, text: "self_testing_self_monitoring_recommendation_3".localized),
]
}
@IBAction func doneTapped(_ sender: UIButton) {
viewModel?.returnToMain()
}
}
| 26.958333 | 131 | 0.687017 |
23c85bf8c49579f42d2897f0ab504e6825db33ea | 3,108 | //
// Volume.swift
// MarsOrbiter
//
// Created by Sebastian Grail on 20/02/2016.
// Copyright © 2016 Sebastian Grail. All rights reserved.
//
public typealias Liter = Unit<LiterTrait>
public struct LiterTrait: UnitTrait {
public typealias BaseTrait = MeterTrait
public typealias Dimension = Three
public static func toBaseUnit () -> Double {
return 0.001
}
public static func abbreviation() -> String {
return "l"
}
}
public struct Imperial {
public typealias Pint = Unit<PintTrait>
public struct PintTrait: UnitTrait {
public typealias BaseTrait = MeterTrait
public typealias Dimension = Three
public static func toBaseUnit () -> Double {
return 0.000568261
}
public static func abbreviation() -> String {
return "imp pt"
}
}
public typealias Quart = Unit<QuartTrait>
public struct QuartTrait: UnitTrait {
public typealias BaseTrait = MeterTrait
public typealias Dimension = Three
public static func toBaseUnit () -> Double {
return 0.00113652
}
public static func abbreviation() -> String {
return "imp qt"
}
}
public typealias Gallon = Unit<GallonTrait>
public struct GallonTrait: UnitTrait {
public typealias BaseTrait = MeterTrait
public typealias Dimension = Three
public static func toBaseUnit () -> Double {
return 0.00454609
}
public static func abbreviation() -> String {
return "imp gal"
}
}
}
public struct USLiquid {
public typealias Pint = Unit<PintTrait>
public struct PintTrait: UnitTrait {
public typealias BaseTrait = MeterTrait
public typealias Dimension = Three
public static func toBaseUnit () -> Double {
return 0.000473176
}
public static func abbreviation() -> String {
return "imp pt"
}
}
public typealias Quart = Unit<QuartTrait>
public struct QuartTrait: UnitTrait {
public typealias BaseTrait = MeterTrait
public typealias Dimension = Three
public static func toBaseUnit () -> Double {
return 0.000946353
}
public static func abbreviation() -> String {
return "imp qt"
}
}
public typealias Gallon = Unit<GallonTrait>
public struct GallonTrait: UnitTrait {
public typealias BaseTrait = MeterTrait
public typealias Dimension = Three
public static func toBaseUnit () -> Double {
return 0.00378541
}
public static func abbreviation() -> String {
return "imp gal"
}
}
}
public typealias FluidOunce = Unit<FluidOunceTrait>
public struct FluidOunceTrait: UnitTrait {
public typealias BaseTrait = MeterTrait
public typealias Dimension = Three
public static func toBaseUnit () -> Double {
return 2.95735e-5
}
public static func abbreviation() -> String {
return "imp gal"
}
}
| 28.777778 | 58 | 0.614543 |
8763b3bce021215150f86076769c5e1bb3b9d425 | 920 | //
// TipCalculatorTests.swift
// TipCalculatorTests
//
// Created by Alex Rich on 1/9/19.
// Copyright © 2019 Alex Rich. All rights reserved.
//
import XCTest
@testable import TipCalculator
class TipCalculatorTests: XCTestCase {
override func 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.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.285714 | 111 | 0.659783 |
f863b0160eb2a46d04d00558633861d1a8fd2027 | 26,575 | //
// MainWindowController.swift
// NetNewsWire
//
// Created by Brent Simmons on 8/1/15.
// Copyright © 2015 Ranchero Software, LLC. All rights reserved.
//
import AppKit
import Articles
import Account
import RSCore
enum TimelineSourceMode {
case regular, search
}
class MainWindowController : NSWindowController, NSUserInterfaceValidations {
private var isShowingExtractedArticle = false
private var articleExtractor: ArticleExtractor? = nil
private var sharingServicePickerDelegate: NSSharingServicePickerDelegate?
private let windowAutosaveName = NSWindow.FrameAutosaveName("MainWindow")
static var didPositionWindowOnFirstRun = false
private var currentFeedOrFolder: AnyObject? {
// Nil for none or multiple selection.
guard let selectedObjects = selectedObjectsInSidebar(), selectedObjects.count == 1 else {
return nil
}
return selectedObjects.first
}
private var shareToolbarItem: NSToolbarItem? {
return window?.toolbar?.existingItem(withIdentifier: .Share)
}
private static var detailViewMinimumThickness = 384
private var sidebarViewController: SidebarViewController?
private var timelineContainerViewController: TimelineContainerViewController?
private var detailViewController: DetailViewController?
private var currentSearchField: NSSearchField? = nil
private var searchString: String? = nil
private var lastSentSearchString: String? = nil
private var timelineSourceMode: TimelineSourceMode = .regular {
didSet {
timelineContainerViewController?.showTimeline(for: timelineSourceMode)
detailViewController?.showDetail(for: timelineSourceMode)
}
}
private var searchSmartFeed: SmartFeed? = nil
// MARK: - NSWindowController
override func windowDidLoad() {
super.windowDidLoad()
sharingServicePickerDelegate = SharingServicePickerDelegate(self.window)
if !AppDefaults.showTitleOnMainWindow {
window?.titleVisibility = .hidden
}
window?.setFrameUsingName(windowAutosaveName, force: true)
if AppDefaults.isFirstRun && !MainWindowController.didPositionWindowOnFirstRun {
if let window = window {
let point = NSPoint(x: 128, y: 64)
let size = NSSize(width: 1000, height: 700)
let minSize = NSSize(width: 600, height: 600)
window.setPointAndSizeAdjustingForScreen(point: point, size: size, minimumSize: minSize)
MainWindowController.didPositionWindowOnFirstRun = true
}
}
detailSplitViewItem?.minimumThickness = CGFloat(MainWindowController.detailViewMinimumThickness)
restoreSplitViewState()
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate(_:)), name: NSApplication.willTerminateNotification, object: nil)
sidebarViewController = splitViewController?.splitViewItems[0].viewController as? SidebarViewController
sidebarViewController!.delegate = self
timelineContainerViewController = splitViewController?.splitViewItems[1].viewController as? TimelineContainerViewController
timelineContainerViewController!.delegate = self
detailViewController = splitViewController?.splitViewItems[2].viewController as? DetailViewController
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshDidBegin, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshDidFinish, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(refreshProgressDidChange(_:)), name: .AccountRefreshProgressDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil)
DispatchQueue.main.async {
self.updateWindowTitle()
}
}
// MARK: - API
func saveState() {
saveSplitViewState()
}
func selectedObjectsInSidebar() -> [AnyObject]? {
return sidebarViewController?.selectedObjects
}
// MARK: - Notifications
// func window(_ window: NSWindow, willEncodeRestorableState state: NSCoder) {
//
// saveSplitViewState(to: state)
// }
//
// func window(_ window: NSWindow, didDecodeRestorableState state: NSCoder) {
//
// restoreSplitViewState(from: state)
//
// // Make sure the timeline view is first responder if possible, to start out viewing
// // whatever preserved selection might have been restored
// makeTimelineViewFirstResponder()
// }
@objc func applicationWillTerminate(_ note: Notification) {
saveState()
window?.saveFrame(usingName: windowAutosaveName)
}
@objc func refreshProgressDidChange(_ note: Notification) {
CoalescingQueue.standard.add(self, #selector(makeToolbarValidate))
}
@objc func unreadCountDidChange(_ note: Notification) {
updateWindowTitleIfNecessary(note.object)
}
@objc func displayNameDidChange(_ note: Notification) {
updateWindowTitleIfNecessary(note.object)
}
private func updateWindowTitleIfNecessary(_ noteObject: Any?) {
if let folder = currentFeedOrFolder as? Folder, let noteObject = noteObject as? Folder {
if folder == noteObject {
updateWindowTitle()
return
}
}
if let feed = currentFeedOrFolder as? Feed, let noteObject = noteObject as? Feed {
if feed == noteObject {
updateWindowTitle()
return
}
}
// If we don't recognize the changed object, we will test it for identity instead
// of equality. This works well for us if the window title is displaying a
// PsuedoFeed object.
if let currentObject = currentFeedOrFolder, let noteObject = noteObject {
if currentObject === noteObject as AnyObject {
updateWindowTitle()
}
}
}
// MARK: - Toolbar
@objc func makeToolbarValidate() {
window?.toolbar?.validateVisibleItems()
}
// MARK: - NSUserInterfaceValidations
public func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
if item.action == #selector(openArticleInBrowser(_:)) {
return currentLink != nil
}
if item.action == #selector(nextUnread(_:)) {
return canGoToNextUnread()
}
if item.action == #selector(markAllAsRead(_:)) {
return canMarkAllAsRead()
}
if item.action == #selector(toggleRead(_:)) {
return validateToggleRead(item)
}
if item.action == #selector(toggleStarred(_:)) {
return validateToggleStarred(item)
}
if item.action == #selector(markOlderArticlesAsRead(_:)) {
return canMarkOlderArticlesAsRead()
}
if item.action == #selector(toggleArticleExtractor(_:)) {
return validateToggleArticleExtractor(item)
}
if item.action == #selector(toolbarShowShareMenu(_:)) {
return canShowShareMenu()
}
if item.action == #selector(moveFocusToSearchField(_:)) {
return currentSearchField != nil
}
if item.action == #selector(toggleSidebar(_:)) {
guard let splitViewItem = sidebarSplitViewItem else {
return false
}
let sidebarIsShowing = !splitViewItem.isCollapsed
if let menuItem = item as? NSMenuItem {
let title = sidebarIsShowing ? NSLocalizedString("Hide Sidebar", comment: "Menu item") : NSLocalizedString("Show Sidebar", comment: "Menu item")
menuItem.title = title
}
return true
}
return true
}
// MARK: - Actions
@IBAction func scrollOrGoToNextUnread(_ sender: Any?) {
guard let detailViewController = detailViewController else {
return
}
detailViewController.canScrollDown { (canScroll) in
NSCursor.setHiddenUntilMouseMoves(true)
canScroll ? detailViewController.scrollPageDown(sender) : self.nextUnread(sender)
}
}
@IBAction func openArticleInBrowser(_ sender: Any?) {
if let link = currentLink {
Browser.open(link)
}
}
@IBAction func openInBrowser(_ sender: Any?) {
openArticleInBrowser(sender)
}
@IBAction func nextUnread(_ sender: Any?) {
guard let timelineViewController = currentTimelineViewController, let sidebarViewController = sidebarViewController else {
return
}
NSCursor.setHiddenUntilMouseMoves(true)
// TODO: handle search mode
if timelineViewController.canGoToNextUnread() {
goToNextUnreadInTimeline()
}
else if sidebarViewController.canGoToNextUnread() {
sidebarViewController.goToNextUnread()
if timelineViewController.canGoToNextUnread() {
goToNextUnreadInTimeline()
}
}
}
@IBAction func markAllAsRead(_ sender: Any?) {
currentTimelineViewController?.markAllAsRead()
}
@IBAction func toggleRead(_ sender: Any?) {
currentTimelineViewController?.toggleReadStatusForSelectedArticles()
}
@IBAction func markRead(_ sender: Any?) {
currentTimelineViewController?.markSelectedArticlesAsRead(sender)
}
@IBAction func markUnread(_ sender: Any?) {
currentTimelineViewController?.markSelectedArticlesAsUnread(sender)
}
@IBAction func toggleStarred(_ sender: Any?) {
currentTimelineViewController?.toggleStarredStatusForSelectedArticles()
}
@IBAction func toggleArticleExtractor(_ sender: Any?) {
guard let currentLink = currentLink, let article = oneSelectedArticle else {
return
}
defer {
makeToolbarValidate()
}
guard articleExtractor?.state != .processing else {
articleExtractor?.cancel()
articleExtractor = nil
isShowingExtractedArticle = false
detailViewController?.setState(DetailState.article(article), mode: timelineSourceMode)
return
}
guard !isShowingExtractedArticle else {
isShowingExtractedArticle = false
detailViewController?.setState(DetailState.article(article), mode: timelineSourceMode)
return
}
if let articleExtractor = articleExtractor, let extractedArticle = articleExtractor.article {
if currentLink == articleExtractor.articleLink {
isShowingExtractedArticle = true
let detailState = DetailState.extracted(article, extractedArticle)
detailViewController?.setState(detailState, mode: timelineSourceMode)
}
} else {
startArticleExtractorForCurrentLink()
}
}
@IBAction func markAllAsReadAndGoToNextUnread(_ sender: Any?) {
markAllAsRead(sender)
nextUnread(sender)
}
@IBAction func markUnreadAndGoToNextUnread(_ sender: Any?) {
markUnread(sender)
nextUnread(sender)
}
@IBAction func markReadAndGoToNextUnread(_ sender: Any?) {
markUnread(sender)
nextUnread(sender)
}
@IBAction func toggleSidebar(_ sender: Any?) {
splitViewController!.toggleSidebar(sender)
}
@IBAction func markOlderArticlesAsRead(_ sender: Any?) {
currentTimelineViewController?.markOlderArticlesRead()
}
@IBAction func navigateToTimeline(_ sender: Any?) {
currentTimelineViewController?.focus()
}
@IBAction func navigateToSidebar(_ sender: Any?) {
sidebarViewController?.focus()
}
@IBAction func navigateToDetail(_ sender: Any?) {
detailViewController?.focus()
}
@IBAction func goToPreviousSubscription(_ sender: Any?) {
sidebarViewController?.outlineView.selectPreviousRow(sender)
}
@IBAction func goToNextSubscription(_ sender: Any?) {
sidebarViewController?.outlineView.selectNextRow(sender)
}
@IBAction func gotoToday(_ sender: Any?) {
sidebarViewController?.gotoToday(sender)
}
@IBAction func gotoAllUnread(_ sender: Any?) {
sidebarViewController?.gotoAllUnread(sender)
}
@IBAction func gotoStarred(_ sender: Any?) {
sidebarViewController?.gotoStarred(sender)
}
@IBAction func toolbarShowShareMenu(_ sender: Any?) {
guard let selectedArticles = selectedArticles, !selectedArticles.isEmpty else {
assertionFailure("Expected toolbarShowShareMenu to be called only when there are selected articles.")
return
}
guard let shareToolbarItem = shareToolbarItem else {
assertionFailure("Expected toolbarShowShareMenu to be called only by the Share item in the toolbar.")
return
}
guard let view = shareToolbarItem.view else {
// TODO: handle menu form representation
return
}
let sortedArticles = selectedArticles.sortedByDate(.orderedAscending)
let items = sortedArticles.map { ArticlePasteboardWriter(article: $0) }
let sharingServicePicker = NSSharingServicePicker(items: items)
sharingServicePicker.delegate = sharingServicePickerDelegate
sharingServicePicker.show(relativeTo: view.bounds, of: view, preferredEdge: .minY)
}
@IBAction func moveFocusToSearchField(_ sender: Any?) {
guard let searchField = currentSearchField else {
return
}
window?.makeFirstResponder(searchField)
}
}
// MARK: - SidebarDelegate
extension MainWindowController: SidebarDelegate {
func sidebarSelectionDidChange(_: SidebarViewController, selectedObjects: [AnyObject]?) {
// Don’t update the timeline if it already has those objects.
let representedObjectsAreTheSame = timelineContainerViewController?.regularTimelineViewControllerHasRepresentedObjects(selectedObjects) ?? false
if !representedObjectsAreTheSame {
timelineContainerViewController?.setRepresentedObjects(selectedObjects, mode: .regular)
forceSearchToEnd()
}
updateWindowTitle()
NotificationCenter.default.post(name: .InspectableObjectsDidChange, object: nil)
}
func unreadCount(for representedObject: AnyObject) -> Int {
guard let timelineViewController = regularTimelineViewController else {
return 0
}
guard timelineViewController.representsThisObjectOnly(representedObject) else {
return 0
}
return timelineViewController.unreadCount
}
}
// MARK: - TimelineContainerViewControllerDelegate
extension MainWindowController: TimelineContainerViewControllerDelegate {
func timelineSelectionDidChange(_: TimelineContainerViewController, articles: [Article]?, mode: TimelineSourceMode) {
articleExtractor?.cancel()
articleExtractor = nil
isShowingExtractedArticle = false
makeToolbarValidate()
let detailState: DetailState
if let articles = articles {
if articles.count == 1 {
if articles.first?.feed?.isArticleExtractorAlwaysOn ?? false {
detailState = .loading
startArticleExtractorForCurrentLink()
} else {
detailState = .article(articles.first!)
}
} else {
detailState = .multipleSelection
}
} else {
detailState = .noSelection
}
detailViewController?.setState(detailState, mode: mode)
}
}
// MARK: - NSSearchFieldDelegate
extension MainWindowController: NSSearchFieldDelegate {
func searchFieldDidStartSearching(_ sender: NSSearchField) {
startSearchingIfNeeded()
}
func searchFieldDidEndSearching(_ sender: NSSearchField) {
stopSearchingIfNeeded()
}
@IBAction func runSearch(_ sender: NSSearchField) {
if sender.stringValue == "" {
return
}
startSearchingIfNeeded()
handleSearchFieldTextChange(sender)
}
private func handleSearchFieldTextChange(_ searchField: NSSearchField) {
let s = searchField.stringValue
if s == searchString {
return
}
searchString = s
updateSmartFeed()
}
func updateSmartFeed() {
guard timelineSourceMode == .search, let searchString = searchString else {
return
}
if searchString == lastSentSearchString {
return
}
lastSentSearchString = searchString
let smartFeed = SmartFeed(delegate: SearchFeedDelegate(searchString: searchString))
timelineContainerViewController?.setRepresentedObjects([smartFeed], mode: .search)
searchSmartFeed = smartFeed
}
func forceSearchToEnd() {
timelineSourceMode = .regular
searchString = nil
lastSentSearchString = nil
if let searchField = currentSearchField {
searchField.stringValue = ""
}
}
private func startSearchingIfNeeded() {
timelineSourceMode = .search
}
private func stopSearchingIfNeeded() {
searchString = nil
lastSentSearchString = nil
timelineSourceMode = .regular
timelineContainerViewController?.setRepresentedObjects(nil, mode: .search)
}
}
// MARK: - ArticleExtractorDelegate
extension MainWindowController: ArticleExtractorDelegate {
func articleExtractionDidFail(with: Error) {
makeToolbarValidate()
}
func articleExtractionDidComplete(extractedArticle: ExtractedArticle) {
if let article = oneSelectedArticle, articleExtractor?.state != .cancelled {
isShowingExtractedArticle = true
let detailState = DetailState.extracted(article, extractedArticle)
detailViewController?.setState(detailState, mode: timelineSourceMode)
makeToolbarValidate()
}
}
}
// MARK: - Scripting Access
/*
the ScriptingMainWindowController protocol exposes a narrow set of accessors with
internal visibility which are very similar to some private vars.
These would be unnecessary if the similar accessors were marked internal rather than private,
but for now, we'll keep the stratification of visibility
*/
extension MainWindowController : ScriptingMainWindowController {
internal var scriptingCurrentArticle: Article? {
return self.oneSelectedArticle
}
internal var scriptingSelectedArticles: [Article] {
return self.selectedArticles ?? []
}
}
// MARK: - NSToolbarDelegate
extension NSToolbarItem.Identifier {
static let Share = NSToolbarItem.Identifier("share")
static let Search = NSToolbarItem.Identifier("search")
}
extension MainWindowController: NSToolbarDelegate {
func toolbarWillAddItem(_ notification: Notification) {
guard let item = notification.userInfo?["item"] as? NSToolbarItem else {
return
}
if item.itemIdentifier == .Share, let button = item.view as? NSButton {
// The share button should send its action on mouse down, not mouse up.
button.sendAction(on: .leftMouseDown)
}
if item.itemIdentifier == .Search, let searchField = item.view as? NSSearchField {
searchField.delegate = self
searchField.target = self
searchField.action = #selector(runSearch(_:))
currentSearchField = searchField
}
}
func toolbarDidRemoveItem(_ notification: Notification) {
guard let item = notification.userInfo?["item"] as? NSToolbarItem else {
return
}
if item.itemIdentifier == .Search, let searchField = item.view as? NSSearchField {
searchField.delegate = nil
searchField.target = nil
searchField.action = nil
currentSearchField = nil
}
}
}
// MARK: - Private
private extension MainWindowController {
var splitViewController: NSSplitViewController? {
guard let viewController = contentViewController else {
return nil
}
return viewController.children.first as? NSSplitViewController
}
var currentTimelineViewController: TimelineViewController? {
return timelineContainerViewController?.currentTimelineViewController
}
var regularTimelineViewController: TimelineViewController? {
return timelineContainerViewController?.regularTimelineViewController
}
var sidebarSplitViewItem: NSSplitViewItem? {
return splitViewController?.splitViewItems[0]
}
var detailSplitViewItem: NSSplitViewItem? {
return splitViewController?.splitViewItems[2]
}
var selectedArticles: [Article]? {
return currentTimelineViewController?.selectedArticles
}
var oneSelectedArticle: Article? {
if let articles = selectedArticles {
return articles.count == 1 ? articles[0] : nil
}
return nil
}
var currentLink: String? {
return oneSelectedArticle?.preferredLink
}
// MARK: - Command Validation
func canGoToNextUnread() -> Bool {
guard let timelineViewController = currentTimelineViewController, let sidebarViewController = sidebarViewController else {
return false
}
// TODO: handle search mode
return timelineViewController.canGoToNextUnread() || sidebarViewController.canGoToNextUnread()
}
func canMarkAllAsRead() -> Bool {
return currentTimelineViewController?.canMarkAllAsRead() ?? false
}
func validateToggleRead(_ item: NSValidatedUserInterfaceItem) -> Bool {
let validationStatus = currentTimelineViewController?.markReadCommandStatus() ?? .canDoNothing
let markingRead: Bool
let result: Bool
switch validationStatus {
case .canMark:
markingRead = true
result = true
case .canUnmark:
markingRead = false
result = true
case .canDoNothing:
markingRead = true
result = false
}
let commandName = markingRead ? NSLocalizedString("Mark as Read", comment: "Command") : NSLocalizedString("Mark as Unread", comment: "Command")
if let toolbarItem = item as? NSToolbarItem {
toolbarItem.toolTip = commandName
}
if let menuItem = item as? NSMenuItem {
menuItem.title = commandName
}
return result
}
func validateToggleArticleExtractor(_ item: NSValidatedUserInterfaceItem) -> Bool {
guard let toolbarItem = item as? NSToolbarItem, let toolbarButton = toolbarItem.view as? ArticleExtractorButton else {
if let menuItem = item as? NSMenuItem {
menuItem.state = isShowingExtractedArticle ? .on : .off
}
return currentLink != nil
}
toolbarButton.state = isShowingExtractedArticle ? .on : .off
guard let state = articleExtractor?.state else {
toolbarButton.isError = false
toolbarButton.isInProgress = false
toolbarButton.state = .off
return currentLink != nil
}
switch state {
case .processing:
toolbarButton.isError = false
toolbarButton.isInProgress = true
case .failedToParse:
toolbarButton.isError = true
toolbarButton.isInProgress = false
case .ready, .cancelled, .complete:
toolbarButton.isError = false
toolbarButton.isInProgress = false
}
return true
}
func canMarkOlderArticlesAsRead() -> Bool {
return currentTimelineViewController?.canMarkOlderArticlesAsRead() ?? false
}
func canShowShareMenu() -> Bool {
guard let selectedArticles = selectedArticles else {
return false
}
return !selectedArticles.isEmpty
}
func validateToggleStarred(_ item: NSValidatedUserInterfaceItem) -> Bool {
let validationStatus = currentTimelineViewController?.markStarredCommandStatus() ?? .canDoNothing
let starring: Bool
let result: Bool
switch validationStatus {
case .canMark:
starring = true
result = true
case .canUnmark:
starring = false
result = true
case .canDoNothing:
starring = true
result = false
}
let commandName = starring ? NSLocalizedString("Mark as Starred", comment: "Command") : NSLocalizedString("Mark as Unstarred", comment: "Command")
if let toolbarItem = item as? NSToolbarItem {
toolbarItem.toolTip = commandName
// if let button = toolbarItem.view as? NSButton {
// button.image = NSImage(named: starring ? .star : .unstar)
// }
}
if let menuItem = item as? NSMenuItem {
menuItem.title = commandName
}
return result
}
// MARK: - Misc.
func goToNextUnreadInTimeline() {
guard let timelineViewController = currentTimelineViewController else {
return
}
if timelineViewController.canGoToNextUnread() {
timelineViewController.goToNextUnread()
makeTimelineViewFirstResponder()
}
}
func makeTimelineViewFirstResponder() {
guard let window = window, let timelineViewController = currentTimelineViewController else {
return
}
window.makeFirstResponderUnlessDescendantIsFirstResponder(timelineViewController.tableView)
}
func updateWindowTitle() {
var displayName: String? = nil
var unreadCount: Int? = nil
if let displayNameProvider = currentFeedOrFolder as? DisplayNameProvider {
displayName = displayNameProvider.nameForDisplay
}
if let unreadCountProvider = currentFeedOrFolder as? UnreadCountProvider {
unreadCount = unreadCountProvider.unreadCount
}
if displayName != nil {
if unreadCount ?? 0 > 0 {
window?.title = "\(displayName!) (\(unreadCount!))"
}
else {
window?.title = "\(displayName!)"
}
}
else {
window?.title = appDelegate.appName!
return
}
}
func startArticleExtractorForCurrentLink() {
if let link = currentLink, let extractor = ArticleExtractor(link) {
extractor.delegate = self
extractor.process()
articleExtractor = extractor
}
}
func saveSplitViewState() {
// TODO: Update this for multiple windows.
// Also: use standard state restoration mechanism.
guard let splitView = splitViewController?.splitView else {
return
}
let widths = splitView.arrangedSubviews.map{ Int(floor($0.frame.width)) }
if AppDefaults.mainWindowWidths != widths {
AppDefaults.mainWindowWidths = widths
}
}
func restoreSplitViewState() {
// TODO: Update this for multiple windows.
// Also: use standard state restoration mechanism.
guard let splitView = splitViewController?.splitView, let widths = AppDefaults.mainWindowWidths, widths.count == 3, let window = window else {
return
}
let windowWidth = Int(floor(window.frame.width))
let dividerThickness: Int = Int(splitView.dividerThickness)
let sidebarWidth: Int = widths[0]
let timelineWidth: Int = widths[1]
// Make sure the detail view has its mimimum thickness, at least.
if windowWidth < sidebarWidth + dividerThickness + timelineWidth + dividerThickness + MainWindowController.detailViewMinimumThickness {
return
}
splitView.setPosition(CGFloat(sidebarWidth), ofDividerAt: 0)
splitView.setPosition(CGFloat(sidebarWidth + dividerThickness + timelineWidth), ofDividerAt: 1)
}
// func saveSplitViewState(to coder: NSCoder) {
//
// // TODO: Update this for multiple windows.
//
// guard let splitView = splitViewController?.splitView else {
// return
// }
//
// let widths = splitView.arrangedSubviews.map{ Int(floor($0.frame.width)) }
// coder.encode(widths, forKey: MainWindowController.mainWindowWidthsStateKey)
//
// }
// func arrayOfIntFromCoder(_ coder: NSCoder, withKey: String) -> [Int]? {
// let decodedFloats: [Int]?
// do {
// decodedFloats = try coder.decodeTopLevelObject(forKey: MainWindowController.mainWindowWidthsStateKey) as? [Int]? ?? nil
// }
// catch {
// decodedFloats = nil
// }
// return decodedFloats
// }
// func restoreSplitViewState(from coder: NSCoder) {
//
// // TODO: Update this for multiple windows.
// guard let splitView = splitViewController?.splitView, let widths = arrayOfIntFromCoder(coder, withKey: MainWindowController.mainWindowWidthsStateKey), widths.count == 3, let window = window else {
// return
// }
//
// let windowWidth = Int(floor(window.frame.width))
// let dividerThickness: Int = Int(splitView.dividerThickness)
// let sidebarWidth: Int = widths[0]
// let timelineWidth: Int = widths[1]
//
// // Make sure the detail view has its mimimum thickness, at least.
// if windowWidth < sidebarWidth + dividerThickness + timelineWidth + dividerThickness + MainWindowController.detailViewMinimumThickness {
// return
// }
//
// splitView.setPosition(CGFloat(sidebarWidth), ofDividerAt: 0)
// splitView.setPosition(CGFloat(sidebarWidth + dividerThickness + timelineWidth), ofDividerAt: 1)
// }
}
| 28.72973 | 200 | 0.751872 |
90b220e16176d038ab1419d10c72be77344bdfe5 | 625 | //
// UIButton+Extension.swift
// WeiboSwift
//
// Created by fenglin on 2016/10/4.
// Copyright © 2016年 fenglin. All rights reserved.
//
import UIKit
extension UIButton {
convenience init(imageNamed imageName: String ,backgroundImageNamed bgImageName: String) {
self.init();
setImage(UIImage(named: imageName), for: .normal);
setImage(UIImage(named: imageName + "highlighted"), for: .highlighted);
setBackgroundImage(UIImage(named: bgImageName), for: .normal);
setBackgroundImage(UIImage(named: bgImageName + "highlighted"), for: .highlighted);
sizeToFit();
}
}
| 29.761905 | 94 | 0.68 |
1dcae107ff33a2a3e7cd6e2c70816c9bf3ddf7f2 | 696 | //
// Mocka
//
import Foundation
/// App constants enum.
enum Size {
/// Minimum Sidebar width.
static let minimumSidebarWidth: CGFloat = 140
/// Fixed Sidebar height.
static let fixedSidebarHeight: CGFloat = 88
/// Minimum App height.
static let minimumAppHeight: CGFloat = 600
/// Minimum List width.
static let minimumListWidth: CGFloat = 370
/// Minimum Detail width.
static let minimumDetailWidth: CGFloat = 400
/// Minimum Filter text field width.
static var minimumFilterTextFieldWidth: CGFloat {
minimumListWidth - 140
}
/// Minimum App section width.
static var minimumAppSectionWidth: CGFloat {
minimumListWidth + minimumDetailWidth
}
}
| 20.470588 | 51 | 0.712644 |
2846ece1e7f2267afaf9aada5cad3351a1ffdf7a | 1,410 | //
// AppDelegate.swift
// SEExtensionDemo
//
// Created by JOJO on 2019/11/20.
// Copyright © 2019 JOJO. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 37.105263 | 179 | 0.747518 |
de3db8573cc31fdeac9acfbd54f3ecb7343826df | 1,924 | //
// SettingsTabsView.swift
// Sphinx
//
// Created by Tomas Timinskas on 24/08/2020.
// Copyright © 2020 Sphinx. All rights reserved.
//
import Cocoa
protocol SettingsTabsDelegate: AnyObject {
func didChangeSettingsTab(tag: Int)
}
class SettingsTabsView: NSView, LoadableNib {
weak var delegate: SettingsTabsDelegate?
@IBOutlet var contentView: NSView!
@IBOutlet weak var basicSettingsBox: NSBox!
@IBOutlet weak var advancedSettingsBox: NSBox!
@IBOutlet weak var basicSettingsButton: CustomButton!
@IBOutlet weak var advancedSettingsButton: CustomButton!
enum Tabs: Int {
case Basic = 0
case Settings = 1
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
loadViewFromNib()
configureView()
setSelected()
}
func configureView() {
basicSettingsButton.cursor = .pointingHand
advancedSettingsButton.cursor = .pointingHand
}
func setSelected() {
toggleAll(selectedTag: 0)
}
func toggleAll(selectedTag: Int = -1) {
basicSettingsBox.fillColor = (selectedTag == Tabs.Basic.rawValue) ? NSColor.Sphinx.PrimaryBlue : NSColor.Sphinx.Body
advancedSettingsBox.fillColor = (selectedTag == Tabs.Basic.rawValue) ? NSColor.Sphinx.Body : NSColor.Sphinx.PrimaryBlue
if #available(OSX 10.14, *) {
basicSettingsButton.contentTintColor = (selectedTag == Tabs.Basic.rawValue) ? NSColor.white : NSColor.Sphinx.Text
advancedSettingsButton.contentTintColor = (selectedTag == Tabs.Basic.rawValue) ? NSColor.Sphinx.Text : NSColor.white
}
}
@IBAction func buttonClicked(_ sender: NSButton) {
toggleAll(selectedTag: sender.tag)
delegate?.didChangeSettingsTab(tag: sender.tag)
}
}
| 29.151515 | 128 | 0.662162 |
e6362279696902292bfd853e0ecad9a04ce2e270 | 2,588 | //
// DragTargetView.swift
// Health Data Importer XML Splitter
//
// Created by Dan Loewenherz on 9/22/18.
// Copyright © 2018 Lionheart Software LLC. All rights reserved.
//
import Cocoa
@objc
protocol DragViewDelegate {
var busy: Bool { get }
func dragDidStart()
func dragDidEnd()
func dragView(didDragFileWith url: URL)
func dragViewDidTouchUpInside()
func invalidFileTypeDragged()
func invalidFileTypeDropped()
}
class DragTargetView: NSView {
@IBOutlet var delegate: DragViewDelegate?
let acceptedFileExtensions: Set<String> = ["zip", "xml"]
var isDroppedFileOk = false
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
registerForDraggedTypes([.fileURL])
}
override func mouseDown(with event: NSEvent) {
guard let busy = delegate?.busy,
!busy else {
return
}
delegate?.dragViewDidTouchUpInside()
}
func checkExtensionForDrag(_ drag: NSDraggingInfo) -> Bool {
guard let urlString = drag.draggedFileURL?.absoluteString,
let last = urlString.split(separator: ".").last,
let busy = delegate?.busy,
!busy else {
return false
}
return acceptedFileExtensions.contains(String(last))
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
isDroppedFileOk = checkExtensionForDrag(sender)
if isDroppedFileOk {
delegate?.dragDidStart()
} else {
delegate?.invalidFileTypeDragged()
}
return []
}
override func draggingExited(_ sender: NSDraggingInfo?) {
delegate?.dragDidEnd()
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
guard isDroppedFileOk else {
return []
}
return .generic
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
if !isDroppedFileOk {
delegate?.invalidFileTypeDropped()
}
guard let url = sender.draggedFileURL else {
return false
}
delegate?.dragView(didDragFileWith: url)
return true
}
}
extension NSDraggingInfo {
var draggedFileURL: URL? {
guard let data = draggingPasteboard.data(forType: .fileURL),
let string = String(data: data, encoding: .utf8),
let url = URL(string: string) else {
return nil
}
return url
}
}
| 25.126214 | 80 | 0.6051 |
8a6a9b33d93c5e40cef9a62fffbed4b0b071448a | 710 | //
// GumletVideoPlayerData.swift
// GumletVideoAnalyticsSDK
//
//
import Foundation
public struct GumletInsightsCustomPlayerData {
public var GumletPlayerName: String
public var GumletPlayerIntegrationVersion: String
public var gumletPageType:String
public init()
{
self.GumletPlayerName = ""
self.GumletPlayerIntegrationVersion = ""
self.gumletPageType = ""
}
public init(gumletPageType:String,GumletPlayerIntegrationVersion:String,GumletPlayerName:String) {
self.GumletPlayerName = GumletPlayerName
self.GumletPlayerIntegrationVersion = GumletPlayerIntegrationVersion
self.gumletPageType = gumletPageType
}
}
| 21.515152 | 101 | 0.723944 |
fe2b1726b0cabb15478f8deeb3fb468e88668e5a | 8,341 | //
// GridViewCell.swift
// FYPhoto
//
// Created by xiaoyang on 2020/7/15.
//
import UIKit
import UIKit
protocol GridViewCellDelegate: AnyObject {
func gridCell(_ cell: GridViewCell, buttonClickedAt indexPath: IndexPath, assetIdentifier: String)
}
class GridViewCell: UICollectionViewCell {
static let reuseIdentifier = "GridViewCell"
var imageView = UIImageView()
var livePhotoBadgeImageView = UIImageView()
var videoDurationLabel = UILabel()
var selectionButton = SelectionButton()
var overlayView = UIView()
let editedAnnotation = UIImageView(image: Asset.Crop.icons8EditImage.image)
var representedAssetIdentifier: String!
weak var delegate: GridViewCellDelegate?
var indexPath: IndexPath?
var thumbnailImage: UIImage! {
didSet {
imageView.image = thumbnailImage
}
}
var selectionButtonTitleColor = UIColor.white
var selectionButtonBackgroundColor = UIColor.systemBlue
var livePhotoBadgeImage: UIImage! {
didSet {
livePhotoBadgeImageView.image = livePhotoBadgeImage
isVideoAsset = false
}
}
var videoDuration: String! {
didSet {
videoDurationLabel.text = videoDuration
isVideoAsset = true
}
}
var isVideoAsset: Bool = false {
didSet {
selectionButton.isHidden = isVideoAsset
}
}
var isEnable: Bool = false {
willSet {
overlayView.isHidden = newValue
isUserInteractionEnabled = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
imageView.image = nil
livePhotoBadgeImageView.image = nil
selectionButton.setImage(Asset.imageSelectedSmallOff.image, for: .normal)
indexPath = nil
isVideoAsset = false
editedAnnotation.isHidden = true
}
func setupUI() {
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
videoDurationLabel.font = UIFont.systemFont(ofSize: 11, weight: .light)
videoDurationLabel.textColor = .white
selectionButton.setImage(Asset.imageSelectedSmallOff.image, for: .normal)
selectionButton.addTarget(self, action: #selector(selectionButtonClicked(_:)), for: .touchUpInside)
selectionButton.layer.masksToBounds = true
selectionButton.layer.cornerRadius = 16
overlayView.backgroundColor = UIColor(white: 0, alpha: 0.5)
overlayView.isHidden = true
editedAnnotation.contentMode = .scaleAspectFit
editedAnnotation.isHidden = true
contentView.addSubview(imageView)
contentView.addSubview(livePhotoBadgeImageView)
contentView.addSubview(videoDurationLabel)
// contentView.addSubview(selectionButton)
contentView.addSubview(overlayView)
contentView.addSubview(editedAnnotation)
imageView.translatesAutoresizingMaskIntoConstraints = false
livePhotoBadgeImageView.translatesAutoresizingMaskIntoConstraints = false
videoDurationLabel.translatesAutoresizingMaskIntoConstraints = false
selectionButton.translatesAutoresizingMaskIntoConstraints = false
overlayView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
imageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
NSLayoutConstraint.activate([
livePhotoBadgeImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
livePhotoBadgeImageView.topAnchor.constraint(equalTo: contentView.topAnchor),
livePhotoBadgeImageView.widthAnchor.constraint(equalToConstant: 28),
livePhotoBadgeImageView.heightAnchor.constraint(equalToConstant: 28)
])
NSLayoutConstraint.activate([
videoDurationLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5),
videoDurationLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5)
])
// NSLayoutConstraint.activate([
// selectionButton.topAnchor.constraint(equalTo: topAnchor, constant: 7),
// selectionButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -7),
// selectionButton.widthAnchor.constraint(equalToConstant: 34),
// selectionButton.heightAnchor.constraint(equalToConstant: 34)
// ])
NSLayoutConstraint.activate([
overlayView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
overlayView.topAnchor.constraint(equalTo: contentView.topAnchor),
overlayView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
overlayView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
editedAnnotation.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
editedAnnotation.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10),
editedAnnotation.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -10),
editedAnnotation.widthAnchor.constraint(equalToConstant: 16),
editedAnnotation.heightAnchor.constraint(equalToConstant: 16)
])
}
@objc func selectionButtonClicked(_ sender: UIButton) {
if let indexPath = indexPath {
delegate?.gridCell(self, buttonClickedAt: indexPath, assetIdentifier: representedAssetIdentifier)
} else {
assertionFailure("indexpath couldn't be nil!")
}
}
/// change button style: image or number
/// - Parameter title: if title is empty, button display cirle image, otherwise, button display number string.
fileprivate func displayButtonTitle(_ title: String) {
if title.isEmpty {
selectionButton.setImage(Asset.imageSelectedSmallOff.image, for: .normal)
selectionButton.setTitle(title, for: .normal)
selectionButton.backgroundColor = .clear
selectionButton.transform = CGAffineTransform(scaleX: 1, y: 1)
} else {
selectionButton.setImage(nil, for: .normal)
selectionButton.setTitle(title, for: .normal)
selectionButton.setTitleColor(selectionButtonTitleColor, for: .normal)
selectionButton.backgroundColor = selectionButtonBackgroundColor
selectionButton.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}
}
func updateSelectionButtonTitle(_ title: String, _ isAnimated: Bool) {
let isSelected = !title.isEmpty
displayButtonTitle(title)
if isAnimated {
selectionButtonAnimation(isSelected: isSelected)
}
}
func selectionButtonAnimation(isSelected: Bool) {
let animationValues: [CGFloat]
if isSelected {
animationValues = [1.0, 0.7, 0.9, 0.8, 0.7]
} else {
animationValues = [1.2, 0.8, 1.1, 0.9, 1.0]
}
selectionButton.layer.removeAnimation(forKey: "selectionButtonAnimation")
let keyAnimation = CAKeyframeAnimation.init(keyPath: "transform.scale")
keyAnimation.duration = 0.25
keyAnimation.values = animationValues
selectionButton.layer.add(keyAnimation, forKey: "selectionButtonAnimation")
}
func hideUselessViewsForSingleSelection(_ isSingleSelection: Bool) {
if isSingleSelection {
selectionButton.isHidden = true
overlayView.isHidden = true
livePhotoBadgeImageView.isHidden = true
} else {
selectionButton.isHidden = false
overlayView.isHidden = false
livePhotoBadgeImageView.isHidden = false
}
}
func showEditAnnotation(_ show: Bool) {
editedAnnotation.isHidden = !show
}
}
| 36.90708 | 114 | 0.682412 |
5078035142193082fa47b862ccd3afc018129e3d | 281 | //
// memoriseApp.swift
// memorise
//
// Created by Karan Kadam on 26/1/21.
//
import SwiftUI
@main
struct memoriseApp: App {
let game = EmojiMemoryGame()
var body: some Scene {
WindowGroup {
EmojiMemoryGameView(viewModel: game)
}
}
}
| 14.789474 | 48 | 0.597865 |
71084518dd1c236cabae09ad384b4cf77fb30222 | 605 | //
// Generated file. Do not edit.
//
import FlutterMacOS
import Foundation
import file_chooser
import path_provider_macos
import shared_preferences_macos
import window_size
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FileChooserPlugin.register(with: registry.registrar(forPlugin: "FileChooserPlugin"))
PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
WindowSizePlugin.register(with: registry.registrar(forPlugin: "WindowSizePlugin"))
}
| 31.842105 | 98 | 0.831405 |
46689b2bf7d0d7caa01dd9822ddb95fe17835d0f | 461 | //
// Copyright (c) Vatsal Manot
//
import Swift
import SwiftUI
public struct HorizontalSpacer: View {
@inlinable
public var body: some View {
HStack {
Spacer()
}
}
@inlinable
public init() {
}
}
public struct VerticalSpacer: View {
@inlinable
public var body: some View {
VStack {
Spacer()
}
}
@inlinable
public init() {
}
}
| 13.171429 | 38 | 0.496746 |
622dfc1f896cedd631f05142665829b308574e43 | 2,085 | //
// Colors.swift
//
//
// Created by Brendan on 2021-02-05.
//
import SwiftUI
public struct ColorTheme {
public var primary: Color
public var primaryVariant: Color
public var onPrimary: Color
public var secondary: Color
public var secondaryVariant: Color
public var onSecondary: Color
public var background: Color
public var onBackground: Color
public var error: Color
public var onError: Color
public var surface: Color
public var onSurface: Color
public var shadow: Color
public init(primary: Color? = nil,
primaryVariant: Color? = nil,
onPrimary: Color? = nil,
secondary: Color? = nil,
secondaryVariant: Color? = nil,
onSecondary: Color? = nil,
background: Color? = nil,
onBackground: Color? = nil,
error: Color? = nil,
onError: Color? = nil,
surface: Color? = nil,
onSurface: Color? = nil,
shadow: Color? = nil) {
self.primary = primary ?? Color("primary", bundle: Bundle.module)
self.primaryVariant = primaryVariant ?? Color("primaryVariant", bundle: Bundle.module)
self.onPrimary = onPrimary ?? Color("onPrimary", bundle: Bundle.module)
self.secondary = secondary ?? Color("secondary", bundle: Bundle.module)
self.secondaryVariant = secondaryVariant ?? Color("secondaryVariant", bundle: Bundle.module)
self.onSecondary = onSecondary ?? Color("onSecondary", bundle: Bundle.module)
self.background = background ?? Color("background", bundle: Bundle.module)
self.onBackground = onBackground ?? Color("onBackground", bundle: Bundle.module)
self.error = error ?? Color("error", bundle: Bundle.module)
self.onError = onError ?? Color("onError", bundle: Bundle.module)
self.surface = surface ?? Color("surface", bundle: Bundle.module)
self.onSurface = onSurface ?? Color("onSurface", bundle: Bundle.module)
self.shadow = shadow ?? Color.black.opacity(0.15)
}
}
| 33.095238 | 100 | 0.633094 |
62555f5b3ba14c38225349184b12344139b7646c | 1,557 | //
// XCTUnwrap.swift
//
//
// Created by Sergej Jaskiewicz on 15.06.2019.
//
import XCTest
// FIXME: Remove this shim as soon is XCTUnwrap is added to swift-corelibs-xctest
private struct UnwrappingFailure: Error {}
/// Asserts that an expression is not `nil`, and returns its unwrapped value.
///
/// Generates a failure when `expression == nil`.
///
/// - Parameters:
/// - expression: An expression of type `T?` to compare against `nil`. Its type will
/// determine the type of the returned value.
/// - message: An optional description of the failure.
/// - file: The file in which failure occurred. Defaults to the file name of the test
/// case in which this function was called.
/// - line: The line number on which failure occurred. Defaults to the line number on
/// which this function was called.
/// - Returns: A value of type `T`, the result of evaluating and unwrapping the given
/// `expression`.
/// - Throws: An error when `expression == nil`. It will also rethrow any error thrown
/// while evaluating the given expression.
public func XCTUnwrap<Result>(_ expression: @autoclosure () throws -> Result?,
_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line) throws -> Result {
let result = try expression()
XCTAssertNotNil(result, message(), file: file, line: line)
if let result = result {
return result
} else {
throw UnwrappingFailure()
}
}
| 37.071429 | 87 | 0.639049 |
e633871b254df5a64059481f7a4c53cd90a7d9e7 | 3,452 | import XCTest
@testable import Alicerce
class NetworkStorePerformanceMetricsTrackerTestCase: XCTestCase {
private struct MockResource: Resource {
var mockParse: (Remote) throws -> Local = { _ in throw MockError.💥 }
enum MockError: Swift.Error { case 💥 }
typealias Remote = String
typealias Local = Int
typealias Error = MockError
var parse: ResourceMapClosure<Remote, Local> { return mockParse }
var serialize: ResourceMapClosure<Local, Remote> { fatalError() }
var errorParser: ResourceErrorParseClosure<Remote, Error> { fatalError() }
}
private var tracker: MockNetworkStorePerformanceMetricsTracker!
override func setUp() {
super.setUp()
tracker = MockNetworkStorePerformanceMetricsTracker()
}
override func tearDown() {
tracker = nil
super.tearDown()
}
// measureParse
func testMeasureParse_WithSuccessfulParse_ShouldInvokeStartAndStopOnTheTrackerAndSucceed() {
let measure = self.expectation(description: "measure")
defer { waitForExpectations(timeout: 1) }
var testResource = MockResource()
let testPayload = "🎁"
let testParsedResult = 1337
let testMetadata: PerformanceMetrics.Metadata = [ "📈" : 9000, "🔨" : false]
tracker.measureSyncInvokedClosure = { identifier, metadata in
XCTAssertEqual(identifier, self.tracker.makeParseIdentifier(for: testResource, payload: testPayload))
XCTAssertDumpsEqual(metadata, testMetadata)
measure.fulfill()
}
testResource.mockParse = { remote in
XCTAssertEqual(remote, testPayload)
return testParsedResult
}
do {
let result = try tracker.measureParse (of: testResource, payload: testPayload, metadata: testMetadata) {
try testResource.parse(testPayload)
}
XCTAssertEqual(testParsedResult, result)
} catch {
XCTFail("unexpected error \(error)!")
}
}
func testMeasureParse_WithFailingParse_ShouldInvokeStartAndStopOnTheTrackerAndFail() {
let measure = self.expectation(description: "measure")
defer { waitForExpectations(timeout: 1) }
var testResource = MockResource()
let testPayload = "💣"
let testMetadata: PerformanceMetrics.Metadata = [ "📈" : 9001, "🔨" : false]
tracker.measureSyncInvokedClosure = { identifier, metadata in
XCTAssertEqual(identifier, self.tracker.makeParseIdentifier(for: testResource, payload: testPayload))
XCTAssertDumpsEqual(metadata, testMetadata)
measure.fulfill()
}
testResource.mockParse = { remote in
XCTAssertEqual(remote, testPayload)
throw MockResource.MockError.💥
}
do {
let _ = try tracker.measureParse (of: testResource, payload: testPayload, metadata: testMetadata) {
try testResource.parse(testPayload)
}
XCTFail("unexpected error success!")
} catch MockResource.MockError.💥 {
// expected error
} catch {
XCTFail("unexpected error \(error)!")
}
}
}
final class MockNetworkStorePerformanceMetricsTracker: MockPerformanceMetricsTracker,
NetworkStorePerformanceMetricsTracker {
}
| 33.843137 | 116 | 0.637022 |
b9cb8d4b9989fbd9e900dd0ec87447ea229ba5fc | 814 | //
// ContentView.swift
// SwiftUI-d6-ListsAndScrollViews
//
// Created by pgq on 2020/3/19.
// Copyright © 2020 pq. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List {
NavigationLink(destination: ListExample()) {
Text("List")
}
NavigationLink(destination: ForEachExample()) {
Text("ForEach")
}
NavigationLink(destination: ScrollViewExample()) {
Text("ScrollViewExample")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 22 | 66 | 0.488943 |
8a4e31ce8b882e7a6e4848bcf6b5756d93511fb7 | 594 | //
// DetailVCCell.swift
// Interval Timer
//
// Created by Алексей Пархоменко on 23/10/2018.
// Copyright © 2018 Алексей Пархоменко. All rights reserved.
//
import UIKit
class DetailVCCell: UITableViewCell {
@IBOutlet weak var keyLabel: UILabel!
@IBOutlet weak var valueLabel: 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
}
}
| 21.214286 | 65 | 0.673401 |
f8ea74ced7e1ed1242762f0ce2cb155783a48f60 | 1,350 | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 Fuzzilli
let hermesProfile = Profile(
processArguments: ["--replr"],
processEnv: ["UBSAN_OPTIONS": "exitcode=122", "ASAN_OPTIONS": "exitcode=122"],
codePrefix: """
function main() {
""",
codeSuffix: """
}
main();
""",
ecmaVersion: ECMAScriptVersion.es6,
crashTests: ["FuzzilliCrash(1)", "FuzzilliCrash(2)"],
// crashTests: ["fuzzilli('FuzzilliCrash2')", "fuzzilli('FuzzilliCrash1')"],
additionalCodeGenerators: WeightedList<CodeGenerator>([]),
additionalProgramTemplates: WeightedList<ProgramTemplate>([]),
disabledCodeGenerators: [],
additionalBuiltins: [
"gc" : .function([] => .undefined),
]
)
| 29.347826 | 82 | 0.647407 |
db51b76c1bbf4b3ed782a929a12f3fb3d5ae94d3 | 2,274 | //
// ContentView.swift
// Converter Huge
//
// Created by Eric Lewis on 6/21/19.
// Copyright © 2019 Eric Lewis, Inc. All rights reserved.
//
import SwiftUI
// TODO: allow a way to select a "from" unit
struct ContentView : View {
var body: some View {
NavigationView {
ScrollView {
ForEach(categories.identified(by: \.title)) { cat in
HStack {
VStack(alignment: .leading) {
HStack {
Image(systemName: cat.icon ?? "")
.imageScale(.medium)
.font(.largeTitle)
Text(cat.title)
.font(.title)
Spacer()
}
.padding(.leading, 90)
HStack {
ForEach(cat.measurements.identified(by: \.title)) { measurement in
NavigationButton(destination: DetailView(title: cat.title, selectedUnit: measurement.unit, data: cat.measurements)) {
Text(measurement.title)
.font(.title)
.padding(.all, 50)
}
}
}
.padding(.horizontal, 90)
.padding(.top, 20)
.padding(.bottom, 50)
}
}
}
}
.edgesIgnoringSafeArea(.horizontal)
.navigationBarTitle(Text("Conversions"))
}
}
}
struct DetailView : View {
var title: String
var selectedUnit: Dimension
var data: [MeasurementData]
@State var input = "0"
var body: some View {
let cleanInput = Double($input.value.filter("01234567890.".contains)) ?? 0
return Group {
TextField($input).font(.largeTitle).navigationBarTitle(Text(title))
List(data.identified(by: \.title)) { measurement in
Button(action: {}) {
HStack {
Text(measurement.title)
Spacer()
Text(Measurement(value: cleanInput,
unit: self.selectedUnit).converted(to: measurement.unit).description)
}
}
}
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
| 27.39759 | 137 | 0.510114 |
7a7a324d7162b038f87d4c3eda089c45741c0261 | 2,340 | //
// SceneDelegate.swift
// tippy2
//
// Created by Tony Park on 12/19/19.
// Copyright © 2019 Tony Park. All rights reserved.
//
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 neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.333333 | 147 | 0.712393 |
03effc6b25b5588d74004408d6a82cdd5852ee54 | 705 | //
// Strings.swift
// EasyMoneyExchanger
//
// Created by Leon on 08/12/20.
//
import Foundation
import UIKit
struct Strings {
struct ExchangeScreen {
static let internetError = "You have no internet connection"
static let errorMessage = "Please, add a value"
static let amountLabel = "Amount"
static let fromLabel = "From"
static let toLabel = "To"
static let convertButton = "Convert"
static let currencyName = "Currency Name"
static let formButton = "🏳️ Select Cirrency"
static let toButton = "🏳️ Select Cirrency"
}
struct SupportedCurrenciesScreen {
static let title = "Supported Currencies"
}
}
| 23.5 | 68 | 0.641135 |
ffa6c9992bd50ba3ac412f446cfe80d3919cc74d | 3,480 | /// Copyright (c) 2022 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// This project and source code may use libraries or frameworks that are
/// released under various Open-Source licenses. Use of those libraries and
/// frameworks are governed by their own individual licenses.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
// swiftlint:disable force_unwrapping
import MetalKit
struct SceneLighting {
static func buildDefaultLight() -> Light {
var light = Light()
light.position = [0, 0, 0]
light.color = float3(repeating: 1.0)
light.specularColor = float3(repeating: 0.6)
light.attenuation = [1, 0, 0]
light.type = Sun
return light
}
let sunlight: Light = {
var light = Self.buildDefaultLight()
light.position = [3, 3, -2]
light.color = float3(repeating: 0.8)
return light
}()
let backLight: Light = {
var light = Self.buildDefaultLight()
light.position = [0, 3, 2]
light.color = float3(repeating: 1.0)
return light
}()
let leftFillLight: Light = {
var light = Self.buildDefaultLight()
light.position = [3, -2, 0]
light.color = float3(repeating: 0.3)
return light
}()
let rightFillLight: Light = {
var light = Self.buildDefaultLight()
light.position = [-2, -1, 1]
light.color = float3(repeating: 0.1)
return light
}()
let ambientLight: Light = {
var light = Self.buildDefaultLight()
light.type = Ambient
light.color = [0.3, 0.3, 0.3]
return light
}()
var lights: [Light] = []
var lightsBuffer: MTLBuffer
init() {
lights = [sunlight, backLight, leftFillLight, rightFillLight, ambientLight]
lightsBuffer = Self.createBuffer(lights: lights)
}
static func createBuffer(lights: [Light]) -> MTLBuffer {
var lights = lights
return Renderer.device.makeBuffer(
bytes: &lights,
length: MemoryLayout<Light>.stride * lights.count,
options: [])!
}
}
| 36.631579 | 83 | 0.702874 |
14e630969e4971cd36760c445a4cff558b9ca6a5 | 3,619 | // Copyright 2019 Algorand, Inc.
// 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.
//
// DeepLinkParser.swift
import UIKit
struct DeepLinkParser {
private let url: URL
init(url: URL) {
self.url = url
}
var wcSessionRequestText: String? {
let initialAlgorandPrefix = "algorand-wc://"
if !url.absoluteString.hasPrefix(initialAlgorandPrefix) {
return nil
}
let uriQueryKey = "uri"
guard let possibleWCRequestText = url.queryParameters?[uriQueryKey] else {
return nil
}
if possibleWCRequestText.isWalletConnectConnection {
return possibleWCRequestText
}
return nil
}
var expectedScreen: Screen? {
guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true),
let accountAddress = urlComponents.host,
accountAddress.isValidatedAddress(),
let qrText = url.buildQRText() else {
return nil
}
switch qrText.mode {
case .address:
return .addContact(mode: .new(address: accountAddress, name: qrText.label))
case .algosRequest:
if let amount = qrText.amount {
return .sendAlgosTransactionPreview(
account: nil,
receiver: .address(address: accountAddress, amount: "\(amount)"),
isSenderEditable: false,
qrText: qrText
)
}
case .assetRequest:
guard let assetId = qrText.asset,
let userAccounts = UIApplication.shared.appConfiguration?.session.accounts else {
return nil
}
var requestedAssetDetail: AssetDetail?
for account in userAccounts {
for assetDetail in account.assetDetails where assetDetail.id == assetId {
requestedAssetDetail = assetDetail
}
}
guard let assetDetail = requestedAssetDetail else {
let assetAlertDraft = AssetAlertDraft(
account: nil,
assetIndex: assetId,
assetDetail: nil,
title: "asset-support-title".localized,
detail: "asset-support-error".localized,
actionTitle: "title-ok".localized
)
return .assetSupport(assetAlertDraft: assetAlertDraft)
}
if let amount = qrText.amount {
return .sendAssetTransactionPreview(
account: nil,
receiver: .address(address: accountAddress, amount: "\(amount)"),
assetDetail: assetDetail,
isSenderEditable: false,
isMaxTransaction: false,
qrText: qrText
)
}
case .mnemonic:
return nil
}
return nil
}
}
| 32.3125 | 97 | 0.553744 |
206354c2def9eacbc30a4bb636d3a2e4ce4cb512 | 2,163 | //
// TodayNookazonSection.swift
// ACHNBrowserUI
//
// Created by Thomas Ricouard on 09/05/2020.
// Copyright © 2020 Thomas Ricouard. All rights reserved.
//
import SwiftUI
import UI
struct TodayNookazonSection: View {
@Binding var sheet: Sheet.SheetType?
@ObservedObject var viewModel: DashboardViewModel
var body: some View {
Section(header: SectionHeaderView(text: "New on Nookazon", icon: "cart.fill")) {
if viewModel.recentListings?.isEmpty == false {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 0) {
ForEach(viewModel.recentListings!) { listing in
HStack {
VStack {
ItemImage(path: listing.img?.absoluteString, size: 66)
Text("\(listing.name!)")
.font(.system(.subheadline, design: .rounded))
.fontWeight(.bold)
.foregroundColor(.acText)
.padding(.bottom, 4)
}
.padding(.horizontal)
.onTapGesture { self.sheet = .safari(URL.nookazon(listing: listing)!) }
Divider()
}
}
}
}
.listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
.frame(maxWidth: .infinity)
.padding(.vertical)
} else {
RowLoadingView(isLoading: .constant(true))
}
}
}
}
struct TodayNookazonSection_Previews: PreviewProvider {
static var previews: some View {
List {
TodayNookazonSection(sheet: .constant(nil),
viewModel: DashboardViewModel())
}
.listStyle(GroupedListStyle())
.environment(\.horizontalSizeClass, .regular)
}
}
| 36.05 | 103 | 0.460472 |
d5c86d01e65b663e5077e509d1975e95a6659080 | 3,655 | //
// UIViewExtensions.swift
// Catwalk
//
// Created by CTWLK on 8/15/21.
// Copyright © 2021 CATWALK. All rights reserved.
//
import UIKit
extension UIView {
func clearConstraints() {
self.removeConstraints(self.constraints)
}
func anchor(top: NSLayoutYAxisAnchor? = nil,
left: NSLayoutXAxisAnchor? = nil,
bottom: NSLayoutYAxisAnchor? = nil,
right: NSLayoutXAxisAnchor? = nil,
paddingTop: CGFloat = 0,
paddingLeft: CGFloat = 0,
paddingBottom: CGFloat = 0,
paddingRight: CGFloat = 0,
width: CGFloat? = nil,
height: CGFloat? = nil) {
translatesAutoresizingMaskIntoConstraints = false
if let top = top {
topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
}
if let left = left {
leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
}
if let bottom = bottom {
bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
}
if let right = right {
rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
}
if let width = width {
widthAnchor.constraint(equalToConstant: width).isActive = true
}
if let height = height {
heightAnchor.constraint(equalToConstant: height).isActive = true
}
}
func center(inView view: UIView, yConstant: CGFloat? = 0) {
translatesAutoresizingMaskIntoConstraints = false
centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: yConstant!).isActive = true
}
func centerX(inView view: UIView, topAnchor: NSLayoutYAxisAnchor? = nil, paddingTop: CGFloat? = 0) {
translatesAutoresizingMaskIntoConstraints = false
centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
if let topAnchor = topAnchor {
self.topAnchor.constraint(equalTo: topAnchor, constant: paddingTop!).isActive = true
}
}
func centerY(inView view: UIView, leftAnchor: NSLayoutXAxisAnchor? = nil,
paddingLeft: CGFloat = 0, constant: CGFloat = 0) {
translatesAutoresizingMaskIntoConstraints = false
centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: constant).isActive = true
if let left = leftAnchor {
anchor(left: left, paddingLeft: paddingLeft)
}
}
func setDimensions(height: CGFloat, width: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
heightAnchor.constraint(equalToConstant: height).isActive = true
widthAnchor.constraint(equalToConstant: width).isActive = true
}
func setHeight(_ height: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
heightAnchor.constraint(equalToConstant: height).isActive = true
}
func setWidth(_ width: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
widthAnchor.constraint(equalToConstant: width).isActive = true
}
func fillSuperview() {
translatesAutoresizingMaskIntoConstraints = false
guard let view = superview else { return }
anchor(top: view.topAnchor, left: view.leftAnchor,
bottom: view.bottomAnchor, right: view.rightAnchor)
}
}
| 34.809524 | 104 | 0.623803 |
1c6014fe5361ad5918180afe519f27042d32fdcc | 2,066 | //
// ViewController.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 14/01/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import FormValidatorSwift
import UIKit
final class FormViewController: UIViewController {
// MARK: - Properties
var form = ControlForm()
fileprivate var underlyingView: FormView {
if let myView = view as? FormView {
return myView
}
let newView = FormView()
view = newView
return newView
}
// MARK: - View Lifecycle
override func loadView() {
view = FormView()
}
override func viewDidLoad() {
super.viewDidLoad()
form.addEntry(underlyingView.titleEntry.textField)
form.addEntry(underlyingView.nameEntry.textField)
form.addEntry(underlyingView.emailEntry.textField)
underlyingView.submitButton.addTarget(self, action: #selector(FormViewController.submitButtonPressed(_:)), for: .touchUpInside)
}
// MARK: - Control Actions
@objc func submitButtonPressed(_ sender: UIButton) {
let alertTitle: String
let alertMessage: String
if form.isValid {
alertTitle = NSLocalizedString("Success", comment: "")
alertMessage = NSLocalizedString("Your data has been submitted!", comment: "")
} else {
alertTitle = NSLocalizedString("Error", comment: "")
alertMessage = NSLocalizedString("Please correct your entries in the form.", comment: "")
}
let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
alertController.popoverPresentationController?.sourceView = sender
let doneAction = UIAlertAction(title: NSLocalizedString("Done", comment: ""), style: .default, handler: nil)
alertController.addAction(doneAction)
present(alertController, animated: true, completion: nil)
}
}
| 29.098592 | 135 | 0.631655 |
3893f924b9920b94f79ccb14b36f4848d5edac5a | 1,081 | //===--- Calculator.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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
//
//===----------------------------------------------------------------------===//
import TestsUtils
import Foundation
@inline(never)
func my_atoi_impl(_ input : String) -> Int {
switch input {
case "0": return 0
case "1": return 1
case "2": return 2
case "3": return 3
case "4": return 4
case "5": return 5
case "6": return 6
case "7": return 7
case "8": return 8
case "9": return 9
default: return 0
}
}
@inline(never)
public func run_Calculator(_ N: Int) {
var c = 0
for _ in 1...N*5000 {
c += my_atoi_impl("10")
}
CheckResults(c == 0, "IncorrectResults in run_Calculator")
}
| 25.738095 | 80 | 0.571693 |
396798ba7564282b1cf8db2f16fae34bedbe838b | 2,171 | //
// AppDelegate.swift
// iOS-W2-Assignment
//
// Created by Van Do on 10/18/16.
// Copyright © 2016 Van Do. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.191489 | 285 | 0.75403 |
1e8bbb26189bbe1f8b2f882b7c7f4f29c528a051 | 2,445 | //
// URLTransform.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-27.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2018 Tristan Himmelman
//
// 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
open class URLTransform: TransformType {
public typealias Object = URL
public typealias JSON = String
private let shouldEncodeURLString: Bool
private let allowedCharacterSet: CharacterSet
/**
Initializes the URLTransform with an option to encode URL strings before converting them to an NSURL
- parameter shouldEncodeUrlString: when true (the default) the string is encoded before passing
to `NSURL(string:)`
- returns: an initialized transformer
*/
public init(shouldEncodeURLString: Bool = false, allowedCharacterSet: CharacterSet = .urlQueryAllowed) {
self.shouldEncodeURLString = shouldEncodeURLString
self.allowedCharacterSet = allowedCharacterSet
}
open func transformFromJSON(_ value: Any?) -> URL? {
guard let URLString = value as? String else { return nil }
if !shouldEncodeURLString {
return URL(string: URLString)
}
guard let escapedURLString = URLString.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) else {
return nil
}
return URL(string: escapedURLString)
}
open func transformToJSON(_ value: URL?) -> String? {
if let URL = value {
return URL.absoluteString
}
return nil
}
}
| 35.955882 | 113 | 0.754601 |
7a0470368e521dc4ff135bbccfcf1a664bc8a52d | 7,278 | //
// JSONDecodable.swift
// Freddy
//
// Created by Matthew D. Mathias on 3/24/15.
// Copyright © 2015 Big Nerd Ranch. Licensed under MIT.
//
/// A protocol to provide functionality for creating a model object with a `JSON`
/// value.
public protocol JSONDecodable {
/// Creates an instance of the model with a `JSON` instance.
/// - parameter json: An instance of a `JSON` value from which to
/// construct an instance of the implementing type.
/// - throws: Any `JSON.Error` for errors derived from inspecting the
/// `JSON` value, or any other error involved in decoding.
init(json: JSON) throws
}
extension Double: JSONDecodable {
/// An initializer to create an instance of `Double` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `Double` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
switch json {
case let .double(double):
self = double
case let .int(int):
self = Double(int)
default:
throw JSON.Error.valueNotConvertible(value: json, to: Double.self)
}
}
}
extension Int: JSONDecodable {
/// An initializer to create an instance of `Int` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `Int` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
switch json {
case let .double(double) where double <= Double(Int.max):
self = Int(double)
case let .int(int):
self = int
default:
throw JSON.Error.valueNotConvertible(value: json, to: Int.self)
}
}
}
extension String: JSONDecodable {
/// An initializer to create an instance of `String` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `String` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
switch json {
case let .string(string):
self = string
case let .int(int):
self = String(int)
case let .bool(bool):
self = String(bool)
case let .double(double):
self = String(double)
default:
throw JSON.Error.valueNotConvertible(value: json, to: String.self)
}
}
}
extension Bool: JSONDecodable {
/// An initializer to create an instance of `Bool` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `Bool` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
guard case let .bool(bool) = json else {
throw JSON.Error.valueNotConvertible(value: json, to: Bool.self)
}
self = bool
}
}
extension RawRepresentable where RawValue: JSONDecodable {
/// An initializer to create an instance of `RawRepresentable` from a `JSON` value.
/// - parameter json: An instance of `JSON`.
/// - throws: The initializer will throw an instance of `JSON.Error` if
/// an instance of `RawRepresentable` cannot be created from the `JSON` value that was
/// passed to this initializer.
public init(json: JSON) throws {
let raw = try json.decode(type: RawValue.self)
guard let value = Self(rawValue: raw) else {
throw JSON.Error.valueNotConvertible(value: json, to: Self.self)
}
self = value
}
}
internal extension JSON {
/// Retrieves a `[JSON]` from the JSON.
/// - parameter: A `JSON` to be used to create the returned `Array`.
/// - returns: An `Array` of `JSON` elements
/// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`.
/// - seealso: `JSON.decode(_:type:)`
static func getArray(from json: JSON) throws -> [JSON] {
// Ideally should be expressed as a conditional protocol implementation on Swift.Array.
guard case let .array(array) = json else {
throw Error.valueNotConvertible(value: json, to: Swift.Array<JSON>)
}
return array
}
/// Retrieves a `[String: JSON]` from the JSON.
/// - parameter: A `JSON` to be used to create the returned `Dictionary`.
/// - returns: An `Dictionary` of `String` mapping to `JSON` elements
/// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`.
/// - seealso: `JSON.decode(_:type:)`
static func getDictionary(from json: JSON) throws -> [String: JSON] {
// Ideally should be expressed as a conditional protocol implementation on Swift.Dictionary.
guard case let .dictionary(dictionary) = json else {
throw Error.valueNotConvertible(value: json, to: Swift.Dictionary<String, JSON>)
}
return dictionary
}
/// Attempts to decode many values from a descendant JSON array at a path
/// into JSON.
/// - parameter json: A `JSON` to be used to create the returned `Array` of some type conforming to `JSONDecodable`.
/// - returns: An `Array` of `Decoded` elements.
/// - throws: Any of the `JSON.Error` cases thrown by `decode(type:)`, as
/// well as any error that arises from decoding the contained values.
/// - seealso: `JSON.decode(_:type:)`
static func decodedArray<Decoded: JSONDecodable>(from json: JSON) throws -> [Decoded] {
// Ideally should be expressed as a conditional protocol implementation on Swift.Dictionary.
// This implementation also doesn't do the `type = Type.self` trick.
return try getArray(from: json).map(Decoded.init)
}
/// Attempts to decode many values from a descendant JSON object at a path
/// into JSON.
/// - parameter json: A `JSON` to be used to create the returned `Dictionary` of some type conforming to `JSONDecodable`.
/// - returns: A `Dictionary` of string keys and `Decoded` values.
/// - throws: One of the `JSON.Error` cases thrown by `decode(_:type:)` or
/// any error that arises from decoding the contained values.
/// - seealso: `JSON.decode(_:type:)`
static func decodedDictionary<Decoded: JSONDecodable>(from json: JSON) throws -> [Swift.String: Decoded] {
guard case let .dictionary(dictionary) = json else {
throw Error.valueNotConvertible(value: json, to: Swift.Dictionary<String, Decoded>)
}
var decodedDictionary = Swift.Dictionary<String, Decoded>(minimumCapacity: dictionary.count)
for (key, value) in dictionary {
decodedDictionary[key] = try Decoded(json: value)
}
return decodedDictionary
}
}
| 40.88764 | 125 | 0.620363 |
678bfe7b65aef7971146fd99321980a3376258fc | 148 | import XCTest
import SDSSharingServicePickerTests
var tests = [XCTestCaseEntry]()
tests += SDSSharingServicePickerTests.allTests()
XCTMain(tests)
| 18.5 | 48 | 0.824324 |
16264302b7691010de9a039f3299a557a0076184 | 889 | //
// ObserverType+Extensions.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/13/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
@available(*, deprecated=2.0.0, message="Please use observer.on(event)")
public func send<O: ObserverType>(observer: O, _ event: Event<O.E>) {
observer.on(event)
}
@available(*, deprecated=2.0.0, message="Please use observer.on(.Next(element))")
public func sendNext<O: ObserverType>(observer: O, _ element: O.E) {
observer.on(.Next(element))
}
@available(*, deprecated=2.0.0, message="Please use observer.on(.Error(error))")
public func sendError<O: ObserverType>(observer: O, _ error: ErrorType) {
observer.on(.Error(error))
}
@available(*, deprecated=2.0.0, message="Please use observer.on(.Completed)")
public func sendCompleted<O: ObserverType>(observer: O) {
observer.on(.Completed)
}
| 29.633333 | 81 | 0.705287 |
4813c9693d5bc1460a9dd42c7760200ac3a38919 | 1,422 | //
// PreworkUITests.swift
// PreworkUITests
//
// Created by Asam Zaman on 8/23/21.
//
import XCTest
class PreworkUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}
| 33.069767 | 182 | 0.654712 |
1c807db68ea52911df2af519a6b3c9c1b165a0bd | 2,142 | //
// MFeed.swift
// Funpedia
//
// Created by M Usman Saeed on 30/03/2016.
// Copyright © 2016 Soarlabs. All rights reserved.
//
import Foundation
class MFeed {
var price:String = ""
var itemId:String = ""
var description:String = ""
var title:String = ""
var authorName:String = ""
var releaseDate:String = ""
var buyItem:NSURL = NSURL(string: "https://github.com/soarlabs/iFunpedia/blob/master/iFunpedia/Resourace/background.png")!
var image:NSURL = NSURL(string: "https://github.com/soarlabs/iFunpedia/blob/master/iFunpedia/Resourace/background.png")!
var imageThumb:NSURL = NSURL(string: "https://github.com/soarlabs/iFunpedia/blob/master/iFunpedia/Resourace/background.png")!
var media:NSURL = NSURL(string: "https://github.com/soarlabs/iFunpedia/blob/master/iFunpedia/Resourace/background.png")!
init?(json: Dict) {
self.title = (json["im:name"]!["label"] as? String)!
self.image = NSURL(string:(((((json["im:image"]) as! AnyArray)[0] as! Dict)["label"]) as! String).stringByReplacingOccurrencesOfString("55x55", withString: "300x300"))!
self.imageThumb = NSURL(string:(((((json["im:image"]) as! AnyArray)[0] as! Dict)["label"]) as! String))!
self.price = (json["im:price"]!["label"] as? String)!
self.authorName = (json["im:artist"]!["label"] as? String)!
self.buyItem = NSURL(string:(((((json["link"]) as! AnyArray)[0] as! Dict)["attributes"]!["href"]) as! String))!
self.media = NSURL(string:(((((json["link"]) as! AnyArray)[1] as! Dict)["attributes"]!["href"]) as! String))!
self.releaseDate = (json["im:releaseDate"]!["attributes"]!!["label"] as? String)!
self.itemId = ((json["id"]!["attributes"]!!["im:id"]) as? String)!
}
class func parseFeed(feedCollection:AnyArray) -> AnyArray {
var feeds:AnyArray = AnyArray()
for dict in feedCollection {
let feedObjc = MFeed(json: dict as! Dict)
feeds.append(feedObjc!)
}
return feeds
}
}
| 30.169014 | 176 | 0.602241 |
d5900652c8909dc4af0dfe872686667a1b8c1708 | 1,629 | // MIT License
//
// Copyright © 2019_DEV_182
//
// 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.
//
// ID: BD9ADD22-8EC4-438E-BE70-91275D9FB07A
//
// Pkg: TicTacToe
//
// Swift: 5.0
//
// MacOS: 10.15
//
import Foundation
/// Returns a Boolean value indicating whether every element of a sequence
/// is the same.
///
/// - Parameter element: The element that you want to check.
/// - Returns: `true` if the sequence only contains the element passed in.
extension Sequence where Element: Equatable {
func elements(areAll element: Element) -> Bool {
return allSatisfy { e in
element == e
}
}
}
| 35.413043 | 81 | 0.73849 |
239edae91e668390ec789d560d433e98f4c24103 | 596 | import Leaf
import Vapor
/// Called before your application initializes.
///
/// [Learn More →](https://docs.vapor.codes/3.0/getting-started/structure/#configureswift)
public func configure(
_ config: inout Config,
_ env: inout Environment,
_ services: inout Services
) throws {
// Register routes to the router
let router = EngineRouter.default()
try routes(router)
services.register(router, as: Router.self)
// Configure the rest of your application here
try services.register(LeafProvider())
config.prefer(LeafRenderer.self, for: ViewRenderer.self)
}
| 28.380952 | 90 | 0.718121 |
f41b5b3013e70929579703a00c5034034af3562c | 4,330 | //
// CurrencyListMetaData.swift
// breadwallet
//
// Created by Adrian Corscadden on 2018-04-10.
// Copyright © 2018-2019 Breadwinner AG. All rights reserved.
//
import Foundation
/// KV-store object that saves the users enabled and hidden currencies
class AssetIndex: BRKVStoreObject, Codable {
static let key = "asset-index"
var classVersion = 2
var enabledAssetIds = [CurrencyId]()
enum CodingKeys: String, CodingKey {
case classVersion
case enabledAssetIds
}
/// Create new
init() {
enabledAssetIds = AssetIndex.defaultCurrencyIds
super.init(key: AssetIndex.key, version: 0, lastModified: Date(), deleted: false, data: Data())
}
/// Find existing
init?(kvStore: BRReplicatedKVStore) {
var ver: UInt64
var date: Date
var del: Bool
var bytes: [UInt8]
do {
(ver, date, del, bytes) = try kvStore.get(AssetIndex.key)
print("[KV] loading asset index ver:\(ver)...")
} catch let e {
print("[KV] unable to load asset index: \(e)")
return nil
}
let bytesData = Data(bytes: &bytes, count: bytes.count)
super.init(key: AssetIndex.key, version: ver, lastModified: date, deleted: del, data: bytesData)
}
override func getData() -> Data? {
return BRKeyedArchiver.archiveData(withRootObject: self)
}
override func dataWasSet(_ value: Data) {
guard let s: AssetIndex = BRKeyedUnarchiver.unarchiveObject(withData: value) else { return }
enabledAssetIds = s.enabledAssetIds
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
classVersion = try container.decode(Int.self, forKey: .classVersion)
enabledAssetIds = try container.decode([CurrencyId].self, forKey: .enabledAssetIds)
super.init(key: "", version: 0, lastModified: Date(), deleted: true, data: Data())
}
func resetToDefault() {
enabledAssetIds = AssetIndex.defaultCurrencyIds
}
static var defaultCurrencyIds: [CurrencyId] {
return Currencies.allCases.map { $0.uid }.filter { $0 != Currencies.bch.uid }
}
}
/// The old asset index (formerly CurrencyListMetaData) KV-store object.
/// This declration is for supporting migration to the new index above.
class LegacyAssetIndex: BRKVStoreObject, BRCoding {
static let key = "token-list-metadata-2"
var classVersion = 2
var enabledCurrencies = [String]()
var hiddenCurrencies = [String]()
var doesRequireSave = 0
//Find existing
init?(kvStore: BRReplicatedKVStore) {
var ver: UInt64
var date: Date
var del: Bool
var bytes: [UInt8]
do {
(ver, date, del, bytes) = try kvStore.get(LegacyAssetIndex.key)
} catch let e {
print("Unable to initialize TokenListMetaData: \(e)")
return nil
}
let bytesData = Data(bytes: &bytes, count: bytes.count)
super.init(key: LegacyAssetIndex.key, version: ver, lastModified: date, deleted: del, data: bytesData)
}
override func getData() -> Data? {
return BRKeyedArchiver.archivedDataWithRootObject(self)
}
override func dataWasSet(_ value: Data) {
guard let s: LegacyAssetIndex = BRKeyedUnarchiver.unarchiveObjectWithData(value) else { return }
enabledCurrencies = s.enabledCurrencies
hiddenCurrencies = s.hiddenCurrencies
doesRequireSave = s.doesRequireSave
}
required public init?(coder decoder: BRCoder) {
classVersion = decoder.decode("classVersion")
enabledCurrencies = decoder.decode("enabledCurrencies")
hiddenCurrencies = decoder.decode("hiddenCurrencies")
doesRequireSave = decoder.decode("doesRequireSave")
super.init(key: "", version: 0, lastModified: Date(), deleted: true, data: Data())
}
func encode(_ coder: BRCoder) {
coder.encode(classVersion, key: "classVersion")
coder.encode(enabledCurrencies, key: "enabledCurrencies")
coder.encode(hiddenCurrencies, key: "hiddenCurrencies")
coder.encode(doesRequireSave, key: "doesRequireSave")
}
}
| 34.365079 | 110 | 0.640185 |
efa59a926e3c74abd45dd6611dc992686a08928d | 307 | //
// DaLiConfiguration.swift
// CocoaLib
//
// Created by Rodrigo Casillas on 7/17/19.
//
import Foundation
class DaLiConfiguration {
init(config: URLSessionConfiguration) {
}
public static func config() {
URLProtocol.registerClass(DaLiURLProtocol.self)
}
}
| 15.35 | 55 | 0.641694 |
0342d2e533f2372de4ba26a705fbb95b51652c79 | 90,234 | // Generated using Sourcery 0.18.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
@testable import SwiftLintFrameworkTests
import XCTest
// swiftlint:disable line_length file_length
extension AccessControlLevelTests {
static var allTests: [(String, (AccessControlLevelTests) -> () throws -> Void)] = [
("testDescription", testDescription),
("testPriority", testPriority)
]
}
extension AnyObjectProtocolRuleTests {
static var allTests: [(String, (AnyObjectProtocolRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ArrayInitRuleTests {
static var allTests: [(String, (ArrayInitRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension AttributesRuleTests {
static var allTests: [(String, (AttributesRuleTests) -> () throws -> Void)] = [
("testAttributesWithDefaultConfiguration", testAttributesWithDefaultConfiguration),
("testAttributesWithAlwaysOnSameLine", testAttributesWithAlwaysOnSameLine),
("testAttributesWithAlwaysOnLineAbove", testAttributesWithAlwaysOnLineAbove),
("testAttributesWithAttributesOnLineAboveButOnOtherDeclaration", testAttributesWithAttributesOnLineAboveButOnOtherDeclaration)
]
}
extension BlockBasedKVORuleTests {
static var allTests: [(String, (BlockBasedKVORuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ClassDelegateProtocolRuleTests {
static var allTests: [(String, (ClassDelegateProtocolRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ClosingBraceRuleTests {
static var allTests: [(String, (ClosingBraceRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ClosureBodyLengthRuleTests {
static var allTests: [(String, (ClosureBodyLengthRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ClosureEndIndentationRuleTests {
static var allTests: [(String, (ClosureEndIndentationRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ClosureParameterPositionRuleTests {
static var allTests: [(String, (ClosureParameterPositionRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ClosureSpacingRuleTests {
static var allTests: [(String, (ClosureSpacingRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension CollectingRuleTests {
static var allTests: [(String, (CollectingRuleTests) -> () throws -> Void)] = [
("testCollectsIntoStorage", testCollectsIntoStorage),
("testCollectsAllFiles", testCollectsAllFiles),
("testCollectsAnalyzerFiles", testCollectsAnalyzerFiles),
("testCorrects", testCorrects)
]
}
extension CollectionAlignmentRuleTests {
static var allTests: [(String, (CollectionAlignmentRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testCollectionAlignmentWithAlignLeft", testCollectionAlignmentWithAlignLeft),
("testCollectionAlignmentWithAlignColons", testCollectionAlignmentWithAlignColons)
]
}
extension ColonRuleTests {
static var allTests: [(String, (ColonRuleTests) -> () throws -> Void)] = [
("testColonWithDefaultConfiguration", testColonWithDefaultConfiguration),
("testColonWithFlexibleRightSpace", testColonWithFlexibleRightSpace),
("testColonWithoutApplyToDictionaries", testColonWithoutApplyToDictionaries)
]
}
extension CommaRuleTests {
static var allTests: [(String, (CommaRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension CommandTests {
static var allTests: [(String, (CommandTests) -> () throws -> Void)] = [
("testNoCommandsInEmptyFile", testNoCommandsInEmptyFile),
("testEmptyString", testEmptyString),
("testDisable", testDisable),
("testDisablePrevious", testDisablePrevious),
("testDisableThis", testDisableThis),
("testDisableNext", testDisableNext),
("testEnable", testEnable),
("testEnablePrevious", testEnablePrevious),
("testEnableThis", testEnableThis),
("testEnableNext", testEnableNext),
("testTrailingComment", testTrailingComment),
("testTrailingCommentWithUrl", testTrailingCommentWithUrl),
("testTrailingCommentUrlOnly", testTrailingCommentUrlOnly),
("testActionInverse", testActionInverse),
("testNoModifierCommandExpandsToItself", testNoModifierCommandExpandsToItself),
("testExpandPreviousCommand", testExpandPreviousCommand),
("testExpandThisCommand", testExpandThisCommand),
("testExpandNextCommand", testExpandNextCommand),
("testSuperfluousDisableCommands", testSuperfluousDisableCommands),
("testDisableAllOverridesSuperfluousDisableCommand", testDisableAllOverridesSuperfluousDisableCommand),
("testSuperfluousDisableCommandsIgnoreDelimiter", testSuperfluousDisableCommandsIgnoreDelimiter),
("testInvalidDisableCommands", testInvalidDisableCommands),
("testSuperfluousDisableCommandsDisabled", testSuperfluousDisableCommandsDisabled),
("testSuperfluousDisableCommandsDisabledOnConfiguration", testSuperfluousDisableCommandsDisabledOnConfiguration)
]
}
extension CompilerProtocolInitRuleTests {
static var allTests: [(String, (CompilerProtocolInitRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testViolationMessageForExpressibleByIntegerLiteral", testViolationMessageForExpressibleByIntegerLiteral)
]
}
extension ComputedAccessorsOrderRuleTests {
static var allTests: [(String, (ComputedAccessorsOrderRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testSetGetConfiguration", testSetGetConfiguration),
("testGetSetPropertyReason", testGetSetPropertyReason),
("testGetSetSubscriptReason", testGetSetSubscriptReason),
("testSetGetPropertyReason", testSetGetPropertyReason),
("testSetGetSubscriptReason", testSetGetSubscriptReason)
]
}
extension ConditionalReturnsOnNewlineRuleTests {
static var allTests: [(String, (ConditionalReturnsOnNewlineRuleTests) -> () throws -> Void)] = [
("testConditionalReturnsOnNewlineWithDefaultConfiguration", testConditionalReturnsOnNewlineWithDefaultConfiguration),
("testConditionalReturnsOnNewlineWithIfOnly", testConditionalReturnsOnNewlineWithIfOnly)
]
}
extension ConfigurationAliasesTests {
static var allTests: [(String, (ConfigurationAliasesTests) -> () throws -> Void)] = [
("testConfiguresCorrectlyFromDeprecatedAlias", testConfiguresCorrectlyFromDeprecatedAlias),
("testReturnsNilWithDuplicatedConfiguration", testReturnsNilWithDuplicatedConfiguration),
("testInitsFromDeprecatedAlias", testInitsFromDeprecatedAlias),
("testWhitelistRulesFromDeprecatedAlias", testWhitelistRulesFromDeprecatedAlias),
("testDisabledRulesFromDeprecatedAlias", testDisabledRulesFromDeprecatedAlias)
]
}
extension ConfigurationTests {
static var allTests: [(String, (ConfigurationTests) -> () throws -> Void)] = [
("testInit", testInit),
("testEmptyConfiguration", testEmptyConfiguration),
("testInitWithRelativePathAndRootPath", testInitWithRelativePathAndRootPath),
("testEnableAllRulesConfiguration", testEnableAllRulesConfiguration),
("testWhitelistRules", testWhitelistRules),
("testWarningThreshold_value", testWarningThreshold_value),
("testWarningThreshold_nil", testWarningThreshold_nil),
("testOtherRuleConfigurationsAlongsideWhitelistRules", testOtherRuleConfigurationsAlongsideWhitelistRules),
("testDisabledRules", testDisabledRules),
("testDisabledRulesWithUnknownRule", testDisabledRulesWithUnknownRule),
("testDuplicatedRules", testDuplicatedRules),
("testExcludedPaths", testExcludedPaths),
("testForceExcludesFile", testForceExcludesFile),
("testForceExcludesFileNotPresentInExcluded", testForceExcludesFileNotPresentInExcluded),
("testForceExcludesDirectory", testForceExcludesDirectory),
("testForceExcludesDirectoryThatIsNotInExcludedButHasChildrenThatAre", testForceExcludesDirectoryThatIsNotInExcludedButHasChildrenThatAre),
("testLintablePaths", testLintablePaths),
("testGlobExcludePaths", testGlobExcludePaths),
("testIsEqualTo", testIsEqualTo),
("testIsNotEqualTo", testIsNotEqualTo),
("testCustomConfiguration", testCustomConfiguration),
("testConfigurationWithSwiftFileAsRoot", testConfigurationWithSwiftFileAsRoot),
("testConfigurationWithSwiftFileAsRootAndCustomConfiguration", testConfigurationWithSwiftFileAsRootAndCustomConfiguration),
("testIndentationTabs", testIndentationTabs),
("testIndentationSpaces", testIndentationSpaces),
("testIndentationFallback", testIndentationFallback),
("testConfiguresCorrectlyFromDict", testConfiguresCorrectlyFromDict),
("testConfigureFallsBackCorrectly", testConfigureFallsBackCorrectly),
("testAllowZeroLintableFiles", testAllowZeroLintableFiles),
("testMerge", testMerge),
("testLevel0", testLevel0),
("testLevel1", testLevel1),
("testLevel2", testLevel2),
("testLevel3", testLevel3),
("testNestedConfigurationWithCustomRootPath", testNestedConfigurationWithCustomRootPath),
("testMergedWarningThreshold", testMergedWarningThreshold),
("testNestedWhitelistedRules", testNestedWhitelistedRules),
("testNestedConfigurationsWithCustomRulesMerge", testNestedConfigurationsWithCustomRulesMerge),
("testNestedConfigurationAllowsDisablingParentsCustomRules", testNestedConfigurationAllowsDisablingParentsCustomRules)
]
}
extension ContainsOverFilterCountRuleTests {
static var allTests: [(String, (ContainsOverFilterCountRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ContainsOverFilterIsEmptyRuleTests {
static var allTests: [(String, (ContainsOverFilterIsEmptyRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ContainsOverFirstNotNilRuleTests {
static var allTests: [(String, (ContainsOverFirstNotNilRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testFirstReason", testFirstReason),
("testFirstIndexReason", testFirstIndexReason)
]
}
extension ContainsOverRangeNilComparisonRuleTests {
static var allTests: [(String, (ContainsOverRangeNilComparisonRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ControlStatementRuleTests {
static var allTests: [(String, (ControlStatementRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ConvenienceTypeRuleTests {
static var allTests: [(String, (ConvenienceTypeRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension CustomRulesTests {
static var allTests: [(String, (CustomRulesTests) -> () throws -> Void)] = [
("testCustomRuleConfigurationSetsCorrectlyWithMatchKinds", testCustomRuleConfigurationSetsCorrectlyWithMatchKinds),
("testCustomRuleConfigurationSetsCorrectlyWithExcludedMatchKinds", testCustomRuleConfigurationSetsCorrectlyWithExcludedMatchKinds),
("testCustomRuleConfigurationThrows", testCustomRuleConfigurationThrows),
("testCustomRuleConfigurationMatchKindAmbiguity", testCustomRuleConfigurationMatchKindAmbiguity),
("testCustomRuleConfigurationIgnoreInvalidRules", testCustomRuleConfigurationIgnoreInvalidRules),
("testCustomRules", testCustomRules),
("testLocalDisableCustomRule", testLocalDisableCustomRule),
("testLocalDisableCustomRuleWithMultipleRules", testLocalDisableCustomRuleWithMultipleRules),
("testCustomRulesIncludedDefault", testCustomRulesIncludedDefault),
("testCustomRulesIncludedExcludesFile", testCustomRulesIncludedExcludesFile),
("testCustomRulesExcludedExcludesFile", testCustomRulesExcludedExcludesFile),
("testCustomRulesCaptureGroup", testCustomRulesCaptureGroup)
]
}
extension CyclomaticComplexityConfigurationTests {
static var allTests: [(String, (CyclomaticComplexityConfigurationTests) -> () throws -> Void)] = [
("testCyclomaticComplexityConfigurationInitializerSetsLevels", testCyclomaticComplexityConfigurationInitializerSetsLevels),
("testCyclomaticComplexityConfigurationInitializerSetsIgnoresCaseStatements", testCyclomaticComplexityConfigurationInitializerSetsIgnoresCaseStatements),
("testCyclomaticComplexityConfigurationApplyConfigurationWithDictionary", testCyclomaticComplexityConfigurationApplyConfigurationWithDictionary),
("testCyclomaticComplexityConfigurationThrowsOnBadConfigValues", testCyclomaticComplexityConfigurationThrowsOnBadConfigValues),
("testCyclomaticComplexityConfigurationCompares", testCyclomaticComplexityConfigurationCompares)
]
}
extension CyclomaticComplexityRuleTests {
static var allTests: [(String, (CyclomaticComplexityRuleTests) -> () throws -> Void)] = [
("testCyclomaticComplexity", testCyclomaticComplexity),
("testIgnoresCaseStatementsConfigurationEnabled", testIgnoresCaseStatementsConfigurationEnabled),
("testIgnoresCaseStatementsConfigurationDisabled", testIgnoresCaseStatementsConfigurationDisabled)
]
}
extension DeploymentTargetConfigurationTests {
static var allTests: [(String, (DeploymentTargetConfigurationTests) -> () throws -> Void)] = [
("testAppliesConfigurationFromDictionary", testAppliesConfigurationFromDictionary),
("testThrowsOnBadConfig", testThrowsOnBadConfig)
]
}
extension DeploymentTargetRuleTests {
static var allTests: [(String, (DeploymentTargetRuleTests) -> () throws -> Void)] = [
("testRule", testRule),
("testMacOSAttributeReason", testMacOSAttributeReason),
("testWatchOSConditionReason", testWatchOSConditionReason)
]
}
extension DisableAllTests {
static var allTests: [(String, (DisableAllTests) -> () throws -> Void)] = [
("testViolatingPhrase", testViolatingPhrase),
("testDisableAll", testDisableAll),
("testEnableAll", testEnableAll),
("testDisableAllPrevious", testDisableAllPrevious),
("testEnableAllPrevious", testEnableAllPrevious),
("testDisableAllNext", testDisableAllNext),
("testEnableAllNext", testEnableAllNext),
("testDisableAllThis", testDisableAllThis),
("testEnableAllThis", testEnableAllThis)
]
}
extension DiscardedNotificationCenterObserverRuleTests {
static var allTests: [(String, (DiscardedNotificationCenterObserverRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension DiscouragedDirectInitRuleTests {
static var allTests: [(String, (DiscouragedDirectInitRuleTests) -> () throws -> Void)] = [
("testDiscouragedDirectInitWithDefaultConfiguration", testDiscouragedDirectInitWithDefaultConfiguration),
("testDiscouragedDirectInitWithConfiguredSeverity", testDiscouragedDirectInitWithConfiguredSeverity),
("testDiscouragedDirectInitWithNewIncludedTypes", testDiscouragedDirectInitWithNewIncludedTypes),
("testDiscouragedDirectInitWithReplacedTypes", testDiscouragedDirectInitWithReplacedTypes)
]
}
extension DiscouragedObjectLiteralRuleTests {
static var allTests: [(String, (DiscouragedObjectLiteralRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testWithImageLiteral", testWithImageLiteral),
("testWithColorLiteral", testWithColorLiteral)
]
}
extension DiscouragedOptionalBooleanRuleTests {
static var allTests: [(String, (DiscouragedOptionalBooleanRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension DiscouragedOptionalCollectionRuleTests {
static var allTests: [(String, (DiscouragedOptionalCollectionRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension DuplicateEnumCasesRuleTests {
static var allTests: [(String, (DuplicateEnumCasesRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension DuplicateImportsRuleTests {
static var allTests: [(String, (DuplicateImportsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension DynamicInlineRuleTests {
static var allTests: [(String, (DynamicInlineRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension EmptyCollectionLiteralRuleTests {
static var allTests: [(String, (EmptyCollectionLiteralRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension EmptyCountRuleTests {
static var allTests: [(String, (EmptyCountRuleTests) -> () throws -> Void)] = [
("testEmptyCountWithDefaultConfiguration", testEmptyCountWithDefaultConfiguration),
("testEmptyCountWithOnlyAfterDot", testEmptyCountWithOnlyAfterDot)
]
}
extension EmptyEnumArgumentsRuleTests {
static var allTests: [(String, (EmptyEnumArgumentsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension EmptyParametersRuleTests {
static var allTests: [(String, (EmptyParametersRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension EmptyParenthesesWithTrailingClosureRuleTests {
static var allTests: [(String, (EmptyParenthesesWithTrailingClosureRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension EmptyStringRuleTests {
static var allTests: [(String, (EmptyStringRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension EmptyXCTestMethodRuleTests {
static var allTests: [(String, (EmptyXCTestMethodRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension EnumCaseAssociatedValuesLengthRuleTests {
static var allTests: [(String, (EnumCaseAssociatedValuesLengthRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ExampleTests {
static var allTests: [(String, (ExampleTests) -> () throws -> Void)] = [
("testEquatableDoesNotLookAtFile", testEquatableDoesNotLookAtFile),
("testEquatableDoesNotLookAtLine", testEquatableDoesNotLookAtLine),
("testEquatableLooksAtCode", testEquatableLooksAtCode),
("testTestMultiByteOffsets", testTestMultiByteOffsets),
("testTestOnLinux", testTestOnLinux),
("testRemovingViolationMarkers", testRemovingViolationMarkers),
("testComparable", testComparable),
("testWithCode", testWithCode)
]
}
extension ExpiringTodoRuleTests {
static var allTests: [(String, (ExpiringTodoRuleTests) -> () throws -> Void)] = [
("testExpiringTodo", testExpiringTodo),
("testExpiredTodo", testExpiredTodo),
("testExpiredFixMe", testExpiredFixMe),
("testApproachingExpiryTodo", testApproachingExpiryTodo),
("testNonExpiredTodo", testNonExpiredTodo),
("testExpiredCustomDelimiters", testExpiredCustomDelimiters),
("testExpiredCustomSeparator", testExpiredCustomSeparator),
("testExpiredCustomFormat", testExpiredCustomFormat)
]
}
extension ExplicitACLRuleTests {
static var allTests: [(String, (ExplicitACLRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ExplicitEnumRawValueRuleTests {
static var allTests: [(String, (ExplicitEnumRawValueRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ExplicitInitRuleTests {
static var allTests: [(String, (ExplicitInitRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ExplicitSelfRuleTests {
static var allTests: [(String, (ExplicitSelfRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ExplicitTopLevelACLRuleTests {
static var allTests: [(String, (ExplicitTopLevelACLRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ExplicitTypeInterfaceConfigurationTests {
static var allTests: [(String, (ExplicitTypeInterfaceConfigurationTests) -> () throws -> Void)] = [
("testDefaultConfiguration", testDefaultConfiguration),
("testApplyingCustomConfiguration", testApplyingCustomConfiguration),
("testInvalidKeyInCustomConfiguration", testInvalidKeyInCustomConfiguration),
("testInvalidTypeOfCustomConfiguration", testInvalidTypeOfCustomConfiguration),
("testInvalidTypeOfValueInCustomConfiguration", testInvalidTypeOfValueInCustomConfiguration),
("testConsoleDescription", testConsoleDescription)
]
}
extension ExplicitTypeInterfaceRuleTests {
static var allTests: [(String, (ExplicitTypeInterfaceRuleTests) -> () throws -> Void)] = [
("testExplicitTypeInterface", testExplicitTypeInterface),
("testExcludeLocalVars", testExcludeLocalVars),
("testExcludeClassVars", testExcludeClassVars),
("testAllowRedundancy", testAllowRedundancy),
("testEmbededInStatements", testEmbededInStatements),
("testCaptureGroup", testCaptureGroup),
("testFastEnumerationDeclaration", testFastEnumerationDeclaration),
("testSwitchCaseDeclarations", testSwitchCaseDeclarations)
]
}
extension ExtendedNSStringTests {
static var allTests: [(String, (ExtendedNSStringTests) -> () throws -> Void)] = [
("testLineAndCharacterForByteOffset_forContentsContainingMultibyteCharacters", testLineAndCharacterForByteOffset_forContentsContainingMultibyteCharacters)
]
}
extension ExtendedStringTests {
static var allTests: [(String, (ExtendedStringTests) -> () throws -> Void)] = [
("testCountOccurrences", testCountOccurrences)
]
}
extension ExtensionAccessModifierRuleTests {
static var allTests: [(String, (ExtensionAccessModifierRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension FallthroughRuleTests {
static var allTests: [(String, (FallthroughRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension FatalErrorMessageRuleTests {
static var allTests: [(String, (FatalErrorMessageRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension FileHeaderRuleTests {
static var allTests: [(String, (FileHeaderRuleTests) -> () throws -> Void)] = [
("testFileHeaderWithDefaultConfiguration", testFileHeaderWithDefaultConfiguration),
("testFileHeaderWithRequiredString", testFileHeaderWithRequiredString),
("testFileHeaderWithRequiredPattern", testFileHeaderWithRequiredPattern),
("testFileHeaderWithRequiredStringAndURLComment", testFileHeaderWithRequiredStringAndURLComment),
("testFileHeaderWithForbiddenString", testFileHeaderWithForbiddenString),
("testFileHeaderWithForbiddenPattern", testFileHeaderWithForbiddenPattern),
("testFileHeaderWithForbiddenPatternAndDocComment", testFileHeaderWithForbiddenPatternAndDocComment),
("testFileHeaderWithRequiredStringUsingFilenamePlaceholder", testFileHeaderWithRequiredStringUsingFilenamePlaceholder),
("testFileHeaderWithForbiddenStringUsingFilenamePlaceholder", testFileHeaderWithForbiddenStringUsingFilenamePlaceholder),
("testFileHeaderWithRequiredPatternUsingFilenamePlaceholder", testFileHeaderWithRequiredPatternUsingFilenamePlaceholder),
("testFileHeaderWithForbiddenPatternUsingFilenamePlaceholder", testFileHeaderWithForbiddenPatternUsingFilenamePlaceholder)
]
}
extension FileLengthRuleTests {
static var allTests: [(String, (FileLengthRuleTests) -> () throws -> Void)] = [
("testFileLengthWithDefaultConfiguration", testFileLengthWithDefaultConfiguration),
("testFileLengthIgnoringLinesWithOnlyComments", testFileLengthIgnoringLinesWithOnlyComments)
]
}
extension FileNameNoSpaceRuleTests {
static var allTests: [(String, (FileNameNoSpaceRuleTests) -> () throws -> Void)] = [
("testFileNameDoesntTrigger", testFileNameDoesntTrigger),
("testFileWithSpaceDoesTrigger", testFileWithSpaceDoesTrigger),
("testExtensionNameDoesntTrigger", testExtensionNameDoesntTrigger),
("testExtensionWithSpaceDoesTrigger", testExtensionWithSpaceDoesTrigger),
("testCustomExcludedList", testCustomExcludedList)
]
}
extension FileNameRuleTests {
static var allTests: [(String, (FileNameRuleTests) -> () throws -> Void)] = [
("testMainDoesntTrigger", testMainDoesntTrigger),
("testLinuxMainDoesntTrigger", testLinuxMainDoesntTrigger),
("testClassNameDoesntTrigger", testClassNameDoesntTrigger),
("testStructNameDoesntTrigger", testStructNameDoesntTrigger),
("testExtensionNameDoesntTrigger", testExtensionNameDoesntTrigger),
("testNestedExtensionDoesntTrigger", testNestedExtensionDoesntTrigger),
("testNestedTypeSeparatorDoesntTrigger", testNestedTypeSeparatorDoesntTrigger),
("testWrongNestedTypeSeparatorDoesTrigger", testWrongNestedTypeSeparatorDoesTrigger),
("testMisspelledNameDoesTrigger", testMisspelledNameDoesTrigger),
("testMisspelledNameDoesntTriggerWithOverride", testMisspelledNameDoesntTriggerWithOverride),
("testMainDoesTriggerWithoutOverride", testMainDoesTriggerWithoutOverride),
("testCustomSuffixPattern", testCustomSuffixPattern),
("testCustomPrefixPattern", testCustomPrefixPattern),
("testCustomPrefixAndSuffixPatterns", testCustomPrefixAndSuffixPatterns)
]
}
extension FileTypesOrderRuleTests {
static var allTests: [(String, (FileTypesOrderRuleTests) -> () throws -> Void)] = [
("testFileTypesOrderWithDefaultConfiguration", testFileTypesOrderWithDefaultConfiguration),
("testFileTypesOrderReversedOrder", testFileTypesOrderReversedOrder),
("testFileTypesOrderGroupedOrder", testFileTypesOrderGroupedOrder)
]
}
extension FirstWhereRuleTests {
static var allTests: [(String, (FirstWhereRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension FlatMapOverMapReduceRuleTests {
static var allTests: [(String, (FlatMapOverMapReduceRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ForWhereRuleTests {
static var allTests: [(String, (ForWhereRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ForceCastRuleTests {
static var allTests: [(String, (ForceCastRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ForceTryRuleTests {
static var allTests: [(String, (ForceTryRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ForceUnwrappingRuleTests {
static var allTests: [(String, (ForceUnwrappingRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension FunctionBodyLengthRuleTests {
static var allTests: [(String, (FunctionBodyLengthRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testFunctionBodyLengths", testFunctionBodyLengths),
("testFunctionBodyLengthsWithComments", testFunctionBodyLengthsWithComments),
("testFunctionBodyLengthsWithMultilineComments", testFunctionBodyLengthsWithMultilineComments)
]
}
extension FunctionDefaultParameterAtEndRuleTests {
static var allTests: [(String, (FunctionDefaultParameterAtEndRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension FunctionParameterCountRuleTests {
static var allTests: [(String, (FunctionParameterCountRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testFunctionParameterCount", testFunctionParameterCount),
("testDefaultFunctionParameterCount", testDefaultFunctionParameterCount)
]
}
extension GenericTypeNameRuleTests {
static var allTests: [(String, (GenericTypeNameRuleTests) -> () throws -> Void)] = [
("testGenericTypeName", testGenericTypeName),
("testGenericTypeNameWithAllowedSymbols", testGenericTypeNameWithAllowedSymbols),
("testGenericTypeNameWithAllowedSymbolsAndViolation", testGenericTypeNameWithAllowedSymbolsAndViolation),
("testGenericTypeNameWithIgnoreStartWithLowercase", testGenericTypeNameWithIgnoreStartWithLowercase)
]
}
extension GlobTests {
static var allTests: [(String, (GlobTests) -> () throws -> Void)] = [
("testOnlyGlobForWildcard", testOnlyGlobForWildcard),
("testNoMatchReturnsEmpty", testNoMatchReturnsEmpty),
("testMatchesFiles", testMatchesFiles),
("testMatchesSingleCharacter", testMatchesSingleCharacter),
("testMatchesOneCharacterInBracket", testMatchesOneCharacterInBracket),
("testNoMatchOneCharacterInBracket", testNoMatchOneCharacterInBracket),
("testMatchesCharacterInRange", testMatchesCharacterInRange),
("testNoMatchCharactersInRange", testNoMatchCharactersInRange),
("testMatchesMultipleFiles", testMatchesMultipleFiles),
("testMatchesNestedDirectory", testMatchesNestedDirectory),
("testNoGlobstarSupport", testNoGlobstarSupport)
]
}
extension IBInspectableInExtensionRuleTests {
static var allTests: [(String, (IBInspectableInExtensionRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension IdenticalOperandsRuleTests {
static var allTests: [(String, (IdenticalOperandsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension IdentifierNameRuleTests {
static var allTests: [(String, (IdentifierNameRuleTests) -> () throws -> Void)] = [
("testIdentifierName", testIdentifierName),
("testIdentifierNameWithAllowedSymbols", testIdentifierNameWithAllowedSymbols),
("testIdentifierNameWithAllowedSymbolsAndViolation", testIdentifierNameWithAllowedSymbolsAndViolation),
("testIdentifierNameWithIgnoreStartWithLowercase", testIdentifierNameWithIgnoreStartWithLowercase),
("testLinuxCrashOnEmojiNames", testLinuxCrashOnEmojiNames)
]
}
extension ImplicitGetterRuleTests {
static var allTests: [(String, (ImplicitGetterRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ImplicitReturnConfigurationTests {
static var allTests: [(String, (ImplicitReturnConfigurationTests) -> () throws -> Void)] = [
("testImplicitReturnConfigurationFromDictionary", testImplicitReturnConfigurationFromDictionary),
("testImplicitReturnConfigurationThrowsOnUnrecognizedModifierGroup", testImplicitReturnConfigurationThrowsOnUnrecognizedModifierGroup)
]
}
extension ImplicitReturnRuleTests {
static var allTests: [(String, (ImplicitReturnRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testOnlyClosureKindIncluded", testOnlyClosureKindIncluded),
("testOnlyFunctionKindIncluded", testOnlyFunctionKindIncluded),
("testOnlyGetterKindIncluded", testOnlyGetterKindIncluded)
]
}
extension ImplicitlyUnwrappedOptionalConfigurationTests {
static var allTests: [(String, (ImplicitlyUnwrappedOptionalConfigurationTests) -> () throws -> Void)] = [
("testImplicitlyUnwrappedOptionalConfigurationProperlyAppliesConfigurationFromDictionary", testImplicitlyUnwrappedOptionalConfigurationProperlyAppliesConfigurationFromDictionary),
("testImplicitlyUnwrappedOptionalConfigurationThrowsOnBadConfig", testImplicitlyUnwrappedOptionalConfigurationThrowsOnBadConfig)
]
}
extension ImplicitlyUnwrappedOptionalRuleTests {
static var allTests: [(String, (ImplicitlyUnwrappedOptionalRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testImplicitlyUnwrappedOptionalRuleDefaultConfiguration", testImplicitlyUnwrappedOptionalRuleDefaultConfiguration),
("testImplicitlyUnwrappedOptionalRuleWarnsOnOutletsInAllMode", testImplicitlyUnwrappedOptionalRuleWarnsOnOutletsInAllMode)
]
}
extension IndentationWidthRuleTests {
static var allTests: [(String, (IndentationWidthRuleTests) -> () throws -> Void)] = [
("testFirstLineIndentation", testFirstLineIndentation),
("testMixedTabSpaceIndentation", testMixedTabSpaceIndentation),
("testMixedTabsAndSpacesIndentation", testMixedTabsAndSpacesIndentation),
("testKeepingIndentation", testKeepingIndentation),
("testIndentationLength", testIndentationLength),
("testUnindentation", testUnindentation),
("testEmptyLinesBetween", testEmptyLinesBetween),
("testsBrackets", testsBrackets),
("testCommentLines", testCommentLines),
("testDuplicateWarningAvoidanceMechanism", testDuplicateWarningAvoidanceMechanism)
]
}
extension InertDeferRuleTests {
static var allTests: [(String, (InertDeferRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension IntegrationTests {
static var allTests: [(String, (IntegrationTests) -> () throws -> Void)] = [
("testSwiftLintLints", testSwiftLintLints),
("testSwiftLintAutoCorrects", testSwiftLintAutoCorrects),
("testSimulateHomebrewTest", testSimulateHomebrewTest),
("testSimulateHomebrewTestWithDisableSourceKit", testSimulateHomebrewTestWithDisableSourceKit)
]
}
extension IsDisjointRuleTests {
static var allTests: [(String, (IsDisjointRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension JoinedDefaultParameterRuleTests {
static var allTests: [(String, (JoinedDefaultParameterRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LargeTupleRuleTests {
static var allTests: [(String, (LargeTupleRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LastWhereRuleTests {
static var allTests: [(String, (LastWhereRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LegacyCGGeometryFunctionsRuleTests {
static var allTests: [(String, (LegacyCGGeometryFunctionsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LegacyConstantRuleTests {
static var allTests: [(String, (LegacyConstantRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LegacyConstructorRuleTests {
static var allTests: [(String, (LegacyConstructorRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LegacyHashingRuleTests {
static var allTests: [(String, (LegacyHashingRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LegacyMultipleRuleTests {
static var allTests: [(String, (LegacyMultipleRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LegacyNSGeometryFunctionsRuleTests {
static var allTests: [(String, (LegacyNSGeometryFunctionsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LegacyRandomRuleTests {
static var allTests: [(String, (LegacyRandomRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LetVarWhitespaceRuleTests {
static var allTests: [(String, (LetVarWhitespaceRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LineEndingTests {
static var allTests: [(String, (LineEndingTests) -> () throws -> Void)] = [
("testCarriageReturnDoesNotCauseError", testCarriageReturnDoesNotCauseError)
]
}
extension LineLengthConfigurationTests {
static var allTests: [(String, (LineLengthConfigurationTests) -> () throws -> Void)] = [
("testLineLengthConfigurationInitializerSetsLength", testLineLengthConfigurationInitializerSetsLength),
("testLineLengthConfigurationInitialiserSetsIgnoresURLs", testLineLengthConfigurationInitialiserSetsIgnoresURLs),
("testLineLengthConfigurationInitialiserSetsIgnoresFunctionDeclarations", testLineLengthConfigurationInitialiserSetsIgnoresFunctionDeclarations),
("testLineLengthConfigurationInitialiserSetsIgnoresComments", testLineLengthConfigurationInitialiserSetsIgnoresComments),
("testLineLengthConfigurationInitialiserSetsIgnoresInterpolatedStrings", testLineLengthConfigurationInitialiserSetsIgnoresInterpolatedStrings),
("testLineLengthConfigurationParams", testLineLengthConfigurationParams),
("testLineLengthConfigurationPartialParams", testLineLengthConfigurationPartialParams),
("testLineLengthConfigurationThrowsOnBadConfig", testLineLengthConfigurationThrowsOnBadConfig),
("testLineLengthConfigurationThrowsOnBadConfigValues", testLineLengthConfigurationThrowsOnBadConfigValues),
("testLineLengthConfigurationApplyConfigurationWithArray", testLineLengthConfigurationApplyConfigurationWithArray),
("testLineLengthConfigurationApplyConfigurationWithDictionary", testLineLengthConfigurationApplyConfigurationWithDictionary),
("testLineLengthConfigurationCompares", testLineLengthConfigurationCompares)
]
}
extension LineLengthRuleTests {
static var allTests: [(String, (LineLengthRuleTests) -> () throws -> Void)] = [
("testLineLength", testLineLength),
("testLineLengthWithIgnoreFunctionDeclarationsEnabled", testLineLengthWithIgnoreFunctionDeclarationsEnabled),
("testLineLengthWithIgnoreCommentsEnabled", testLineLengthWithIgnoreCommentsEnabled),
("testLineLengthWithIgnoreURLsEnabled", testLineLengthWithIgnoreURLsEnabled),
("testLineLengthWithIgnoreInterpolatedStringsTrue", testLineLengthWithIgnoreInterpolatedStringsTrue),
("testLineLengthWithIgnoreInterpolatedStringsFalse", testLineLengthWithIgnoreInterpolatedStringsFalse)
]
}
extension LinterCacheTests {
static var allTests: [(String, (LinterCacheTests) -> () throws -> Void)] = [
("testUnchangedFilesReusesCache", testUnchangedFilesReusesCache),
("testConfigFileReorderedReusesCache", testConfigFileReorderedReusesCache),
("testConfigFileWhitespaceAndCommentsChangedOrAddedOrRemovedReusesCache", testConfigFileWhitespaceAndCommentsChangedOrAddedOrRemovedReusesCache),
("testConfigFileUnrelatedKeysChangedOrAddedOrRemovedReusesCache", testConfigFileUnrelatedKeysChangedOrAddedOrRemovedReusesCache),
("testChangedFileCausesJustThatFileToBeLintWithCacheUsedForAllOthers", testChangedFileCausesJustThatFileToBeLintWithCacheUsedForAllOthers),
("testFileRemovedPreservesThatFileInTheCacheAndDoesntCauseAnyOtherFilesToBeLinted", testFileRemovedPreservesThatFileInTheCacheAndDoesntCauseAnyOtherFilesToBeLinted),
("testCustomRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted", testCustomRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted),
("testDisabledRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted", testDisabledRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted),
("testOptInRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted", testOptInRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted),
("testEnabledRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted", testEnabledRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted),
("testWhitelistRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted", testWhitelistRulesChangedOrAddedOrRemovedCausesAllFilesToBeReLinted),
("testRuleConfigurationChangedOrAddedOrRemovedCausesAllFilesToBeReLinted", testRuleConfigurationChangedOrAddedOrRemovedCausesAllFilesToBeReLinted),
("testSwiftVersionChangedRemovedCausesAllFilesToBeReLinted", testSwiftVersionChangedRemovedCausesAllFilesToBeReLinted)
]
}
extension LiteralExpressionEndIdentationRuleTests {
static var allTests: [(String, (LiteralExpressionEndIdentationRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension LowerACLThanParentRuleTests {
static var allTests: [(String, (LowerACLThanParentRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension MissingDocsRuleConfigurationTests {
static var allTests: [(String, (MissingDocsRuleConfigurationTests) -> () throws -> Void)] = [
("testDescriptionEmpty", testDescriptionEmpty),
("testDescriptionSingleServety", testDescriptionSingleServety),
("testDescriptionMultipleSeverities", testDescriptionMultipleSeverities),
("testDescriptionMultipleAcls", testDescriptionMultipleAcls),
("testParsingSingleServety", testParsingSingleServety),
("testParsingMultipleSeverities", testParsingMultipleSeverities),
("testParsingMultipleAcls", testParsingMultipleAcls),
("testInvalidServety", testInvalidServety),
("testInvalidAcl", testInvalidAcl),
("testInvalidDuplicateAcl", testInvalidDuplicateAcl)
]
}
extension MissingDocsRuleTests {
static var allTests: [(String, (MissingDocsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ModifierOrderTests {
static var allTests: [(String, (ModifierOrderTests) -> () throws -> Void)] = [
("testAttributeTypeMethod", testAttributeTypeMethod),
("testRightOrderedModifierGroups", testRightOrderedModifierGroups),
("testAtPrefixedGroup", testAtPrefixedGroup),
("testNonSpecifiedModifiersDontInterfere", testNonSpecifiedModifiersDontInterfere),
("testCorrectionsAreAppliedCorrectly", testCorrectionsAreAppliedCorrectly),
("testCorrectionsAreNotAppliedToIrrelevantModifier", testCorrectionsAreNotAppliedToIrrelevantModifier),
("testTypeMethodClassCorrection", testTypeMethodClassCorrection),
("testViolationMessage", testViolationMessage)
]
}
extension MultilineArgumentsBracketsRuleTests {
static var allTests: [(String, (MultilineArgumentsBracketsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension MultilineArgumentsRuleTests {
static var allTests: [(String, (MultilineArgumentsRuleTests) -> () throws -> Void)] = [
("testMultilineArgumentsWithDefaultConfiguration", testMultilineArgumentsWithDefaultConfiguration),
("testMultilineArgumentsWithWithNextLine", testMultilineArgumentsWithWithNextLine),
("testMultilineArgumentsWithWithSameLine", testMultilineArgumentsWithWithSameLine),
("testMultilineArgumentsWithOnlyEnforceAfterFirstClosureOnFirstLine", testMultilineArgumentsWithOnlyEnforceAfterFirstClosureOnFirstLine)
]
}
extension MultilineFunctionChainsRuleTests {
static var allTests: [(String, (MultilineFunctionChainsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension MultilineLiteralBracketsRuleTests {
static var allTests: [(String, (MultilineLiteralBracketsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension MultilineParametersBracketsRuleTests {
static var allTests: [(String, (MultilineParametersBracketsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension MultilineParametersRuleTests {
static var allTests: [(String, (MultilineParametersRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension MultipleClosuresWithTrailingClosureRuleTests {
static var allTests: [(String, (MultipleClosuresWithTrailingClosureRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NSLocalizedStringKeyRuleTests {
static var allTests: [(String, (NSLocalizedStringKeyRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NSLocalizedStringRequireBundleRuleTests {
static var allTests: [(String, (NSLocalizedStringRequireBundleRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NSObjectPreferIsEqualRuleTests {
static var allTests: [(String, (NSObjectPreferIsEqualRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NestingRuleTests {
static var allTests: [(String, (NestingRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NimbleOperatorRuleTests {
static var allTests: [(String, (NimbleOperatorRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NoExtensionAccessModifierRuleTests {
static var allTests: [(String, (NoExtensionAccessModifierRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NoFallthroughOnlyRuleTests {
static var allTests: [(String, (NoFallthroughOnlyRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NoGroupingExtensionRuleTests {
static var allTests: [(String, (NoGroupingExtensionRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NoSpaceInMethodCallRuleTests {
static var allTests: [(String, (NoSpaceInMethodCallRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NotificationCenterDetachmentRuleTests {
static var allTests: [(String, (NotificationCenterDetachmentRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension NumberSeparatorRuleTests {
static var allTests: [(String, (NumberSeparatorRuleTests) -> () throws -> Void)] = [
("testNumberSeparatorWithDefaultConfiguration", testNumberSeparatorWithDefaultConfiguration),
("testNumberSeparatorWithMinimumLength", testNumberSeparatorWithMinimumLength),
("testNumberSeparatorWithMinimumFractionLength", testNumberSeparatorWithMinimumFractionLength),
("testNumberSeparatorWithExcludeRanges", testNumberSeparatorWithExcludeRanges)
]
}
extension ObjectLiteralRuleTests {
static var allTests: [(String, (ObjectLiteralRuleTests) -> () throws -> Void)] = [
("testObjectLiteralWithDefaultConfiguration", testObjectLiteralWithDefaultConfiguration),
("testObjectLiteralWithImageLiteral", testObjectLiteralWithImageLiteral),
("testObjectLiteralWithColorLiteral", testObjectLiteralWithColorLiteral),
("testObjectLiteralWithImageAndColorLiteral", testObjectLiteralWithImageAndColorLiteral)
]
}
extension OpeningBraceRuleTests {
static var allTests: [(String, (OpeningBraceRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension OperatorFunctionWhitespaceRuleTests {
static var allTests: [(String, (OperatorFunctionWhitespaceRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension OperatorUsageWhitespaceRuleTests {
static var allTests: [(String, (OperatorUsageWhitespaceRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension OptionalEnumCaseMatchingRuleTests {
static var allTests: [(String, (OptionalEnumCaseMatchingRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension OverriddenSuperCallRuleTests {
static var allTests: [(String, (OverriddenSuperCallRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension OverrideInExtensionRuleTests {
static var allTests: [(String, (OverrideInExtensionRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ParserDiagnosticsTests {
static var allTests: [(String, (ParserDiagnosticsTests) -> () throws -> Void)] = [
("testFileWithParserDiagnostics", testFileWithParserDiagnostics),
("testFileWithoutParserDiagnostics", testFileWithoutParserDiagnostics)
]
}
extension PatternMatchingKeywordsRuleTests {
static var allTests: [(String, (PatternMatchingKeywordsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension PreferSelfTypeOverTypeOfSelfRuleTests {
static var allTests: [(String, (PreferSelfTypeOverTypeOfSelfRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension PreferZeroOverExplicitInitRuleTests {
static var allTests: [(String, (PreferZeroOverExplicitInitRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension PrefixedTopLevelConstantRuleTests {
static var allTests: [(String, (PrefixedTopLevelConstantRuleTests) -> () throws -> Void)] = [
("testDefaultConfiguration", testDefaultConfiguration),
("testPrivateOnly", testPrivateOnly)
]
}
extension PrivateActionRuleTests {
static var allTests: [(String, (PrivateActionRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension PrivateOutletRuleTests {
static var allTests: [(String, (PrivateOutletRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testWithAllowPrivateSet", testWithAllowPrivateSet)
]
}
extension PrivateOverFilePrivateRuleTests {
static var allTests: [(String, (PrivateOverFilePrivateRuleTests) -> () throws -> Void)] = [
("testPrivateOverFilePrivateWithDefaultConfiguration", testPrivateOverFilePrivateWithDefaultConfiguration),
("testPrivateOverFilePrivateValidatingExtensions", testPrivateOverFilePrivateValidatingExtensions),
("testPrivateOverFilePrivateNotValidatingExtensions", testPrivateOverFilePrivateNotValidatingExtensions)
]
}
extension PrivateUnitTestRuleTests {
static var allTests: [(String, (PrivateUnitTestRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ProhibitedInterfaceBuilderRuleTests {
static var allTests: [(String, (ProhibitedInterfaceBuilderRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ProhibitedSuperRuleTests {
static var allTests: [(String, (ProhibitedSuperRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ProtocolPropertyAccessorsOrderRuleTests {
static var allTests: [(String, (ProtocolPropertyAccessorsOrderRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension QuickDiscouragedCallRuleTests {
static var allTests: [(String, (QuickDiscouragedCallRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension QuickDiscouragedFocusedTestRuleTests {
static var allTests: [(String, (QuickDiscouragedFocusedTestRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension QuickDiscouragedPendingTestRuleTests {
static var allTests: [(String, (QuickDiscouragedPendingTestRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RawValueForCamelCasedCodableEnumRuleTests {
static var allTests: [(String, (RawValueForCamelCasedCodableEnumRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ReduceBooleanRuleTests {
static var allTests: [(String, (ReduceBooleanRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ReduceIntoRuleTests {
static var allTests: [(String, (ReduceIntoRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RedundantDiscardableLetRuleTests {
static var allTests: [(String, (RedundantDiscardableLetRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RedundantNilCoalescingRuleTests {
static var allTests: [(String, (RedundantNilCoalescingRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RedundantObjcAttributeRuleTests {
static var allTests: [(String, (RedundantObjcAttributeRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RedundantOptionalInitializationRuleTests {
static var allTests: [(String, (RedundantOptionalInitializationRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RedundantSetAccessControlRuleTests {
static var allTests: [(String, (RedundantSetAccessControlRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RedundantStringEnumValueRuleTests {
static var allTests: [(String, (RedundantStringEnumValueRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RedundantTypeAnnotationRuleTests {
static var allTests: [(String, (RedundantTypeAnnotationRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RedundantVoidReturnRuleTests {
static var allTests: [(String, (RedundantVoidReturnRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RegionTests {
static var allTests: [(String, (RegionTests) -> () throws -> Void)] = [
("testNoRegionsInEmptyFile", testNoRegionsInEmptyFile),
("testNoRegionsInFileWithNoCommands", testNoRegionsInFileWithNoCommands),
("testRegionsFromSingleCommand", testRegionsFromSingleCommand),
("testRegionsFromMatchingPairCommands", testRegionsFromMatchingPairCommands),
("testRegionsFromThreeCommandForSingleLine", testRegionsFromThreeCommandForSingleLine),
("testSeveralRegionsFromSeveralCommands", testSeveralRegionsFromSeveralCommands)
]
}
extension ReporterTests {
static var allTests: [(String, (ReporterTests) -> () throws -> Void)] = [
("testReporterFromString", testReporterFromString),
("testXcodeReporter", testXcodeReporter),
("testEmojiReporter", testEmojiReporter),
("testGitHubActionsLoggingReporter", testGitHubActionsLoggingReporter),
("testGitLabJUnitReporter", testGitLabJUnitReporter),
("testJSONReporter", testJSONReporter),
("testCSVReporter", testCSVReporter),
("testCheckstyleReporter", testCheckstyleReporter),
("testJunitReporter", testJunitReporter),
("testHTMLReporter", testHTMLReporter),
("testSonarQubeReporter", testSonarQubeReporter),
("testMarkdownReporter", testMarkdownReporter)
]
}
extension RequiredDeinitRuleTests {
static var allTests: [(String, (RequiredDeinitRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RequiredEnumCaseRuleTestCase {
static var allTests: [(String, (RequiredEnumCaseRuleTestCase) -> () throws -> Void)] = [
("testRequiredCaseHashValue", testRequiredCaseHashValue),
("testRequiredCaseEquatableReturnsTrue", testRequiredCaseEquatableReturnsTrue),
("testRequiredCaseEquatableReturnsFalseBecauseOfDifferentName", testRequiredCaseEquatableReturnsFalseBecauseOfDifferentName),
("testConsoleDescriptionReturnsAllConfiguredProtocols", testConsoleDescriptionReturnsAllConfiguredProtocols),
("testConsoleDescriptionReturnsNoConfiguredProtocols", testConsoleDescriptionReturnsNoConfiguredProtocols),
("testRegisterProtocolCasesRegistersCasesWithSpecifiedSeverity", testRegisterProtocolCasesRegistersCasesWithSpecifiedSeverity),
("testRegisterProtocols", testRegisterProtocols),
("testApplyThrowsErrorBecausePassedConfigurationCantBeCast", testApplyThrowsErrorBecausePassedConfigurationCantBeCast),
("testApplyRegistersProtocols", testApplyRegistersProtocols),
("testEqualsReturnsTrue", testEqualsReturnsTrue),
("testEqualsReturnsFalseBecauseProtocolsArentEqual", testEqualsReturnsFalseBecauseProtocolsArentEqual),
("testEqualsReturnsFalseBecauseSeverityIsntEqual", testEqualsReturnsFalseBecauseSeverityIsntEqual)
]
}
extension ReturnArrowWhitespaceRuleTests {
static var allTests: [(String, (ReturnArrowWhitespaceRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension RuleConfigurationTests {
static var allTests: [(String, (RuleConfigurationTests) -> () throws -> Void)] = [
("testNameConfigurationSetsCorrectly", testNameConfigurationSetsCorrectly),
("testNameConfigurationThrowsOnBadConfig", testNameConfigurationThrowsOnBadConfig),
("testNameConfigurationMinLengthThreshold", testNameConfigurationMinLengthThreshold),
("testNameConfigurationMaxLengthThreshold", testNameConfigurationMaxLengthThreshold),
("testNestingConfigurationSetsCorrectly", testNestingConfigurationSetsCorrectly),
("testNestingConfigurationThrowsOnBadConfig", testNestingConfigurationThrowsOnBadConfig),
("testSeverityConfigurationFromString", testSeverityConfigurationFromString),
("testSeverityConfigurationFromDictionary", testSeverityConfigurationFromDictionary),
("testSeverityConfigurationThrowsOnBadConfig", testSeverityConfigurationThrowsOnBadConfig),
("testSeverityLevelConfigParams", testSeverityLevelConfigParams),
("testSeverityLevelConfigPartialParams", testSeverityLevelConfigPartialParams),
("testSeverityLevelConfigApplyNilErrorValue", testSeverityLevelConfigApplyNilErrorValue),
("testSeverityLevelConfigApplyMissingErrorValue", testSeverityLevelConfigApplyMissingErrorValue),
("testRegexConfigurationThrows", testRegexConfigurationThrows),
("testRegexRuleDescription", testRegexRuleDescription),
("testTrailingWhitespaceConfigurationThrowsOnBadConfig", testTrailingWhitespaceConfigurationThrowsOnBadConfig),
("testTrailingWhitespaceConfigurationInitializerSetsIgnoresEmptyLines", testTrailingWhitespaceConfigurationInitializerSetsIgnoresEmptyLines),
("testTrailingWhitespaceConfigurationInitializerSetsIgnoresComments", testTrailingWhitespaceConfigurationInitializerSetsIgnoresComments),
("testTrailingWhitespaceConfigurationApplyConfigurationSetsIgnoresEmptyLines", testTrailingWhitespaceConfigurationApplyConfigurationSetsIgnoresEmptyLines),
("testTrailingWhitespaceConfigurationApplyConfigurationSetsIgnoresComments", testTrailingWhitespaceConfigurationApplyConfigurationSetsIgnoresComments),
("testTrailingWhitespaceConfigurationCompares", testTrailingWhitespaceConfigurationCompares),
("testTrailingWhitespaceConfigurationApplyConfigurationUpdatesSeverityConfiguration", testTrailingWhitespaceConfigurationApplyConfigurationUpdatesSeverityConfiguration),
("testOverridenSuperCallConfigurationFromDictionary", testOverridenSuperCallConfigurationFromDictionary),
("testModifierOrderConfigurationFromDictionary", testModifierOrderConfigurationFromDictionary),
("testModifierOrderConfigurationThrowsOnUnrecognizedModifierGroup", testModifierOrderConfigurationThrowsOnUnrecognizedModifierGroup),
("testModifierOrderConfigurationThrowsOnNonModifiableGroup", testModifierOrderConfigurationThrowsOnNonModifiableGroup),
("testComputedAccessorsOrderRuleConfiguration", testComputedAccessorsOrderRuleConfiguration)
]
}
extension RuleTests {
static var allTests: [(String, (RuleTests) -> () throws -> Void)] = [
("testRuleIsEqualTo", testRuleIsEqualTo),
("testRuleIsNotEqualTo", testRuleIsNotEqualTo),
("testRuleArraysWithDifferentCountsNotEqual", testRuleArraysWithDifferentCountsNotEqual),
("testSeverityLevelRuleInitsWithConfigDictionary", testSeverityLevelRuleInitsWithConfigDictionary),
("testSeverityLevelRuleInitsWithWarningOnlyConfigDictionary", testSeverityLevelRuleInitsWithWarningOnlyConfigDictionary),
("testSeverityLevelRuleInitsWithErrorOnlyConfigDictionary", testSeverityLevelRuleInitsWithErrorOnlyConfigDictionary),
("testSeverityLevelRuleInitsWithConfigArray", testSeverityLevelRuleInitsWithConfigArray),
("testSeverityLevelRuleInitsWithSingleValueConfigArray", testSeverityLevelRuleInitsWithSingleValueConfigArray),
("testSeverityLevelRuleInitsWithLiteral", testSeverityLevelRuleInitsWithLiteral),
("testSeverityLevelRuleNotEqual", testSeverityLevelRuleNotEqual),
("testDifferentSeverityLevelRulesNotEqual", testDifferentSeverityLevelRulesNotEqual)
]
}
extension RulesTests {
static var allTests: [(String, (RulesTests) -> () throws -> Void)] = [
("testLeadingWhitespace", testLeadingWhitespace),
("testMark", testMark),
("testRequiredEnumCase", testRequiredEnumCase),
("testTrailingNewline", testTrailingNewline),
("testOrphanedDocComment", testOrphanedDocComment)
]
}
extension ShorthandOperatorRuleTests {
static var allTests: [(String, (ShorthandOperatorRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension SingleTestClassRuleTests {
static var allTests: [(String, (SingleTestClassRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension SortedFirstLastRuleTests {
static var allTests: [(String, (SortedFirstLastRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension SortedImportsRuleTests {
static var allTests: [(String, (SortedImportsRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension SourceKitCrashTests {
static var allTests: [(String, (SourceKitCrashTests) -> () throws -> Void)] = [
("testAssertHandlerIsNotCalledOnNormalFile", testAssertHandlerIsNotCalledOnNormalFile),
("testAssertHandlerIsCalledOnFileThatCrashedSourceKitService", testAssertHandlerIsCalledOnFileThatCrashedSourceKitService),
("testRulesWithFileThatCrashedSourceKitService", testRulesWithFileThatCrashedSourceKitService)
]
}
extension StatementPositionRuleTests {
static var allTests: [(String, (StatementPositionRuleTests) -> () throws -> Void)] = [
("testStatementPosition", testStatementPosition),
("testStatementPositionUncuddled", testStatementPositionUncuddled)
]
}
extension StaticOperatorRuleTests {
static var allTests: [(String, (StaticOperatorRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension StrictFilePrivateRuleTests {
static var allTests: [(String, (StrictFilePrivateRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension StrongIBOutletRuleTests {
static var allTests: [(String, (StrongIBOutletRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension SwiftVersionTests {
static var allTests: [(String, (SwiftVersionTests) -> () throws -> Void)] = [
("testDetectSwiftVersion", testDetectSwiftVersion)
]
}
extension SwitchCaseAlignmentRuleTests {
static var allTests: [(String, (SwitchCaseAlignmentRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testSwitchCaseAlignmentWithoutIndentedCases", testSwitchCaseAlignmentWithoutIndentedCases),
("testSwitchCaseAlignmentWithIndentedCases", testSwitchCaseAlignmentWithIndentedCases)
]
}
extension SwitchCaseOnNewlineRuleTests {
static var allTests: [(String, (SwitchCaseOnNewlineRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension SyntacticSugarRuleTests {
static var allTests: [(String, (SyntacticSugarRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension TodoRuleTests {
static var allTests: [(String, (TodoRuleTests) -> () throws -> Void)] = [
("testTodo", testTodo),
("testTodoMessage", testTodoMessage),
("testFixMeMessage", testFixMeMessage)
]
}
extension ToggleBoolRuleTests {
static var allTests: [(String, (ToggleBoolRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension TrailingClosureConfigurationTests {
static var allTests: [(String, (TrailingClosureConfigurationTests) -> () throws -> Void)] = [
("testDefaultConfiguration", testDefaultConfiguration),
("testApplyingCustomConfiguration", testApplyingCustomConfiguration)
]
}
extension TrailingClosureRuleTests {
static var allTests: [(String, (TrailingClosureRuleTests) -> () throws -> Void)] = [
("testDefaultConfiguration", testDefaultConfiguration),
("testWithOnlySingleMutedParameterEnabled", testWithOnlySingleMutedParameterEnabled)
]
}
extension TrailingCommaRuleTests {
static var allTests: [(String, (TrailingCommaRuleTests) -> () throws -> Void)] = [
("testTrailingCommaRuleWithDefaultConfiguration", testTrailingCommaRuleWithDefaultConfiguration),
("testTrailingCommaRuleWithMandatoryComma", testTrailingCommaRuleWithMandatoryComma)
]
}
extension TrailingSemicolonRuleTests {
static var allTests: [(String, (TrailingSemicolonRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension TrailingWhitespaceTests {
static var allTests: [(String, (TrailingWhitespaceTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration),
("testWithIgnoresEmptyLinesEnabled", testWithIgnoresEmptyLinesEnabled),
("testWithIgnoresCommentsDisabled", testWithIgnoresCommentsDisabled)
]
}
extension TypeBodyLengthRuleTests {
static var allTests: [(String, (TypeBodyLengthRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension TypeContentsOrderRuleTests {
static var allTests: [(String, (TypeContentsOrderRuleTests) -> () throws -> Void)] = [
("testTypeContentsOrderWithDefaultConfiguration", testTypeContentsOrderWithDefaultConfiguration),
("testTypeContentsOrderReversedOrder", testTypeContentsOrderReversedOrder),
("testTypeContentsOrderGroupedOrder", testTypeContentsOrderGroupedOrder)
]
}
extension TypeNameRuleTests {
static var allTests: [(String, (TypeNameRuleTests) -> () throws -> Void)] = [
("testTypeName", testTypeName),
("testTypeNameWithAllowedSymbols", testTypeNameWithAllowedSymbols),
("testTypeNameWithAllowedSymbolsAndViolation", testTypeNameWithAllowedSymbolsAndViolation),
("testTypeNameWithIgnoreStartWithLowercase", testTypeNameWithIgnoreStartWithLowercase)
]
}
extension UnavailableFunctionRuleTests {
static var allTests: [(String, (UnavailableFunctionRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnneededBreakInSwitchRuleTests {
static var allTests: [(String, (UnneededBreakInSwitchRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnneededNotificationCenterRemovalRuleTests {
static var allTests: [(String, (UnneededNotificationCenterRemovalRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnneededParenthesesInClosureArgumentRuleTests {
static var allTests: [(String, (UnneededParenthesesInClosureArgumentRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnownedVariableCaptureRuleTests {
static var allTests: [(String, (UnownedVariableCaptureRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UntypedErrorInCatchRuleTests {
static var allTests: [(String, (UntypedErrorInCatchRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnusedCaptureListRuleTests {
static var allTests: [(String, (UnusedCaptureListRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnusedClosureParameterRuleTests {
static var allTests: [(String, (UnusedClosureParameterRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnusedControlFlowLabelRuleTests {
static var allTests: [(String, (UnusedControlFlowLabelRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnusedDeclarationRuleTests {
static var allTests: [(String, (UnusedDeclarationRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnusedEnumeratedRuleTests {
static var allTests: [(String, (UnusedEnumeratedRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnusedImportRuleTests {
static var allTests: [(String, (UnusedImportRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension UnusedOptionalBindingRuleTests {
static var allTests: [(String, (UnusedOptionalBindingRuleTests) -> () throws -> Void)] = [
("testDefaultConfiguration", testDefaultConfiguration),
("testIgnoreOptionalTryEnabled", testIgnoreOptionalTryEnabled)
]
}
extension UnusedSetterValueRuleTests {
static var allTests: [(String, (UnusedSetterValueRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension ValidIBInspectableRuleTests {
static var allTests: [(String, (ValidIBInspectableRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension VerticalParameterAlignmentOnCallRuleTests {
static var allTests: [(String, (VerticalParameterAlignmentOnCallRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension VerticalParameterAlignmentRuleTests {
static var allTests: [(String, (VerticalParameterAlignmentRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension VerticalWhitespaceBetweenCasesRuleTests {
static var allTests: [(String, (VerticalWhitespaceBetweenCasesRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension VerticalWhitespaceClosingBracesRuleTests {
static var allTests: [(String, (VerticalWhitespaceClosingBracesRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension VerticalWhitespaceOpeningBracesRuleTests {
static var allTests: [(String, (VerticalWhitespaceOpeningBracesRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension VerticalWhitespaceRuleTests {
static var allTests: [(String, (VerticalWhitespaceRuleTests) -> () throws -> Void)] = [
("testVerticalWhitespaceWithDefaultConfiguration", testVerticalWhitespaceWithDefaultConfiguration),
("testAttributesWithMaxEmptyLines", testAttributesWithMaxEmptyLines),
("testAutoCorrectionWithMaxEmptyLines", testAutoCorrectionWithMaxEmptyLines),
("testViolationMessageWithMaxEmptyLines", testViolationMessageWithMaxEmptyLines),
("testViolationMessageWithDefaultConfiguration", testViolationMessageWithDefaultConfiguration)
]
}
extension VoidReturnRuleTests {
static var allTests: [(String, (VoidReturnRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension WeakDelegateRuleTests {
static var allTests: [(String, (WeakDelegateRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension XCTFailMessageRuleTests {
static var allTests: [(String, (XCTFailMessageRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
extension XCTSpecificMatcherRuleTests {
static var allTests: [(String, (XCTSpecificMatcherRuleTests) -> () throws -> Void)] = [
("testRule", testRule),
("testEqualTrue", testEqualTrue),
("testEqualFalse", testEqualFalse),
("testEqualNil", testEqualNil),
("testNotEqualTrue", testNotEqualTrue),
("testNotEqualFalse", testNotEqualFalse),
("testNotEqualNil", testNotEqualNil),
("testEqualOptionalFalse", testEqualOptionalFalse),
("testEqualUnwrappedOptionalFalse", testEqualUnwrappedOptionalFalse),
("testEqualNilNil", testEqualNilNil),
("testEqualTrueTrue", testEqualTrueTrue),
("testEqualFalseFalse", testEqualFalseFalse),
("testNotEqualNilNil", testNotEqualNilNil),
("testNotEqualTrueTrue", testNotEqualTrueTrue),
("testNotEqualFalseFalse", testNotEqualFalseFalse)
]
}
extension YamlParserTests {
static var allTests: [(String, (YamlParserTests) -> () throws -> Void)] = [
("testParseEmptyString", testParseEmptyString),
("testParseValidString", testParseValidString),
("testParseReplacesEnvVar", testParseReplacesEnvVar),
("testParseTreatNoAsString", testParseTreatNoAsString),
("testParseTreatYesAsString", testParseTreatYesAsString),
("testParseTreatOnAsString", testParseTreatOnAsString),
("testParseTreatOffAsString", testParseTreatOffAsString),
("testParseInvalidStringThrows", testParseInvalidStringThrows)
]
}
extension YamlSwiftLintTests {
static var allTests: [(String, (YamlSwiftLintTests) -> () throws -> Void)] = [
("testFlattenYaml", testFlattenYaml)
]
}
extension YodaConditionRuleTests {
static var allTests: [(String, (YodaConditionRuleTests) -> () throws -> Void)] = [
("testWithDefaultConfiguration", testWithDefaultConfiguration)
]
}
XCTMain([
testCase(AccessControlLevelTests.allTests),
testCase(AnyObjectProtocolRuleTests.allTests),
testCase(ArrayInitRuleTests.allTests),
testCase(AttributesRuleTests.allTests),
testCase(BlockBasedKVORuleTests.allTests),
testCase(ClassDelegateProtocolRuleTests.allTests),
testCase(ClosingBraceRuleTests.allTests),
testCase(ClosureBodyLengthRuleTests.allTests),
testCase(ClosureEndIndentationRuleTests.allTests),
testCase(ClosureParameterPositionRuleTests.allTests),
testCase(ClosureSpacingRuleTests.allTests),
testCase(CollectingRuleTests.allTests),
testCase(CollectionAlignmentRuleTests.allTests),
testCase(ColonRuleTests.allTests),
testCase(CommaRuleTests.allTests),
testCase(CommandTests.allTests),
testCase(CompilerProtocolInitRuleTests.allTests),
testCase(ComputedAccessorsOrderRuleTests.allTests),
testCase(ConditionalReturnsOnNewlineRuleTests.allTests),
testCase(ConfigurationAliasesTests.allTests),
testCase(ConfigurationTests.allTests),
testCase(ContainsOverFilterCountRuleTests.allTests),
testCase(ContainsOverFilterIsEmptyRuleTests.allTests),
testCase(ContainsOverFirstNotNilRuleTests.allTests),
testCase(ContainsOverRangeNilComparisonRuleTests.allTests),
testCase(ControlStatementRuleTests.allTests),
testCase(ConvenienceTypeRuleTests.allTests),
testCase(CustomRulesTests.allTests),
testCase(CyclomaticComplexityConfigurationTests.allTests),
testCase(CyclomaticComplexityRuleTests.allTests),
testCase(DeploymentTargetConfigurationTests.allTests),
testCase(DeploymentTargetRuleTests.allTests),
testCase(DisableAllTests.allTests),
testCase(DiscardedNotificationCenterObserverRuleTests.allTests),
testCase(DiscouragedDirectInitRuleTests.allTests),
testCase(DiscouragedObjectLiteralRuleTests.allTests),
testCase(DiscouragedOptionalBooleanRuleTests.allTests),
testCase(DiscouragedOptionalCollectionRuleTests.allTests),
testCase(DuplicateEnumCasesRuleTests.allTests),
testCase(DuplicateImportsRuleTests.allTests),
testCase(DynamicInlineRuleTests.allTests),
testCase(EmptyCollectionLiteralRuleTests.allTests),
testCase(EmptyCountRuleTests.allTests),
testCase(EmptyEnumArgumentsRuleTests.allTests),
testCase(EmptyParametersRuleTests.allTests),
testCase(EmptyParenthesesWithTrailingClosureRuleTests.allTests),
testCase(EmptyStringRuleTests.allTests),
testCase(EmptyXCTestMethodRuleTests.allTests),
testCase(EnumCaseAssociatedValuesLengthRuleTests.allTests),
testCase(ExampleTests.allTests),
testCase(ExpiringTodoRuleTests.allTests),
testCase(ExplicitACLRuleTests.allTests),
testCase(ExplicitEnumRawValueRuleTests.allTests),
testCase(ExplicitInitRuleTests.allTests),
testCase(ExplicitSelfRuleTests.allTests),
testCase(ExplicitTopLevelACLRuleTests.allTests),
testCase(ExplicitTypeInterfaceConfigurationTests.allTests),
testCase(ExplicitTypeInterfaceRuleTests.allTests),
testCase(ExtendedNSStringTests.allTests),
testCase(ExtendedStringTests.allTests),
testCase(ExtensionAccessModifierRuleTests.allTests),
testCase(FallthroughRuleTests.allTests),
testCase(FatalErrorMessageRuleTests.allTests),
testCase(FileHeaderRuleTests.allTests),
testCase(FileLengthRuleTests.allTests),
testCase(FileNameNoSpaceRuleTests.allTests),
testCase(FileNameRuleTests.allTests),
testCase(FileTypesOrderRuleTests.allTests),
testCase(FirstWhereRuleTests.allTests),
testCase(FlatMapOverMapReduceRuleTests.allTests),
testCase(ForWhereRuleTests.allTests),
testCase(ForceCastRuleTests.allTests),
testCase(ForceTryRuleTests.allTests),
testCase(ForceUnwrappingRuleTests.allTests),
testCase(FunctionBodyLengthRuleTests.allTests),
testCase(FunctionDefaultParameterAtEndRuleTests.allTests),
testCase(FunctionParameterCountRuleTests.allTests),
testCase(GenericTypeNameRuleTests.allTests),
testCase(GlobTests.allTests),
testCase(IBInspectableInExtensionRuleTests.allTests),
testCase(IdenticalOperandsRuleTests.allTests),
testCase(IdentifierNameRuleTests.allTests),
testCase(ImplicitGetterRuleTests.allTests),
testCase(ImplicitReturnConfigurationTests.allTests),
testCase(ImplicitReturnRuleTests.allTests),
testCase(ImplicitlyUnwrappedOptionalConfigurationTests.allTests),
testCase(ImplicitlyUnwrappedOptionalRuleTests.allTests),
testCase(IndentationWidthRuleTests.allTests),
testCase(InertDeferRuleTests.allTests),
testCase(IntegrationTests.allTests),
testCase(IsDisjointRuleTests.allTests),
testCase(JoinedDefaultParameterRuleTests.allTests),
testCase(LargeTupleRuleTests.allTests),
testCase(LastWhereRuleTests.allTests),
testCase(LegacyCGGeometryFunctionsRuleTests.allTests),
testCase(LegacyConstantRuleTests.allTests),
testCase(LegacyConstructorRuleTests.allTests),
testCase(LegacyHashingRuleTests.allTests),
testCase(LegacyMultipleRuleTests.allTests),
testCase(LegacyNSGeometryFunctionsRuleTests.allTests),
testCase(LegacyRandomRuleTests.allTests),
testCase(LetVarWhitespaceRuleTests.allTests),
testCase(LineEndingTests.allTests),
testCase(LineLengthConfigurationTests.allTests),
testCase(LineLengthRuleTests.allTests),
testCase(LinterCacheTests.allTests),
testCase(LiteralExpressionEndIdentationRuleTests.allTests),
testCase(LowerACLThanParentRuleTests.allTests),
testCase(MissingDocsRuleConfigurationTests.allTests),
testCase(MissingDocsRuleTests.allTests),
testCase(ModifierOrderTests.allTests),
testCase(MultilineArgumentsBracketsRuleTests.allTests),
testCase(MultilineArgumentsRuleTests.allTests),
testCase(MultilineFunctionChainsRuleTests.allTests),
testCase(MultilineLiteralBracketsRuleTests.allTests),
testCase(MultilineParametersBracketsRuleTests.allTests),
testCase(MultilineParametersRuleTests.allTests),
testCase(MultipleClosuresWithTrailingClosureRuleTests.allTests),
testCase(NSLocalizedStringKeyRuleTests.allTests),
testCase(NSLocalizedStringRequireBundleRuleTests.allTests),
testCase(NSObjectPreferIsEqualRuleTests.allTests),
testCase(NestingRuleTests.allTests),
testCase(NimbleOperatorRuleTests.allTests),
testCase(NoExtensionAccessModifierRuleTests.allTests),
testCase(NoFallthroughOnlyRuleTests.allTests),
testCase(NoGroupingExtensionRuleTests.allTests),
testCase(NoSpaceInMethodCallRuleTests.allTests),
testCase(NotificationCenterDetachmentRuleTests.allTests),
testCase(NumberSeparatorRuleTests.allTests),
testCase(ObjectLiteralRuleTests.allTests),
testCase(OpeningBraceRuleTests.allTests),
testCase(OperatorFunctionWhitespaceRuleTests.allTests),
testCase(OperatorUsageWhitespaceRuleTests.allTests),
testCase(OptionalEnumCaseMatchingRuleTests.allTests),
testCase(OverriddenSuperCallRuleTests.allTests),
testCase(OverrideInExtensionRuleTests.allTests),
testCase(ParserDiagnosticsTests.allTests),
testCase(PatternMatchingKeywordsRuleTests.allTests),
testCase(PreferSelfTypeOverTypeOfSelfRuleTests.allTests),
testCase(PreferZeroOverExplicitInitRuleTests.allTests),
testCase(PrefixedTopLevelConstantRuleTests.allTests),
testCase(PrivateActionRuleTests.allTests),
testCase(PrivateOutletRuleTests.allTests),
testCase(PrivateOverFilePrivateRuleTests.allTests),
testCase(PrivateUnitTestRuleTests.allTests),
testCase(ProhibitedInterfaceBuilderRuleTests.allTests),
testCase(ProhibitedSuperRuleTests.allTests),
testCase(ProtocolPropertyAccessorsOrderRuleTests.allTests),
testCase(QuickDiscouragedCallRuleTests.allTests),
testCase(QuickDiscouragedFocusedTestRuleTests.allTests),
testCase(QuickDiscouragedPendingTestRuleTests.allTests),
testCase(RawValueForCamelCasedCodableEnumRuleTests.allTests),
testCase(ReduceBooleanRuleTests.allTests),
testCase(ReduceIntoRuleTests.allTests),
testCase(RedundantDiscardableLetRuleTests.allTests),
testCase(RedundantNilCoalescingRuleTests.allTests),
testCase(RedundantObjcAttributeRuleTests.allTests),
testCase(RedundantOptionalInitializationRuleTests.allTests),
testCase(RedundantSetAccessControlRuleTests.allTests),
testCase(RedundantStringEnumValueRuleTests.allTests),
testCase(RedundantTypeAnnotationRuleTests.allTests),
testCase(RedundantVoidReturnRuleTests.allTests),
testCase(RegionTests.allTests),
testCase(ReporterTests.allTests),
testCase(RequiredDeinitRuleTests.allTests),
testCase(RequiredEnumCaseRuleTestCase.allTests),
testCase(ReturnArrowWhitespaceRuleTests.allTests),
testCase(RuleConfigurationTests.allTests),
testCase(RuleTests.allTests),
testCase(RulesTests.allTests),
testCase(ShorthandOperatorRuleTests.allTests),
testCase(SingleTestClassRuleTests.allTests),
testCase(SortedFirstLastRuleTests.allTests),
testCase(SortedImportsRuleTests.allTests),
testCase(SourceKitCrashTests.allTests),
testCase(StatementPositionRuleTests.allTests),
testCase(StaticOperatorRuleTests.allTests),
testCase(StrictFilePrivateRuleTests.allTests),
testCase(StrongIBOutletRuleTests.allTests),
testCase(SwiftVersionTests.allTests),
testCase(SwitchCaseAlignmentRuleTests.allTests),
testCase(SwitchCaseOnNewlineRuleTests.allTests),
testCase(SyntacticSugarRuleTests.allTests),
testCase(TodoRuleTests.allTests),
testCase(ToggleBoolRuleTests.allTests),
testCase(TrailingClosureConfigurationTests.allTests),
testCase(TrailingClosureRuleTests.allTests),
testCase(TrailingCommaRuleTests.allTests),
testCase(TrailingSemicolonRuleTests.allTests),
testCase(TrailingWhitespaceTests.allTests),
testCase(TypeBodyLengthRuleTests.allTests),
testCase(TypeContentsOrderRuleTests.allTests),
testCase(TypeNameRuleTests.allTests),
testCase(UnavailableFunctionRuleTests.allTests),
testCase(UnneededBreakInSwitchRuleTests.allTests),
testCase(UnneededNotificationCenterRemovalRuleTests.allTests),
testCase(UnneededParenthesesInClosureArgumentRuleTests.allTests),
testCase(UnownedVariableCaptureRuleTests.allTests),
testCase(UntypedErrorInCatchRuleTests.allTests),
testCase(UnusedCaptureListRuleTests.allTests),
testCase(UnusedClosureParameterRuleTests.allTests),
testCase(UnusedControlFlowLabelRuleTests.allTests),
testCase(UnusedDeclarationRuleTests.allTests),
testCase(UnusedEnumeratedRuleTests.allTests),
testCase(UnusedImportRuleTests.allTests),
testCase(UnusedOptionalBindingRuleTests.allTests),
testCase(UnusedSetterValueRuleTests.allTests),
testCase(ValidIBInspectableRuleTests.allTests),
testCase(VerticalParameterAlignmentOnCallRuleTests.allTests),
testCase(VerticalParameterAlignmentRuleTests.allTests),
testCase(VerticalWhitespaceBetweenCasesRuleTests.allTests),
testCase(VerticalWhitespaceClosingBracesRuleTests.allTests),
testCase(VerticalWhitespaceOpeningBracesRuleTests.allTests),
testCase(VerticalWhitespaceRuleTests.allTests),
testCase(VoidReturnRuleTests.allTests),
testCase(WeakDelegateRuleTests.allTests),
testCase(XCTFailMessageRuleTests.allTests),
testCase(XCTSpecificMatcherRuleTests.allTests),
testCase(YamlParserTests.allTests),
testCase(YamlSwiftLintTests.allTests),
testCase(YodaConditionRuleTests.allTests)
])
| 46.46447 | 187 | 0.762418 |
fcf04258647185fe8baaa7255344cfed702aaae2 | 21,000 | //
// ValiantZip.swift
// unzip
//
// Created by xiangwenwen on 15/11/12.
// Copyright © 2015年 xiangwenwen. All rights reserved.
//
import Foundation
typealias LHMCheckingVersionCompletion = (error:NSError?,willUpdateTable:NSArray) -> Void
typealias LHMEmptyCallback = (Void)->Void
typealias LHMErrorCallback = (error:NSError?)->Void
typealias LHMModuleCallback = (fetchModule:ValiantFetchModule,error:NSError?) ->Void
private let cacheDirPath:NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as NSString
private let docDirPath:NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as NSString
private let defaultLeJiaYuanWebViewDir:NSString = docDirPath.stringByAppendingPathComponent("ljyWebViewContainer") as NSString
private let defaultLeJiaYuanDownloadDir:String = cacheDirPath.stringByAppendingPathComponent("ljyDownloadZip")
private let defailtLeJiaYuanVersionInfo:String = defaultLeJiaYuanWebViewDir.stringByAppendingString("/LHM-Zip-Config.plist")
/**
* 内部使用的Error类型
*
* 标注错误的行数,错误上下文
*/
protocol ValiantContextError : ErrorType {
mutating func addContext<T>(type: T.Type)
}
protocol ValiantContextualizable {}
extension ValiantContextualizable {
func addContext(var error: ValiantContextError) -> ValiantContextError {
error.addContext(self.dynamicType)
print("ContextError:\(error)\r\n")
return error
}
}
struct ValiantError:ValiantContextError {
var source : String
let reason : String
init(reason: String, file: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) {
self.reason = reason
self.source = "\(file):\(function):\(line)"
}
mutating func addContext<T>(type: T.Type) {
source += ":\(type)"
}
}
// ValianError处理结束(包裹注释,请忽略)
extension NSData:ValiantContextualizable{
/**
NSData转换字典
- returns: 返回一个JSON格式的字典
*/
func JSONParse() throws -> NSDictionary{
let JSON:NSDictionary
do{
JSON = try NSJSONSerialization.JSONObjectWithData(self, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
}catch{
throw addContext(ValiantError(reason: "NSData For NSDictionary"))
}
return JSON
}
}
extension NSDictionary:ValiantContextualizable{
/**
字典转字符串
- returns: <#return value description#>
*/
func JSONStringify() throws ->String{
let JSON:String
do{
let JSONData = try NSJSONSerialization.dataWithJSONObject(self, options: NSJSONWritingOptions.PrettyPrinted)
JSON = String(data: JSONData, encoding: NSUTF8StringEncoding)!
}catch{
throw addContext(ValiantError(reason: "NSDictionary For String"))
}
return JSON
}
}
extension NSArray{
/**
筛选取反
- parameter callback: <#callback description#>
- returns: <#return value description#>
*/
func reject(callback:(obj:AnyObject)->Bool)->NSArray{
return self.filteredArrayUsingPredicate( NSPredicate { (obj, bindings) -> Bool in
return !callback(obj: obj)
})
}
}
//获取module描述
enum ValiantFetchModule:Int{
case URLLocation //可以成功获取本地地址
case URLRequest //可以成功获取远程地址
case URLNone //获取本地和远程地址皆失败
}
/// 单例,管理中心
class ValiantCenterManager:NSObject,ValiantContextualizable{
/// 管理中心单例
class var sharedInstanceManager: ValiantCenterManager {
struct centerStatic {
static var onceToken:dispatch_once_t = 0
static var instance:ValiantCenterManager? = nil
}
dispatch_once(¢erStatic.onceToken) { () -> Void in
centerStatic.instance = ValiantCenterManager()
}
return centerStatic.instance!
}
//快速获取远程地址
var fetchRunHTTP:[String:AnyObject?] = [:]
//文件管理
lazy var manager:NSFileManager = {
return NSFileManager.defaultManager()
}()
/**
检查远程版本信息,是否需要更新(接口一使用)
- parameter completion: 检查完成之后的block,此block以切换到主线程中
*/
func checkingZipUpdateVersion(completion:LHMCheckingVersionCompletion){
//先请求从服务端请求接口获取版本信息数据
//再从本地信息库中读取配置文件
//与服务端版本信息进行比对
//装载一个Update List Array
//分发给completion 闭包
let config:NSURLSessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let session:NSURLSession = NSURLSession(configuration: config)
let request:NSURLRequest = NSURLRequest(URL: NSURL(string: "")!)
session.dataTaskWithRequest(request, completionHandler: {
[unowned self] (data:NSData?,response:NSURLResponse?,error:NSError?) ->Void in
//处理版本信息比对
})
if let version:NSArray = self.readingLocationVersionInfo(){
print("version info \(version)")
}else{
}
completion(error: nil, willUpdateTable: [["zip":"app-676e15c4873b99459fc62ee93cc22d0a.zip"]] as NSArray)
}
/**
检查远程单个module配置信息(接口二使用)
- parameter module: 本地HTML5包标识名
- parameter url: 本地HTML5地址目标
- parameter completion: 处理之后的block,此block以切换到主线程中
*/
func checkingModuleConfig(module:String,url:String,completion:LHMModuleCallback){
//当用户点击某个模块的时候,请求接口二,判断使用本地还是远程HTTP
let config:NSURLSessionConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let session:NSURLSession = NSURLSession(configuration: config)
let request:NSURLRequest = NSURLRequest(URL: NSURL(string: url)!)
session.dataTaskWithRequest(request, completionHandler: {
[unowned self ](data:NSData?,response:NSURLResponse?,error:NSError?) -> Void in
var load:ValiantFetchModule = .URLLocation
if (error == nil){
if let responseData:NSData = data{
do{
let handlerJson:NSDictionary = try responseData.JSONParse()
print("module配置信息 --- > \(handlerJson)")
if (self.fetchRunHTTP[module] != nil){
self.fetchRunHTTP.removeValueForKey(module)
}
self.fetchRunHTTP.updateValue(handlerJson["url"], forKey: module)
load = ValiantFetchModule.URLRequest
}catch{
self.addContext(ValiantError(reason: "检查远程单个module配置信息数据转换JSON出错"))
}
}
}
//回调到主线程处理
dispatch_async(dispatch_get_main_queue(), {
completion(fetchModule: load, error: error)
})
})
}
/**
解析zip包信息
- parameter pathName: zip包名
- returns: 返回一个字典
*/
func extname(pathName:String) -> NSDictionary?{
print("传入的是.zip包? ---> \(pathName.hasSuffix(".zip"))")
if pathName.hasSuffix(".zip"){
if let pathArray:Array = pathName.characters.split(Character("-")){
let projectName:String = String(pathArray.first!)
var zipChar:String = String(pathArray.last!)
zipChar.removeRange(Range(start: zipChar.characters.indexOf(".")!, end: zipChar.characters.endIndex))
return ["name":projectName,"md5":zipChar] as NSDictionary
}
}
return nil
}
/**
清除已经下载的zip
- parameter completion: 清除成功之后的block,此block以切换到主线程中
*/
func cleanDownloadZip(completion:LHMErrorCallback){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
[unowned self] _ in
var notifySignal:Int = 0
var message:[String:AnyObject] = [:]
var error:NSError?
if let files:NSArray = self.manager.subpathsAtPath(defaultLeJiaYuanDownloadDir){
for filePath in files{
let rmPath:String = defaultLeJiaYuanDownloadDir+"/d"+(filePath as! String)
if self.manager.fileExistsAtPath(rmPath){
do{
try self.manager.removeItemAtPath(rmPath)
}catch{
notifySignal++
message["name"] = rmPath
break;
}
}
}
dispatch_async(dispatch_get_main_queue(), {
if notifySignal == 0{
error = nil
}else{
error = NSError(domain: "LHM REMOVE ALL ZIP FILE", code: 500, userInfo: message)
}
completion(error: error)
})
}
})
}
/**
解压zip包
- parameter fetchInfo: 待解压zip信息["name":"module标识","savePath":"存储的目标路径"]
- returns: <#return value description#>
*/
func unzipFileTo(fetchInfo:NSDictionary) ->Bool{
let tagName:String = fetchInfo["name"] as! String
let zipPath:String = fetchInfo["savePath"] as! String
if let unToZipPath:String = self.fetchZipAddress(tagName){
let isZipSuccess:Bool = SSZipArchive.unzipFileAtPath(zipPath, toDestination: unToZipPath)
return isZipSuccess
}
return false
}
/**
根据module以及page url获取本地运行地址
- parameter module: 本地HTML5标识
- parameter pageURL: 你需要运行的页面名
- returns: <#return value description#>
*/
func fetchContainerRun(module:String,runPageURL pageURL:String)->NSURL?{
var container:NSURL? = nil
if let page:String = self.fetchRunContainer(module, page: pageURL){
container = NSURL(string: page)
}
return container
}
/**
根据module获取在线地址
- parameter module: 本地HTML5标识
- returns: <#return value description#>
*/
func fetchContainerRun(module:String)->NSURLRequest?{
var container:NSURLRequest? = nil
if let url:String = self.fetchRunHTTP[module] as? String{
container = NSURLRequest(URL: NSURL(string: url)!)
}
return container
}
/**
拼接文件在容器中的位置
- parameter module: 本地HTML5标识
- parameter source: 资源名
- returns: <#return value description#>
*/
func fetchContainerPath(module:String,sourcePath source:String)->String{
let appPath:NSString = self.fetchZipAddress(module) as NSString
return appPath.stringByAppendingPathComponent(source)
}
/**
递归版查询目录下的某个文件,没事不要随便乱用,除非真的不知道完整路径(如果你都不知道,这不科学,真的)
- parameter moduel: 本地HTML5标识
- parameter source: 资源名
- returns: <#return value description#>
*/
func fetchContainerPath(moduel:String,recursivePath source:String) -> [String]{
let appPath:NSString = self.fetchZipAddress(moduel) as NSString
var sourcesPath:[String] = []
var i:Int = 0
if let sources:[String] = self.manager.subpathsAtPath(appPath as String){
let count = sources.count
if count > 0{
while true{
let target:String = sources[i]
i++
if target.containsString(source){
sourcesPath.append(appPath.stringByAppendingPathComponent(target))
continue
}
if count == i{
break
}
}
}
}
return sourcesPath
}
private func fetchRunContainer(module:String,page:String)->String?{
var container:String? = nil
let appPath:NSString = self.fetchZipAddress(module) as NSString
let isHtml = page.containsString(".html")
if isHtml{
container = appPath.stringByAppendingPathComponent(page)
}
return container
}
/**
根据module获取放置zip包的位置
- parameter module: <#module description#>
- returns: <#return value description#>
*/
private func fetchZipAddress(module:String) -> String{
let appPath:NSString = defaultLeJiaYuanWebViewDir.stringByAppendingPathComponent(module) as NSString
let isDir:Bool = self.manager.fileExistsAtPath(appPath as String)
if !isDir{
do{
try self.manager.createDirectoryAtPath(appPath as String, withIntermediateDirectories: true, attributes: nil)
}catch{
self.addContext(ValiantError(reason: "创建module dir 失败 module name:\(module)"))
}
}
return appPath as String
}
/**
获取本地存储的配置信息
- returns: <#return value description#>
*/
private func readingLocationVersionInfo() -> NSArray?{
if let version:NSArray = NSArray(contentsOfFile: defailtLeJiaYuanVersionInfo){
return version
}
return nil
}
/**
保存远程配置数据到本地
- parameter config: <#config description#>
- returns: <#return value description#>
*/
private func saveConfigPlist(config:NSArray) -> Bool?{
var isWrite:Bool = true
//写入文件
if self.manager.fileExistsAtPath(defailtLeJiaYuanVersionInfo){
//如果存在,先删除再写入
do{
try self.manager.removeItemAtPath(defailtLeJiaYuanVersionInfo)
isWrite = config.writeToFile(defailtLeJiaYuanVersionInfo, atomically: true)
return isWrite
}catch{
return false
}
}else{
//写入
isWrite = config.writeToFile(defailtLeJiaYuanVersionInfo, atomically: true)
return isWrite
}
}
/**
远程数据格式转换
- returns: <#return value description#>
*/
private func formatter(completion:LHMEmptyCallback) -> NSArray?{
return nil
}
}
struct LHMFetchZipDataInfo {
//下载任务URL
let url:String
//下载名称
let name:String
//下载MD5信息
let md5:String
//下载的zip存储地址
let saveZipPath:String
//用于保存断点数据
var tempData:NSData?
let id:String
/**
构造器
- parameter name: <#name description#>
- parameter url: <#url description#>
- parameter md5: <#md5 description#>
- returns: <#return value description#>
*/
init(name:String,url:String,md5:String,id:Int){
self.name = name
self.url = url
self.md5 = md5
self.id = "zip_\(id)"
let manager = NSFileManager.defaultManager()
if !(manager.fileExistsAtPath(defaultLeJiaYuanDownloadDir)){
do{
try manager.createDirectoryAtPath(defaultLeJiaYuanDownloadDir, withIntermediateDirectories: true, attributes: nil)
}catch{
print("LHM create zip root path error #### name:\(self.name) md5:\(self.md5)")
print("LHM create zip root Path #### path:\(defaultLeJiaYuanDownloadDir)")
}
}
self.saveZipPath = (defaultLeJiaYuanDownloadDir as NSString).stringByAppendingPathComponent(self.name+".zip")
}
}
@objc protocol ValiantFetchZipDelegate{
optional func fetchZipDidFinishLoading(location:NSDictionary)->Void //队列中单个zip包下载完成之后调用
optional func fetchZip(progress:Int,didReceiveSingleData location:NSDictionary)->Void //zip包下载进度
optional func fetchZip(location:NSDictionary,didCompleteWithError error:NSError?)->Void //下载单个失败
}
class ValiantFetchZip:NSObject,NSURLSessionDownloadDelegate,ValiantContextualizable{
let id:String
//管理中心
private lazy var valiantCenter:ValiantCenterManager = {
return ValiantCenterManager.sharedInstanceManager
}()
private let fetchInfo:NSDictionary
//一个下载单元结构体
var info:LHMFetchZipDataInfo
//下载进度
var speed:[Int] = []
//一个下载单元任务
var task:NSURLSessionDownloadTask?
//计时器
var timer:NSTimer?
//协议
weak var delegate:ValiantFetchZipDelegate?
//session
var session:NSURLSession?
var backgroundURLSessionFinishEvents:LHMEmptyCallback?
init(info:LHMFetchZipDataInfo,delegate:ValiantFetchZipDelegate?) {
//暂时传递一个nil
self.info = info
self.delegate = delegate
self.id = "icepy_queue_\(info.id)"
self.fetchInfo = ["name":self.info.name,"md5":self.info.md5,"savePath":self.info.saveZipPath]
super.init()
self.session = self.createBackgroundSession()
}
func startFetch(){
if let url:NSURL = NSURL(string: self.info.url){
let request:NSURLRequest = NSURLRequest(URL: url)
task = session!.downloadTaskWithRequest(request)
}
task?.resume()
timer?.invalidate()
}
//下载成功时
@objc func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
timer?.invalidate()
if let fromPath = location.path{
if self.removeZipDir(){
do{
try self.valiantCenter.manager.moveItemAtPath(fromPath, toPath: self.info.saveZipPath)
self.finishDownloadZipTask()
}catch{
self.addContext(ValiantError(reason: "下载成功:\(self.id) 移动临时数据到保存目录错误:\(self.info.saveZipPath)"))
}
}
}else{
print("system return location.path error #### current id:\(self.id)")
}
}
//下载失败时
@objc func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let err = error{
self.delegate?.fetchZip?(self.fetchInfo, didCompleteWithError: err)
self.overFetch()
}
}
//下载进度
@objc func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress:Int = Int((Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))*100)
self.speed.append(Int(bytesWritten))
self.delegate?.fetchZip?(progress, didReceiveSingleData: self.fetchInfo)
print(" self id:\(self.id) progress:\(progress) download zip name:\(fetchInfo["name"] as! String)-\(fetchInfo["md5"] as! String).zip")
}
//如果解除引用,系统会通知在这个delegate中
@objc func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
}
//创建普通session或后台session
private func createBackgroundSession() -> NSURLSession{
return NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil)
}
//暂停下载任务
func pasueFetch(){
if let task = self.task{
if task.state == .Running{
//如果任务还在运行当中,将数据存入临时tempData中
task.cancelByProducingResumeData(){
[unowned self](data:NSData?) in
self.info.tempData = data
self.speed = []
self.task = nil
self.timer?.invalidate()
}
}
}
}
//取消下载任务,当前实例的强引用依然由系统持用
func cancelFetch(){
//如果存在下载任务,先取消
if let task = self.task{
task.cancel()
self.task = nil
}
//清空已经下载的数据信息
self.info.tempData = nil
self.speed = []
self.timer?.invalidate()
}
//完全取消,解除系统对当前实例的强引用,并且释放内存
func overFetch(){
self.cancelFetch()
self.session?.invalidateAndCancel()
}
//完成zip下载任务
private func finishDownloadZipTask(){
self.delegate?.fetchZipDidFinishLoading?(self.fetchInfo)
self.overFetch()
}
/**
计算X秒内写入的数据
- returns: <#return value description#>
*/
private func computeSeep() ->String{
var complete = 0
for data in speed{
complete += data
}
speed = []
return "\(complete/256)"
}
//删除单个zip包
private func removeZipDir() -> Bool{
let isExists:Bool = (self.valiantCenter.manager.fileExistsAtPath(self.info.saveZipPath))
if isExists{
do{
try self.valiantCenter.manager.removeItemAtPath(self.info.saveZipPath)
}catch{
self.addContext(ValiantError(reason: "删除单个zip包错误,current id:\(self.id) remove path:\(self.info.saveZipPath)"))
return false
}
}
return true
}
deinit{
//释放池
print("ValiantFetchZip id:\(self.id) release memory")
}
} | 32.608696 | 184 | 0.603381 |
23d87b33e80a7fc81350b2de2a8f81461fa42787 | 1,749 | //
//
//
import Foundation
struct PartycakePlayUiStateBuilder {
// プロパティ単位で変更の通知がいかないので、State丸ごとのセットは初期化時のみ有効
func playUiState(from systemState: PartycakeSystemState) -> PartycakePlayUiState {
let myUserId = appState.account.loginUser.id
let mySeat = systemState.players.first(where: {$0.user_id == myUserId})?.seat
let mySide = systemState.partycakeState.sides.first(where: {$0.seat.rawValue == mySeat})!
let playUiState = PartycakePlayUiState()
playUiState.innerCakeDegree = Double(systemState.partycakeState.innerOffset * 90)
playUiState.outerCakeDegree = Double(systemState.partycakeState.outerOffset * 90)
playUiState.dockHandCards = mySide.handCardIds
playUiState.dockBetLevels = (mySide.playerStep == .bet) ? [.min, .mid, .max] : []
let uiSides = systemState.players.map { player -> PartycakePlayUiSide in
let systemSide = systemState.partycakeState.sides.first(where: {$0.seat.rawValue == player.seat})!
let uiSide = PartycakePlayUiSide(
seat: PartycakeSeat(rawValue: player.seat)!
)
uiSide.playerNickname = player.nickname
uiSide.playerIconUrl = player.icon_url
uiSide.playerBetLevel = systemSide.betLevel
uiSide.chips = systemSide.chips
uiSide.putCard = systemSide.putCardId
if systemState.partycakeState.dealerStep == .waitingBet {
// Bet中なら表向き
uiSide.putCardDegree = 0
} else {
uiSide.putCardDegree = 180
}
return uiSide
}
playUiState.sides = uiSides
return playUiState
}
}
| 38.866667 | 110 | 0.630646 |
28b01a659de1f4a2846e9acd181d5e5844375e48 | 1,300 | //
// Copyright 2018-2019 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import XCTest
// Only @testable so we can get access to `Amplify.reset()`
@testable import Amplify
@testable import AmplifyTestCommon
class APICategoryClientRESTTests: XCTestCase {
var mockAmplifyConfig: AmplifyConfiguration!
override func setUp() {
Amplify.reset()
let apiConfig = APICategoryConfiguration(
plugins: ["MockAPICategoryPlugin": true]
)
mockAmplifyConfig = AmplifyConfiguration(api: apiConfig)
}
func testGet() throws {
let plugin = try makeAndAddMockPlugin()
let methodWasInvokedOnPlugin = expectation(description: "method was invoked on plugin")
plugin.listeners.append { message in
if message == "get" {
methodWasInvokedOnPlugin.fulfill()
}
}
_ = Amplify.API.get(request: RESTRequest()) { _ in }
waitForExpectations(timeout: 0.5)
}
// MARK: - Utilities
func makeAndAddMockPlugin() throws -> MockAPICategoryPlugin {
let plugin = MockAPICategoryPlugin()
try Amplify.add(plugin: plugin)
try Amplify.configure(mockAmplifyConfig)
return plugin
}
}
| 25 | 95 | 0.652308 |
7907ee94ffe78d0797c409bc513ac6629e46d7ca | 2,968 | //
// LoginViewController.swift
// UserLoginAndRegistration
//
// Created by Anastasis Panagoulias on 05/12/2016.
// Copyright © 2016 Anastasis Panagoulias. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let toolbar = UIToolbar()
toolbar.sizeToFit()
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.doneClicked))
toolbar.setItems([flexibleSpace, doneButton], animated: false)
userEmailTextField.inputAccessoryView = toolbar
userPasswordTextField.inputAccessoryView = toolbar
}
func doneClicked() {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginButtonTapped(_ sender: Any) {
let userEmail = userEmailTextField.text
//print (userEmail!)
let userPassword = userPasswordTextField.text
//print (userPassword!)
let userEmailStored = UserDefaults.standard.string(forKey: "userEmail")
if((userEmail?.isEmpty)! || (userPassword?.isEmpty)!) {
//Display Alert Message
displayMyAlertMessage(userMessage: "All fields are required")
return
}
//print (userEmailStored)
let userPasswordStored = UserDefaults.standard.string(forKey: "userPassword")
if (userEmailStored == userEmail) {
if (userPasswordStored == userPassword)
{
//Login is successful
UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
UserDefaults.standard.synchronize()
self.dismiss(animated: true, completion: nil)
} else {
displayMyAlertMessage(userMessage: "The password you entered is wrong")
}
} else {
displayMyAlertMessage(userMessage: "The is no user with that username")
}
}
func displayMyAlertMessage(userMessage: String)
{
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction)
self.present(myAlert, animated:true, completion:nil)
}
}
| 30.916667 | 140 | 0.618261 |
8f0c6e8e7d9de04ac6a2c2b29eb09f8c8ccb928b | 10,198 | //
// OnboardDetailViewController.swift
// HTWDD
//
// Created by Benjamin Herzog on 29.10.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import UIKit
class OnboardDetailViewController<Product>: ViewController, UITextFieldDelegate, KeyboardPresentationHandler {
var onFinish: ((Product?) -> Void)?
struct Config {
var title: String
var description: String
var contentViews: [UIView]
var contentViewsStackViewAxis: NSLayoutConstraint.Axis
var notNowText: String
var continueButtonText: String
}
/// Set this config before calling super.initialSetup!
var config: Config?
private lazy var containerView = UIView()
private lazy var titleContainer = UIView()
private lazy var centerStackView = UIStackView()
private lazy var continueButton = ReactiveButton()
private lazy var topConstraint: NSLayoutConstraint = {
return self.containerView.topAnchor.constraint(equalTo: self.view.htw.safeAreaLayoutGuide.topAnchor, constant: 0)
}()
private lazy var bottomConstraint: NSLayoutConstraint = {
return self.containerView.bottomAnchor.constraint(equalTo: self.view.htw.safeAreaLayoutGuide.bottomAnchor, constant: 0)
}()
private lazy var titleTopConstraint: NSLayoutConstraint = {
return self.titleContainer.topAnchor.constraint(equalTo: self.containerView.htw.safeAreaLayoutGuide.topAnchor, constant: 60)
}()
private lazy var continueButtonTopConstraint: NSLayoutConstraint = {
return self.continueButton.topAnchor.constraint(equalTo: self.centerStackView.bottomAnchor, constant: 12)
}()
// MARK: - Overwrite functions
@objc func continueBoarding() {
preconditionFailure("Overwrite this method in your subclass!")
}
@objc func skipBoarding() {
self.onFinish?(nil)
}
func shouldReplace(textField: UITextField, newString: String) -> Bool {
return true
}
func shouldContinue() -> Bool {
return false
}
func checkState() {
self.continueButton.isEnabled = self.shouldContinue()
}
// MARK: - ViewController lifecycle
override func initialSetup() {
super.initialSetup()
guard let config = self.config else {
preconditionFailure("Tried to use OnboardDetailViewController without config. Abort!")
}
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
// --- Container ---
self.containerView.translatesAutoresizingMaskIntoConstraints = false
self.view.add(self.containerView)
NSLayoutConstraint.activate([
self.containerView.leadingAnchor.constraint(equalTo: self.view.htw.safeAreaLayoutGuide.leadingAnchor),
self.topConstraint,
self.containerView.trailingAnchor.constraint(equalTo: self.view.htw.safeAreaLayoutGuide.trailingAnchor),
self.bottomConstraint
])
// --- Title Label ---
let titleLabel = UILabel()
titleLabel.text = config.title
titleLabel.font = .systemFont(ofSize: 44, weight: .bold)
titleLabel.textColor = UIColor.htw.textHeadline
titleLabel.translatesAutoresizingMaskIntoConstraints = false
self.titleContainer.translatesAutoresizingMaskIntoConstraints = false
self.titleContainer.add(titleLabel)
self.containerView.add(self.titleContainer)
// --- Description Label ---
let descriptionLabel = UILabel()
descriptionLabel.text = config.description
descriptionLabel.font = .systemFont(ofSize: 17, weight: .medium)
descriptionLabel.textColor = UIColor.htw.textBody
descriptionLabel.numberOfLines = 0
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
// --- Text fields ---
let configureTextField: (UIView) -> Void = {
guard let textField = $0 as? UITextField else {
return
}
textField.font = .systemFont(ofSize: 30, weight: .medium)
textField.backgroundColor = UIColor.htw.veryLightGrey
textField.textAlignment = .left
textField.delegate = self
textField.addTarget(self, action: #selector(self.inputChanges(textField:)), for: .editingChanged)
textField.translatesAutoresizingMaskIntoConstraints = false
}
config.contentViews
.forEach(configureTextField)
let textFieldStackView = UIStackView(arrangedSubviews: config.contentViews)
textFieldStackView.axis = config.contentViewsStackViewAxis
textFieldStackView.distribution = .fillEqually
textFieldStackView.spacing = 12
textFieldStackView.translatesAutoresizingMaskIntoConstraints = false
self.centerStackView = UIStackView(arrangedSubviews: [
descriptionLabel,
textFieldStackView
])
self.centerStackView.axis = .vertical
self.centerStackView.distribution = .fill
self.centerStackView.spacing = 40
self.centerStackView.translatesAutoresizingMaskIntoConstraints = false
self.containerView.add(self.centerStackView)
// --- Continue Button ---
self.continueButton.isEnabled = false
self.continueButton.setTitle(config.continueButtonText, for: .normal)
self.continueButton.titleLabel?.font = .systemFont(ofSize: 20, weight: .semibold)
self.continueButton.backgroundColor = UIColor.htw.blue
self.continueButton.layer.cornerRadius = 12
self.continueButton.translatesAutoresizingMaskIntoConstraints = false
self.continueButton.rx
.controlEvent(.touchUpInside)
.subscribe({ [weak self] _ in self?.continueBoarding() })
.disposed(by: self.rx_disposeBag)
self.containerView.add(self.continueButton)
// --- Skip Button ---
let skip = ReactiveButton()
skip.setTitle(config.notNowText, for: .normal)
skip.setTitleColor(UIColor.htw.blue, for: .normal)
skip.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
skip.translatesAutoresizingMaskIntoConstraints = false
skip.rx
.controlEvent(.touchUpInside)
.subscribe({ [weak self] _ in self?.skipBoarding() })
.disposed(by: self.rx_disposeBag)
self.containerView.add(skip)
// --- Constraints ---
let stackViewHeight: CGFloat
if config.contentViewsStackViewAxis == .horizontal {
stackViewHeight = 60
} else {
stackViewHeight = 60.0 * CGFloat(config.contentViews.count) + textFieldStackView.spacing * (CGFloat(config.contentViews.count) - 1)
}
NSLayoutConstraint.activate([
self.titleTopConstraint,
self.titleContainer.centerXAnchor.constraint(equalTo: self.containerView.centerXAnchor),
self.titleContainer.widthAnchor.constraint(equalTo: self.centerStackView.widthAnchor),
self.titleContainer.heightAnchor.constraint(equalTo: titleLabel.heightAnchor, multiplier: 1),
titleLabel.centerXAnchor.constraint(equalTo: self.titleContainer.centerXAnchor),
titleLabel.centerYAnchor.constraint(equalTo: self.titleContainer.centerYAnchor),
skip.topAnchor.constraint(equalTo: self.containerView.topAnchor, constant: 10),
skip.trailingAnchor.constraint(equalTo: self.containerView.trailingAnchor, constant: -20),
self.centerStackView.centerXAnchor.constraint(equalTo: self.containerView.centerXAnchor),
self.centerStackView.topAnchor.constraint(equalTo: self.titleContainer.bottomAnchor, constant: 40),
self.centerStackView.widthAnchor.constraint(equalTo: self.containerView.widthAnchor, multiplier: 0.8),
textFieldStackView.heightAnchor.constraint(equalToConstant: stackViewHeight),
self.continueButton.heightAnchor.constraint(equalToConstant: 55),
self.continueButton.centerXAnchor.constraint(equalTo: self.containerView.centerXAnchor),
self.continueButton.widthAnchor.constraint(equalTo: self.centerStackView.widthAnchor),
self.continueButton.bottomAnchor.constraint(equalTo: self.containerView.htw.safeAreaLayoutGuide.bottomAnchor, constant: -20)
])
self.registerForKeyboardNotifications()
#if DEBUG
// Add Key Commands for debug mode
let returnKeyCommand = UIKeyCommand(input: "\r", modifierFlags: [], action: #selector(continueBoarding))
self.addKeyCommand(returnKeyCommand)
let escapeKeyCommand = UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(skipBoarding))
self.addKeyCommand(escapeKeyCommand)
#endif
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
@objc func inputChanges(textField: TextField) {
self.checkState()
}
// MARK: - UITextFieldDelegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentString = (textField.text ?? "") as NSString
let newString = currentString.replacingCharacters(in: range, with: string) as String
return self.shouldReplace(textField: textField, newString: newString)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
// MARK: - KeyboardPresentationHandler
@objc
func keyboardWillShow(_ notification: Notification) {
self.animateWithKeyboardNotification(notification, layout: { frame in
self.bottomConstraint.constant = -frame.height
self.topConstraint.constant = -frame.height
self.titleTopConstraint.isActive = false
self.continueButtonTopConstraint.isActive = true
}) {
self.view.layoutIfNeeded()
}
}
@objc
func keyboardWillHide(_ notification: Notification) {
self.animateWithKeyboardNotification(notification, layout: { frame in
self.bottomConstraint.constant = 0
self.topConstraint.constant = 0
self.titleTopConstraint.isActive = true
self.continueButtonTopConstraint.isActive = false
}) {
self.view.layoutIfNeeded()
}
}
}
| 38.052239 | 143 | 0.707492 |
7a10390d494a43e979f1890657738eb2c55f2445 | 2,176 | //
// AppDelegate.swift
// WineChoice
//
// Created by Romi Alsaid on 02/12/2017.
// Copyright © 2017 Romi Alsaid. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.297872 | 285 | 0.755515 |
5623b276b1c7cc889267f312a102dd4143725778 | 662 | //
// SKSpriteNode.swift
// SwitchTheShitOutOfTheColor
//
// Created by NP2 on 5/4/19.
// Copyright © 2019 shndrs. All rights reserved.
//
import SpriteKit
extension SKSpriteNode {
func aspectFillToSize(fillSize: CGSize) {
if texture != nil {
self.size = texture!.size()
let verticalRatio = fillSize.height / self.texture!.size().height
let horizontalRatio = fillSize.width / self.texture!.size().width
let scaleRatio = horizontalRatio > verticalRatio ? horizontalRatio : verticalRatio
self.setScale(scaleRatio)
}
}
}
| 24.518519 | 94 | 0.590634 |
331f61849a44615ac0ab83877fab2c5c6bff159b | 1,081 | //
// UISegmentedControlExtensions.swift
// YYSwift
//
// Created by Phoenix on 2018/1/8.
// Copyright © 2018年 Phoenix. All rights reserved.
//
#if canImport(UIKit)
import UIKit
// MARK: - Properties
public extension UISegmentedControl {
/// YYSwift: Segments titles.
var segmentTitles: [String] {
get {
let range = 0..<numberOfSegments
return range.compactMap { titleForSegment(at: $0) }
}
set {
removeAllSegments()
for (index, title) in newValue.enumerated() {
insertSegment(withTitle: title, at: index, animated: false)
}
}
}
/// YYSwift: Segments images.
var segmentImages: [UIImage] {
get {
let range = 0..<numberOfSegments
return range.compactMap { imageForSegment(at: $0) }
}
set {
removeAllSegments()
for (index, image) in newValue.enumerated() {
insertSegment(with: image, at: index, animated: false)
}
}
}
}
#endif
| 24.568182 | 75 | 0.552266 |
877b1696bb34d85129bdbe4989a03f1e0e7ad0aa | 4,467 | // RUN: %target-swift-frontend -module-name foo -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize
// CHECK: %swift.type = type { [[INT]] }
// -- Classes with generic bases can't go in the @objc_classes list, since
// they need runtime initialization before they're valid.
// CHECK-NOT: @objc_classes
class Base<T> {
var first, second: T
required init(x: T) {
first = x
second = x
}
func present() {
print("\(type(of: self)) \(T.self) \(first) \(second)")
}
}
// CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s3foo12SuperDerivedCMa"(
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s3foo12SuperDerivedCMl", i32 0, i32 0)
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s3foo12SuperDerivedCMn" to %swift.type_descriptor*))
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[NEW_METADATA:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 0, %entry ], [ [[STATUS]], %cacheIsNull ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[NEW_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
class SuperDerived: Derived {
}
// CHECK-LABEL: define hidden swiftcc %swift.metadata_response @"$s3foo7DerivedCMa"(
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s3foo7DerivedCMl", i32 0, i32 0)
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s3foo7DerivedCMn" to %swift.type_descriptor*))
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[NEW_METADATA:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 0, %entry ], [ [[STATUS]], %cacheIsNull ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[NEW_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
class Derived: Base<String> {
var third: String
required init(x: String) {
third = x
super.init(x: x)
}
override func present() {
super.present()
print("...and \(third)")
}
}
func presentBase<T>(_ base: Base<T>) {
base.present()
}
presentBase(SuperDerived(x: "two"))
presentBase(Derived(x: "two"))
presentBase(Base(x: "two"))
presentBase(Base(x: 2))
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s3foo12SuperDerivedCMr"(%swift.type*, i8*, i8**)
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s3foo7DerivedCMa"([[INT]] 257)
// CHECK-NEXT: [[SUPERCLASS:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[RESULT:%.*]] = icmp ule [[INT]] [[STATUS]], 1
// CHECK-NEXT: br i1 [[RESULT]], label %dependency-satisfied, label %metadata-dependencies.cont
// CHECK: dependency-satisfied:
// -- ClassLayoutFlags = 0x100 (HasStaticVTable)
// CHECK: call void @swift_initClassMetadata(%swift.type* %0, %swift.type* [[SUPERCLASS]], [[INT]] 256, {{.*}})
// CHECK: metadata-dependencies.cont:
// CHECK: ret %swift.metadata_response
| 45.581633 | 211 | 0.626371 |
224820a13e1d3a167273d20ecb21cf180635c7d7 | 10,818 | import Foundation
import XCTest
@testable import Treesquid
final class BTreeTests: XCTestCase {
//
// Helper functions for testing:
//
func validate(tree: BTree<Int, Any>, is reference: String) {
XCTAssert(traverse(tree) == reference, "Trees differ. Expected:\n\(reference)")
}
func traverseBTreeNode(_ node: BTreeNode<Int, Any>, _ minExpectedKeys: Int, _ level: Int, _ leafLevels: inout [Int]) {
XCTAssertGreaterThanOrEqual(node.keys.count,
minExpectedKeys,
"Node has \(node.keys.count) keys. Expected at least: \(minExpectedKeys).")
XCTAssertEqual(node.keys.count,
node.values.count,
"Node has \(node.values.count) values, but \(node.keys.count) keys. Expected then to be equal.")
XCTAssertEqual(node.keys,
node.keys.sorted(),
"Node keys are not sorted: \(node.keys).")
if node.children.count > 0 {
// Not a leaf:
XCTAssertEqual(node.keys.count + 1,
node.children.count,
"Keys: \(node.keys.count). Children: \(node.children.count). Expected children to be keys + 1.")
if type(of: node.keys.first!) == String.self {
for (key, index) in node.keys.enumerated() {
XCTAssertEqual("\(key)",
node.values[index] as! String,
"Node key and string-value mismatch at index \(index).")
}
}
for (index, child) in node.children.enumerated() {
if index < node.keys.count {
XCTAssertLessThan(node.children[index]!.keys.last!,
node.keys[index],
"B-tree property violated. Child key too large.")
} else {
XCTAssertGreaterThan(node.children[index]!.keys.first!,
node.keys.last!,
"B-tree property violated. Child key too small.")
}
XCTAssertTrue(child?.parent === node, "Child's `parent` is pointing to a different node.")
traverseBTreeNode(child!, Int(ceil(Float(node.tree!.m) / 2)) - 1, level + 1, &leafLevels)
}
return
}
// A leaf:
XCTAssertEqual(node.children.count,
0,
"Children: \(node.children.count). Expected them to be zero (leaf node).")
leafLevels.append(level)
return
}
// Assumes that the value is "\(key)". Needed to make sure that values
// are rotated properly alongside their keys.
func checkBTreeProperties(_ tree: BTree<Int, Any>) {
guard let root = tree.root else { return }
var leafLevels: [Int] = []
traverseBTreeNode(root, 0, 0, &leafLevels)
let leafLevelsConcur = Set(leafLevels).count == 1
XCTAssertTrue(leafLevelsConcur, "Leaves on different levels: \(leafLevels).")
}
//
// Unit tests:
//
// Example from:
// https://www.programiz.com/dsa/insertion-into-a-b-tree
// (October 9th, 2021)
func testProgramizTree() {
let treeProgramizTree = BTree<Int, Any>(m: 3)
validate(tree: treeProgramizTree.insert("8", forKey: 8), is: """
008•---
""")
validate(tree: treeProgramizTree.insert("9", forKey: 9), is: """
008•009
""")
validate(tree: treeProgramizTree.insert("10", forKey: 10), is: """
009•---
008•--- 010•--- ---◦---
""")
validate(tree: treeProgramizTree.insert("11", forKey: 11), is: """
009•---
008•--- 010•011 ---◦---
""")
validate(tree: treeProgramizTree.insert("15", forKey: 15), is: """
009•011
008•--- 010•--- 015•---
""")
validate(tree: treeProgramizTree.insert("20", forKey: 20), is: """
009•011
008•--- 010•--- 015•020
""")
validate(tree: treeProgramizTree.insert("17", forKey: 17), is: """
011•---
009•--- 017•--- ---◦---
008•--- 010•--- ---◦--- 015•--- 020•--- ---◦--- ---◦--- ---◦--- ---◦---
""")
}
// Example from:
// https://www.programiz.com/dsa/insertion-into-a-b-tree
// Includes a correction for the third depicted tree, which has two duplicate 45 nodes on the web-site.
// This is a typo on their end. The leftmost 45 is supposed to be a 35.
// (November 4th, 2021)
func testProgramizTreeDeletion() {
let tree = BTree<Int, Any>(m: 3)
let node5 = BTreeNode<Int, Any>(keys: [5],
values: ["5"],
children: [],
tree: tree)
let node15 = BTreeNode<Int, Any>(keys: [15],
values: ["15"],
children: [],
tree: tree)
let node25_28 = BTreeNode<Int, Any>(keys: [25, 28],
values: ["25", "28"],
children: [],
tree: tree)
let node31_32 = BTreeNode<Int, Any>(keys: [31, 32],
values: ["31", "32"],
children: [],
tree: tree)
let node35 = BTreeNode<Int, Any>(keys: [35],
values: ["35"],
children: [],
tree: tree)
let node45 = BTreeNode<Int, Any>(keys: [45],
values: ["45"],
children: [],
tree: tree)
let node55 = BTreeNode<Int, Any>(keys: [55],
values: ["55"],
children: [],
tree: tree)
let node65 = BTreeNode<Int, Any>(keys: [65],
values: ["65"],
children: [],
tree: tree)
let node10 = BTreeNode<Int, Any>(keys: [10],
values: ["10"],
children: [node5, node15],
tree: tree)
let node30_33 = BTreeNode<Int, Any>(keys: [30, 33],
values: ["30", "33"],
children: [node25_28, node31_32, node35],
tree: tree)
let node50_60 = BTreeNode<Int, Any>(keys: [50, 66],
values: ["50", "66"],
children: [node45, node55, node65],
tree: tree)
let node20_40 = BTreeNode<Int, Any>(keys: [20, 40],
values: ["20", "40"],
children: [node10, node30_33, node50_60],
tree: tree)
tree.root = node20_40
validate(tree: tree, is: """
020•040
010•--- 030•033 050•066
005•--- 015•--- ---◦--- 025•028 031•032 035•--- 045•--- 055•--- 065•---
""")
tree.delete(withKey: 32)
validate(tree: tree, is: """
020•040
010•--- 030•033 050•066
005•--- 015•--- ---◦--- 025•028 031•--- 035•--- 045•--- 055•--- 065•---
""")
tree.delete(withKey: 31)
validate(tree: tree, is: """
020•040
010•--- 028•033 050•066
005•--- 015•--- ---◦--- 025•--- 030•--- 035•--- 045•--- 055•--- 065•---
""")
tree.delete(withKey: 30)
validate(tree: tree, is: """
020•040
010•--- 033•--- 050•066
005•--- 015•--- ---◦--- 025•028 035•--- ---◦--- 045•--- 055•--- 065•---
""")
}
// Example from:
// https://www.cpp.edu/~ftang/courses/CS241/notes/b-tree.htm
// (December 5th, 2021)
func testCPPTree() {
let treeCPPTree = BTree<Int, Any>(m: 3)
validate(tree: treeCPPTree.insert("4", forKey: 4), is: """
004•---
""")
validate(tree: treeCPPTree.insert("6", forKey: 6), is: """
004•006
""")
validate(tree: treeCPPTree.insert("12", forKey: 12), is: """
006•---
004•--- 012•--- ---◦---
""")
validate(tree: treeCPPTree.insert("17", forKey: 17), is: """
006•---
004•--- 012•017 ---◦---
""")
validate(tree: treeCPPTree.insert("19", forKey: 19), is: """
006•017
004•--- 012•--- 019•---
""")
validate(tree: treeCPPTree.insert("22", forKey: 22), is: """
006•017
004•--- 012•--- 019•022
""")
validate(tree: treeCPPTree.insert("18", forKey: 18), is: """
017•---
006•--- 019•--- ---◦---
004•--- 012•--- ---◦--- 018•--- 022•--- ---◦--- ---◦--- ---◦--- ---◦---
""")
}
func testRandomTesting() {
for m in [3, 4, 5, 11, 12] {
for seed in [8271, 99001873, 3, 12349] {
srand48(seed)
for nodes in [1, 2, 3, 4, 5, 6, 7, 100, 2000] {
var availableKeys = Array(0..<nodes)
var insert_keys: [Int] = []
var delete_keys: [Int] = []
while !availableKeys.isEmpty {
let key = availableKeys.remove(at: Int(drand48() * Double(availableKeys.count - 1)))
insert_keys.append(key)
delete_keys.insert(key, at: Int(drand48() * Double(delete_keys.count)))
}
let tree = BTree<Int, Any>(m: m)
for key in insert_keys {
tree.insert("\(key)", forKey: key)
checkBTreeProperties(tree)
}
for key in delete_keys {
tree.delete(withKey: key)
checkBTreeProperties(tree)
}
}
}
}
}
}
| 43.272 | 123 | 0.414957 |
ef124330354059ad91ca23de0b0715d20d1173f9 | 2,637 | //
// MyNewsReaderTests.swift
// MyNewsReaderTests
//
// Created by Himanshu T on 14/4/21.
//
import XCTest
@testable import MyNewsReader
class MyNewsReaderTests: XCTestCase {
var presenter: Presenter?
var serverData: Data?
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
super.setUp()
presenter = Presenter()
if let url = Bundle.main.url(forResource: "ServerResponse", withExtension: nil) {
serverData = try Data(contentsOf: url)
}
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
serverData = nil
}
func testBasicWebServiceUrlGeneration() {
let endpoint = XMLToJSONEndPoint.abcNewsFeed()
XCTAssertEqual(endpoint.url, URL(string: "https://api.rss2json.com/v1/api.json?rss_url=http://www.abc.net.au/news/feed/51120/rss.xml"))
}
func testCellIdentifierForFeaturedItem() {
let indexPath = IndexPath(row: 0, section: 0)
let identifier = presenter?.identifierForNewsItemCell(for: indexPath)
XCTAssertEqual(identifier, "newsItemLarge")
}
func testCellIdentifierForOtherItem() {
let indexPath = IndexPath(row: 1, section: 0)
let identifier = presenter?.identifierForNewsItemCell(for: indexPath)
XCTAssertEqual(identifier, "newsItemSmall")
}
func testCellIdentifierForOtherItem2() {
let indexPath = IndexPath(row: 2, section: 0)
let identifier = presenter?.identifierForNewsItemCell(for: indexPath)
XCTAssertEqual(identifier, "newsItemSmall")
}
func testNumberOfArticlesInServerResponse() throws {
if let data = serverData {
let feed:RssRoot = try JSONDecoder().decode(RssRoot.self, from: data)
XCTAssertEqual(feed.items.count, 10)
}
}
func testIfServerResponseIsAValidJSON() throws {
if let data = serverData {
let j = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
XCTAssert(JSONSerialization.isValidJSONObject(j))
}
}
func testIfServerResponseIsNotAValidJSON() throws {
if let url = Bundle.main.url(forResource: "InValidServerReponse", withExtension: nil) {
let data = try Data(contentsOf: url)
XCTAssertThrowsError(try JSONSerialization.jsonObject(with: data, options: .allowFragments))
}
}
}
| 34.697368 | 143 | 0.664012 |
22886ce4ea25a6a8ab3e4ab7394a363367d64e51 | 692 | //
// TwitterClient.swift
// Twitter
//
// Created by Juan Hernandez on 2/9/16.
// Copyright © 2016 Juan Hernandez. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
let twitterConsumerKey = "E9Mwop8b4Q3XOcfuHe87rAZi1"
let twitterConsumerSecret = "3FoRTPIWoXyzBSv8vIYJDZCRQ1xr5p4fP4pmDn2Akb3GI95m5G"
let twitterBaseUrl = NSURL(string: "https://api.twitter.com")
class TwitterClient: BDBOAuth1SessionManager {
class var sharedInstance: TwitterClient {
struct Static {
static let instance = TwitterClient(baseURL: twitterBaseUrl, consumerKey: twitterConsumerKey, consumerSecret: twitterConsumerSecret)
}
return Static.instance
}
}
| 27.68 | 144 | 0.748555 |
d668fc5420b928474cd837539e4c7a278394343d | 5,119 | //
// UIColor+Helpers.swift
// Eyerise Extensions
//
// Created by Gleb Karpushkin on 14/10/2017.
// Copyright © 2017 Gleb Karpushkin. All rights reserved.
//
public extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xFF,
green: (rgb >> 8) & 0xFF,
blue: rgb & 0xFF
)
}
private class func colorComponentsFrom(string: NSString, start: Int, length: Int) -> Float {
NSMakeRange(start, length)
let subString = string.substring(with: NSMakeRange(start, length))
var hexValue: UInt32 = 0
Scanner(string: subString).scanHexInt32(&hexValue)
return Float(hexValue) / 255.0
}
convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (255, 0, 0, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
public func hexString(_ includeAlpha: Bool = true) -> String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
if (includeAlpha) {
return String(format: "%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255))
} else {
return String(format: "%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
}
}
}
#if os(iOS) || os(tvOS)
import UIKit
public extension UIColor {
/// init method with RGB values from 0 to 255, instead of 0 to 1. With alpha(default:1)
public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a)
}
/// init method with hex string and alpha(default: 1)
public convenience init?(hexString: String, alpha: CGFloat = 1.0) {
var formatted = hexString.replacingOccurrences(of: "0x", with: "")
formatted = formatted.replacingOccurrences(of: "#", with: "")
if let hex = Int(formatted, radix: 16) {
let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0)
let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0)
let blue = CGFloat(CGFloat((hex & 0x0000FF) >> 0)/255.0)
self.init(red: red, green: green, blue: blue, alpha: alpha) } else {
return nil
}
}
/// init method from Gray value and alpha(default:1)
public convenience init(gray: CGFloat, alpha: CGFloat = 1) {
self.init(red: gray/255, green: gray/255, blue: gray/255, alpha: alpha)
}
/// Red component of UIColor (get-only)
public var redComponent: Int {
var r: CGFloat = 0
getRed(&r, green: nil, blue: nil, alpha: nil)
return Int(r * 255)
}
/// Green component of UIColor (get-only)
public var greenComponent: Int {
var g: CGFloat = 0
getRed(nil, green: &g, blue: nil, alpha: nil)
return Int(g * 255)
}
/// blue component of UIColor (get-only)
public var blueComponent: Int {
var b: CGFloat = 0
getRed(nil, green: nil, blue: &b, alpha: nil)
return Int(b * 255)
}
/// Alpha of UIColor (get-only)
public var alpha: CGFloat {
var a: CGFloat = 0
getRed(nil, green: nil, blue: nil, alpha: &a)
return a
}
/// Returns random UIColor with random alpha(default: false)
public static func random(randomAlpha: Bool = false) -> UIColor {
let randomRed = CGFloat.random()
let randomGreen = CGFloat.random()
let randomBlue = CGFloat.random()
let alpha = randomAlpha ? CGFloat.random() : 1.0
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: alpha)
}
}
#endif
| 37.639706 | 116 | 0.527837 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.