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
75ba7b2ffe43087feb0e1de139c2a838fabd2324
680
// // SettingsViewModel.swift // BrakhQ // // Created by Kiryl Holubeu on 4/17/19. // Copyright © 2019 brakhmen. All rights reserved. // import UIKit protocol SettingsViewModelDelegate: class { func settingsViewModel(_ settingsViewModel: SettingsViewModel, readyToExit: Bool) } final class SettingsViewModel { weak var delegate: SettingsViewModelDelegate? func getUpdateViewController() -> UIViewController { let viewModel = UpdateProfileViewModel() return UpdateProfileViewController(viewModel: viewModel) } func exit() { AuthManager.shared.logout() DataManager.shared.logout() delegate?.settingsViewModel(self, readyToExit: true) } }
18.888889
82
0.745588
f846dd51157745d88bb80b5ad801bc79ec646790
2,873
import UIKit final class Zoom: UIView { private weak var centre: NSLayoutConstraint! private weak var indicator: UIView! private let zoom: ClosedRange<Int> required init?(coder: NSCoder) { nil } init(_ zoom: ClosedRange<Int>) { self.zoom = zoom super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false isUserInteractionEnabled = false let indicator = UIView() indicator.translatesAutoresizingMaskIntoConstraints = false indicator.isUserInteractionEnabled = false indicator.layer.cornerRadius = 2 indicator.layer.borderWidth = 1 indicator.layer.borderColor = .white addSubview(indicator) self.indicator = indicator let track = UIView() track.translatesAutoresizingMaskIntoConstraints = false track.isUserInteractionEnabled = false track.backgroundColor = .shade track.layer.borderColor = .white track.layer.borderWidth = 1 track.layer.cornerRadius = 2 addSubview(track) let range = UIView() range.translatesAutoresizingMaskIntoConstraints = false range.isUserInteractionEnabled = false range.backgroundColor = .white addSubview(range) widthAnchor.constraint(equalToConstant: 12).isActive = true heightAnchor.constraint(equalToConstant: 46).isActive = true track.widthAnchor.constraint(equalToConstant: 4).isActive = true track.leftAnchor.constraint(equalTo: leftAnchor).isActive = true track.topAnchor.constraint(equalTo: topAnchor).isActive = true track.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true range.widthAnchor.constraint(equalToConstant: 2).isActive = true range.leftAnchor.constraint(equalTo: leftAnchor, constant: 1).isActive = true range.bottomAnchor.constraint(equalTo: bottomAnchor, constant: .init(zoom.min()! * -2)).isActive = true range.topAnchor.constraint(equalTo: bottomAnchor, constant: .init(zoom.max()! * -2)).isActive = true indicator.leftAnchor.constraint(equalTo: track.rightAnchor, constant: -3).isActive = true indicator.rightAnchor.constraint(equalTo: rightAnchor, constant: -1).isActive = true indicator.heightAnchor.constraint(equalToConstant: 4).isActive = true centre = indicator.centerYAnchor.constraint(equalTo: bottomAnchor) centre.isActive = true } func update(_ value: CGFloat) { centre.constant = value * -2 UIView.animate(withDuration: 0.3) { [weak self] in guard let self = self else { return } self.indicator.backgroundColor = self.zoom.contains(Int(round(value))) ? .white : .shade self.layoutIfNeeded() } } }
42.25
111
0.668639
282859535a690583a1250206f7cf1c7a0428c8c4
4,515
// // Copyright (c) Vatsal Manot // import Dispatch import Swift import SwiftUI #if os(iOS) || os(macOS) || os(tvOS) || targetEnvironment(macCatalyst) public struct AttributedText: AppKitOrUIKitViewRepresentable { public typealias AppKitOrUIKitViewType = AppKitOrUIKitLabel struct Configuration: Hashable { var appKitOrUIKitFont: AppKitOrUIKitFont? var appKitOrUIKitForegroundColor: AppKitOrUIKitColor? } @Environment(\.accessibilityEnabled) var accessibilityEnabled @Environment(\.adjustsFontSizeToFitWidth) var adjustsFontSizeToFitWidth @Environment(\.allowsTightening) var allowsTightening @Environment(\.font) var font @Environment(\.isEnabled) var isEnabled @Environment(\.lineBreakMode) var lineBreakMode @Environment(\.lineLimit) var lineLimit @Environment(\.minimumScaleFactor) var minimumScaleFactor @Environment(\.preferredMaximumLayoutWidth) var preferredMaximumLayoutWidth #if os(macOS) @Environment(\.layoutDirection) var layoutDirection #endif public let content: NSAttributedString var configuration = Configuration() public init(_ content: NSAttributedString) { self.content = content } public init<S: StringProtocol>(_ content: S) { self.init(NSAttributedString(string: String(content))) } public func makeAppKitOrUIKitView(context: Context) -> AppKitOrUIKitViewType { AppKitOrUIKitViewType() } public func updateAppKitOrUIKitView(_ view: AppKitOrUIKitViewType, context: Context) { view.configure(with: self) } } // MARK: - API - extension AttributedText { public func font(_ font: AppKitOrUIKitFont) -> Self { then({ $0.configuration.appKitOrUIKitFont = font }) } public func foregroundColor(_ foregroundColor: AppKitOrUIKitColor) -> Self { then({ $0.configuration.appKitOrUIKitForegroundColor = foregroundColor }) } #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst) public func foregroundColor(_ foregroundColor: Color) -> Self { then({ $0.configuration.appKitOrUIKitForegroundColor = foregroundColor.toUIColor() }) } #endif } // MARK: - Auxiliary Implementation - extension AppKitOrUIKitLabel { func configure(with attributedText: AttributedText) { #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst) self.allowsDefaultTighteningForTruncation = attributedText.allowsTightening #endif self.font = attributedText.configuration.appKitOrUIKitFont ?? self.font self.adjustsFontSizeToFitWidth = attributedText.adjustsFontSizeToFitWidth self.lineBreakMode = attributedText.lineBreakMode self.minimumScaleFactor = attributedText.minimumScaleFactor self.numberOfLines = attributedText.lineLimit ?? 0 self.textColor = attributedText.configuration.appKitOrUIKitForegroundColor ?? self.textColor #if os(macOS) self.setAccessibilityEnabled(attributedText.accessibilityEnabled) self.userInterfaceLayoutDirection = .init(attributedText.layoutDirection) #endif #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst) if let font = attributedText.configuration.appKitOrUIKitFont ?? attributedText.font?.toUIFont() { let string = NSMutableAttributedString(attributedString: attributedText.content) string.addAttribute(.font, value: font, range: .init(location: 0, length: string.length)) self.attributedText = attributedText.content } else { self.attributedText = attributedText.content } #else self.attributedText = attributedText.content #endif if let preferredMaximumLayoutWidth = attributedText.preferredMaximumLayoutWidth, preferredMaxLayoutWidth != attributedText.preferredMaximumLayoutWidth { preferredMaxLayoutWidth = preferredMaximumLayoutWidth frame.size.width = min(frame.size.width, preferredMaximumLayoutWidth) #if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst) setNeedsLayout() layoutIfNeeded() #endif } setContentCompressionResistancePriority(.defaultHigh, for: .vertical) setContentHuggingPriority(.defaultHigh, for: .horizontal) setContentHuggingPriority(.defaultLow, for: .vertical) } } #endif
37.008197
160
0.696124
72893e936408077d4951957b2094dee42864ee93
8,510
// // CipherChaCha20Tests.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 27/12/14. // Copyright (C) 2014-2017 Krzyzanowski. All rights reserved. // import XCTest import Foundation @testable import CryptoSwift final class ChaCha20Tests: XCTestCase { func testChaCha20() { let keys: [Array<UInt8>] = [ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f], ] let ivs: [Array<UInt8>] = [ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01], [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07], ] let expectedHexes = [ "76B8E0ADA0F13D90405D6AE55386BD28BDD219B8A08DED1AA836EFCC8B770DC7DA41597C5157488D7724E03FB8D84A376A43B8F41518A11CC387B669B2EE6586", "4540F05A9F1FB296D7736E7B208E3C96EB4FE1834688D2604F450952ED432D41BBE2A0B6EA7566D2A5D1E7E20D42AF2C53D792B1C43FEA817E9AD275AE546963", "DE9CBA7BF3D69EF5E786DC63973F653A0B49E015ADBFF7134FCB7DF137821031E85A050278A7084527214F73EFC7FA5B5277062EB7A0433E445F41E3", "EF3FDFD6C61578FBF5CF35BD3DD33B8009631634D21E42AC33960BD138E50D32111E4CAF237EE53CA8AD6426194A88545DDC497A0B466E7D6BBDB0041B2F586B", "F798A189F195E66982105FFB640BB7757F579DA31602FC93EC01AC56F85AC3C134A4547B733B46413042C9440049176905D3BE59EA1C53F15916155C2BE8241A38008B9A26BC35941E2444177C8ADE6689DE95264986D95889FB60E84629C9BD9A5ACB1CC118BE563EB9B3A4A472F82E09A7E778492B562EF7130E88DFE031C79DB9D4F7C7A899151B9A475032B63FC385245FE054E3DD5A97A5F576FE064025D3CE042C566AB2C507B138DB853E3D6959660996546CC9C4A6EAFDC777C040D70EAF46F76DAD3979E5C5360C3317166A1C894C94A371876A94DF7628FE4EAAF2CCB27D5AAAE0AD7AD0F9D4B6AD3B54098746D4524D38407A6DEB3AB78FAB78C9", ] for idx in 0..<keys.count { let expectedHex = expectedHexes[idx] let message = Array<UInt8>(repeating: 0, count: (expectedHex.count / 2)) do { let encrypted = try message.encrypt(cipher: ChaCha20(key: keys[idx], iv: ivs[idx])) let decrypted = try encrypted.decrypt(cipher: ChaCha20(key: keys[idx], iv: ivs[idx])) XCTAssertEqual(message, decrypted, "ChaCha20 decryption failed") XCTAssertEqual(encrypted, Array<UInt8>(hex: expectedHex)) } catch CipherError.encrypt { XCTAssert(false, "Encryption failed") } catch CipherError.decrypt { XCTAssert(false, "Decryption failed") } catch { XCTAssert(false, "Failed") } } } func testCore() { let key: Array<UInt8> = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] var counter: Array<UInt8> = [1, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 74, 0, 0, 0, 0] let input = Array<UInt8>.init(repeating: 0, count: 129) let chacha = try! ChaCha20(key: key, iv: Array(key[4..<16])) let result = chacha.process(bytes: input, counter: &counter, key: key) XCTAssertEqual(result.toHexString(), "10f1e7e4d13b5915500fdd1fa32071c4c7d1f4c733c068030422aa9ac3d46c4ed2826446079faa0914c2d705d98b02a2b5129cd1de164eb9cbd083e8a2503c4e0a88837739d7bf4ef8ccacb0ea2bb9d69d56c394aa351dfda5bf459f0a2e9fe8e721f89255f9c486bf21679c683d4f9c5cf2fa27865526005b06ca374c86af3bdc") } func testVector1Py() { let key: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] let iv: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] let expected: Array<UInt8> = [0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, 0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7, 0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, 0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c, 0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86] let message = Array<UInt8>(repeating: 0, count: expected.count) do { let encrypted = try ChaCha20(key: key, iv: iv).encrypt(message) XCTAssertEqual(encrypted, expected, "Ciphertext failed") } catch { XCTFail() } } func testChaCha20EncryptPartial() { let key: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f] let iv: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07] let expectedHex = "F798A189F195E66982105FFB640BB7757F579DA31602FC93EC01AC56F85AC3C134A4547B733B46413042C9440049176905D3BE59EA1C53F15916155C2BE8241A38008B9A26BC35941E2444177C8ADE6689DE95264986D95889FB60E84629C9BD9A5ACB1CC118BE563EB9B3A4A472F82E09A7E778492B562EF7130E88DFE031C79DB9D4F7C7A899151B9A475032B63FC385245FE054E3DD5A97A5F576FE064025D3CE042C566AB2C507B138DB853E3D6959660996546CC9C4A6EAFDC777C040D70EAF46F76DAD3979E5C5360C3317166A1C894C94A371876A94DF7628FE4EAAF2CCB27D5AAAE0AD7AD0F9D4B6AD3B54098746D4524D38407A6DEB3AB78FAB78C9" let plaintext: Array<UInt8> = Array<UInt8>(repeating: 0, count: (expectedHex.count / 2)) do { let cipher = try ChaCha20(key: key, iv: iv) var ciphertext = Array<UInt8>() var encryptor = cipher.makeEncryptor() ciphertext += try encryptor.update(withBytes: Array(plaintext[0..<8])) ciphertext += try encryptor.update(withBytes: Array(plaintext[8..<16])) ciphertext += try encryptor.update(withBytes: Array(plaintext[16..<80])) ciphertext += try encryptor.update(withBytes: Array(plaintext[80..<256])) ciphertext += try encryptor.finish() XCTAssertEqual(Array<UInt8>(hex: expectedHex), ciphertext) } catch { XCTFail() } } } #if !CI extension ChaCha20Tests { func testChaCha20Performance() { let key: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f] let iv: Array<UInt8> = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07] let message = Array<UInt8>(repeating: 7, count: 1024) measureMetrics([XCTPerformanceMetric.wallClockTime], automaticallyStartMeasuring: true, for: { () -> Void in do { _ = try ChaCha20(key: key, iv: iv).encrypt(message) } catch { XCTFail() } self.stopMeasuring() }) } } #endif extension ChaCha20Tests { static func allTests() -> [(String, (ChaCha20Tests) -> () -> Void)] { var tests = [ ("testChaCha20", testChaCha20), ("testCore", testCore), ("testVector1Py", testVector1Py), ("testChaCha20EncryptPartial", testChaCha20EncryptPartial), ] #if !CI tests += [("testChaCha20Performance", testChaCha20Performance)] #endif return tests } }
60.35461
540
0.663102
11ab63dae56142b4e2617a9ff0cce9e7e799fa3c
675
// // UIStackView+extensions.swift // MobileClasswork // // Created by Macbook Pro 15 on 3/28/20. // Copyright © 2020 SamuelFolledo. All rights reserved. // import UIKit extension UIStackView { /// setup vertical stackView func setupStandardVertical() { self.translatesAutoresizingMaskIntoConstraints = false self.distribution = .fill self.axis = .vertical self.alignment = .fill } /// setup horizontail stackView func setupStandardHorizontal() { self.translatesAutoresizingMaskIntoConstraints = false self.distribution = .fill self.axis = .horizontal self.alignment = .fill } }
23.275862
62
0.666667
0e4fa14d48e51e13a5856c88d4e3f8465418882d
1,026
import Foundation class TransactionSendTimer { let interval: TimeInterval weak var delegate: ITransactionSendTimerDelegate? var runLoop: RunLoop? var timer: Timer? init(interval: TimeInterval) { self.interval = interval } } extension TransactionSendTimer: ITransactionSendTimer { func startIfNotRunning() { guard runLoop == nil else { return } DispatchQueue.global(qos: .background).async { self.runLoop = .current let timer = Timer(timeInterval: self.interval, repeats: true, block: { [weak self] _ in self?.delegate?.timePassed() }) self.timer = timer RunLoop.current.add(timer, forMode: .common) RunLoop.current.run() } } func stop() { if let runLoop = self.runLoop { timer?.invalidate() timer?.invalidate() CFRunLoopStop(runLoop.getCFRunLoop()) timer = nil self.runLoop = nil } } }
22.304348
131
0.584795
f8d1253340fee9dd052307912829ffb2a939971a
4,204
// // Created by David Whetstone on 1/22/16. // Copyright (c) 2016 humblehacker. All rights reserved. // import UIKit fileprivate extension Selector { static let statusBarHeightWillChange = #selector(MainWindow.statusBarHeightWillChange(n:)) static let dismiss = #selector(MainWindow.dismiss) static let toggleHeader = #selector(MainWindow.toggleHeader) } public class MainWindow: UIWindow { public static let instance = MainWindow(frame: UIScreen.main.bounds) private let headerWindow = UIWindow() private let headerVC = HeaderViewController(headerHeight: MainWindow.headerHeight) private class var compressedHeaderHeight: CGFloat { return UIApplication.shared.statusBarFrame.size.height } private class var expandedHeaderHeight: CGFloat { return compressedHeaderHeight + headerHeight } private var headerCompressed = true private static let headerHeight: CGFloat = 30.0 public override init(frame: CGRect) { var f = frame f.origin.y = MainWindow.compressedHeaderHeight f.size.height = UIScreen.main.bounds.size.height - MainWindow.compressedHeaderHeight super.init(frame: f) self.layer.borderColor = UIColor.red.cgColor self.layer.borderWidth = 1.0 NotificationCenter.default.addObserver(self, selector: Selector.statusBarHeightWillChange, name: UIApplication.willChangeStatusBarFrameNotification, object: nil) addHeaderWindow() addGestures() } public required init(coder: NSCoder) { fatalError("not implemented") } func addHeaderWindow() { headerWindow.rootViewController = headerVC headerWindow.frame.origin.y = 0 headerWindow.frame.size.height = MainWindow.compressedHeaderHeight headerWindow.isHidden = false } func addGestures() { let doubleTap = UITapGestureRecognizer(target: self, action: Selector.dismiss) doubleTap.numberOfTapsRequired = 2 self.addGestureRecognizer(doubleTap) let swipe = UISwipeGestureRecognizer(target: self, action: Selector.toggleHeader) swipe.direction = [.down, .up] self.addGestureRecognizer(swipe) } @objc func dismiss() { print("dismiss") rootViewController?.dismiss(animated: true, completion: nil) } @objc func toggleHeader() { if headerCompressed { expandHeader() } else { compressHeader() } } func expandHeader() { print("showHeader") self.adjustWindows(headerHeight: MainWindow.expandedHeaderHeight) { self.headerCompressed = false } } func compressHeader() { print("compressHeader") self.adjustWindows(headerHeight: MainWindow.compressedHeaderHeight) { self.headerCompressed = true } } func adjustWindows(headerHeight: CGFloat, completion: @escaping ()->Void) { // Critical point: Both windows and the statusBar background of the header view controller // must be animated together. The duration matches the duration of the in-call status bar show/hide. UIView.animate(withDuration: 0.35) { let statusBarFrame = UIApplication.shared.statusBarFrame self.headerVC.adjustStatusBarHeight(height: statusBarFrame.size.height) self.headerWindow.frame.size.height = headerHeight self.headerWindow.layoutIfNeeded() self.frame.origin.y = headerHeight self.frame.size.height = UIScreen.main.bounds.size.height - headerHeight self.layoutIfNeeded() completion() } } @objc func statusBarHeightWillChange(n: NSNotification) { // Critical point: We call the header adjustment method for the current header state to ensure // our header sizes animate smoothly with the change in status bar height. if headerCompressed { compressHeader() } else { expandHeader() } } }
28.026667
112
0.651047
717cd530cb94e054331c68c1e09a6e3155f7ed8d
2,741
// // SelectAssetCell.swift // sample-conference-videochat-swift // // Created by Injoit on 12/9/19. // Copyright © 2019 Quickblox. All rights reserved. // import UIKit class SelectAssetCell: UICollectionViewCell { @IBOutlet weak var durationVideoLabel: UILabel! @IBOutlet weak var videoTypeView: UIView! @IBOutlet weak var assetTypeImageView: UIImageView! @IBOutlet weak var assetImageView: UIImageView! @IBOutlet weak var checkBoxImageView: UIImageView! @IBOutlet weak var checkBoxView: UIView! //MARK: - Overrides override func awakeFromNib() { checkBoxView.backgroundColor = UIColor.white.withAlphaComponent(0.35) checkBoxView.setRoundBorderEdgeColorView(cornerRadius: 4.0, borderWidth: 1.0, borderColor: UIColor.white) videoTypeView.setRoundView(cornerRadius: 3) videoTypeView.isHidden = true assetImageView.contentMode = .scaleAspectFill } override func prepareForReuse() { assetTypeImageView.image = nil checkBoxView.backgroundColor = UIColor.white.withAlphaComponent(0.35) checkBoxView.setRoundBorderEdgeColorView(cornerRadius: 4.0, borderWidth: 1.0, borderColor: UIColor.white) videoTypeView.isHidden = true checkBoxImageView.isHidden = true } override var isHighlighted: Bool { willSet { onSelectedCell(newValue) } } override var isSelected: Bool { willSet { onSelectedCell(newValue) } } func onSelectedCell(_ newValue: Bool) { if newValue == true { checkBoxImageView.isHidden = false contentView.backgroundColor = UIColor(red:0.85, green:0.89, blue:0.97, alpha:1) checkBoxView.setRoundBorderEdgeColorView(cornerRadius: 4.0, borderWidth: 1.0, color: UIColor(red:0.22, green:0.47, blue:0.99, alpha:1), borderColor: UIColor(red:0.22, green:0.47, blue:0.99, alpha:1)) } else { checkBoxImageView.isHidden = true contentView.backgroundColor = .clear checkBoxView.setRoundBorderEdgeColorView(cornerRadius: 4.0, borderWidth: 1.0, color: UIColor.white.withAlphaComponent(0.35), borderColor: UIColor.white) } } }
38.069444
116
0.557461
d93d9ef23e0d6bd6112f7ee58b6e90e622ef3035
974
import UIKit //////////////////////// // ENUMS //////////////////////// enum UIBarButtonStyle { case Done case Plain case Bordered } class UIBarButtonItem { var title: String? let style: UIBarButtonStyle var target: AnyObject? var action: Selector init(title: String?, style: UIBarButtonStyle, target: AnyObject?, action: Selector) { self.title = title self.style = style self.target = target self.action = action } } enum Button { // properties with assoiated values case Done(title: String) case Edit(title: String) func toUIBarButtonItem() -> UIBarButtonItem { // switch is best for enums since finite data switch self { case .Done(let title): return UIBarButtonItem(title: title, style: .Done, target: nil, action: nil) case .Edit(let title): return UIBarButtonItem(title: title, style: .Plain, target: nil, action: nil) } } } let doneButton = Button.Done(title: "Done").toUIBarButtonItem()
22.136364
104
0.656057
26d8908568db6a98950255b22109d0105ed56e40
654
// // ID3RecordingYearFrameCreator.swift // // Created by Fabrizio Duroni on 04/03/2018. // 2018 Fabrizio Duroni. // import Foundation class ID3RecordingYearFrameCreator: ID3StringFrameCreator { override func createFrames(id3Tag: ID3Tag, tag: [UInt8]) -> [UInt8] { if id3Tag.properties.version < .version4, let yearFrame = id3Tag.frames[.RecordingYear] as? ID3FrameRecordingYear, let year = yearFrame.year { return createFrameUsing(frameType: .RecordingYear, content: String(year), id3Tag: id3Tag, andAddItTo: tag) } return super.createFrames(id3Tag: id3Tag, tag: tag) } }
32.7
118
0.67737
1d93075c5c217ec683e756c324829f4312d19a8f
13,153
/* * Copyright 2015 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import Blockly import WebKit /** Demo app for using blocks to move a cute little turtle. */ class TurtleSwiftViewController: UIViewController, TurtleViewControllerInterface { // MARK: - Static Properties /// The callback name to access this object from the JS code. /// See "turtle/turtle.js" for an example of its usage. static let JS_CALLBACK_NAME = "TurtleViewControllerCallback" // MARK: - Properties /// The view for holding `self.webView` @IBOutlet var webViewContainer: UIView! /// Text to show generated code @IBOutlet var codeText: UILabel! /// The view for holding `self.workbenchViewController.view` @IBOutlet var editorView: UIView! /// The play/cancel button @IBOutlet weak var playButton: UIButton! /// The web view that runs the turtle code (this is not an outlet because WKWebView isn't /// supported by Interface Builder) var _webView: WKWebView! /// The workbench for the blocks. var _workbenchViewController: WorkbenchViewController! /// Code generator service lazy var _codeGeneratorService: CodeGeneratorService = { // Create the code generator service let codeGeneratorService = CodeGeneratorService( jsCoreDependencies: [ // The JS file containing the Blockly engine "Turtle/blockly_web/blockly_compressed.js", // The JS file containing a list of internationalized messages "Turtle/blockly_web/msg/js/en.js" ]) return codeGeneratorService }() /// Builder for creating code generator service requests lazy var _codeGeneratorServiceRequestBuilder: CodeGeneratorServiceRequestBuilder = { let builder = CodeGeneratorServiceRequestBuilder( // This is the name of the JS object that will generate JavaScript code jsGeneratorObject: "Blockly.JavaScript") builder.addJSBlockGeneratorFiles([ // Use JavaScript code generators for the default blocks "Turtle/blockly_web/javascript_compressed.js", // Use JavaScript code generators for our custom turtle blocks "Turtle/generators.js"]) // Load the block definitions for all default blocks builder.addJSONBlockDefinitionFiles(fromDefaultFiles: .AllDefault) // Load the block definitions for our custom turtle blocks builder.addJSONBlockDefinitionFiles(["Turtle/turtle_blocks.json"]) return builder }() /// Factory that produces block instances lazy var _blockFactory: BlockFactory = { let blockFactory = BlockFactory() // Load default blocks into the block factory blockFactory.load(fromDefaultFiles: [.AllDefault]) // Load custom turtle blocks into the block factory do { try blockFactory.load(fromJSONPaths: ["Turtle/turtle_blocks.json"]) } catch let error { print("An error occurred loading the turtle blocks: \(error)") } return blockFactory }() /// Flag indicating whether the code is currently running. var _currentlyRunning: Bool = false /// Flag indicating if highlighting a block is enabled. var _allowBlockHighlighting: Bool = false /// Flag indicating if scrolling a block into view is enabled. var _allowScrollingToBlockView: Bool = false /// The UUID of the last block that was highlighted. var _lastHighlightedBlockUUID: String? /// Date formatter for timestamping events let _dateFormatter = DateFormatter() // MARK: - Initializers init() { // Load from xib file super.init(nibName: "TurtleViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { // If the Turtle code is currently executing, we need to reset it before deallocating this // instance. if let webView = _webView { webView.configuration.userContentController.removeScriptMessageHandler( forName: TurtleSwiftViewController.JS_CALLBACK_NAME) webView.stopLoading() } resetTurtleCode() _codeGeneratorService.cancelAllRequests() } // MARK: - Super override func viewDidLoad() { super.viewDidLoad() // Don't allow the navigation controller bar cover this view controller self.edgesForExtendedLayout = UIRectEdge() self.navigationItem.title = "Swift Turtle Demo" // Load the block editor _workbenchViewController = WorkbenchViewController(style: .alternate) _workbenchViewController.delegate = self _workbenchViewController.toolboxDrawerStaysOpen = true // Create a workspace do { let workspace = Workspace() try _workbenchViewController.loadWorkspace(workspace) } catch let error { print("Couldn't load the workspace: \(error)") } // Load the toolbox do { let toolboxPath = "Turtle/toolbox.xml" if let bundlePath = Bundle.main.path(forResource: toolboxPath, ofType: nil) { let xmlString = try String(contentsOfFile: bundlePath, encoding: String.Encoding.utf8) let toolbox = try Toolbox.makeToolbox(xmlString: xmlString, factory: _blockFactory) try _workbenchViewController.loadToolbox(toolbox) } else { print("Could not load toolbox XML from '\(toolboxPath)'") } } catch let error { print("An error occurred loading the toolbox: \(error)") } addChildViewController(_workbenchViewController) editorView.autoresizesSubviews = true _workbenchViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] _workbenchViewController.view.frame = editorView.bounds editorView.addSubview(_workbenchViewController.view) _workbenchViewController.didMove(toParentViewController: self) // Programmatically create WKWebView and configure it with a hook so the JS code can callback // into the iOS code. let userContentController = WKUserContentController() userContentController.add(ScriptMessageHandler(self), name: TurtleSwiftViewController.JS_CALLBACK_NAME) let configuration = WKWebViewConfiguration() configuration.userContentController = userContentController _webView = WKWebView(frame: webViewContainer.bounds, configuration: configuration) _webView.autoresizingMask = [.flexibleHeight, .flexibleWidth] _webView.translatesAutoresizingMaskIntoConstraints = true webViewContainer.autoresizesSubviews = true webViewContainer.addSubview(_webView) // Load the turtle executable code if let url = Bundle.main.url(forResource: "Turtle/turtle", withExtension: "html") { _webView.load(URLRequest(url: url)) } else { print("Couldn't load Turtle/turtle.html") } // Make things a bit prettier _webView.layer.borderColor = UIColor.lightGray.cgColor _webView.layer.borderWidth = 1 codeText.superview?.layer.borderColor = UIColor.lightGray.cgColor codeText.superview?.layer.borderWidth = 1 _dateFormatter.dateFormat = "HH:mm:ss.SSS" } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) _codeGeneratorService.cancelAllRequests() } override var prefersStatusBarHidden : Bool { return true } // MARK: - Private @IBAction internal dynamic func didPressPlay(_ button: UIButton) { do { if _currentlyRunning { _webView.evaluateJavaScript("Turtle.cancel()", completionHandler: nil) self.resetPlayButton() } else { if let workspace = _workbenchViewController.workspace { // Cancel pending requests _codeGeneratorService.cancelAllRequests() // Reset the turtle resetTurtleCode() self.codeText.text = "" addTimestampedText("Generating code...") // Request code generation for the workspace let request = try _codeGeneratorServiceRequestBuilder.makeRequest(forWorkspace: workspace) request.onCompletion = { code in self.codeGenerationCompleted(code: code) } request.onError = { error in self.codeGenerationFailed(error: error) } _codeGeneratorService.generateCode(forRequest: request) playButton.setImage(UIImage(named: "cancel_button"), for: .normal) _currentlyRunning = true } } } catch let error { print("An error occurred generating code for the workspace: \(error)") } } fileprivate func codeGenerationCompleted(code: String) { addTimestampedText("Generated code:\n\n====CODE====\n\n\(code)") runCode(code) } fileprivate func codeGenerationFailed(error: String) { addTimestampedText("An error occurred:\n\n====ERROR====\n\n\(error)") resetPlayButton() } fileprivate func resetPlayButton() { _currentlyRunning = false playButton.setImage(UIImage(named: "play_button"), for: .normal) } fileprivate func runCode(_ code: String) { // Allow block highlighting and scrolling a block into view (it can only be disabled by explicit // user interaction) _allowBlockHighlighting = true _allowScrollingToBlockView = true // Run the generated code in the web view by calling `Turtle.execute(<code>)` let codeParam = code.bky_escapedJavaScriptParameter() _webView.evaluateJavaScript( "Turtle.execute(\"\(codeParam)\")", completionHandler: { _, error -> Void in if error != nil { self.codeGenerationFailed(error: "\(error)") } }) } fileprivate func resetTurtleCode() { _webView?.evaluateJavaScript("Turtle.reset();", completionHandler: nil) } fileprivate func addTimestampedText(_ text: String) { self.codeText.text = (self.codeText.text ?? "") + "[\(_dateFormatter.string(from: Date()))] \(text)\n" } } /** Because WKUserContentController makes a strong retain cycle to its delegate, we create an intermediary object here to act as a delegate so we can more easily break a potential retain cycle between WKUserContentController and TurtleSwiftViewController. */ class ScriptMessageHandler : NSObject, WKScriptMessageHandler { weak var delegate : WKScriptMessageHandler? init(_ delegate: WKScriptMessageHandler) { self.delegate = delegate super.init() } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { // Call "real" delegate (which is TurtleSwiftViewController) self.delegate?.userContentController(userContentController, didReceive: message) } } // MARK: - WKScriptMessageHandler implementation /** Handler responsible for relaying messages back from `self.webView`. */ extension TurtleSwiftViewController: WKScriptMessageHandler { @objc func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { guard let dictionary = message.body as? [String: AnyObject], let method = dictionary["method"] as? String else { return } switch method { case "highlightBlock": if let blockID = dictionary["blockID"] as? String { if _allowBlockHighlighting { _workbenchViewController.highlightBlock(blockUUID: blockID) _lastHighlightedBlockUUID = blockID } if _allowScrollingToBlockView { _workbenchViewController.scrollBlockIntoView(blockUUID: blockID, animated: true) } } case "unhighlightLastBlock": if let blockID = _lastHighlightedBlockUUID { _workbenchViewController.unhighlightBlock(blockUUID: blockID) _lastHighlightedBlockUUID = blockID } case "finishExecution": self.resetPlayButton() default: print("Unrecognized method") } } } // MARK: - WorkbenchViewControllerDelegate implementation extension TurtleSwiftViewController: WorkbenchViewControllerDelegate { func workbenchViewController(_ workbenchViewController: WorkbenchViewController, didUpdateState state: WorkbenchViewController.UIState) { // We need to disable automatic block view scrolling / block highlighting based on the latest // user interaction. // Only allow automatic scrolling if the user tapped on the workspace. _allowScrollingToBlockView = state.isSubset(of: [.didTapWorkspace]) // Only allow block highlighting if the user tapped/panned the workspace or opened either the // toolbox or trash can. _allowBlockHighlighting = state.isSubset(of: [.didTapWorkspace, .didPanWorkspace, .categoryOpen, .trashCanOpen]) } }
35.262735
100
0.711853
8f199e905788b9a534398337d0bb8ac70efac59d
23,554
import Foundation import RxSwift import GRPC import NIO /** Enable raw missions as exposed by MAVLink. */ public class MissionRaw { private let service: Mavsdk_Rpc_MissionRaw_MissionRawServiceClient private let scheduler: SchedulerType private let clientEventLoopGroup: EventLoopGroup /** Initializes a new `MissionRaw` plugin. Normally never created manually, but used from the `Drone` helper class instead. - Parameters: - address: The address of the `MavsdkServer` instance to connect to - port: The port of the `MavsdkServer` instance to connect to - scheduler: The scheduler to be used by `Observable`s */ public convenience init(address: String = "localhost", port: Int32 = 50051, scheduler: SchedulerType = ConcurrentDispatchQueueScheduler(qos: .background)) { let eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 2) let channel = ClientConnection.insecure(group: eventLoopGroup).connect(host: address, port: Int(port)) let service = Mavsdk_Rpc_MissionRaw_MissionRawServiceClient(channel: channel) self.init(service: service, scheduler: scheduler, eventLoopGroup: eventLoopGroup) } init(service: Mavsdk_Rpc_MissionRaw_MissionRawServiceClient, scheduler: SchedulerType, eventLoopGroup: EventLoopGroup) { self.service = service self.scheduler = scheduler self.clientEventLoopGroup = eventLoopGroup } public struct RuntimeMissionRawError: Error { public let description: String init(_ description: String) { self.description = description } } public struct MissionRawError: Error { public let code: MissionRaw.MissionRawResult.Result public let description: String } /** Mission progress type. */ public struct MissionProgress: Equatable { public let current: Int32 public let total: Int32 /** Initializes a new `MissionProgress`. - Parameters: - current: Current mission item index (0-based) - total: Total number of mission items */ public init(current: Int32, total: Int32) { self.current = current self.total = total } internal var rpcMissionProgress: Mavsdk_Rpc_MissionRaw_MissionProgress { var rpcMissionProgress = Mavsdk_Rpc_MissionRaw_MissionProgress() rpcMissionProgress.current = current rpcMissionProgress.total = total return rpcMissionProgress } internal static func translateFromRpc(_ rpcMissionProgress: Mavsdk_Rpc_MissionRaw_MissionProgress) -> MissionProgress { return MissionProgress(current: rpcMissionProgress.current, total: rpcMissionProgress.total) } public static func == (lhs: MissionProgress, rhs: MissionProgress) -> Bool { return lhs.current == rhs.current && lhs.total == rhs.total } } /** Mission item exactly identical to MAVLink MISSION_ITEM_INT. */ public struct MissionItem: Equatable { public let seq: UInt32 public let frame: UInt32 public let command: UInt32 public let current: UInt32 public let autocontinue: UInt32 public let param1: Float public let param2: Float public let param3: Float public let param4: Float public let x: Int32 public let y: Int32 public let z: Float public let missionType: UInt32 /** Initializes a new `MissionItem`. - Parameters: - seq: Sequence (uint16_t) - frame: The coordinate system of the waypoint (actually uint8_t) - command: The scheduled action for the waypoint (actually uint16_t) - current: false:0, true:1 (actually uint8_t) - autocontinue: Autocontinue to next waypoint (actually uint8_t) - param1: PARAM1, see MAV_CMD enum - param2: PARAM2, see MAV_CMD enum - param3: PARAM3, see MAV_CMD enum - param4: PARAM4, see MAV_CMD enum - x: PARAM5 / local: x position in meters * 1e4, global: latitude in degrees * 10^7 - y: PARAM6 / y position: local: x position in meters * 1e4, global: longitude in degrees *10^7 - z: PARAM7 / local: Z coordinate, global: altitude (relative or absolute, depending on frame) - missionType: @brief Mission type (actually uint8_t) */ public init(seq: UInt32, frame: UInt32, command: UInt32, current: UInt32, autocontinue: UInt32, param1: Float, param2: Float, param3: Float, param4: Float, x: Int32, y: Int32, z: Float, missionType: UInt32) { self.seq = seq self.frame = frame self.command = command self.current = current self.autocontinue = autocontinue self.param1 = param1 self.param2 = param2 self.param3 = param3 self.param4 = param4 self.x = x self.y = y self.z = z self.missionType = missionType } internal var rpcMissionItem: Mavsdk_Rpc_MissionRaw_MissionItem { var rpcMissionItem = Mavsdk_Rpc_MissionRaw_MissionItem() rpcMissionItem.seq = seq rpcMissionItem.frame = frame rpcMissionItem.command = command rpcMissionItem.current = current rpcMissionItem.autocontinue = autocontinue rpcMissionItem.param1 = param1 rpcMissionItem.param2 = param2 rpcMissionItem.param3 = param3 rpcMissionItem.param4 = param4 rpcMissionItem.x = x rpcMissionItem.y = y rpcMissionItem.z = z rpcMissionItem.missionType = missionType return rpcMissionItem } internal static func translateFromRpc(_ rpcMissionItem: Mavsdk_Rpc_MissionRaw_MissionItem) -> MissionItem { return MissionItem(seq: rpcMissionItem.seq, frame: rpcMissionItem.frame, command: rpcMissionItem.command, current: rpcMissionItem.current, autocontinue: rpcMissionItem.autocontinue, param1: rpcMissionItem.param1, param2: rpcMissionItem.param2, param3: rpcMissionItem.param3, param4: rpcMissionItem.param4, x: rpcMissionItem.x, y: rpcMissionItem.y, z: rpcMissionItem.z, missionType: rpcMissionItem.missionType) } public static func == (lhs: MissionItem, rhs: MissionItem) -> Bool { return lhs.seq == rhs.seq && lhs.frame == rhs.frame && lhs.command == rhs.command && lhs.current == rhs.current && lhs.autocontinue == rhs.autocontinue && lhs.param1 == rhs.param1 && lhs.param2 == rhs.param2 && lhs.param3 == rhs.param3 && lhs.param4 == rhs.param4 && lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.missionType == rhs.missionType } } /** Result type. */ public struct MissionRawResult: Equatable { public let result: Result public let resultStr: String /** Possible results returned for action requests. */ public enum Result: Equatable { /// Unknown result. case unknown /// Request succeeded. case success /// Error. case error /// Too many mission items in the mission. case tooManyMissionItems /// Vehicle is busy. case busy /// Request timed out. case timeout /// Invalid argument. case invalidArgument /// Mission downloaded from the system is not supported. case unsupported /// No mission available on the system. case noMissionAvailable /// Mission transfer (upload or download) has been cancelled. case transferCancelled case UNRECOGNIZED(Int) internal var rpcResult: Mavsdk_Rpc_MissionRaw_MissionRawResult.Result { switch self { case .unknown: return .unknown case .success: return .success case .error: return .error case .tooManyMissionItems: return .tooManyMissionItems case .busy: return .busy case .timeout: return .timeout case .invalidArgument: return .invalidArgument case .unsupported: return .unsupported case .noMissionAvailable: return .noMissionAvailable case .transferCancelled: return .transferCancelled case .UNRECOGNIZED(let i): return .UNRECOGNIZED(i) } } internal static func translateFromRpc(_ rpcResult: Mavsdk_Rpc_MissionRaw_MissionRawResult.Result) -> Result { switch rpcResult { case .unknown: return .unknown case .success: return .success case .error: return .error case .tooManyMissionItems: return .tooManyMissionItems case .busy: return .busy case .timeout: return .timeout case .invalidArgument: return .invalidArgument case .unsupported: return .unsupported case .noMissionAvailable: return .noMissionAvailable case .transferCancelled: return .transferCancelled case .UNRECOGNIZED(let i): return .UNRECOGNIZED(i) } } } /** Initializes a new `MissionRawResult`. - Parameters: - result: Result enum value - resultStr: Human-readable English string describing the result */ public init(result: Result, resultStr: String) { self.result = result self.resultStr = resultStr } internal var rpcMissionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult { var rpcMissionRawResult = Mavsdk_Rpc_MissionRaw_MissionRawResult() rpcMissionRawResult.result = result.rpcResult rpcMissionRawResult.resultStr = resultStr return rpcMissionRawResult } internal static func translateFromRpc(_ rpcMissionRawResult: Mavsdk_Rpc_MissionRaw_MissionRawResult) -> MissionRawResult { return MissionRawResult(result: Result.translateFromRpc(rpcMissionRawResult.result), resultStr: rpcMissionRawResult.resultStr) } public static func == (lhs: MissionRawResult, rhs: MissionRawResult) -> Bool { return lhs.result == rhs.result && lhs.resultStr == rhs.resultStr } } /** Upload a list of raw mission items to the system. The raw mission items are uploaded to a drone. Once uploaded the mission can be started and executed even if the connection is lost. - Parameter missionItems: The mission items */ public func uploadMission(missionItems: [MissionItem]) -> Completable { return Completable.create { completable in var request = Mavsdk_Rpc_MissionRaw_UploadMissionRequest() missionItems.forEach({ elem in request.missionItems.append(elem.rpcMissionItem) }) do { let response = self.service.uploadMission(request) let result = try response.response.wait().missionRawResult if (result.result == Mavsdk_Rpc_MissionRaw_MissionRawResult.Result.success) { completable(.completed) } else { completable(.error(MissionRawError(code: MissionRawResult.Result.translateFromRpc(result.result), description: result.resultStr))) } } catch { completable(.error(error)) } return Disposables.create() } } /** Cancel an ongoing mission upload. */ public func cancelMissionUpload() -> Completable { return Completable.create { completable in let request = Mavsdk_Rpc_MissionRaw_CancelMissionUploadRequest() do { let response = self.service.cancelMissionUpload(request) let result = try response.response.wait().missionRawResult if (result.result == Mavsdk_Rpc_MissionRaw_MissionRawResult.Result.success) { completable(.completed) } else { completable(.error(MissionRawError(code: MissionRawResult.Result.translateFromRpc(result.result), description: result.resultStr))) } } catch { completable(.error(error)) } return Disposables.create() } } /** Download a list of raw mission items from the system (asynchronous). */ public func downloadMission() -> Single<[MissionItem]> { return Single<[MissionItem]>.create { single in let request = Mavsdk_Rpc_MissionRaw_DownloadMissionRequest() do { let response = self.service.downloadMission(request) let result = try response.response.wait().missionRawResult if (result.result != Mavsdk_Rpc_MissionRaw_MissionRawResult.Result.success) { single(.error(MissionRawError(code: MissionRawResult.Result.translateFromRpc(result.result), description: result.resultStr))) return Disposables.create() } let missionItems = try response.response.wait().missionItems.map{ MissionItem.translateFromRpc($0) } single(.success(missionItems)) } catch { single(.error(error)) } return Disposables.create() } } /** Cancel an ongoing mission download. */ public func cancelMissionDownload() -> Completable { return Completable.create { completable in let request = Mavsdk_Rpc_MissionRaw_CancelMissionDownloadRequest() do { let response = self.service.cancelMissionDownload(request) let result = try response.response.wait().missionRawResult if (result.result == Mavsdk_Rpc_MissionRaw_MissionRawResult.Result.success) { completable(.completed) } else { completable(.error(MissionRawError(code: MissionRawResult.Result.translateFromRpc(result.result), description: result.resultStr))) } } catch { completable(.error(error)) } return Disposables.create() } } /** Start the mission. A mission must be uploaded to the vehicle before this can be called. */ public func startMission() -> Completable { return Completable.create { completable in let request = Mavsdk_Rpc_MissionRaw_StartMissionRequest() do { let response = self.service.startMission(request) let result = try response.response.wait().missionRawResult if (result.result == Mavsdk_Rpc_MissionRaw_MissionRawResult.Result.success) { completable(.completed) } else { completable(.error(MissionRawError(code: MissionRawResult.Result.translateFromRpc(result.result), description: result.resultStr))) } } catch { completable(.error(error)) } return Disposables.create() } } /** Pause the mission. Pausing the mission puts the vehicle into [HOLD mode](https://docs.px4.io/en/flight_modes/hold.html). A multicopter should just hover at the spot while a fixedwing vehicle should loiter around the location where it paused. */ public func pauseMission() -> Completable { return Completable.create { completable in let request = Mavsdk_Rpc_MissionRaw_PauseMissionRequest() do { let response = self.service.pauseMission(request) let result = try response.response.wait().missionRawResult if (result.result == Mavsdk_Rpc_MissionRaw_MissionRawResult.Result.success) { completable(.completed) } else { completable(.error(MissionRawError(code: MissionRawResult.Result.translateFromRpc(result.result), description: result.resultStr))) } } catch { completable(.error(error)) } return Disposables.create() } } /** Clear the mission saved on the vehicle. */ public func clearMission() -> Completable { return Completable.create { completable in let request = Mavsdk_Rpc_MissionRaw_ClearMissionRequest() do { let response = self.service.clearMission(request) let result = try response.response.wait().missionRawResult if (result.result == Mavsdk_Rpc_MissionRaw_MissionRawResult.Result.success) { completable(.completed) } else { completable(.error(MissionRawError(code: MissionRawResult.Result.translateFromRpc(result.result), description: result.resultStr))) } } catch { completable(.error(error)) } return Disposables.create() } } /** Sets the raw mission item index to go to. By setting the current index to 0, the mission is restarted from the beginning. If it is set to a specific index of a raw mission item, the mission will be set to this item. - Parameter index: Index of the mission item to be set as the next one (0-based) */ public func setCurrentMissionItem(index: Int32) -> Completable { return Completable.create { completable in var request = Mavsdk_Rpc_MissionRaw_SetCurrentMissionItemRequest() request.index = index do { let response = self.service.setCurrentMissionItem(request) let result = try response.response.wait().missionRawResult if (result.result == Mavsdk_Rpc_MissionRaw_MissionRawResult.Result.success) { completable(.completed) } else { completable(.error(MissionRawError(code: MissionRawResult.Result.translateFromRpc(result.result), description: result.resultStr))) } } catch { completable(.error(error)) } return Disposables.create() } } /** Subscribe to mission progress updates. */ public lazy var missionProgress: Observable<MissionProgress> = createMissionProgressObservable() private func createMissionProgressObservable() -> Observable<MissionProgress> { return Observable.create { observer in let request = Mavsdk_Rpc_MissionRaw_SubscribeMissionProgressRequest() _ = self.service.subscribeMissionProgress(request, handler: { (response) in let missionProgress = MissionProgress.translateFromRpc(response.missionProgress) observer.onNext(missionProgress) }) return Disposables.create() } .retryWhen { error in error.map { guard $0 is RuntimeMissionRawError else { throw $0 } } } .share(replay: 1) } /** * Subscribes to mission changed. This notification can be used to be informed if a ground station has been uploaded or changed by a ground station or companion computer. @param callback Callback to notify about change. */ public lazy var missionChanged: Observable<Bool> = createMissionChangedObservable() private func createMissionChangedObservable() -> Observable<Bool> { return Observable.create { observer in let request = Mavsdk_Rpc_MissionRaw_SubscribeMissionChangedRequest() _ = self.service.subscribeMissionChanged(request, handler: { (response) in let missionChanged = response.missionChanged observer.onNext(missionChanged) }) return Disposables.create() } .retryWhen { error in error.map { guard $0 is RuntimeMissionRawError else { throw $0 } } } .share(replay: 1) } }
31.321809
421
0.53787
ffeda5c049a2087ffec68c6db8192bbe684f4926
1,553
// // PopoverViewController.swift // FocusHour // // Created by Midrash Elucidator on 2019/2/11. // Copyright © 2019 Midrash Elucidator. All rights reserved. // import UIKit class SoundSelectorVC: UITableViewController { var soundList: [SoundKey] = [] var timerVC: TimerVC! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = ColorKey.LightYellow.uiColor() soundList = SoundKey.getKeyList() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return soundList.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SoundSelectorCell", for: indexPath) as! SoundSelectorCell cell.sound = soundList[indexPath.row] cell.setSelected(timerVC.soundPlayer.soundKey == soundList[indexPath.row]) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { for tableCell in self.tableView.visibleCells { let cell = tableCell as! SoundSelectorCell cell.setSelected(timerVC.soundPlayer.soundKey == cell.sound) } self.dismiss(animated: true, completion: nil) timerVC.soundPlayer.play(sound: soundList[indexPath.row]) timerVC.setSoundButtonStyle() } }
33.042553
123
0.687057
f8234179daf561288775775bff88099e83ae1310
554
import Foundation // MARK: - Workspace public class Workspace: Codable { // MARK: - Codable enum CodingKeys: String, CodingKey { case name case projects } // Workspace name public let name: String // Relative paths to the projects. // Note: The paths are relative from the folder that contains the workspace. public let projects: [String] public init(name: String, projects: [String]) { self.name = name self.projects = projects dumpIfNeeded(self) } }
20.518519
80
0.611913
33422aee844f37c9ec6f3805d2afa51fbdcd9e33
730
// // MLDiscoverCell.swift // MissLi // // Created by chengxianghe on 16/7/20. // Copyright © 2016年 cn. All rights reserved. // import UIKit class MLDiscoverCell: UITableViewCell { @IBOutlet weak var iconImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func setInfo(_ url: URL?) { iconImageView.yy_setImage(with: url!, placeholder: UIImage(named: "banner_default_320x170_"), options: .setImageWithFadeAnimation, completion: nil) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
23.548387
155
0.673973
ffce5a8f0d42fd1629cd36a1f333eb4a23536010
919
// Copyright 2020 Swift Studies // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. enum XMLDecodingError : Error { case propertyHasNoValue(String, type:XMLRawPropertyType) case unknownLevelElement(String) case unsupportedTileDataFormat(encoding:TileDataEncoding, compression:TileDataCompression) case unsupportOnPlatform(String) case decompressionFailure(String) }
41.772727
94
0.747552
fc1e618ed92a2d7592627f2b77eb26cd52a741ac
930
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // WorkflowRunActionPropertiesProtocol is the workflow run action properties. public protocol WorkflowRunActionPropertiesProtocol : Codable { var startTime: Date? { get set } var endTime: Date? { get set } var status: WorkflowStatusEnum? { get set } var code: String? { get set } var error: [String: String?]? { get set } var trackingId: String? { get set } var correlation: CorrelationProtocol? { get set } var inputsLink: ContentLinkProtocol? { get set } var outputsLink: ContentLinkProtocol? { get set } var trackedProperties: [String: String?]? { get set } var retryHistory: [RetryHistoryProtocol?]? { get set } }
46.5
96
0.696774
2636ef23c41eebf5ee87ac33e7bfb5f46effaed0
2,186
// // SpotterGuideTVC.swift // Spotters // // Created by Walter Edgar on 11/27/17. // Copyright © 2017 Walter Edgar. All rights reserved. // import UIKit import SafariServices class SpotterGuideTVC: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } class TableRow: UITableViewCell { } @IBAction func launchIAHGuideButtonPressed() { if let url = URL(string: "http://www.houstonspotters.net/resources/airports/airport.asp?AirportID=KIAH") { let safariVC = SFSafariViewController(url: url) present(safariVC, animated: true, completion: nil) } } @IBAction func launchDWHGuideButtonPressed() { if let url = URL(string: "http://www.houstonspotters.net/resources/airports/airport.asp?AirportID=KDWH") { let safariVC = SFSafariViewController(url: url) present(safariVC, animated: true, completion: nil) } } @IBAction func launchHOUGuideButtonPressed() { if let url = URL(string: "http://www.houstonspotters.net/resources/airports/airport.asp?AirportID=KHOU") { let safariVC = SFSafariViewController(url: url) present(safariVC, animated: true, completion: nil) } } @IBAction func launchEFDGuideButtonPressed() { if let url = URL(string: "http://www.houstonspotters.net/resources/airports/airport.asp?AirportID=KEFD") { let safariVC = SFSafariViewController(url: url) present(safariVC, animated: true, completion: nil) } } @IBAction func launchIWSGuideButtonPressed() { if let url = URL(string: "http://www.houstonspotters.net/resources/airports/airport.asp?AirportID=KIWS") { let safariVC = SFSafariViewController(url: url) present(safariVC, animated: true, completion: nil) } } @IBAction func launchGLSGuideButtonPressed() { if let url = URL(string: "http://www.houstonspotters.net/resources/airports/airport.asp?AirportID=KGLS") { let safariVC = SFSafariViewController(url: url) present(safariVC, animated: true, completion: nil) } } }
36.433333
114
0.656908
50f089a021b0a28096c2999319e8adcb67b88324
3,677
// // Copyright (c) 2021 Adyen N.V. // // This file is open source and available under the MIT license. See the LICENSE file for more info. // import UIKit /// :nodoc: /// Represents a picker item view. open class BaseFormPickerItemView<T: CustomStringConvertible & Equatable>: FormValueItemView<BasePickerElement<T>, FormTextItemStyle, BaseFormPickerItem<T>>, UIPickerViewDelegate, UIPickerViewDataSource { /// The underlying `UIPickerView`. internal lazy var pickerView: UIPickerView = { let pickerView = UIPickerView() pickerView.delegate = self pickerView.dataSource = self pickerView.autoresizingMask = [.flexibleHeight, .flexibleWidth] return pickerView }() /// Initializes the picker item view. /// /// - Parameter item: The item represented by the view. public required init(item: BaseFormPickerItem<T>) { super.init(item: item) initialize() select(value: item.value) } /// :nodoc: override open var canBecomeFirstResponder: Bool { true } /// :nodoc: override open func becomeFirstResponder() -> Bool { inputControl.becomeFirstResponder() } /// :nodoc: override open func resignFirstResponder() -> Bool { inputControl.resignFirstResponder() } // MARK: - Abstract internal func getInputControl() -> PickerTextInputControl { BasePickerInputControl(inputView: pickerView, style: item.style.text) } internal func updateSelection() { inputControl.label = item.value.description } internal func initialize() { addSubview(inputControl) inputControl.translatesAutoresizingMaskIntoConstraints = false inputControl.preservesSuperviewLayoutMargins = true (inputControl as UIView).adyen.anchor(inside: self) } internal lazy var inputControl: PickerTextInputControl = { let view = getInputControl() view.showChevron = item.selectableValues.count > 1 view.accessibilityIdentifier = item.identifier.map { ViewIdentifierBuilder.build(scopeInstance: $0, postfix: "inputControl") } view.onDidBecomeFirstResponder = { [weak self] in self?.isEditing = true } view.onDidResignFirstResponder = { [weak self] in self?.isEditing = false } view.onDidTap = { [weak self] in guard let self = self, self.item.selectableValues.count > 1 else { return } _ = self.becomeFirstResponder() } return view }() // MARK: - UIPickerViewDelegate and UIPickerViewDataSource public func numberOfComponents(in pickerView: UIPickerView) -> Int { 1 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { item.selectableValues.count } public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { guard row < item.selectableValues.count else { return nil } return item.selectableValues[row].description } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { guard row < item.selectableValues.count else { return } select(value: item.selectableValues[row]) } // MARK: - Private private func select(value: BasePickerElement<T>) { self.item.value = value updateSelection() let selectedIndex = item.selectableValues.firstIndex(where: { $0.identifier == item.value.identifier }) ?? 0 pickerView.selectRow(selectedIndex, inComponent: 0, animated: false) } }
32.254386
134
0.670655
56b222518eb376077cec22e0e5b122546c9c190e
1,552
// // AnimationQueue.swift // BaseApplication // // Created by Dang Huu Tri on 1/19/20. // Copyright © 2020 Dang Huu Tri. All rights reserved. // import Foundation import UIKit public class AnimationQueue { private let queue: DispatchQueue public init(label: String) { self.queue = DispatchQueue(label: label) } public func submitAnimations(withDuration duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) { let semaphore = DispatchSemaphore(value: 0) queue.async { let _ = semaphore.wait(timeout: .now() + 60.0) } DispatchQueue.main.async { UIView.animate(withDuration: duration, animations: animations, completion: { (finished) in semaphore.signal() completion?(finished) }) } } public func submitBatchUpdates(to collectionView: UICollectionView, updates: @escaping () -> Void, completion: ((Bool) -> Void)?) { let semaphore = DispatchSemaphore(value: 0) queue.async { let _ = semaphore.wait(timeout: .now() + 60.0) } DispatchQueue.main.async { UIView.beginAnimations(nil, context:nil) CATransaction.begin() collectionView.performBatchUpdates(updates, completion: { (finished) in semaphore.signal() completion?(finished) }) CATransaction.commit() UIView.commitAnimations() } } }
31.04
136
0.588918
dd5a707d42a909afad51d611c7e2b0ca6bc599f8
970
// // tippyTests.swift // tippyTests // // Created by Vibhu Appalaraju on 8/10/18. // Copyright © 2018 Vibhu Appalaraju. All rights reserved. // import XCTest @testable import tippy class tippyTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.216216
111
0.631959
1c1104f62fd2647fb964073d9997d77a8cdd66c0
180
// // Posix.swift // SwiftCompiler // // Created by Alex Telek on 27/12/2015. // Copyright © 2015 Alex Telek. All rights reserved. // import Cocoa class Posix: NSObject { }
12.857143
53
0.661111
280346e53918b929149e870fd639a20ea98b1d3a
1,351
// aoc (12/23/20) // © 2020 Joe Sherwood. All rights reserved. import XCTest class Test202016: 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 testp1_1() { let input = """ class: 1-3 or 5-7 row: 6-11 or 33-44 seat: 13-40 or 45-50 your ticket: 7,1,14 nearby tickets: 7,3,47 40,4,50 55,2,20 38,6,12 """ let d = AOC20.Day16(raw: input) let p = d.p1() XCTAssertEqual(p, "71") } func testp2_1() { let input = """ departure class: 0-1 or 4-19 departure row: 0-5 or 8-19 departure seat: 0-13 or 16-19 your ticket: 11,12,13 nearby tickets: 3,9,18 15,1,5 5,14,9 """ let d = AOC20.Day16(raw: input) let p = d.p2() XCTAssertEqual(p, "1716") } }
22.898305
107
0.440415
d512f0cf2c38e1625a26f7fc67543d14de5c1565
652
import TSCBasic import TuistCore import TuistGraph public final class MockXcodeProjectBuildDirectoryLocator: XcodeProjectBuildDirectoryLocating { public init() {} enum MockXcodeProjectBuildDirectoryLocatorError: Error { case noStub } public var locateStub: ((Platform, AbsolutePath, String) throws -> AbsolutePath)? public func locate(platform: Platform, projectPath: AbsolutePath, configuration: String) throws -> AbsolutePath { guard let stub = locateStub else { throw MockXcodeProjectBuildDirectoryLocatorError.noStub } return try stub(platform, projectPath, configuration) } }
32.6
117
0.739264
8902b3303d3115c85e85a8c88a09c90a6d3a7069
2,983
// // HubProxy.swift // SignalR-Swift // // // Copyright © 2017 Jordan Camara. All rights reserved. // import Foundation public class HubProxy: HubProxyProtocol { public var state = [String: Any]() private weak var connection: HubConnectionProtocol? private let hubName: String private var subscriptions = [String: Subscription]() // MARK: - Init public init(connection: HubConnectionProtocol, hubName: String) { self.connection = connection self.hubName = hubName } // MARK: - Subscribe public func on(eventName: String, handler: @escaping Subscription) -> Subscription? { guard !eventName.isEmpty else { NSException.raise(.invalidArgumentException, format: NSLocalizedString("Argument eventName is null", comment: "null event name exception"), arguments: getVaList(["nil"])) return nil } return self.subscriptions[eventName] ?? self.subscriptions.updateValue(handler, forKey: eventName) ?? handler } public func invokeEvent(eventName: String, withArgs args: [Any]) { if let subscription = self.subscriptions[eventName] { subscription(args) } } // MARK: - Publish public func invoke(method: String, withArgs args: [Any]) { self.invoke(method: method, withArgs: args, completionHandler: nil) } public func invoke(method: String, withArgs args: [Any], completionHandler: ((Any?, Error?) -> ())?) { guard !method.isEmpty else { NSException.raise(.invalidArgumentException, format: NSLocalizedString("Argument method is null", comment: "null event name exception"), arguments: getVaList(["nil"])) return } guard let connection = self.connection else { return } let callbackId = connection.registerCallback { result in guard let hubResult = result else { return } hubResult.state?.forEach { (key, value) in self.state[key] = value } if hubResult.error == nil { completionHandler?(hubResult.result, nil) } else { let userInfo = [ NSLocalizedFailureReasonErrorKey: NSExceptionName.objectNotAvailableException.rawValue, NSLocalizedDescriptionKey: hubResult.error! ] let error = NSError(domain: "com.autosoftdms.SignalR-Swift.\(type(of: self))", code: 0, userInfo: userInfo) completionHandler?(nil, error) } } let hubData = HubInvocation(callbackId: callbackId, hub: self.hubName, method: method, args: args, state: self.state) connection.send(object: hubData.toJSONString()!, completionHandler: completionHandler) } }
36.82716
182
0.592021
3996c55408b64f2e69b3dea7690de6050ae80acf
1,401
// // BlockedUsers.swift // AdForest // // Created by apple on 5/24/18. // Copyright © 2018 apple. All rights reserved. // import Foundation struct BlockedUsers { var id : String! var image : String! var location : String! var name : String! var text : String! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: [String:Any]){ id = dictionary["id"] as? String image = dictionary["image"] as? String location = dictionary["location"] as? String name = dictionary["name"] as? String text = dictionary["text"] as? String } /** * Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> [String:Any] { var dictionary = [String:Any]() if id != nil{ dictionary["id"] = id } if image != nil{ dictionary["image"] = image } if location != nil{ dictionary["location"] = location } if name != nil{ dictionary["name"] = name } if text != nil{ dictionary["text"] = text } return dictionary } }
25.017857
183
0.558887
14f07bf69db946c5d82eda6d0a39cf4523f89d21
2,504
// // CommentRepository.swift // testsPostsApp // // Created by Guillermo Asencio Sanchez on 23/3/21. // import Foundation private enum CommentAPIEndpoint { static let getComments = "/comments" } protocol CommentRepositoryLogic { func getComments(completion: @escaping(Result<[CommentEntity], GetCommentsError>) -> Void) } class CommentRepository: CommentRepositoryLogic { // MARK: - Public func getComments(completion: @escaping(Result<[CommentEntity], GetCommentsError>) -> Void) { if let comments = getCommentsFromDatabase(), !comments.isEmpty { completion(.success(comments)) } else { let requestData = GetCommentsRequestData() var urlComponents = URLComponents(string: NetworkConfig.baseUrl) urlComponents?.path = CommentAPIEndpoint.getComments let path = urlComponents?.url?.absoluteString ?? "" let networkRequest = NetworkRequest(httpMethod: .get, encoding: .json, path: path, headers: requestData.getHeaders()) Managers.network.request(networkRequest) { networkResult in switch networkResult { case .success(let response): let parser = NetworkEntityParser() if let entity = parser.parse(data: response.data, entityType: GetCommentsResponse.self, statusCode: response.statusCode, headers: response.headers) { self.saveData(entity) completion(.success(entity)) } else { completion(.failure(.responseProblems)) } case .failure(let error): switch error.code { case .noConnection: completion(.failure(.noConnection)) case .badRequest: completion(.failure(.badRequest)) case .notFound: completion(.failure(.notFound)) default: completion(.failure(.responseProblems)) } } } } } // MARK: - Private private func getCommentsFromDatabase() -> [CommentEntity]? { guard let comments = try? Managers.database.get(CommentObject.self) else { return nil } return comments.compactMap({ $0.convertToEntity() }) } private func saveData(_ entities: [CommentEntity]) { try? Managers.database.add(entities.map({ CommentObject(from: $0) })) } }
32.519481
94
0.597045
2fcfe795bb7e22c07fddd5d391ef64f86e2703c1
2,179
// // AppDelegate.swift // Tip Calculator // // Created by Justin Leong on 1/9/19. // Copyright © 2019 Justin Leong. All rights reserved. // import UIKit @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. 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.361702
285
0.754933
8ae753fdfbf01c85adc4726179780cffc05026ec
269
// // Color.swift // Brewery // // Created by Alvaro Blazquez on 18/10/18. // Copyright © 2018 Alvaro Blazquez. All rights reserved. // import UIKit extension UIColor { struct Brewery { static let Yellow = UIColor(named: "Yellow")! } }
14.944444
58
0.613383
1aa1a081b8f33b4c5cc9b697703fee3b83746858
1,249
// // MainListCell.swift // // Created by Daniel on 5/6/20. // Copyright © 2020 dk. All rights reserved. // import UIKit class MainListCell: UITableViewCell { var item: Item? { didSet { textLabel?.text = item?.title detailTextLabel?.text = item?.subtitle accessoryType = item?.destination == nil ? .none : .disclosureIndicator imageView?.image = item?.image if let c = item?.color { backgroundColor = c } else { detailTextLabel?.textColor = .secondaryLabel } } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) setup() } required init?(coder: NSCoder) { fatalError("not implemented") } override func prepareForReuse() { super.prepareForReuse() textLabel?.text = nil detailTextLabel?.text = nil imageView?.image = nil } } private extension MainListCell { func setup() { imageView?.tintColor = .secondaryLabel textLabel?.numberOfLines = 0 detailTextLabel?.numberOfLines = 0 } }
22.709091
83
0.578863
fb06532b539df05704760cb1b738062131dd566e
1,693
// // FavoritePresenter.swift // GitHubManager // // Created by Jonathan Martins on 07/03/20. // Copyright © 2020 Jonathan Martins. All rights reserved. // import Foundation // MARK: - FavoriteDelegate protocol FavoriteDelegate { /// Checks if the given GistItem should be favorited or not func favorite(_ item: GistItem) } // MARK: - FavoritePresenter class FavoritePresenter: MainPresenterDelegate { /// The list of gists to be used as datasource. It should be private but we make it public for testing purposes var gists:[Gist] = [] /// Manager for the storage private var storage: StorageDelegate /// Instance of the view so we can update it private weak var view: MainViewDelegate? init(_ storage: StorageDelegate) { self.storage = storage } /// Binds a view to this presenter func attach(to view: MainViewDelegate) { self.view = view } func selectGist(at position: Int) { let gist = gists[position] view?.goToGistDetails(gist) } func loadFavorites() { gists = storage.loadFavorites() let items = gists.map { GistItem($0, isFavorite: true) } view?.reloadGistList(items) if items.isEmpty { view?.showFeedback(message: "You have no favorites yet") } } func favorite(_ item: GistItem) { let gist = item.gist if !storage.isGistFavorite(gist) { item.isFavorite = true storage.addToFavorite(gist) } else { item.isFavorite = false storage.removeFromFavorite(gist) } view?.updateGistList() } }
26.046154
115
0.619019
4b876a4b177b4609a10abcac976729ac6d9d2ec9
1,742
// // ViewController.swift // iOSCoreMLDemo // // Created by Aravind Vasudevan on 24/07/18. // Copyright © 2018 Aravind Vasudevan. All rights reserved. // import UIKit class ViewController: UITableViewController { var pictures = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. navigationController?.navigationBar.prefersLargeTitles = true title = "Img Viewer" let fm = FileManager.default let path = Bundle.main.resourcePath! let items = try! fm.contentsOfDirectory(atPath: path) for item in items { if item.hasPrefix("img") { pictures.append(item) } } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return pictures.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Picture", for: indexPath) cell.textLabel?.text = pictures[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController { vc.selectedImage = pictures[indexPath.row] navigationController?.pushViewController(vc, animated: true) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
30.034483
110
0.649254
d724ea5930ea25f9285e31902cc9ead36d42c852
239
// // Constants.swift // Le Monde RSS // // Created by dpalagi on 25/04/2018. // Copyright © 2018 dpalagi. All rights reserved. // import Foundation struct Constants { let baseUrl: String = "https://www.lemonde.fr/rss/une.xml" }
17.071429
62
0.669456
23dc5ac991e76dd8c7fb2c7317dde70de41b14db
614
// 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 // RUN: not %target-swift-frontend %s -typecheck struct i<f : f, g: f where g.i == f.i> { b = i) { } let i { f func p(k: b) -> <i>(() -> i) -> b { n { o f "\(k): \(o() } f m : m { } func i<o : o, m : m n m.f == o> (l: m) { } } func p<m>() -> [l<m>] { } func f<o>()
26.695652
79
0.610749
c117cb667f116815b15839b84f4324cb152d7d50
2,033
// // StatusItemView.swift // WhichSpace // // Created by Stephen Sykes on 30/10/15. // Copyright © 2020 George Christou. All rights reserved. // import Cocoa class StatusItemCell: NSStatusBarButtonCell { var isMenuVisible = false override func drawImage(_ image: NSImage, withFrame frame: NSRect, in controlView: NSView) { var darkColor: NSColor var whiteColor: NSColor if AppDelegate.darkModeEnabled { darkColor = NSColor(calibratedWhite: 0.7, alpha: 1) whiteColor = NSColor(calibratedWhite: 0, alpha: 1) } else { darkColor = NSColor(calibratedWhite: 0.3, alpha: 1) whiteColor = NSColor(calibratedWhite: 1, alpha: 1) } let foregroundColor = isMenuVisible ? darkColor : whiteColor let titleRect = NSRect(x: frame.origin.x, y: frame.origin.y + 3, width: frame.size.width, height: frame.size.height) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = NSTextAlignment.center let font = NSFont.systemFont(ofSize: 13) let attributes = [convertFromNSAttributedStringKey(NSAttributedString.Key.font): font, convertFromNSAttributedStringKey(NSAttributedString.Key.paragraphStyle): paragraphStyle, convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): foregroundColor] title.draw(in: titleRect, withAttributes:convertToOptionalNSAttributedStringKeyDictionary(attributes)) } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
42.354167
274
0.715691
1e57a2462815b87a8af032532ff64af452396536
706
// // JSONLoader.swift // MovieListingTests // // Created by Gökhan KOCA on 31.01.2021. // import Foundation final class JSONLoader { static func load<T: Decodable>(from file: String) -> T? { if let path = Bundle(for: JSONLoader.self).path(forResource: file, ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) { do { let decoder = JSONDecoder() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" decoder.dateDecodingStrategy = .formatted(dateFormatter) let response = try decoder.decode(T.self, from: data) return response } catch { return nil } } else { return nil } } }
24.344828
91
0.672805
7a50bf1efbff3a56a2899cb2aa9f8dd791bf1b9f
4,614
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation #if canImport(AppStoreConnectModels) import AppStoreConnectModels import AppStoreConnectSharedCode #endif extension AppStoreConnect.AppScreenshotSets { public enum AppScreenshotSetsDeleteInstance { public static let service = APIService<Response>( id: "appScreenshotSets-delete_instance", tag: "AppScreenshotSets", method: "DELETE", path: "/v1/appScreenshotSets/{id}", hasBody: false, securityRequirement: SecurityRequirement(type: "itc-bearer-token", scopes: [])) public final class Request: APIRequest<Response> { public struct Options { /** the id of the requested resource */ public var id: String public init(id: String) { self.id = id } } public var options: Options public init(options: Options) { self.options = options super.init(service: AppScreenshotSetsDeleteInstance.service) } /// convenience initialiser so an Option doesn't have to be created public convenience init(id: String) { let options = Options(id: id) self.init(options: options) } public override var path: String { return super.path.replacingOccurrences(of: "{" + "id" + "}", with: "\(self.options.id)") } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = Never /** Success (no content) */ case status204 /** Parameter error(s) */ case status400(ASCErrorResponse) /** Forbidden error */ case status403(ASCErrorResponse) /** Not found error */ case status404(ASCErrorResponse) /** Request entity error(s) */ case status409(ASCErrorResponse) public var success: Never? { switch self { case .status204: return () default: return nil } } public var failure: ASCErrorResponse? { switch self { case .status400(let response): return response case .status403(let response): return response case .status404(let response): return response case .status409(let response): return response default: return nil } } /// either success or failure value. Success is anything in the 200..<300 status code range public var responseResult: APIResponseResult<Never, ASCErrorResponse> { if let successValue = success { return .success(successValue) } else if let failureValue = failure { return .failure(failureValue) } else { fatalError("Response does not have success or failure response") } } public var response: Any { switch self { case .status400(let response): return response case .status403(let response): return response case .status404(let response): return response case .status409(let response): return response default: return () } } public var statusCode: Int { switch self { case .status204: return 204 case .status400: return 400 case .status403: return 403 case .status404: return 404 case .status409: return 409 } } public var successful: Bool { switch self { case .status204: return true case .status400: return false case .status403: return false case .status404: return false case .status409: return false } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 204: self = .status204 case 400: self = try .status400(decoder.decode(ASCErrorResponse.self, from: data)) case 403: self = try .status403(decoder.decode(ASCErrorResponse.self, from: data)) case 404: self = try .status404(decoder.decode(ASCErrorResponse.self, from: data)) case 409: self = try .status409(decoder.decode(ASCErrorResponse.self, from: data)) default: throw APIClientError.unexpectedStatusCode(statusCode: statusCode, data: data) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
29.961039
99
0.627655
d90cad64a52552ad5bff7d67772db444b8b19f3d
1,421
// // DataForAccountRemoteTestCase.swift // stellarsdkTests // // Created by Rogobete Christian on 19.02.18. // Copyright © 2018 Soneso. All rights reserved. // import XCTest import stellarsdk class DataForAccountRemoteTestCase: XCTestCase { let sdk = StellarSDK() let testSuccessAccountId = "GALA3JYOCVM4ENFPXMMXQBFGTQZKWRIOAVZSHGGNUVC4KOGOB3A4EFGZ" 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 testGetDataForAccount() { let expectation = XCTestExpectation(description: "Get data value for a given account and key") sdk.accounts.getDataForAccount(accountId: testSuccessAccountId, key:"soneso") { (response) -> (Void) in switch response { case .success(let dataForAccount): XCTAssertEqual(dataForAccount.value.base64Decoded(), "is super") case .failure(let error): StellarSDKLog.printHorizonRequestErrorMessage(tag:"GDFA testcase", horizonRequestError: error) XCTAssert(false) } expectation.fulfill() } wait(for: [expectation], timeout: 15.0) } }
33.833333
111
0.662913
0388943244cb7c170c1bc65afd49e0bf965b9a9b
734
// // FavouriteGamesTableViewCell.swift // Game In-Depth // // Created by Indra Permana on 01/08/20. // Copyright © 2020 IndraPP. All rights reserved. // import UIKit class FavouriteGamesTableViewCell: UITableViewCell { @IBOutlet weak var favouriteGameImageView: UIImageView! @IBOutlet weak var favouriteGameTitle: UILabel! @IBOutlet weak var favouriteGameRating: UILabel! @IBOutlet weak var favouriteGameReleased: 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 } }
25.310345
65
0.709809
7a159ba0a2b14eac0d2b4c804c0f5995dceb5c40
162
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(CalendarViewTests.allTests), ] } #endif
16.2
45
0.679012
cc91a13799383e962080a9d76aaf0cd7e5515447
1,755
// // DeitailMoviesViewController.swift // Movies // // Created by Long Nguyen on 6/16/17. // Copyright © 2017 Long Nguyen. All rights reserved. // import UIKit class DeitailMoviesViewController: UIViewController { @IBOutlet weak var imgDetail: UIImageView! @IBOutlet weak var srollContend: UIScrollView! @IBOutlet weak var viewContend: UIView! @IBOutlet weak var lbNam: UILabel! @IBOutlet weak var lbDate: UILabel! @IBOutlet weak var lbContend: UILabel! var urlImageDetail = String() var date = String() var content = String() var name = String() var voterate = Int() override func viewDidLoad() { super.viewDidLoad() imgDetail.setImageWith(NSURL(string: urlImageDetail)! as URL) // Do any additional setup after loading the view. self.srollContend.contentSize = CGSize(width: self.srollContend.frame.size.width, height: self.viewContend.frame.origin.y + self.viewContend.frame.height) self.lbNam.text = name self.lbDate.text = date self.lbContend.text = content } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
30.789474
162
0.679772
b934d602837543ab0fc5839ca2304cdc4338cabb
11,095
import XCTest import ComposableArchitecture import Combine @testable import Tube_Service class ArrivalsPickerTests: XCTestCase { let scheduler = DispatchQueue.test func testAppear_filteredByAllStations() throws { var userPrefs = UserPreferences.fake() userPrefs.lastUsedFilterOption = .all let globalState = Global.State.fake(userPreferences: userPrefs) let stations: [Station] = .fakes() let store = TestStore(initialState: .fake(globalState: globalState), reducer: ArrivalsPicker.reducer, environment: .unitTest) store.assert( .send(.onAppear) { $0.navigationBarTitle = "arrivals.picker.navigation.title" $0.placeholderSearchText = "arrivals.picker.search.placeholder" $0.selectedFilterOption = .all }, .receive(.didLoadStations(stations)) { $0.hasLoaded = true $0.stations = IdentifiedArray(uniqueElements: stations) }, .receive(.refreshStations) { $0.selectableStations = $0.stations } ) } func testAppear_filteredByFavouriteStations() throws { let highBarnet = Station.fake(ofType: .highBarnet) let boundsGreen = Station.fake(ofType: .boundsGreen) let favouriteArrivalsGroupIds = Set([ highBarnet.arrivalsGroups[0].id, boundsGreen.arrivalsGroups[0].id ]) var userPrefs = UserPreferences.fake() userPrefs.lastUsedFilterOption = .favourites userPrefs.favourites = favouriteArrivalsGroupIds let globalState = Global.State.fake(userPreferences: userPrefs) let stations: [Station] = .fakes() let store = TestStore(initialState: .fake(globalState: globalState), reducer: ArrivalsPicker.reducer, environment: .unitTest) store.assert( .send(.onAppear) { $0.navigationBarTitle = "arrivals.picker.navigation.title" $0.placeholderSearchText = "arrivals.picker.search.placeholder" $0.selectedFilterOption = .favourites }, .receive(.didLoadStations(stations)) { $0.hasLoaded = true $0.stations = IdentifiedArray(uniqueElements: stations) }, .receive(.refreshStations) { $0.selectableStations = [boundsGreen, highBarnet] } ) } func testChangeFilterOption() { let highBarnet = Station.fake(ofType: .highBarnet) let boundsGreen = Station.fake(ofType: .boundsGreen) let favouriteArrivalsGroupIds = Set([ boundsGreen.arrivalsGroups[0].id, highBarnet.arrivalsGroups[0].id ]) var initialUserPrefs = UserPreferences.fake() initialUserPrefs.lastUsedFilterOption = .all initialUserPrefs.favourites = favouriteArrivalsGroupIds let globalState = Global.State.fake(userPreferences: initialUserPrefs) var viewState = ArrivalsPicker.ViewState.fake() viewState.stations = IdentifiedArrayOf(uniqueElements: Station.fakes()) let store = TestStore(initialState: .fake(globalState: globalState, viewState: viewState), reducer: ArrivalsPicker.reducer, environment: .unitTest) var updatedUserPrefs = initialUserPrefs updatedUserPrefs.lastUsedFilterOption = .favourites // 1. Select "favourites" filter store.assert( .send(.selectFilterOption(.favourites)) { $0.selectedFilterOption = .favourites }, .receive(.global(.updateUserPreferences(updatedUserPrefs))), .receive(.refreshStations) { $0.selectableStations = [boundsGreen, highBarnet] }, .receive(.global(.didUpdateUserPreferences(updatedUserPrefs))) { $0.userPreferences.lastUsedFilterOption = .favourites } ) // 2. Re-select same filter store.assert( .send(.selectFilterOption(.favourites)) // No changes ) updatedUserPrefs.lastUsedFilterOption = .all // 3. Select "All" again store.assert( .send(.selectFilterOption(.all)) { $0.selectedFilterOption = .all }, .receive(.global(.updateUserPreferences(updatedUserPrefs))), .receive(.refreshStations) { $0.selectableStations = $0.stations }, .receive(.global(.didUpdateUserPreferences(updatedUserPrefs))) { $0.userPreferences.lastUsedFilterOption = .all } ) } func testSearch() throws { var viewState = ArrivalsPicker.ViewState.fake() viewState.stations = IdentifiedArrayOf(uniqueElements: Station.fakes()) let initialState = ArrivalsPicker.State.fake(viewState: viewState) let store = TestStore(initialState: initialState, reducer: ArrivalsPicker.reducer, environment: .unitTest) let kingsCross = Station.fake(ofType: .kingsCross) let barkingside = Station.fake(ofType: .barkingSide) let kingsbury = Station.fake(ofType: .kingsbury) // 1. Begin search store.assert( .environment { $0.mainQueue = self.scheduler.eraseToAnyScheduler() }, .send(.search(text: "Kings")) { $0.searchText = "Kings" }, .do { self.scheduler.advance(by: 0.3) }, .receive(.refreshStations) { $0.selectableStations = [barkingside, kingsCross, kingsbury] $0.searchResultsCountText = "arrivals.picker.search.results.count" }, .send(.search(text: "Kings C")) { $0.searchText = "Kings C" }, .send(.search(text: "Kings Cr")) { $0.searchText = "Kings Cr" }, .do { self.scheduler.advance(by: 0.3) }, .receive(.refreshStations) { $0.selectableStations = [kingsCross] $0.searchResultsCountText = "arrivals.picker.search.results.count" } ) // 2. End search store.assert( .send(.search(text: "")) { $0.searchText = "" }, .do { self.scheduler.advance(by: 0.3) }, .receive(.refreshStations) { $0.selectableStations = initialState.selectableStations } ) } func testRowSelection() { let highBarnet = Station.fake(ofType: .highBarnet) let highBarnetArrivalsListId = highBarnet.arrivalsBoardsListId(at: 0) let finchleyCentral = Station.fake(ofType: .finchleyCentral) let finchleyCentralArrivalsListId = finchleyCentral.arrivalsBoardsListId(at: 0) let boundsGreen = Station.fake(ofType: .boundsGreen) let boundsGreenArrivalsListId = boundsGreen.arrivalsBoardsListId(at: 0) let store = TestStore(initialState: .fake(), reducer: ArrivalsPicker.reducer, environment: .unitTest) // 1. Select arrivals group row store.assert( .send(.selectRow(highBarnetArrivalsListId)) { $0.rowSelection.id = highBarnetArrivalsListId $0.rowSelection.navigationStates = IdentifiedArrayOf( uniqueElements: [.init(globalState: $0.globalState, viewState: .init(id: highBarnetArrivalsListId))] ) } ) // 2. Select another... store.assert( .send(.selectRow(finchleyCentralArrivalsListId)) { $0.rowSelection.id = finchleyCentralArrivalsListId $0.rowSelection.navigationStates = IdentifiedArrayOf(uniqueElements: [ .init(globalState: $0.globalState, viewState: .init(id: highBarnetArrivalsListId)), .init(globalState: $0.globalState, viewState: .init(id: finchleyCentralArrivalsListId)) ] ) } ) // 2. ... and another store.assert( .send(.selectRow(boundsGreenArrivalsListId)) { $0.rowSelection.id = boundsGreenArrivalsListId $0.rowSelection.navigationStates = IdentifiedArrayOf(uniqueElements: [.init(globalState: $0.globalState, viewState: .init(id: highBarnetArrivalsListId)), .init(globalState: $0.globalState, viewState: .init(id: finchleyCentralArrivalsListId)), .init(globalState: $0.globalState, viewState: .init(id: boundsGreenArrivalsListId))] ) } ) // 2. Remove deselected row states store.assert( .send(.selectRow(nil)) { $0.rowSelection.id = nil $0.rowSelection.navigationStates = IdentifiedArrayOf(uniqueElements: [.init(globalState: $0.globalState, viewState: .init(id: boundsGreenArrivalsListId))] ) } ) } func testToggleRowState() { let kingsCross = Station.fake(ofType: .kingsCross) let paddington = Station.fake(ofType: .paddington) let store = TestStore(initialState: .fake(), reducer: ArrivalsPicker.reducer, environment: .unitTest) // 1. Expand "King's Cross", then "Paddington" store.assert( .send(.toggleExpandedRowState(for: kingsCross)), .receive(.setExpandedRowState(to: true, for: kingsCross)) { $0.expandedRows = Set([kingsCross]) }, .send(.toggleExpandedRowState(for: paddington)), .receive(.setExpandedRowState(to: true, for: paddington)) { $0.expandedRows = Set([kingsCross, paddington]) } ) // 2. Collapse King's Cross, then Paddington store.assert( .send(.toggleExpandedRowState(for: kingsCross)), .receive(.setExpandedRowState(to: false, for: kingsCross)) { $0.expandedRows = Set([paddington]) }, .send(.toggleExpandedRowState(for: paddington)), .receive(.setExpandedRowState(to: false, for: paddington)) { $0.expandedRows = Set() } ) } }
38.524306
120
0.552681
e997930b7a247f566f8d3017fa0e541ed23629fd
4,341
import XCTest import SwiftSyntax public class SyntaxTests: XCTestCase { public func testSyntaxAPI() { let source = "struct A { func f() {} }" let tree = try! SyntaxParser.parse(source: source) XCTAssertEqual("\(tree.firstToken!)", "struct ") XCTAssertEqual("\(tree.firstToken!.nextToken!)", "A ") let funcKW = tree.firstToken!.nextToken!.nextToken!.nextToken! XCTAssertEqual("\(funcKW)", "func ") XCTAssertEqual("\(funcKW.nextToken!.nextToken!.nextToken!.nextToken!.nextToken!.nextToken!)", "}") XCTAssertEqual(tree.lastToken!.tokenKind, .eof) XCTAssertEqual("\(funcKW.parent!.lastToken!)", "} ") XCTAssertEqual("\(funcKW.nextToken!.previousToken!)", "func ") XCTAssertEqual("\(funcKW.previousToken!)", "{ ") let toks = Array(funcKW.parent!.tokens) XCTAssertEqual(toks.count, 6) guard toks.count == 6 else { return } XCTAssertEqual("\(toks[0])", "func ") XCTAssertEqual("\(toks[1])", "f") XCTAssertEqual("\(toks[2])", "(") XCTAssertEqual("\(toks[3])", ") ") XCTAssertEqual("\(toks[4])", "{") XCTAssertEqual("\(toks[5])", "} ") let rtoks = Array(funcKW.parent!.tokens.reversed()) XCTAssertEqual(rtoks.count, 6) guard rtoks.count == 6 else { return } XCTAssertEqual("\(rtoks[5])", "func ") XCTAssertEqual("\(rtoks[4])", "f") XCTAssertEqual("\(rtoks[3])", "(") XCTAssertEqual("\(rtoks[2])", ") ") XCTAssertEqual("\(rtoks[1])", "{") XCTAssertEqual("\(rtoks[0])", "} ") XCTAssertEqual(toks[0], rtoks[5]) XCTAssertEqual(toks[1], rtoks[4]) XCTAssertEqual(toks[2], rtoks[3]) XCTAssertEqual(toks[3], rtoks[2]) XCTAssertEqual(toks[4], rtoks[1]) XCTAssertEqual(toks[5], rtoks[0]) let tokset = Set(toks+rtoks) XCTAssertEqual(tokset.count, 6) XCTAssertEqual(toks[0].id, rtoks[5].id) XCTAssertEqual(toks[1].id, rtoks[4].id) XCTAssertEqual(toks[2].id, rtoks[3].id) XCTAssertEqual(toks[3].id, rtoks[2].id) XCTAssertEqual(toks[4].id, rtoks[1].id) XCTAssertEqual(toks[5].id, rtoks[0].id) } public func testPositions() { func testFuncKw(_ funcKW: TokenSyntax) { XCTAssertEqual("\(funcKW)", " func ") XCTAssertEqual(funcKW.position, AbsolutePosition(utf8Offset: 0)) XCTAssertEqual(funcKW.positionAfterSkippingLeadingTrivia, AbsolutePosition(utf8Offset: 2)) XCTAssertEqual(funcKW.endPositionBeforeTrailingTrivia, AbsolutePosition(utf8Offset: 6)) XCTAssertEqual(funcKW.endPosition, AbsolutePosition(utf8Offset: 7)) XCTAssertEqual(funcKW.contentLength, SourceLength(utf8Length: 4)) } do { let source = " func f() {}" let tree = try! SyntaxParser.parse(source: source) let funcKW = tree.firstToken! testFuncKw(funcKW) } do { let leading = Trivia(pieces: [ .spaces(2) ]) let trailing = Trivia(pieces: [ .spaces(1) ]) let funcKW = SyntaxFactory.makeFuncKeyword( leadingTrivia: leading, trailingTrivia: trailing) testFuncKw(funcKW) } } public func testCasting() { let integerExpr = IntegerLiteralExprSyntax { $0.useDigits(SyntaxFactory.makeIntegerLiteral("1", trailingTrivia: .spaces(1))) } let expr = ExprSyntax(integerExpr) let node = Syntax(expr) XCTAssertTrue(expr.is(IntegerLiteralExprSyntax.self)) XCTAssertTrue(node.is(IntegerLiteralExprSyntax.self)) XCTAssertTrue(node.as(ExprSyntax.self)!.is(IntegerLiteralExprSyntax.self)) XCTAssertTrue(node.is(ExprSyntaxProtocol.self)) XCTAssertTrue(node.as(ExprSyntaxProtocol.self) is IntegerLiteralExprSyntax) XCTAssertTrue(expr.as(ExprSyntaxProtocol.self) is IntegerLiteralExprSyntax) XCTAssertTrue(expr.as(ExprSyntaxProtocol.self) as? IntegerLiteralExprSyntax == integerExpr) XCTAssertFalse(node.is(BracedSyntax.self)) XCTAssertNil(node.as(BracedSyntax.self)) XCTAssertFalse(expr.is(BracedSyntax.self)) XCTAssertNil(expr.as(BracedSyntax.self)) let classDecl = SyntaxFactory.makeCodeBlock( leftBrace: SyntaxFactory.makeToken(.leftBrace, presence: .present), statements: SyntaxFactory.makeCodeBlockItemList([]), rightBrace: SyntaxFactory.makeToken(.rightBrace, presence: .present) ) XCTAssertTrue(classDecl.is(BracedSyntax.self)) XCTAssertNotNil(classDecl.as(BracedSyntax.self)) } }
36.788136
102
0.679797
3a4d3070c68b8b7e3d78d19d3457d8c13e73ae96
1,803
// // UICollectionViewExtension.swift // Rocket.Chat // // Created by Elen on 24/12/2018. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation public extension UICollectionView{ func register<T: UICollectionViewCell>(_: T.Type){ self.register(T.self, forCellWithReuseIdentifier: String(describing: T.self)) } func registerNib<T: UICollectionViewCell>(_: T.Type){ let nib = UINib(nibName: String(describing: T.self), bundle: Bundle(for: T.self)) self.register(nib, forCellWithReuseIdentifier: String(describing: T.self)) } func registerNib<T:UICollectionReusableView>(_: T.Type, forSupplementaryViewOfKind kind: String){ let nib = UINib(nibName: String(describing: T.self), bundle: Bundle(for: T.self)) self.register(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: String(describing: T.self)) } func register<T:UICollectionReusableView>(_: T.Type, forSupplementaryViewOfKind kind: String){ self.register(T.self, forSupplementaryViewOfKind: kind, withReuseIdentifier: String(describing: T.self)) } func dequeueReusableCollectionCell<T: UICollectionViewCell>(_: T.Type,indexPath: IndexPath) -> T { guard let cell = self.dequeueReusableCell(withReuseIdentifier: String(describing: T.self), for: indexPath) as? T else { return T() } return cell } func dequeueReusableCollectionHeaderFooterView<T: UICollectionReusableView>(_: T.Type,ofKind:String,indexPath: IndexPath) -> T{ guard let view = self.dequeueReusableSupplementaryView(ofKind: ofKind, withReuseIdentifier: String(describing: T.self), for: indexPath) as? T else{ return T()} return view } }
34.673077
167
0.688297
69a14223e4736c7096d2d7a491772053a4e8330f
1,519
// // Created by Anton Heestand on 2022-03-06. // #if !os(tvOS) import Foundation import CoreGraphics import RenderKit import Resolution import PixelColor public struct P5JSPixelModel: PixelResourceModel { // MARK: Global public var id: UUID = UUID() public var name: String = "p5.js" public var typeName: String = "pix-content-resource-p5js" public var bypass: Bool = false public var outputNodeReferences: [NodeReference] = [] public var viewInterpolation: ViewInterpolation = .linear public var interpolation: PixelInterpolation = .linear public var extend: ExtendMode = .zero // MARK: Local public var resolution: Resolution = .auto } extension P5JSPixelModel { enum LocalCodingKeys: String, CodingKey, CaseIterable { case resolution } public init(from decoder: Decoder) throws { self = try PixelResourceModelDecoder.decode(from: decoder, model: self) as! Self let container = try decoder.container(keyedBy: LocalCodingKeys.self) resolution = try container.decode(Resolution.self, forKey: .resolution) } } extension P5JSPixelModel { public func isEqual(to nodeModel: NodeModel) -> Bool { guard let pixelModel = nodeModel as? Self else { return false } guard isPixelResourceEqual(to: pixelModel) else { return false } guard resolution == pixelModel.resolution else { return false } return true } } #endif
25.316667
88
0.670836
56f30b92035131c2cc1e784b2f9e86d01945b330
108,229
// RUN: rm -rf %t // RUN: mkdir -p %t // // RUN: %gyb %s -o %t/main.swift // RUN: if [ %target-runtime == "objc" ]; then \ // RUN: %target-clang -fobjc-arc %S/Inputs/SlurpFastEnumeration/SlurpFastEnumeration.m -c -o %t/SlurpFastEnumeration.o; \ // RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %S/Inputs/DictionaryKeyValueTypesObjC.swift %t/main.swift -I %S/Inputs/SlurpFastEnumeration/ -Xlinker %t/SlurpFastEnumeration.o -o %t/Set -Xfrontend -disable-access-control; \ // RUN: else \ // RUN: %line-directive %t/main.swift -- %target-build-swift %S/Inputs/DictionaryKeyValueTypes.swift %t/main.swift -o %t/Set -Xfrontend -disable-access-control; \ // RUN: fi // // RUN: %line-directive %t/main.swift -- %target-run %t/Set // REQUIRES: executable_test import StdlibUnittest import StdlibCollectionUnittest // For rand32 import SwiftPrivate #if _runtime(_ObjC) import Foundation #else // for random, srandom import Glibc #endif // For experimental Set operators import SwiftExperimental extension Set { func _rawIdentifier() -> Int { return unsafeBitCast(self, to: Int.self) } } // Check that the generic parameter is called 'Element'. protocol TestProtocol1 {} extension Set where Element : TestProtocol1 { var _elementIsTestProtocol1: Bool { fatalError("not implemented") } } extension SetIndex where Element : TestProtocol1 { var _elementIsTestProtocol1: Bool { fatalError("not implemented") } } extension SetIterator where Element : TestProtocol1 { var _elementIsTestProtocol1: Bool { fatalError("not implemented") } } let hugeNumberArray = Array(0..<500) var SetTestSuite = TestSuite("Set") SetTestSuite.setUp { resetLeaksOfDictionaryKeysValues() #if _runtime(_ObjC) resetLeaksOfObjCDictionaryKeysValues() #endif } SetTestSuite.tearDown { expectNoLeaksOfDictionaryKeysValues() #if _runtime(_ObjC) expectNoLeaksOfObjCDictionaryKeysValues() #endif } func getCOWFastSet(_ members: [Int] = [1010, 2020, 3030]) -> Set<Int> { var s = Set<Int>(minimumCapacity: 10) for member in members { s.insert(member) } expectTrue(isNativeSet(s)) return s } func getCOWSlowSet(_ members: [Int] = [1010, 2020, 3030]) -> Set<TestKeyTy> { var s = Set<TestKeyTy>(minimumCapacity: 10) for member in members { s.insert(TestKeyTy(member)) } expectTrue(isNativeSet(s)) return s } func helperDeleteThree(_ k1: TestKeyTy, _ k2: TestKeyTy, _ k3: TestKeyTy) { var s1 = Set<TestKeyTy>(minimumCapacity: 10) s1.insert(k1) s1.insert(k2) s1.insert(k3) expectTrue(s1.contains(k1)) expectTrue(s1.contains(k2)) expectTrue(s1.contains(k3)) s1.remove(k1) expectTrue(s1.contains(k2)) expectTrue(s1.contains(k3)) s1.remove(k2) expectTrue(s1.contains(k3)) s1.remove(k3) expectEqual(0, s1.count) } func uniformRandom(_ max: Int) -> Int { return Int(rand32(exclusiveUpperBound: UInt32(max))) } func pickRandom<T>(_ a: [T]) -> T { return a[uniformRandom(a.count)] } func equalsUnordered(_ lhs: Set<Int>, _ rhs: Set<Int>) -> Bool { return lhs.sorted().elementsEqual(rhs.sorted()) { $0 == $1 } } func isNativeSet<T : Hashable>(_ s: Set<T>) -> Bool { switch s._variantStorage { case .native: return true case .cocoa: return false } } #if _runtime(_ObjC) func isNativeNSSet(_ s: NSSet) -> Bool { let className: NSString = NSStringFromClass(type(of: s)) as NSString return className.range(of: "NativeSetStorage").length > 0 } func isCocoaNSSet(_ s: NSSet) -> Bool { let className: NSString = NSStringFromClass(type(of: s)) as NSString return className.range(of: "NSSet").length > 0 || className.range(of: "NSCFSet").length > 0 } func getBridgedEmptyNSSet() -> NSSet { let s = Set<TestObjCKeyTy>() let bridged = unsafeBitCast(convertSetToNSSet(s), to: NSSet.self) expectTrue(isNativeNSSet(bridged)) return bridged } func isCocoaSet<T : Hashable>(_ s: Set<T>) -> Bool { return !isNativeSet(s) } /// Get an NSSet of TestObjCKeyTy values func getAsNSSet(_ members: [Int] = [1010, 2020, 3030]) -> NSSet { let nsArray = NSMutableArray() for member in members { nsArray.add(TestObjCKeyTy(member)) } return NSMutableSet(array: nsArray as [AnyObject]) } /// Get an NSMutableSet of TestObjCKeyTy values func getAsNSMutableSet(_ members: [Int] = [1010, 2020, 3030]) -> NSMutableSet { let nsArray = NSMutableArray() for member in members { nsArray.add(TestObjCKeyTy(member)) } return NSMutableSet(array: nsArray as [AnyObject]) } public func convertSetToNSSet<T>(_ s: Set<T>) -> NSSet { return s._bridgeToObjectiveC() } public func convertNSSetToSet<T : Hashable>(_ s: NSSet?) -> Set<T> { if _slowPath(s == nil) { return [] } var result: Set<T>? Set._forceBridgeFromObjectiveC(s!, result: &result) return result! } /// Get a Set<NSObject> (Set<TestObjCKeyTy>) backed by Cocoa storage func getBridgedVerbatimSet(_ members: [Int] = [1010, 2020, 3030]) -> Set<NSObject> { let nss = getAsNSSet(members) let result: Set<NSObject> = convertNSSetToSet(nss) expectTrue(isCocoaSet(result)) return result } /// Get a Set<NSObject> (Set<TestObjCKeyTy>) backed by native storage func getNativeBridgedVerbatimSet(_ members: [Int] = [1010, 2020, 3030]) -> Set<NSObject> { let result: Set<NSObject> = Set(members.map({ TestObjCKeyTy($0) })) expectTrue(isNativeSet(result)) return result } /// Get a Set<NSObject> (Set<TestObjCKeyTy>) backed by Cocoa storage func getHugeBridgedVerbatimSet() -> Set<NSObject> { let nss = getAsNSSet(hugeNumberArray) let result: Set<NSObject> = convertNSSetToSet(nss) expectTrue(isCocoaSet(result)) return result } /// Get a Set<TestBridgedKeyTy> backed by native storage func getBridgedNonverbatimSet(_ members: [Int] = [1010, 2020, 3030]) -> Set<TestBridgedKeyTy> { let nss = getAsNSSet(members) let _ = unsafeBitCast(nss, to: Int.self) let result: Set<TestBridgedKeyTy> = Swift._forceBridgeFromObjectiveC(nss, Set.self) expectTrue(isNativeSet(result)) return result } /// Get a larger Set<TestBridgedKeyTy> backed by native storage func getHugeBridgedNonverbatimSet() -> Set<TestBridgedKeyTy> { let nss = getAsNSSet(hugeNumberArray) let _ = unsafeBitCast(nss, to: Int.self) let result: Set<TestBridgedKeyTy> = Swift._forceBridgeFromObjectiveC(nss, Set.self) expectTrue(isNativeSet(result)) return result } func getBridgedVerbatimSetAndNSMutableSet() -> (Set<NSObject>, NSMutableSet) { let nss = getAsNSMutableSet() return (convertNSSetToSet(nss), nss) } func getBridgedNonverbatimSetAndNSMutableSet() -> (Set<TestBridgedKeyTy>, NSMutableSet) { let nss = getAsNSMutableSet() return (Swift._forceBridgeFromObjectiveC(nss, Set.self), nss) } func getBridgedNSSetOfRefTypesBridgedVerbatim() -> NSSet { expectTrue(_isBridgedVerbatimToObjectiveC(TestObjCKeyTy.self)) var s = Set<TestObjCKeyTy>(minimumCapacity: 32) s.insert(TestObjCKeyTy(1010)) s.insert(TestObjCKeyTy(2020)) s.insert(TestObjCKeyTy(3030)) let bridged = unsafeBitCast(convertSetToNSSet(s), to: NSSet.self) expectTrue(isNativeNSSet(bridged)) return bridged } func getBridgedNSSet_ValueTypesCustomBridged( numElements: Int = 3 ) -> NSSet { expectTrue(!_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self)) var s = Set<TestBridgedKeyTy>() for i in 1..<(numElements + 1) { s.insert(TestBridgedKeyTy(i * 1000 + i * 10)) } let bridged = convertSetToNSSet(s) expectTrue(isNativeNSSet(bridged)) return bridged } func getRoundtripBridgedNSSet() -> NSSet { let items = NSMutableArray() items.add(TestObjCKeyTy(1010)) items.add(TestObjCKeyTy(2020)) items.add(TestObjCKeyTy(3030)) let nss = NSSet(array: items as [AnyObject]) let s: Set<NSObject> = convertNSSetToSet(nss) let bridgedBack = convertSetToNSSet(s) expectTrue(isCocoaNSSet(bridgedBack)) // FIXME: this should be true. //expectTrue(unsafeBitCast(nsd, to: Int.self) == unsafeBitCast(bridgedBack, to: Int.self)) return bridgedBack } func getBridgedNSSet_MemberTypesCustomBridged() -> NSSet { expectFalse(_isBridgedVerbatimToObjectiveC(TestBridgedKeyTy.self)) var s = Set<TestBridgedKeyTy>() s.insert(TestBridgedKeyTy(1010)) s.insert(TestBridgedKeyTy(2020)) s.insert(TestBridgedKeyTy(3030)) let bridged = convertSetToNSSet(s) expectTrue(isNativeNSSet(bridged)) return bridged } #endif // _runtime(_ObjC) SetTestSuite.test("AssociatedTypes") { typealias Collection = Set<MinimalHashableValue> expectCollectionAssociatedTypes( collectionType: Collection.self, iteratorType: SetIterator<MinimalHashableValue>.self, subSequenceType: Slice<Collection>.self, indexType: SetIndex<MinimalHashableValue>.self, indexDistanceType: Int.self, indicesType: DefaultIndices<Collection>.self) } SetTestSuite.test("sizeof") { var s = Set(["Hello", "world"]) #if arch(i386) || arch(arm) expectEqual(4, MemoryLayout.size(ofValue: s)) #else expectEqual(8, MemoryLayout.size(ofValue: s)) #endif } SetTestSuite.test("COW.Smoke") { var s1 = Set<TestKeyTy>(minimumCapacity: 10) for i in [1010, 2020, 3030]{ s1.insert(TestKeyTy(i)) } var identity1 = s1._rawIdentifier() var s2 = s1 _fixLifetime(s2) expectEqual(identity1, s2._rawIdentifier()) s2.insert(TestKeyTy(4040)) expectNotEqual(identity1, s2._rawIdentifier()) s2.insert(TestKeyTy(5050)) expectEqual(identity1, s1._rawIdentifier()) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } SetTestSuite.test("COW.Fast.IndexesDontAffectUniquenessCheck") { var s = getCOWFastSet() var identity1 = s._rawIdentifier() var startIndex = s.startIndex var endIndex = s.endIndex expectNotEqual(startIndex, endIndex) expectTrue(startIndex < endIndex) expectTrue(startIndex <= endIndex) expectFalse(startIndex >= endIndex) expectFalse(startIndex > endIndex) expectEqual(identity1, s._rawIdentifier()) s.insert(4040) expectEqual(identity1, s._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } SetTestSuite.test("COW.Slow.IndexesDontAffectUniquenessCheck") { var s = getCOWSlowSet() var identity1 = s._rawIdentifier() var startIndex = s.startIndex var endIndex = s.endIndex expectNotEqual(startIndex, endIndex) expectTrue(startIndex < endIndex) expectTrue(startIndex <= endIndex) expectFalse(startIndex >= endIndex) expectFalse(startIndex > endIndex) expectEqual(identity1, s._rawIdentifier()) s.insert(TestKeyTy(4040)) expectEqual(identity1, s._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } SetTestSuite.test("COW.Fast.SubscriptWithIndexDoesNotReallocate") { var s = getCOWFastSet() var identity1 = s._rawIdentifier() var startIndex = s.startIndex let empty = startIndex == s.endIndex expectNotEqual(empty, (s.startIndex < s.endIndex)) expectTrue(s.startIndex <= s.endIndex) expectEqual(empty, (s.startIndex >= s.endIndex)) expectFalse(s.startIndex > s.endIndex) expectEqual(identity1, s._rawIdentifier()) expectNotEqual(0, s[startIndex]) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("COW.Slow.SubscriptWithIndexDoesNotReallocate") { var s = getCOWSlowSet() var identity1 = s._rawIdentifier() var startIndex = s.startIndex let empty = startIndex == s.endIndex expectNotEqual(empty, (s.startIndex < s.endIndex)) expectTrue(s.startIndex <= s.endIndex) expectEqual(empty, (s.startIndex >= s.endIndex)) expectFalse(s.startIndex > s.endIndex) expectEqual(identity1, s._rawIdentifier()) expectNotEqual(TestKeyTy(0), s[startIndex]) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("COW.Fast.ContainsDoesNotReallocate") { var s = getCOWFastSet() var identity1 = s._rawIdentifier() expectTrue(s.contains(1010)) expectEqual(identity1, s._rawIdentifier()) do { var s2: Set<MinimalHashableValue> = [] MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashValueWasCalled = 0 expectFalse(s2.contains(MinimalHashableValue(42))) // If the set is empty, we shouldn't be computing the hash value of the // provided key. expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashValueWasCalled) } } SetTestSuite.test("COW.Slow.ContainsDoesNotReallocate") { var s = getCOWSlowSet() var identity1 = s._rawIdentifier() expectTrue(s.contains(TestKeyTy(1010))) expectEqual(identity1, s._rawIdentifier()) // Insert a new key-value pair. s.insert(TestKeyTy(4040)) expectEqual(identity1, s._rawIdentifier()) expectEqual(4, s.count) expectTrue(s.contains(TestKeyTy(1010))) expectTrue(s.contains(TestKeyTy(2020))) expectTrue(s.contains(TestKeyTy(3030))) expectTrue(s.contains(TestKeyTy(4040))) // Delete an existing key. s.remove(TestKeyTy(1010)) expectEqual(identity1, s._rawIdentifier()) expectEqual(3, s.count) expectTrue(s.contains(TestKeyTy(2020))) expectTrue(s.contains(TestKeyTy(3030))) expectTrue(s.contains(TestKeyTy(4040))) // Try to delete a key that does not exist. s.remove(TestKeyTy(777)) expectEqual(identity1, s._rawIdentifier()) expectEqual(3, s.count) expectTrue(s.contains(TestKeyTy(2020))) expectTrue(s.contains(TestKeyTy(3030))) expectTrue(s.contains(TestKeyTy(4040))) do { var s2: Set<MinimalHashableClass> = [] MinimalHashableClass.timesEqualEqualWasCalled = 0 MinimalHashableClass.timesHashValueWasCalled = 0 expectFalse(s2.contains(MinimalHashableClass(42))) // If the set is empty, we shouldn't be computing the hash value of the // provided key. expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableClass.timesHashValueWasCalled) } } SetTestSuite.test("COW.Fast.InsertDoesNotReallocate") { var s1 = getCOWFastSet() let identity1 = s1._rawIdentifier() let count1 = s1.count // Inserting a redundant element should not create new storage s1.insert(2020) expectEqual(identity1, s1._rawIdentifier()) expectEqual(count1, s1.count) s1.insert(4040) s1.insert(5050) s1.insert(6060) expectEqual(count1 + 3, s1.count) expectEqual(identity1, s1._rawIdentifier()) } SetTestSuite.test("COW.Slow.InsertDoesNotReallocate") { do { var s1 = getCOWSlowSet() let identity1 = s1._rawIdentifier() let count1 = s1.count // Inserting a redundant element should not create new storage s1.insert(TestKeyTy(2020)) expectEqual(identity1, s1._rawIdentifier()) expectEqual(count1, s1.count) s1.insert(TestKeyTy(4040)) s1.insert(TestKeyTy(5050)) s1.insert(TestKeyTy(6060)) expectEqual(count1 + 3, s1.count) expectEqual(identity1, s1._rawIdentifier()) } do { var s1 = getCOWSlowSet() var identity1 = s1._rawIdentifier() var s2 = s1 expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) s2.insert(TestKeyTy(2040)) expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, s2._rawIdentifier()) expectEqual(3, s1.count) expectTrue(s1.contains(TestKeyTy(1010))) expectTrue(s1.contains(TestKeyTy(2020))) expectTrue(s1.contains(TestKeyTy(3030))) expectFalse(s1.contains(TestKeyTy(2040))) expectEqual(4, s2.count) expectTrue(s2.contains(TestKeyTy(1010))) expectTrue(s2.contains(TestKeyTy(2020))) expectTrue(s2.contains(TestKeyTy(3030))) expectTrue(s2.contains(TestKeyTy(2040))) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } do { var s1 = getCOWSlowSet() var identity1 = s1._rawIdentifier() var s2 = s1 expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) // Replace a redundant element. s2.update(with: TestKeyTy(2020)) expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, s2._rawIdentifier()) expectEqual(3, s1.count) expectTrue(s1.contains(TestKeyTy(1010))) expectTrue(s1.contains(TestKeyTy(2020))) expectTrue(s1.contains(TestKeyTy(3030))) expectEqual(3, s2.count) expectTrue(s2.contains(TestKeyTy(1010))) expectTrue(s2.contains(TestKeyTy(2020))) expectTrue(s2.contains(TestKeyTy(3030))) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } } SetTestSuite.test("COW.Fast.IndexForMemberDoesNotReallocate") { var s = getCOWFastSet() var identity1 = s._rawIdentifier() // Find an existing key. do { var foundIndex1 = s.index(of: 1010)! expectEqual(identity1, s._rawIdentifier()) var foundIndex2 = s.index(of: 1010)! expectEqual(foundIndex1, foundIndex2) expectEqual(1010, s[foundIndex1]) expectEqual(identity1, s._rawIdentifier()) } // Try to find a key that is not present. do { var foundIndex1 = s.index(of: 1111) expectEmpty(foundIndex1) expectEqual(identity1, s._rawIdentifier()) } do { var s2: Set<MinimalHashableValue> = [] MinimalHashableValue.timesEqualEqualWasCalled = 0 MinimalHashableValue.timesHashValueWasCalled = 0 expectEmpty(s2.index(of: MinimalHashableValue(42))) // If the set is empty, we shouldn't be computing the hash value of the // provided key. expectEqual(0, MinimalHashableValue.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableValue.timesHashValueWasCalled) } } SetTestSuite.test("COW.Slow.IndexForMemberDoesNotReallocate") { var s = getCOWSlowSet() var identity1 = s._rawIdentifier() // Find an existing key. do { var foundIndex1 = s.index(of: TestKeyTy(1010))! expectEqual(identity1, s._rawIdentifier()) var foundIndex2 = s.index(of: TestKeyTy(1010))! expectEqual(foundIndex1, foundIndex2) expectEqual(TestKeyTy(1010), s[foundIndex1]) expectEqual(identity1, s._rawIdentifier()) } // Try to find a key that is not present. do { var foundIndex1 = s.index(of: TestKeyTy(1111)) expectEmpty(foundIndex1) expectEqual(identity1, s._rawIdentifier()) } do { var s2: Set<MinimalHashableClass> = [] MinimalHashableClass.timesEqualEqualWasCalled = 0 MinimalHashableClass.timesHashValueWasCalled = 0 expectEmpty(s2.index(of: MinimalHashableClass(42))) // If the set is empty, we shouldn't be computing the hash value of the // provided key. expectEqual(0, MinimalHashableClass.timesEqualEqualWasCalled) expectEqual(0, MinimalHashableClass.timesHashValueWasCalled) } } SetTestSuite.test("COW.Fast.RemoveAtDoesNotReallocate") { do { var s = getCOWFastSet() var identity1 = s._rawIdentifier() let foundIndex1 = s.index(of: 1010)! expectEqual(identity1, s._rawIdentifier()) expectEqual(1010, s[foundIndex1]) let removed = s.remove(at: foundIndex1) expectEqual(1010, removed) expectEqual(identity1, s._rawIdentifier()) expectEmpty(s.index(of: 1010)) } do { var s1 = getCOWFastSet() var identity1 = s1._rawIdentifier() var s2 = s1 expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) var foundIndex1 = s2.index(of: 1010)! expectEqual(1010, s2[foundIndex1]) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) let removed = s2.remove(at: foundIndex1) expectEqual(1010, removed) expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, s2._rawIdentifier()) expectEmpty(s2.index(of: 1010)) } } SetTestSuite.test("COW.Slow.RemoveAtDoesNotReallocate") { do { var s = getCOWSlowSet() var identity1 = s._rawIdentifier() let foundIndex1 = s.index(of: TestKeyTy(1010))! expectEqual(identity1, s._rawIdentifier()) expectEqual(TestKeyTy(1010), s[foundIndex1]) let removed = s.remove(at: foundIndex1) expectEqual(TestKeyTy(1010), removed) expectEqual(identity1, s._rawIdentifier()) expectEmpty(s.index(of: TestKeyTy(1010))) } do { var s1 = getCOWSlowSet() var identity1 = s1._rawIdentifier() var s2 = s1 expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) var foundIndex1 = s2.index(of: TestKeyTy(1010))! expectEqual(TestKeyTy(1010), s2[foundIndex1]) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) let removed = s2.remove(at: foundIndex1) expectEqual(TestKeyTy(1010), removed) expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, s2._rawIdentifier()) expectEmpty(s2.index(of: TestKeyTy(1010))) } } SetTestSuite.test("COW.Fast.RemoveDoesNotReallocate") { do { var s1 = getCOWFastSet() var identity1 = s1._rawIdentifier() var deleted = s1.remove(0) expectEmpty(deleted) expectEqual(identity1, s1._rawIdentifier()) deleted = s1.remove(1010) expectOptionalEqual(1010, deleted) expectEqual(identity1, s1._rawIdentifier()) // Keep variables alive. _fixLifetime(s1) } do { var s1 = getCOWFastSet() var identity1 = s1._rawIdentifier() var s2 = s1 var deleted = s2.remove(0) expectEmpty(deleted) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) deleted = s2.remove(1010) expectOptionalEqual(1010, deleted) expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, s2._rawIdentifier()) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } } SetTestSuite.test("COW.Slow.RemoveDoesNotReallocate") { do { var s1 = getCOWSlowSet() var identity1 = s1._rawIdentifier() var deleted = s1.remove(TestKeyTy(0)) expectEmpty(deleted) expectEqual(identity1, s1._rawIdentifier()) deleted = s1.remove(TestKeyTy(1010)) expectOptionalEqual(TestKeyTy(1010), deleted) expectEqual(identity1, s1._rawIdentifier()) // Keep variables alive. _fixLifetime(s1) } do { var s1 = getCOWSlowSet() var identity1 = s1._rawIdentifier() var s2 = s1 var deleted = s2.remove(TestKeyTy(0)) expectEmpty(deleted) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) deleted = s2.remove(TestKeyTy(1010)) expectOptionalEqual(TestKeyTy(1010), deleted) expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, s2._rawIdentifier()) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } } SetTestSuite.test("COW.Fast.UnionInPlaceSmallSetDoesNotReallocate") { var s1 = getCOWFastSet() let s2 = Set([4040, 5050, 6060]) let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let identity1 = s1._rawIdentifier() // Adding the empty set should obviously not allocate s1.formUnion(Set<Int>()) expectEqual(identity1, s1._rawIdentifier()) // adding a small set shouldn't cause a reallocation s1.formUnion(s2) expectEqual(s1, s3) expectEqual(identity1, s1._rawIdentifier()) } SetTestSuite.test("COW.Fast.RemoveAllDoesNotReallocate") { do { var s = getCOWFastSet() let originalCapacity = s._variantStorage.asNative.capacity expectEqual(3, s.count) expectTrue(s.contains(1010)) s.removeAll() // We cannot expectTrue that identity changed, since the new buffer of // smaller size can be allocated at the same address as the old one. var identity1 = s._rawIdentifier() expectTrue(s._variantStorage.asNative.capacity < originalCapacity) expectEqual(0, s.count) expectFalse(s.contains(1010)) s.removeAll() expectEqual(identity1, s._rawIdentifier()) expectEqual(0, s.count) expectFalse(s.contains(1010)) } do { var s = getCOWFastSet() var identity1 = s._rawIdentifier() let originalCapacity = s._variantStorage.asNative.capacity expectEqual(3, s.count) expectTrue(s.contains(1010)) s.removeAll(keepingCapacity: true) expectEqual(identity1, s._rawIdentifier()) expectEqual(originalCapacity, s._variantStorage.asNative.capacity) expectEqual(0, s.count) expectFalse(s.contains(1010)) s.removeAll(keepingCapacity: true) expectEqual(identity1, s._rawIdentifier()) expectEqual(originalCapacity, s._variantStorage.asNative.capacity) expectEqual(0, s.count) expectFalse(s.contains(1010)) } do { var s1 = getCOWFastSet() var identity1 = s1._rawIdentifier() expectEqual(3, s1.count) expectTrue(s1.contains(1010)) var s2 = s1 s2.removeAll() var identity2 = s2._rawIdentifier() expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, identity2) expectEqual(3, s1.count) expectTrue(s1.contains(1010)) expectEqual(0, s2.count) expectFalse(s2.contains(1010)) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } do { var s1 = getCOWFastSet() var identity1 = s1._rawIdentifier() let originalCapacity = s1._variantStorage.asNative.capacity expectEqual(3, s1.count) expectTrue(s1.contains(1010)) var s2 = s1 s2.removeAll(keepingCapacity: true) var identity2 = s2._rawIdentifier() expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, identity2) expectEqual(3, s1.count) expectTrue(s1.contains(1010)) expectEqual(originalCapacity, s2._variantStorage.asNative.capacity) expectEqual(0, s2.count) expectFalse(s2.contains(1010)) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } } SetTestSuite.test("COW.Slow.RemoveAllDoesNotReallocate") { do { var s = getCOWSlowSet() let originalCapacity = s._variantStorage.asNative.capacity expectEqual(3, s.count) expectTrue(s.contains(TestKeyTy(1010))) s.removeAll() // We cannot expectTrue that identity changed, since the new buffer of // smaller size can be allocated at the same address as the old one. var identity1 = s._rawIdentifier() expectTrue(s._variantStorage.asNative.capacity < originalCapacity) expectEqual(0, s.count) expectFalse(s.contains(TestKeyTy(1010))) s.removeAll() expectEqual(identity1, s._rawIdentifier()) expectEqual(0, s.count) expectFalse(s.contains(TestKeyTy(1010))) } do { var s = getCOWSlowSet() var identity1 = s._rawIdentifier() let originalCapacity = s._variantStorage.asNative.capacity expectEqual(3, s.count) expectTrue(s.contains(TestKeyTy(1010))) s.removeAll(keepingCapacity: true) expectEqual(identity1, s._rawIdentifier()) expectEqual(originalCapacity, s._variantStorage.asNative.capacity) expectEqual(0, s.count) expectFalse(s.contains(TestKeyTy(1010))) s.removeAll(keepingCapacity: true) expectEqual(identity1, s._rawIdentifier()) expectEqual(originalCapacity, s._variantStorage.asNative.capacity) expectEqual(0, s.count) expectFalse(s.contains(TestKeyTy(1010))) } do { var s1 = getCOWSlowSet() var identity1 = s1._rawIdentifier() expectEqual(3, s1.count) expectTrue(s1.contains(TestKeyTy(1010))) var s2 = s1 s2.removeAll() var identity2 = s2._rawIdentifier() expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, identity2) expectEqual(3, s1.count) expectTrue(s1.contains(TestKeyTy(1010))) expectEqual(0, s2.count) expectFalse(s2.contains(TestKeyTy(1010))) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } do { var s1 = getCOWSlowSet() var identity1 = s1._rawIdentifier() let originalCapacity = s1._variantStorage.asNative.capacity expectEqual(3, s1.count) expectTrue(s1.contains(TestKeyTy(1010))) var s2 = s1 s2.removeAll(keepingCapacity: true) var identity2 = s2._rawIdentifier() expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, identity2) expectEqual(3, s1.count) expectTrue(s1.contains(TestKeyTy(1010))) expectEqual(originalCapacity, s2._variantStorage.asNative.capacity) expectEqual(0, s2.count) expectFalse(s2.contains(TestKeyTy(1010))) // Keep variables alive. _fixLifetime(s1) _fixLifetime(s2) } } SetTestSuite.test("COW.Fast.FirstDoesNotReallocate") { var s = getCOWFastSet() var identity1 = s._rawIdentifier() expectNotEmpty(s.first) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("COW.Fast.CountDoesNotReallocate") { var s = getCOWFastSet() var identity1 = s._rawIdentifier() expectEqual(3, s.count) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("COW.Slow.FirstDoesNotReallocate") { var s = getCOWSlowSet() var identity1 = s._rawIdentifier() expectNotEmpty(s.first) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("COW.Slow.CountDoesNotReallocate") { var s = getCOWSlowSet() var identity1 = s._rawIdentifier() expectEqual(3, s.count) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("COW.Fast.GenerateDoesNotReallocate") { var s = getCOWFastSet() var identity1 = s._rawIdentifier() var iter = s.makeIterator() var items: [Int] = [] while let value = iter.next() { items += [value] } expectTrue(equalsUnordered(items, [ 1010, 2020, 3030 ])) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("COW.Slow.GenerateDoesNotReallocate") { var s = getCOWSlowSet() var identity1 = s._rawIdentifier() var iter = s.makeIterator() var items: [Int] = [] while let value = iter.next() { items.append(value.value) } expectTrue(equalsUnordered(items, [ 1010, 2020, 3030 ])) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("COW.Fast.EqualityTestDoesNotReallocate") { var s1 = getCOWFastSet() var identity1 = s1._rawIdentifier() var s2 = getCOWFastSet() var identity2 = s2._rawIdentifier() expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity2, s2._rawIdentifier()) } SetTestSuite.test("COW.Slow.EqualityTestDoesNotReallocate") { var s1 = getCOWFastSet() var identity1 = s1._rawIdentifier() var s2 = getCOWFastSet() var identity2 = s2._rawIdentifier() expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity2, s2._rawIdentifier()) } //===--- // Native set tests. //===--- SetTestSuite.test("deleteChainCollision") { var k1 = TestKeyTy(value: 1010, hashValue: 0) var k2 = TestKeyTy(value: 2020, hashValue: 0) var k3 = TestKeyTy(value: 3030, hashValue: 0) helperDeleteThree(k1, k2, k3) } SetTestSuite.test("deleteChainNoCollision") { var k1 = TestKeyTy(value: 1010, hashValue: 0) var k2 = TestKeyTy(value: 2020, hashValue: 1) var k3 = TestKeyTy(value: 3030, hashValue: 2) helperDeleteThree(k1, k2, k3) } SetTestSuite.test("deleteChainCollision2") { var k1_0 = TestKeyTy(value: 1010, hashValue: 0) var k2_0 = TestKeyTy(value: 2020, hashValue: 0) var k3_2 = TestKeyTy(value: 3030, hashValue: 2) var k4_0 = TestKeyTy(value: 4040, hashValue: 0) var k5_2 = TestKeyTy(value: 5050, hashValue: 2) var k6_0 = TestKeyTy(value: 6060, hashValue: 0) var s = Set<TestKeyTy>(minimumCapacity: 10) s.insert(k1_0) // in bucket 0 s.insert(k2_0) // in bucket 1 s.insert(k3_2) // in bucket 2 s.insert(k4_0) // in bucket 3 s.insert(k5_2) // in bucket 4 s.insert(k6_0) // in bucket 5 s.remove(k3_2) expectTrue(s.contains(k1_0)) expectTrue(s.contains(k2_0)) expectFalse(s.contains(k3_2)) expectTrue(s.contains(k4_0)) expectTrue(s.contains(k5_2)) expectTrue(s.contains(k6_0)) } SetTestSuite.test("deleteChainCollisionRandomized") { let timeNow = CUnsignedInt(time(nil)) print("time is \(timeNow)") srandom(timeNow) func check(_ s: Set<TestKeyTy>) { var keys = Array(s) for i in 0..<keys.count { for j in 0..<i { expectNotEqual(keys[i], keys[j]) } } for k in keys { expectTrue(s.contains(k)) } } var collisionChainsChoices = Array(1...8) var chainOverlapChoices = Array(0...5) var collisionChains = pickRandom(collisionChainsChoices) var chainOverlap = pickRandom(chainOverlapChoices) print("chose parameters: collisionChains=\(collisionChains) chainLength=\(chainOverlap)") let chainLength = 7 var knownKeys: [TestKeyTy] = [] func getKey(_ value: Int) -> TestKeyTy { for k in knownKeys { if k.value == value { return k } } let hashValue = uniformRandom(chainLength - chainOverlap) * collisionChains let k = TestKeyTy(value: value, hashValue: hashValue) knownKeys += [k] return k } var s = Set<TestKeyTy>(minimumCapacity: 30) for i in 1..<300 { let key = getKey(uniformRandom(collisionChains * chainLength)) if uniformRandom(chainLength * 2) == 0 { s.remove(key) } else { s.insert(TestKeyTy(key.value)) } check(s) } } #if _runtime(_ObjC) @objc class CustomImmutableNSSet : NSSet { init(_privateInit: ()) { super.init() } override init() { expectUnreachable() super.init() } override init(objects: UnsafePointer<AnyObject>, count: Int) { expectUnreachable() super.init(objects: objects, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by CustomImmutableNSSet") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { CustomImmutableNSSet.timesCopyWithZoneWasCalled += 1 return self } override func member(_ object: Any) -> Any? { CustomImmutableNSSet.timesMemberWasCalled += 1 return getAsNSSet([ 1010, 1020, 1030 ]).member(object) } override func objectEnumerator() -> NSEnumerator { CustomImmutableNSSet.timesObjectEnumeratorWasCalled += 1 return getAsNSSet([ 1010, 1020, 1030 ]).objectEnumerator() } override var count: Int { CustomImmutableNSSet.timesCountWasCalled += 1 return 3 } static var timesCopyWithZoneWasCalled = 0 static var timesMemberWasCalled = 0 static var timesObjectEnumeratorWasCalled = 0 static var timesCountWasCalled = 0 } SetTestSuite.test("BridgedFromObjC.Verbatim.SetIsCopied") { var (s, nss) = getBridgedVerbatimSetAndNSMutableSet() expectTrue(isCocoaSet(s)) expectTrue(s.contains(TestObjCKeyTy(1010))) expectNotEmpty(nss.member(TestObjCKeyTy(1010))) nss.remove(TestObjCKeyTy(1010)) expectEmpty(nss.member(TestObjCKeyTy(1010))) expectTrue(s.contains(TestObjCKeyTy(1010))) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.SetIsCopied") { var (s, nss) = getBridgedNonverbatimSetAndNSMutableSet() expectTrue(isNativeSet(s)) expectTrue(s.contains(TestBridgedKeyTy(1010))) expectNotEmpty(nss.member(TestBridgedKeyTy(1010) as AnyObject)) nss.remove(TestBridgedKeyTy(1010) as AnyObject) expectEmpty(nss.member(TestBridgedKeyTy(1010) as AnyObject)) expectTrue(s.contains(TestBridgedKeyTy(1010))) } SetTestSuite.test("BridgedFromObjC.Verbatim.NSSetIsRetained") { var nss: NSSet = NSSet(set: getAsNSSet([ 1010, 1020, 1030 ])) var s: Set<NSObject> = convertNSSetToSet(nss) var bridgedBack: NSSet = convertSetToNSSet(s) expectEqual( unsafeBitCast(nss, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nss) _fixLifetime(s) _fixLifetime(bridgedBack) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.NSSetIsCopied") { var nss: NSSet = NSSet(set: getAsNSSet([ 1010, 1020, 1030 ])) var s: Set<TestBridgedKeyTy> = convertNSSetToSet(nss) var bridgedBack: NSSet = convertSetToNSSet(s) expectNotEqual( unsafeBitCast(nss, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nss) _fixLifetime(s) _fixLifetime(bridgedBack) } SetTestSuite.test("BridgedFromObjC.Verbatim.ImmutableSetIsRetained") { var nss: NSSet = CustomImmutableNSSet(_privateInit: ()) CustomImmutableNSSet.timesCopyWithZoneWasCalled = 0 CustomImmutableNSSet.timesMemberWasCalled = 0 CustomImmutableNSSet.timesObjectEnumeratorWasCalled = 0 CustomImmutableNSSet.timesCountWasCalled = 0 var s: Set<NSObject> = convertNSSetToSet(nss) expectEqual(1, CustomImmutableNSSet.timesCopyWithZoneWasCalled) expectEqual(0, CustomImmutableNSSet.timesMemberWasCalled) expectEqual(0, CustomImmutableNSSet.timesObjectEnumeratorWasCalled) expectEqual(0, CustomImmutableNSSet.timesCountWasCalled) var bridgedBack: NSSet = convertSetToNSSet(s) expectEqual( unsafeBitCast(nss, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nss) _fixLifetime(s) _fixLifetime(bridgedBack) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.ImmutableSetIsCopied") { var nss: NSSet = CustomImmutableNSSet(_privateInit: ()) CustomImmutableNSSet.timesCopyWithZoneWasCalled = 0 CustomImmutableNSSet.timesMemberWasCalled = 0 CustomImmutableNSSet.timesObjectEnumeratorWasCalled = 0 CustomImmutableNSSet.timesCountWasCalled = 0 var s: Set<TestBridgedKeyTy> = convertNSSetToSet(nss) expectEqual(0, CustomImmutableNSSet.timesCopyWithZoneWasCalled) expectEqual(0, CustomImmutableNSSet.timesMemberWasCalled) expectEqual(1, CustomImmutableNSSet.timesObjectEnumeratorWasCalled) expectNotEqual(0, CustomImmutableNSSet.timesCountWasCalled) var bridgedBack: NSSet = convertSetToNSSet(s) expectNotEqual( unsafeBitCast(nss, to: Int.self), unsafeBitCast(bridgedBack, to: Int.self)) _fixLifetime(nss) _fixLifetime(s) _fixLifetime(bridgedBack) } SetTestSuite.test("BridgedFromObjC.Verbatim.IndexForMember") { var s = getBridgedVerbatimSet() var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) // Find an existing key. var member = s[s.index(of: TestObjCKeyTy(1010))!] expectEqual(TestObjCKeyTy(1010), member) member = s[s.index(of: TestObjCKeyTy(2020))!] expectEqual(TestObjCKeyTy(2020), member) member = s[s.index(of: TestObjCKeyTy(3030))!] expectEqual(TestObjCKeyTy(3030), member) // Try to find a key that does not exist. expectEmpty(s.index(of: TestObjCKeyTy(4040))) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.IndexForMember") { var s = getBridgedNonverbatimSet() var identity1 = s._rawIdentifier() do { var member = s[s.index(of: TestBridgedKeyTy(1010))!] expectEqual(TestBridgedKeyTy(1010), member) member = s[s.index(of: TestBridgedKeyTy(2020))!] expectEqual(TestBridgedKeyTy(2020), member) member = s[s.index(of: TestBridgedKeyTy(3030))!] expectEqual(TestBridgedKeyTy(3030), member) } expectEmpty(s.index(of: TestBridgedKeyTy(4040))) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Verbatim.Insert") { do { var s = getBridgedVerbatimSet() var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) expectFalse(s.contains(TestObjCKeyTy(2040))) s.insert(TestObjCKeyTy(2040)) var identity2 = s._rawIdentifier() expectNotEqual(identity1, identity2) expectTrue(isNativeSet(s)) expectEqual(4, s.count) expectTrue(s.contains(TestObjCKeyTy(1010))) expectTrue(s.contains(TestObjCKeyTy(2020))) expectTrue(s.contains(TestObjCKeyTy(3030))) expectTrue(s.contains(TestObjCKeyTy(2040))) } } SetTestSuite.test("BridgedFromObjC.Nonverbatim.Insert") { do { var s = getBridgedNonverbatimSet() var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) expectFalse(s.contains(TestBridgedKeyTy(2040))) s.insert(TestObjCKeyTy(2040) as TestBridgedKeyTy) var identity2 = s._rawIdentifier() expectNotEqual(identity1, identity2) expectTrue(isNativeSet(s)) expectEqual(4, s.count) expectTrue(s.contains(TestBridgedKeyTy(1010))) expectTrue(s.contains(TestBridgedKeyTy(2020))) expectTrue(s.contains(TestBridgedKeyTy(3030))) expectTrue(s.contains(TestBridgedKeyTy(2040))) } } SetTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex") { var s = getBridgedVerbatimSet() var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) var startIndex = s.startIndex var endIndex = s.endIndex expectNotEqual(startIndex, endIndex) expectTrue(startIndex < endIndex) expectTrue(startIndex <= endIndex) expectFalse(startIndex >= endIndex) expectFalse(startIndex > endIndex) expectEqual(identity1, s._rawIdentifier()) var members = [Int]() for i in s.indices { var foundMember: AnyObject = s[i] let member = foundMember as! TestObjCKeyTy members.append(member.value) } expectTrue(equalsUnordered(members, [1010, 2020, 3030])) expectEqual(identity1, s._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex") { var s = getBridgedNonverbatimSet() var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) var startIndex = s.startIndex var endIndex = s.endIndex expectNotEqual(startIndex, endIndex) expectTrue(startIndex < endIndex) expectTrue(startIndex <= endIndex) expectFalse(startIndex >= endIndex) expectFalse(startIndex > endIndex) expectEqual(identity1, s._rawIdentifier()) var members = [Int]() for i in s.indices { var foundMember: AnyObject = s[i] as NSObject let member = foundMember as! TestObjCKeyTy members.append(member.value) } expectTrue(equalsUnordered(members, [1010, 2020, 3030])) expectEqual(identity1, s._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } SetTestSuite.test("BridgedFromObjC.Verbatim.SubscriptWithIndex_Empty") { var s = getBridgedVerbatimSet([]) var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) var startIndex = s.startIndex var endIndex = s.endIndex expectEqual(startIndex, endIndex) expectFalse(startIndex < endIndex) expectTrue(startIndex <= endIndex) expectTrue(startIndex >= endIndex) expectFalse(startIndex > endIndex) expectEqual(identity1, s._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithIndex_Empty") { var s = getBridgedNonverbatimSet([]) var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) var startIndex = s.startIndex var endIndex = s.endIndex expectEqual(startIndex, endIndex) expectFalse(startIndex < endIndex) expectTrue(startIndex <= endIndex) expectTrue(startIndex >= endIndex) expectFalse(startIndex > endIndex) expectEqual(identity1, s._rawIdentifier()) // Keep indexes alive during the calls above. _fixLifetime(startIndex) _fixLifetime(endIndex) } SetTestSuite.test("BridgedFromObjC.Verbatim.Contains") { var s = getBridgedVerbatimSet() var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) expectTrue(s.contains(TestObjCKeyTy(1010))) expectTrue(s.contains(TestObjCKeyTy(2020))) expectTrue(s.contains(TestObjCKeyTy(3030))) expectEqual(identity1, s._rawIdentifier()) // Inserting an item should now create storage unique from the bridged set. s.insert(TestObjCKeyTy(4040)) var identity2 = s._rawIdentifier() expectNotEqual(identity1, identity2) expectTrue(isNativeSet(s)) expectEqual(4, s.count) // Verify items are still present. expectTrue(s.contains(TestObjCKeyTy(1010))) expectTrue(s.contains(TestObjCKeyTy(2020))) expectTrue(s.contains(TestObjCKeyTy(3030))) expectTrue(s.contains(TestObjCKeyTy(4040))) // Insert a redundant item to the set. // A copy should *not* occur here. s.insert(TestObjCKeyTy(1010)) expectEqual(identity2, s._rawIdentifier()) expectTrue(isNativeSet(s)) expectEqual(4, s.count) // Again, verify items are still present. expectTrue(s.contains(TestObjCKeyTy(1010))) expectTrue(s.contains(TestObjCKeyTy(2020))) expectTrue(s.contains(TestObjCKeyTy(3030))) expectTrue(s.contains(TestObjCKeyTy(4040))) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.Contains") { var s = getBridgedNonverbatimSet() var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) expectTrue(s.contains(TestBridgedKeyTy(1010))) expectTrue(s.contains(TestBridgedKeyTy(2020))) expectTrue(s.contains(TestBridgedKeyTy(3030))) expectEqual(identity1, s._rawIdentifier()) // Inserting an item should now create storage unique from the bridged set. s.insert(TestBridgedKeyTy(4040)) var identity2 = s._rawIdentifier() expectNotEqual(identity1, identity2) expectTrue(isNativeSet(s)) expectEqual(4, s.count) // Verify items are still present. expectTrue(s.contains(TestBridgedKeyTy(1010))) expectTrue(s.contains(TestBridgedKeyTy(2020))) expectTrue(s.contains(TestBridgedKeyTy(3030))) expectTrue(s.contains(TestBridgedKeyTy(4040))) // Insert a redundant item to the set. // A copy should *not* occur here. s.insert(TestBridgedKeyTy(1010)) expectEqual(identity2, s._rawIdentifier()) expectTrue(isNativeSet(s)) expectEqual(4, s.count) // Again, verify items are still present. expectTrue(s.contains(TestBridgedKeyTy(1010))) expectTrue(s.contains(TestBridgedKeyTy(2020))) expectTrue(s.contains(TestBridgedKeyTy(3030))) expectTrue(s.contains(TestBridgedKeyTy(4040))) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.SubscriptWithMember") { var s = getBridgedNonverbatimSet() var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) expectTrue(s.contains(TestBridgedKeyTy(1010))) expectTrue(s.contains(TestBridgedKeyTy(2020))) expectTrue(s.contains(TestBridgedKeyTy(3030))) expectEqual(identity1, s._rawIdentifier()) // Insert a new member. // This should trigger a copy. s.insert(TestBridgedKeyTy(4040)) var identity2 = s._rawIdentifier() expectTrue(isNativeSet(s)) expectEqual(4, s.count) // Verify all items in place. expectTrue(s.contains(TestBridgedKeyTy(1010))) expectTrue(s.contains(TestBridgedKeyTy(2020))) expectTrue(s.contains(TestBridgedKeyTy(3030))) expectTrue(s.contains(TestBridgedKeyTy(4040))) // Insert a redundant member. // This should *not* trigger a copy. s.insert(TestBridgedKeyTy(1010)) expectEqual(identity2, s._rawIdentifier()) expectTrue(isNativeSet(s)) expectEqual(4, s.count) // Again, verify all items in place. expectTrue(s.contains(TestBridgedKeyTy(1010))) expectTrue(s.contains(TestBridgedKeyTy(2020))) expectTrue(s.contains(TestBridgedKeyTy(3030))) expectTrue(s.contains(TestBridgedKeyTy(4040))) } SetTestSuite.test("BridgedFromObjC.Verbatim.RemoveAt") { var s = getBridgedVerbatimSet() let identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) let foundIndex1 = s.index(of: TestObjCKeyTy(1010))! expectEqual(TestObjCKeyTy(1010), s[foundIndex1]) expectEqual(identity1, s._rawIdentifier()) let removedElement = s.remove(at: foundIndex1) expectNotEqual(identity1, s._rawIdentifier()) expectTrue(isNativeSet(s)) expectEqual(2, s.count) expectEqual(TestObjCKeyTy(1010), removedElement) expectEmpty(s.index(of: TestObjCKeyTy(1010))) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAt") { var s = getBridgedNonverbatimSet() let identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) let foundIndex1 = s.index(of: TestBridgedKeyTy(1010))! expectEqual(1010, s[foundIndex1].value) expectEqual(identity1, s._rawIdentifier()) let removedElement = s.remove(at: foundIndex1) expectEqual(identity1, s._rawIdentifier()) expectTrue(isNativeSet(s)) expectEqual(1010, removedElement.value) expectEqual(2, s.count) expectEmpty(s.index(of: TestBridgedKeyTy(1010))) } SetTestSuite.test("BridgedFromObjC.Verbatim.Remove") { do { var s = getBridgedVerbatimSet() var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) var deleted: AnyObject? = s.remove(TestObjCKeyTy(0)) expectEmpty(deleted) expectEqual(identity1, s._rawIdentifier()) expectTrue(isCocoaSet(s)) deleted = s.remove(TestObjCKeyTy(1010)) expectEqual(1010, deleted!.value) var identity2 = s._rawIdentifier() expectNotEqual(identity1, identity2) expectTrue(isNativeSet(s)) expectEqual(2, s.count) expectFalse(s.contains(TestObjCKeyTy(1010))) expectTrue(s.contains(TestObjCKeyTy(2020))) expectTrue(s.contains(TestObjCKeyTy(3030))) expectEqual(identity2, s._rawIdentifier()) } do { var s1 = getBridgedVerbatimSet() var identity1 = s1._rawIdentifier() var s2 = s1 expectTrue(isCocoaSet(s1)) expectTrue(isCocoaSet(s2)) var deleted: AnyObject? = s2.remove(TestObjCKeyTy(0)) expectEmpty(deleted) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) expectTrue(isCocoaSet(s1)) expectTrue(isCocoaSet(s2)) deleted = s2.remove(TestObjCKeyTy(1010)) expectEqual(1010, deleted!.value) var identity2 = s2._rawIdentifier() expectNotEqual(identity1, identity2) expectTrue(isCocoaSet(s1)) expectTrue(isNativeSet(s2)) expectEqual(2, s2.count) expectTrue(s1.contains(TestObjCKeyTy(1010))) expectTrue(s1.contains(TestObjCKeyTy(2020))) expectTrue(s1.contains(TestObjCKeyTy(3030))) expectEqual(identity1, s1._rawIdentifier()) expectFalse(s2.contains(TestObjCKeyTy(1010))) expectTrue(s2.contains(TestObjCKeyTy(2020))) expectTrue(s2.contains(TestObjCKeyTy(3030))) expectEqual(identity2, s2._rawIdentifier()) } } SetTestSuite.test("BridgedFromObjC.Nonverbatim.Remove") { do { var s = getBridgedNonverbatimSet() var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) // Trying to remove something not in the set should // leave it completely unchanged. var deleted = s.remove(TestBridgedKeyTy(0)) expectEmpty(deleted) expectEqual(identity1, s._rawIdentifier()) expectTrue(isNativeSet(s)) // Now remove an item that is in the set. This should // not create a new set altogether, however. deleted = s.remove(TestBridgedKeyTy(1010)) expectEqual(1010, deleted!.value) var identity2 = s._rawIdentifier() expectEqual(identity1, identity2) expectTrue(isNativeSet(s)) expectEqual(2, s.count) // Double-check - the removed member should not be found. expectFalse(s.contains(TestBridgedKeyTy(1010))) // ... but others not removed should be found. expectTrue(s.contains(TestBridgedKeyTy(2020))) expectTrue(s.contains(TestBridgedKeyTy(3030))) // Triple-check - we should still be working with the same object. expectEqual(identity2, s._rawIdentifier()) } do { var s1 = getBridgedNonverbatimSet() let identity1 = s1._rawIdentifier() var s2 = s1 expectTrue(isNativeSet(s1)) expectTrue(isNativeSet(s2)) var deleted = s2.remove(TestBridgedKeyTy(0)) expectEmpty(deleted) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s2._rawIdentifier()) expectTrue(isNativeSet(s1)) expectTrue(isNativeSet(s2)) deleted = s2.remove(TestBridgedKeyTy(1010)) expectEqual(1010, deleted!.value) let identity2 = s2._rawIdentifier() expectNotEqual(identity1, identity2) expectTrue(isNativeSet(s1)) expectTrue(isNativeSet(s2)) expectEqual(2, s2.count) expectTrue(s1.contains(TestBridgedKeyTy(1010))) expectTrue(s1.contains(TestBridgedKeyTy(2020))) expectTrue(s1.contains(TestBridgedKeyTy(3030))) expectEqual(identity1, s1._rawIdentifier()) expectFalse(s2.contains(TestBridgedKeyTy(1010))) expectTrue(s2.contains(TestBridgedKeyTy(2020))) expectTrue(s2.contains(TestBridgedKeyTy(3030))) expectEqual(identity2, s2._rawIdentifier()) } } SetTestSuite.test("BridgedFromObjC.Verbatim.RemoveAll") { do { var s = getBridgedVerbatimSet([]) var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) expectEqual(0, s.count) s.removeAll() expectEqual(identity1, s._rawIdentifier()) expectEqual(0, s.count) } do { var s = getBridgedVerbatimSet() var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) expectEqual(3, s.count) expectTrue(s.contains(TestBridgedKeyTy(1010) as NSObject)) s.removeAll() expectEqual(0, s.count) expectFalse(s.contains(TestBridgedKeyTy(1010) as NSObject)) } do { var s1 = getBridgedVerbatimSet() var identity1 = s1._rawIdentifier() expectTrue(isCocoaSet(s1)) expectEqual(3, s1.count) expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject)) var s2 = s1 s2.removeAll() var identity2 = s2._rawIdentifier() expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity2, identity1) expectEqual(3, s1.count) expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject)) expectEqual(0, s2.count) expectFalse(s2.contains(TestBridgedKeyTy(1010) as NSObject)) } do { var s1 = getBridgedVerbatimSet() var identity1 = s1._rawIdentifier() expectTrue(isCocoaSet(s1)) expectEqual(3, s1.count) expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject)) var s2 = s1 s2.removeAll(keepingCapacity: true) var identity2 = s2._rawIdentifier() expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity2, identity1) expectEqual(3, s1.count) expectTrue(s1.contains(TestBridgedKeyTy(1010) as NSObject)) expectEqual(0 , s2.count) expectFalse(s2.contains(TestBridgedKeyTy(1010) as NSObject)) } } SetTestSuite.test("BridgedFromObjC.Nonverbatim.RemoveAll") { do { var s = getBridgedNonverbatimSet([]) var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) expectEqual(0, s.count) s.removeAll() expectEqual(identity1, s._rawIdentifier()) expectEqual(0, s.count) } do { var s = getBridgedNonverbatimSet() var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) expectEqual(3, s.count) expectTrue(s.contains(TestBridgedKeyTy(1010))) s.removeAll() expectEqual(0, s.count) expectFalse(s.contains(TestBridgedKeyTy(1010))) } do { var s1 = getBridgedNonverbatimSet() var identity1 = s1._rawIdentifier() expectTrue(isNativeSet(s1)) expectEqual(3, s1.count) expectTrue(s1.contains(TestBridgedKeyTy(1010))) var s2 = s1 s2.removeAll() var identity2 = s2._rawIdentifier() expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity2, identity1) expectEqual(3, s1.count) expectTrue(s1.contains(TestBridgedKeyTy(1010))) expectEqual(0, s2.count) expectFalse(s2.contains(TestBridgedKeyTy(1010))) } do { var s1 = getBridgedNonverbatimSet() var identity1 = s1._rawIdentifier() expectTrue(isNativeSet(s1)) expectEqual(3, s1.count) expectTrue(s1.contains(TestBridgedKeyTy(1010))) var s2 = s1 s2.removeAll(keepingCapacity: true) var identity2 = s2._rawIdentifier() expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity2, identity1) expectEqual(3, s1.count) expectTrue(s1.contains(TestObjCKeyTy(1010) as TestBridgedKeyTy)) expectEqual(0, s2.count) expectFalse(s2.contains(TestObjCKeyTy(1010) as TestBridgedKeyTy)) } } SetTestSuite.test("BridgedFromObjC.Verbatim.Count") { var s = getBridgedVerbatimSet() var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) expectEqual(3, s.count) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.Count") { var s = getBridgedNonverbatimSet() var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) expectEqual(3, s.count) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Verbatim.Generate") { var s = getBridgedVerbatimSet() var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) var iter = s.makeIterator() var members: [Int] = [] while let member = iter.next() { members.append((member as! TestObjCKeyTy).value) } expectTrue(equalsUnordered(members, [1010, 2020, 3030])) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. expectEmpty(iter.next()) expectEmpty(iter.next()) expectEmpty(iter.next()) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.Generate") { var s = getBridgedNonverbatimSet() var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) var iter = s.makeIterator() var members: [Int] = [] while let member = iter.next() { members.append(member.value) } expectTrue(equalsUnordered(members, [1010, 2020, 3030])) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. expectEmpty(iter.next()) expectEmpty(iter.next()) expectEmpty(iter.next()) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Verbatim.Generate_Empty") { var s = getBridgedVerbatimSet([]) var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) var iter = s.makeIterator() expectEmpty(iter.next()) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. expectEmpty(iter.next()) expectEmpty(iter.next()) expectEmpty(iter.next()) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Empty") { var s = getBridgedNonverbatimSet([]) var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) var iter = s.makeIterator() expectEmpty(iter.next()) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. expectEmpty(iter.next()) expectEmpty(iter.next()) expectEmpty(iter.next()) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Verbatim.Generate_Huge") { var s = getHugeBridgedVerbatimSet() var identity1 = s._rawIdentifier() expectTrue(isCocoaSet(s)) var iter = s.makeIterator() var members = [Int]() while let member = iter.next() { members.append((member as! TestObjCKeyTy).value) } expectTrue(equalsUnordered(members, hugeNumberArray)) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. expectEmpty(iter.next()) expectEmpty(iter.next()) expectEmpty(iter.next()) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.Generate_Huge") { var s = getHugeBridgedNonverbatimSet() var identity1 = s._rawIdentifier() expectTrue(isNativeSet(s)) var iter = s.makeIterator() var members = [Int]() while let member = iter.next() as AnyObject? { members.append((member as! TestBridgedKeyTy).value) } expectTrue(equalsUnordered(members, hugeNumberArray)) // The following is not required by the IteratorProtocol protocol, but // it is a nice QoI. expectEmpty(iter.next()) expectEmpty(iter.next()) expectEmpty(iter.next()) expectEqual(identity1, s._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Empty") { var s1 = getBridgedVerbatimSet([]) var identity1 = s1._rawIdentifier() expectTrue(isCocoaSet(s1)) var s2 = getBridgedVerbatimSet([]) var identity2 = s2._rawIdentifier() expectTrue(isCocoaSet(s2)) expectEqual(identity1, identity2) expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity2, s2._rawIdentifier()) s2.insert(TestObjCKeyTy(4040)) expectTrue(isNativeSet(s2)) expectNotEqual(identity2, s2._rawIdentifier()) identity2 = s2._rawIdentifier() expectNotEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity2, s2._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Empty") { var s1 = getBridgedNonverbatimSet([]) var identity1 = s1._rawIdentifier() expectTrue(isNativeSet(s1)) var s2 = getBridgedNonverbatimSet([]) var identity2 = s2._rawIdentifier() expectTrue(isNativeSet(s2)) expectNotEqual(identity1, identity2) expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity2, s2._rawIdentifier()) s2.insert(TestObjCKeyTy(4040) as TestBridgedKeyTy) expectTrue(isNativeSet(s2)) expectEqual(identity2, s2._rawIdentifier()) expectNotEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity2, s2._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Verbatim.EqualityTest_Small") { var s1 = getBridgedVerbatimSet() let identity1 = s1._rawIdentifier() expectTrue(isCocoaSet(s1)) var s2 = getBridgedVerbatimSet() let identity2 = s2._rawIdentifier() expectTrue(isCocoaSet(s2)) expectNotEqual(identity1, identity2) expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity2, s2._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Nonverbatim.EqualityTest_Small") { var s1 = getBridgedNonverbatimSet() let identity1 = s1._rawIdentifier() expectTrue(isNativeSet(s1)) var s2 = getBridgedNonverbatimSet() let identity2 = s2._rawIdentifier() expectTrue(isNativeSet(s2)) expectNotEqual(identity1, identity2) expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity2, s2._rawIdentifier()) } SetTestSuite.test("BridgedFromObjC.Verbatim.ArrayOfSets") { var nsa = NSMutableArray() for i in 0..<3 { nsa.add( getAsNSSet([1 + i, 2 + i, 3 + i])) } var a = nsa as [AnyObject] as! [Set<NSObject>] for i in 0..<3 { var s = a[i] var iter = s.makeIterator() var items: [Int] = [] while let value = iter.next() { let v = (value as! TestObjCKeyTy).value items.append(v) } var expectedItems = [1 + i, 2 + i, 3 + i] expectTrue(equalsUnordered(items, expectedItems)) } } SetTestSuite.test("BridgedFromObjC.Nonverbatim.ArrayOfSets") { var nsa = NSMutableArray() for i in 0..<3 { nsa.add( getAsNSSet([1 + i, 2 + i, 3 + i])) } var a = nsa as [AnyObject] as! [Set<TestBridgedKeyTy>] for i in 0..<3 { var d = a[i] var iter = d.makeIterator() var items: [Int] = [] while let value = iter.next() { items.append(value.value) } var expectedItems = [1 + i, 2 + i, 3 + i] expectTrue(equalsUnordered(items, expectedItems)) } } //===--- // Dictionary -> NSDictionary bridging tests. // // Value is bridged verbatim. //===--- SetTestSuite.test("BridgedToObjC.Verbatim.Count") { let s = getBridgedNSSetOfRefTypesBridgedVerbatim() expectEqual(3, s.count) } SetTestSuite.test("BridgedToObjC.Verbatim.Contains") { let s = getBridgedNSSetOfRefTypesBridgedVerbatim() var v: AnyObject? = s.member(TestObjCKeyTy(1010)).map { $0 as AnyObject } expectEqual(1010, (v as! TestObjCKeyTy).value) let idValue10 = unsafeBitCast(v, to: UInt.self) v = s.member(TestObjCKeyTy(2020)).map { $0 as AnyObject } expectEqual(2020, (v as! TestObjCKeyTy).value) let idValue20 = unsafeBitCast(v, to: UInt.self) v = s.member(TestObjCKeyTy(3030)).map { $0 as AnyObject } expectEqual(3030, (v as! TestObjCKeyTy).value) let idValue30 = unsafeBitCast(v, to: UInt.self) expectEmpty(s.member(TestObjCKeyTy(4040))) // NSSet can store mixed key types. Swift's Set is typed, but when bridged // to NSSet, it should behave like one, and allow queries for mismatched key // types. expectEmpty(s.member(TestObjCInvalidKeyTy())) for i in 0..<3 { expectEqual(idValue10, unsafeBitCast(s.member(TestObjCKeyTy(1010)).map { $0 as AnyObject }, to: UInt.self)) expectEqual(idValue20, unsafeBitCast(s.member(TestObjCKeyTy(2020)).map { $0 as AnyObject }, to: UInt.self)) expectEqual(idValue30, unsafeBitCast(s.member(TestObjCKeyTy(3030)).map { $0 as AnyObject }, to: UInt.self)) } expectAutoreleasedKeysAndValues(unopt: (3, 0)) } SetTestSuite.test("BridgingRoundtrip") { let s = getRoundtripBridgedNSSet() let enumerator = s.objectEnumerator() var items: [Int] = [] while let value = enumerator.nextObject() { let v = (value as! TestObjCKeyTy).value items.append(v) } expectTrue(equalsUnordered([1010, 2020, 3030], items)) } SetTestSuite.test("BridgedToObjC.Verbatim.ObjectEnumerator.FastEnumeration.UseFromSwift") { let s = getBridgedNSSetOfRefTypesBridgedVerbatim() checkSetFastEnumerationFromSwift( [ 1010, 2020, 3030 ], s, { s.objectEnumerator() }, { ($0 as! TestObjCKeyTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 0)) } SetTestSuite.test("BridgedToObjC.Verbatim.ObjectEnumerator.FastEnumeration.UseFromObjC") { let s = getBridgedNSSetOfRefTypesBridgedVerbatim() checkSetFastEnumerationFromObjC( [ 1010, 2020, 3030 ], s, { s.objectEnumerator() }, { ($0 as! TestObjCKeyTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 0)) } SetTestSuite.test("BridgedToObjC.Verbatim.ObjectEnumerator.FastEnumeration_Empty") { let s = getBridgedEmptyNSSet() checkSetFastEnumerationFromSwift( [], s, { s.objectEnumerator() }, { ($0 as! TestObjCKeyTy).value }) checkSetFastEnumerationFromObjC( [], s, { s.objectEnumerator() }, { ($0 as! TestObjCKeyTy).value }) } SetTestSuite.test("BridgedToObjC.Custom.ObjectEnumerator.FastEnumeration.UseFromObjC") { let s = getBridgedNSSet_MemberTypesCustomBridged() checkSetFastEnumerationFromObjC( [ 1010, 2020, 3030 ], s, { s.objectEnumerator() }, { ($0 as! TestObjCKeyTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 0)) } SetTestSuite.test("BridgedToObjC.Custom.ObjectEnumerator.FastEnumeration.UseFromSwift") { let s = getBridgedNSSet_MemberTypesCustomBridged() checkSetFastEnumerationFromSwift( [ 1010, 2020, 3030 ], s, { s.objectEnumerator() }, { ($0 as! TestObjCKeyTy).value }) expectAutoreleasedKeysAndValues(unopt: (3, 0)) } SetTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromSwift") { let s = getBridgedNSSetOfRefTypesBridgedVerbatim() checkSetFastEnumerationFromSwift( [ 1010, 2020, 3030 ], s, { s }, { ($0 as! TestObjCKeyTy).value }) } SetTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration.UseFromObjC") { let s = getBridgedNSSetOfRefTypesBridgedVerbatim() checkSetFastEnumerationFromObjC( [ 1010, 2020, 3030 ], s, { s }, { ($0 as! TestObjCKeyTy).value }) } SetTestSuite.test("BridgedToObjC.Verbatim.FastEnumeration_Empty") { let s = getBridgedEmptyNSSet() checkSetFastEnumerationFromSwift( [], s, { s }, { ($0 as! TestObjCKeyTy).value }) checkSetFastEnumerationFromObjC( [], s, { s }, { ($0 as! TestObjCKeyTy).value }) } SetTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromSwift") { let s = getBridgedNSSet_ValueTypesCustomBridged() checkSetFastEnumerationFromSwift( [ 1010, 2020, 3030 ], s, { s }, { ($0 as! TestObjCKeyTy).value }) } SetTestSuite.test("BridgedToObjC.Custom.FastEnumeration.UseFromObjC") { let s = getBridgedNSSet_ValueTypesCustomBridged() checkSetFastEnumerationFromObjC( [ 1010, 2020, 3030 ], s, { s }, { ($0 as! TestObjCKeyTy).value }) } SetTestSuite.test("BridgedToObjC.Custom.FastEnumeration_Empty") { let s = getBridgedNSSet_ValueTypesCustomBridged( numElements: 0) checkSetFastEnumerationFromSwift( [], s, { s }, { ($0 as! TestObjCKeyTy).value }) checkSetFastEnumerationFromObjC( [], s, { s }, { ($0 as! TestObjCKeyTy).value }) } SetTestSuite.test("BridgedToObjC.Count") { let s = getBridgedNSSetOfRefTypesBridgedVerbatim() expectEqual(3, s.count) } SetTestSuite.test("BridgedToObjC.ObjectEnumerator.NextObject") { let s = getBridgedNSSetOfRefTypesBridgedVerbatim() let enumerator = s.objectEnumerator() var members = [Int]() while let nextObject = enumerator.nextObject() { members.append((nextObject as! TestObjCKeyTy).value) } expectTrue(equalsUnordered([1010, 2020, 3030], members)) expectEmpty(enumerator.nextObject()) expectEmpty(enumerator.nextObject()) expectEmpty(enumerator.nextObject()) expectAutoreleasedKeysAndValues(unopt: (3, 0)) } SetTestSuite.test("BridgedToObjC.ObjectEnumerator.NextObject.Empty") { let s = getBridgedEmptyNSSet() let enumerator = s.objectEnumerator() expectEmpty(enumerator.nextObject()) expectEmpty(enumerator.nextObject()) expectEmpty(enumerator.nextObject()) } // // Set -> NSSet Bridging // SetTestSuite.test("BridgedToObjC.MemberTypesCustomBridged") { let s = getBridgedNSSet_MemberTypesCustomBridged() let enumerator = s.objectEnumerator() var members = [Int]() while let nextObject = enumerator.nextObject() { members.append((nextObject as! TestObjCKeyTy).value) } expectTrue(equalsUnordered([1010, 2020, 3030], members)) expectAutoreleasedKeysAndValues(unopt: (3, 0)) } // // NSSet -> Set -> NSSet Round trip bridging // SetTestSuite.test("BridgingRoundTrip") { let s = getRoundtripBridgedNSSet() let enumerator = s.objectEnumerator() var members = [Int]() while let nextObject = enumerator.nextObject() { members.append((nextObject as! TestObjCKeyTy).value) } expectTrue(equalsUnordered([1010, 2020, 3030] ,members)) } // // NSSet -> Set implicit conversion // SetTestSuite.test("NSSetToSetConversion") { let nsArray = NSMutableArray() for i in [1010, 2020, 3030] { nsArray.add(TestObjCKeyTy(i)) } let nss = NSSet(array: nsArray as [AnyObject]) let s = nss as Set var members = [Int]() for member: AnyObject in s { members.append((member as! TestObjCKeyTy).value) } expectTrue(equalsUnordered(members, [1010, 2020, 3030])) } SetTestSuite.test("SetToNSSetConversion") { var s = Set<TestObjCKeyTy>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } let nss: NSSet = s as NSSet expectTrue(equalsUnordered(Array(s).map { $0.value }, [1010, 2020, 3030])) } // // Set Casts // SetTestSuite.test("SetUpcastEntryPoint") { var s = Set<TestObjCKeyTy>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } var sAsAnyObject: Set<NSObject> = _setUpCast(s) expectEqual(3, sAsAnyObject.count) expectTrue(sAsAnyObject.contains(TestObjCKeyTy(1010))) expectTrue(sAsAnyObject.contains(TestObjCKeyTy(2020))) expectTrue(sAsAnyObject.contains(TestObjCKeyTy(3030))) } SetTestSuite.test("SetUpcast") { var s = Set<TestObjCKeyTy>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } var sAsAnyObject: Set<NSObject> = s expectEqual(3, sAsAnyObject.count) expectTrue(sAsAnyObject.contains(TestObjCKeyTy(1010))) expectTrue(sAsAnyObject.contains(TestObjCKeyTy(2020))) expectTrue(sAsAnyObject.contains(TestObjCKeyTy(3030))) } SetTestSuite.test("SetUpcastBridgedEntryPoint") { var s = Set<TestBridgedKeyTy>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestBridgedKeyTy(i)) } do { var s: Set<NSObject> = _setBridgeToObjectiveC(s) expectTrue(s.contains(TestBridgedKeyTy(1010) as NSObject)) expectTrue(s.contains(TestBridgedKeyTy(2020) as NSObject)) expectTrue(s.contains(TestBridgedKeyTy(3030) as NSObject)) } do { var s: Set<TestObjCKeyTy> = _setBridgeToObjectiveC(s) expectEqual(3, s.count) expectTrue(s.contains(TestBridgedKeyTy(1010) as TestObjCKeyTy)) expectTrue(s.contains(TestBridgedKeyTy(2020) as TestObjCKeyTy)) expectTrue(s.contains(TestBridgedKeyTy(3030) as TestObjCKeyTy)) } } SetTestSuite.test("SetUpcastBridged") { var s = Set<TestBridgedKeyTy>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestBridgedKeyTy(i)) } do { var s = s as Set<NSObject> expectEqual(3, s.count) expectTrue(s.contains(TestBridgedKeyTy(1010) as NSObject)) expectTrue(s.contains(TestBridgedKeyTy(2020) as NSObject)) expectTrue(s.contains(TestBridgedKeyTy(3030) as NSObject)) } do { var s = s as Set<TestObjCKeyTy> expectEqual(3, s.count) expectTrue(s.contains(TestBridgedKeyTy(1010) as TestObjCKeyTy)) expectTrue(s.contains(TestBridgedKeyTy(2020) as TestObjCKeyTy)) expectTrue(s.contains(TestBridgedKeyTy(3030) as TestObjCKeyTy)) } } // // Set downcasts // SetTestSuite.test("SetDowncastEntryPoint") { var s = Set<NSObject>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } // Successful downcast. let sCC: Set<TestObjCKeyTy> = _setDownCast(s) expectEqual(3, sCC.count) expectTrue(sCC.contains(TestObjCKeyTy(1010))) expectTrue(sCC.contains(TestObjCKeyTy(2020))) expectTrue(sCC.contains(TestObjCKeyTy(3030))) expectAutoreleasedKeysAndValues(unopt: (3, 0)) } SetTestSuite.test("SetDowncast") { var s = Set<NSObject>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } // Successful downcast. let sCC = s as! Set<TestObjCKeyTy> expectEqual(3, sCC.count) expectTrue(sCC.contains(TestObjCKeyTy(1010))) expectTrue(sCC.contains(TestObjCKeyTy(2020))) expectTrue(sCC.contains(TestObjCKeyTy(3030))) expectAutoreleasedKeysAndValues(unopt: (3, 0)) } SetTestSuite.test("SetDowncastConditionalEntryPoint") { var s = Set<NSObject>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } // Successful downcast. if let sCC = _setDownCastConditional(s) as Set<TestObjCKeyTy>? { expectEqual(3, sCC.count) expectTrue(sCC.contains(TestObjCKeyTy(1010))) expectTrue(sCC.contains(TestObjCKeyTy(2020))) expectTrue(sCC.contains(TestObjCKeyTy(3030))) } else { expectTrue(false) } // Unsuccessful downcast s.insert("Hello, world" as NSString) if let sCC = _setDownCastConditional(s) as Set<TestObjCKeyTy>? { expectTrue(false) } } SetTestSuite.test("SetDowncastConditional") { var s = Set<NSObject>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } // Successful downcast. if let sCC = s as? Set<TestObjCKeyTy> { expectEqual(3, sCC.count) expectTrue(sCC.contains(TestObjCKeyTy(1010))) expectTrue(sCC.contains(TestObjCKeyTy(2020))) expectTrue(sCC.contains(TestObjCKeyTy(3030))) } else { expectTrue(false) } // Unsuccessful downcast s.insert("Hello, world, I'm your wild girl. I'm your ch-ch-ch-ch-ch-ch cherry bomb" as NSString) if let sCC = s as? Set<TestObjCKeyTy> { expectTrue(false) } } SetTestSuite.test("SetBridgeFromObjectiveCEntryPoint") { var s = Set<NSObject>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } // Successful downcast. let sCV: Set<TestBridgedKeyTy> = _setBridgeFromObjectiveC(s) do { expectEqual(3, sCV.count) expectTrue(sCV.contains(TestBridgedKeyTy(1010))) expectTrue(sCV.contains(TestBridgedKeyTy(2020))) expectTrue(sCV.contains(TestBridgedKeyTy(3030))) } } SetTestSuite.test("SetBridgeFromObjectiveC") { var s = Set<NSObject>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } // Successful downcast. let sCV = s as! Set<TestObjCKeyTy> do { expectEqual(3, sCV.count) expectTrue(sCV.contains(TestObjCKeyTy(1010))) expectTrue(sCV.contains(TestObjCKeyTy(2020))) expectTrue(sCV.contains(TestObjCKeyTy(3030))) } // Successful downcast. let sVC = s as! Set<TestBridgedKeyTy> do { expectEqual(3, sVC.count) expectTrue(sVC.contains(TestBridgedKeyTy(1010))) expectTrue(sVC.contains(TestBridgedKeyTy(2020))) expectTrue(sVC.contains(TestBridgedKeyTy(3030))) } expectAutoreleasedKeysAndValues(unopt: (3, 0)) } SetTestSuite.test("SetBridgeFromObjectiveCConditionalEntryPoint") { var s = Set<NSObject>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } // Successful downcast. if let sVC = _setBridgeFromObjectiveCConditional(s) as Set<TestBridgedKeyTy>? { expectEqual(3, sVC.count) expectTrue(sVC.contains(TestBridgedKeyTy(1010))) expectTrue(sVC.contains(TestBridgedKeyTy(2020))) expectTrue(sVC.contains(TestBridgedKeyTy(3030))) } else { expectTrue(false) } // Unsuccessful downcasts s.insert("Hello, world, I'm your wild girl. I'm your ch-ch-ch-ch-ch-ch cherry bomb" as NSString) if let sVC = _setBridgeFromObjectiveCConditional(s) as Set<TestBridgedKeyTy>? { expectTrue(false) } } SetTestSuite.test("SetBridgeFromObjectiveCConditional") { var s = Set<NSObject>(minimumCapacity: 32) for i in [1010, 2020, 3030] { s.insert(TestObjCKeyTy(i)) } // Successful downcast. if let sCV = s as? Set<TestObjCKeyTy> { expectEqual(3, sCV.count) expectTrue(sCV.contains(TestObjCKeyTy(1010))) expectTrue(sCV.contains(TestObjCKeyTy(2020))) expectTrue(sCV.contains(TestObjCKeyTy(3030))) } else { expectTrue(false) } // Successful downcast. if let sVC = s as? Set<TestBridgedKeyTy> { expectEqual(3, sVC.count) expectTrue(sVC.contains(TestBridgedKeyTy(1010))) expectTrue(sVC.contains(TestBridgedKeyTy(2020))) expectTrue(sVC.contains(TestBridgedKeyTy(3030))) } else { expectTrue(false) } // Unsuccessful downcasts s.insert("Hello, world, I'm your wild girl. I'm your ch-ch-ch-ch-ch-ch cherry bomb" as NSString) if let sCm = s as? Set<TestObjCKeyTy> { expectTrue(false) } if let sVC = s as? Set<TestBridgedKeyTy> { expectTrue(false) } if let sVm = s as? Set<TestBridgedKeyTy> { expectTrue(false) } } #endif // _runtime(_ObjC) // Public API SetTestSuite.test("init(Sequence:)") { let s1 = Set([1010, 2020, 3030]) var s2 = Set<Int>() s2.insert(1010) s2.insert(2020) s2.insert(3030) expectEqual(s1, s2) // Test the uniquing capabilities of a set let s3 = Set([ 1010, 1010, 1010, 1010, 1010, 1010, 1010, 1010, 1010, 1010, 1010, 1010, 2020, 2020, 2020, 3030, 3030, 3030 ]) expectEqual(s1, s3) } SetTestSuite.test("init(arrayLiteral:)") { let s1: Set<Int> = [1010, 2020, 3030, 1010, 2020, 3030] let s2 = Set([1010, 2020, 3030]) var s3 = Set<Int>() s3.insert(1010) s3.insert(2020) s3.insert(3030) expectEqual(s1, s2) expectEqual(s2, s3) } SetTestSuite.test("isSubsetOf.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectTrue(Set<Int>().isSubset(of: s1)) expectFalse(s1.isSubset(of: Set<Int>())) expectTrue(s1.isSubset(of: s1)) expectTrue(s2.isSubset(of: s1)) } SetTestSuite.test("⊆.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectTrue(Set<Int>().isSubset(of: s1)) expectFalse(s1 ⊆ Set<Int>()) expectTrue(s1 ⊆ s1) expectTrue(s2 ⊆ s1) } SetTestSuite.test("⊈.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectFalse(Set<Int>() ⊈ s1) expectTrue(s1 ⊈ Set<Int>()) expectFalse(s1 ⊈ s1) expectFalse(s2 ⊈ s1) } SetTestSuite.test("isSubsetOf.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectTrue(Set<Int>().isSubset(of: s1)) expectFalse(s1.isSubset(of: Set<Int>())) expectTrue(s1.isSubset(of: s1)) } SetTestSuite.test("⊆.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectTrue(Set<Int>().isSubset(of: s1)) expectFalse(s1 ⊆ Set<Int>()) expectTrue(s1 ⊆ s1) } SetTestSuite.test("⊈.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectFalse(Set<Int>() ⊈ s1) expectTrue(s1 ⊈ Set<Int>()) expectFalse(s1 ⊈ s1) } SetTestSuite.test("isStrictSubsetOf.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectTrue(Set<Int>().isStrictSubset(of: s1)) expectFalse(s1.isStrictSubset(of: Set<Int>())) expectFalse(s1.isStrictSubset(of: s1)) } SetTestSuite.test("⊂.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectTrue(Set<Int>() ⊂ s1) expectFalse(s1 ⊂ Set<Int>()) expectFalse(s1 ⊂ s1) } SetTestSuite.test("⊄.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectFalse(Set<Int>() ⊄ s1) expectTrue(s1 ⊄ Set<Int>()) expectTrue(s1 ⊄ s1) } SetTestSuite.test("isStrictSubsetOf.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectTrue(Set<Int>().isStrictSubset(of: s1)) expectFalse(s1.isStrictSubset(of: Set<Int>())) expectFalse(s1.isStrictSubset(of: s1)) } SetTestSuite.test("⊂.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectTrue(Set<Int>() ⊂ s1) expectFalse(s1 ⊂ Set<Int>()) expectFalse(s1 ⊂ s1) } SetTestSuite.test("⊄.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectFalse(Set<Int>() ⊄ s1) expectTrue(s1 ⊄ Set<Int>()) expectTrue(s1 ⊄ s1) } SetTestSuite.test("isSupersetOf.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectTrue(s1.isSuperset(of: Set<Int>())) expectFalse(Set<Int>().isSuperset(of: s1)) expectTrue(s1.isSuperset(of: s1)) expectTrue(s1.isSuperset(of: s2)) expectFalse(Set<Int>().isSuperset(of: s1)) } SetTestSuite.test("⊇.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectTrue(s1 ⊇ Set<Int>()) expectFalse(Set<Int>() ⊇ s1) expectTrue(s1 ⊇ s1) expectTrue(s1 ⊇ s2) expectFalse(Set<Int>() ⊇ s1) } SetTestSuite.test("⊉.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectFalse(s1 ⊉ Set<Int>()) expectTrue(Set<Int>() ⊉ s1) expectFalse(s1 ⊉ s1) expectFalse(s1 ⊉ s2) expectTrue(Set<Int>() ⊉ s1) } SetTestSuite.test("isSupersetOf.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectTrue(s1.isSuperset(of: Set<Int>())) expectFalse(Set<Int>().isSuperset(of: s1)) expectTrue(s1.isSuperset(of: s1)) expectTrue(s1.isSuperset(of: s2)) expectFalse(Set<Int>().isSuperset(of: s1)) } SetTestSuite.test("⊇.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectTrue(s1 ⊇ Set<Int>()) expectFalse(Set<Int>() ⊇ s1) expectTrue(s1 ⊇ s1) expectTrue(s1 ⊇ s2) expectFalse(Set<Int>() ⊇ s1) } SetTestSuite.test("⊉.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectFalse(s1 ⊉ Set<Int>()) expectTrue(Set<Int>() ⊉ s1) expectFalse(s1 ⊉ s1) expectFalse(s1 ⊉ s2) expectTrue(Set<Int>() ⊉ s1) } SetTestSuite.test("strictSuperset.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectTrue(s1.isStrictSuperset(of: Set<Int>())) expectFalse(Set<Int>().isStrictSuperset(of: s1)) expectFalse(s1.isStrictSuperset(of: s1)) expectTrue(s1.isStrictSuperset(of: s2)) } SetTestSuite.test("⊃.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectTrue(s1 ⊃ Set<Int>()) expectFalse(Set<Int>() ⊃ s1) expectFalse(s1 ⊃ s1) expectTrue(s1 ⊃ s2) } SetTestSuite.test("⊅.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) expectFalse(s1 ⊅ Set<Int>()) expectTrue(Set<Int>() ⊅ s1) expectTrue(s1 ⊅ s1) expectFalse(s1 ⊅ s2) } SetTestSuite.test("strictSuperset.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectTrue(s1.isStrictSuperset(of: Set<Int>())) expectFalse(Set<Int>().isStrictSuperset(of: s1)) expectFalse(s1.isStrictSuperset(of: s1)) expectTrue(s1.isStrictSuperset(of: s2)) } SetTestSuite.test("⊃.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectTrue(s1 ⊃ Set<Int>()) expectFalse(Set<Int>() ⊃ s1) expectFalse(s1 ⊃ s1) expectTrue(s1 ⊃ s2) } SetTestSuite.test("⊅.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) expectFalse(s1 ⊅ Set<Int>()) expectTrue(Set<Int>() ⊅ s1) expectTrue(s1 ⊅ s1) expectFalse(s1 ⊅ s2) } SetTestSuite.test("Equatable.Native.Native") { let s1 = getCOWFastSet() let s2 = getCOWFastSet([1010, 2020, 3030, 4040, 5050, 6060]) checkEquatable(true, s1, s1) checkEquatable(false, s1, Set<Int>()) checkEquatable(true, Set<Int>(), Set<Int>()) checkEquatable(false, s1, s2) } #if _runtime(_ObjC) SetTestSuite.test("Equatable.Native.BridgedVerbatim") { let s1 = getNativeBridgedVerbatimSet() let bvs1 = getBridgedVerbatimSet() let bvs2 = getBridgedVerbatimSet([1010, 2020, 3030, 4040, 5050, 6060]) let bvsEmpty = getBridgedVerbatimSet([]) checkEquatable(true, s1, bvs1) checkEquatable(false, s1, bvs2) checkEquatable(false, s1, bvsEmpty) } SetTestSuite.test("Equatable.BridgedVerbatim.BridgedVerbatim") { let bvs1 = getBridgedVerbatimSet() let bvs2 = getBridgedVerbatimSet([1010, 2020, 3030, 4040, 5050, 6060]) let bvsEmpty = getBridgedVerbatimSet([]) checkEquatable(true, bvs1, bvs1) checkEquatable(false, bvs1, bvs2) checkEquatable(false, bvs1, bvsEmpty) } SetTestSuite.test("Equatable.BridgedNonverbatim.BridgedNonverbatim") { let bnvs1 = getBridgedNonverbatimSet() let bnvs2 = getBridgedNonverbatimSet([1010, 2020, 3030, 4040, 5050, 6060]) let bnvsEmpty = getBridgedNonverbatimSet([]) checkEquatable(true, bnvs1, bnvs1) checkEquatable(false, bnvs1, bnvs2) checkEquatable(false, bnvs1, bnvsEmpty) checkEquatable(false, bnvs2, bnvsEmpty) } #endif // _runtime(_ObjC) SetTestSuite.test("isDisjointWith.Set.Set") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) let s3 = Set([7070, 8080, 9090]) expectTrue(s1.isDisjoint(with: s3)) expectFalse(s1.isDisjoint(with: s2)) expectTrue(Set<Int>().isDisjoint(with: s1)) expectTrue(Set<Int>().isDisjoint(with: Set<Int>())) } SetTestSuite.test("isDisjointWith.Set.Sequence") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = AnySequence([1010, 2020, 3030]) let s3 = AnySequence([7070, 8080, 9090]) expectTrue(s1.isDisjoint(with: s3)) expectFalse(s1.isDisjoint(with: s2)) expectTrue(Set<Int>().isDisjoint(with: s1)) expectTrue(Set<Int>().isDisjoint(with: Set<Int>())) } SetTestSuite.test("insert") { // These are anagrams - they should amount to the same sets. var s1 = Set<TestKeyTy>([1010, 2020, 3030]) let fortyForty: TestKeyTy = 4040 do { // Inserting an element that isn't present let (inserted, currentMember) = s1.insert(fortyForty) expectTrue(inserted) expectTrue(currentMember === fortyForty) } do { // Inserting an element that is already present let (inserted, currentMember) = s1.insert(4040) expectFalse(inserted) expectTrue(currentMember === fortyForty) } expectEqual(4, s1.count) expectTrue(s1.contains(1010)) expectTrue(s1.contains(2020)) expectTrue(s1.contains(3030)) expectTrue(s1.contains(4040)) } SetTestSuite.test("replace") { // These are anagrams - they should amount to the same sets. var s1 = Set<TestKeyTy>([1010, 2020, 3030]) let fortyForty: TestKeyTy = 4040 do { // Replacing an element that isn't present let oldMember = s1.update(with: fortyForty) expectEmpty(oldMember) } do { // Replacing an element that is already present let oldMember = s1.update(with: 4040) expectTrue(oldMember === fortyForty) } expectEqual(4, s1.count) expectTrue(s1.contains(1010)) expectTrue(s1.contains(2020)) expectTrue(s1.contains(3030)) expectTrue(s1.contains(4040)) } SetTestSuite.test("union") { let s1 = Set([1010, 2020, 3030]) let s2 = Set([4040, 5050, 6060]) let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let identity1 = s1._rawIdentifier() let s4 = s1.union(s2) expectEqual(s4, s3) // s1 should be unchanged expectEqual(identity1, s1._rawIdentifier()) expectEqual(Set([1010, 2020, 3030]), s1) // s4 should be a fresh set expectNotEqual(identity1, s4._rawIdentifier()) expectEqual(s4, s3) let s5 = s1.union(s1) expectEqual(s5, s1) expectEqual(identity1, s1._rawIdentifier()) expectEqual(s1, s1.union(Set<Int>())) expectEqual(s1, Set<Int>().union(s1)) } SetTestSuite.test("∪") { let s1 = Set([1010, 2020, 3030]) let s2 = Set([4040, 5050, 6060]) let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let identity1 = s1._rawIdentifier() let s4 = s1 ∪ s2 expectEqual(s4, s3) // s1 should be unchanged expectEqual(identity1, s1._rawIdentifier()) expectEqual(Set([1010, 2020, 3030]), s1) // s4 should be a fresh set expectNotEqual(identity1, s4._rawIdentifier()) expectEqual(s4, s3) let s5 = s1 ∪ s1 expectEqual(s5, s1) expectEqual(identity1, s1._rawIdentifier()) expectEqual(s1, s1 ∪ Set<Int>()) expectEqual(s1, Set<Int>() ∪ s1) } SetTestSuite.test("formUnion") { // These are anagrams - they should amount to the same sets. var s1 = Set("the morse code".characters) let s2 = Set("here come dots".characters) let s3 = Set("and then dashes".characters) let identity1 = s1._rawIdentifier() s1.formUnion("".characters) expectEqual(identity1, s1._rawIdentifier()) expectEqual(s1, s2) s1.formUnion(s2) expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) s1.formUnion(s3) expectNotEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) } SetTestSuite.test("∪=") { // These are anagrams - they should amount to the same sets. var s1 = Set("the morse code".characters) let s2 = Set("here come dots".characters) let s3 = Set("and then dashes".characters) let identity1 = s1._rawIdentifier() s1 ∪= "".characters expectEqual(identity1, s1._rawIdentifier()) expectEqual(s1, s2) s1 ∪= s2 expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) s1 ∪= s3 expectNotEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) } SetTestSuite.test("subtract") { let s1 = Set([1010, 2020, 3030]) let s2 = Set([4040, 5050, 6060]) let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let identity1 = s1._rawIdentifier() // Subtracting a disjoint set should not create a // unique reference let s4 = s1.subtracting(s2) expectEqual(s1, s4) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s4._rawIdentifier()) // Subtracting a superset will leave the set empty let s5 = s1.subtracting(s3) expectTrue(s5.isEmpty) expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, s5._rawIdentifier()) // Subtracting the empty set does nothing expectEqual(s1, s1.subtracting(Set<Int>())) expectEqual(Set<Int>(), Set<Int>().subtracting(s1)) expectEqual(identity1, s1._rawIdentifier()) } SetTestSuite.test("∖") { let s1 = Set([1010, 2020, 3030]) let s2 = Set([4040, 5050, 6060]) let s3 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let identity1 = s1._rawIdentifier() // Subtracting a disjoint set should not create a // unique reference let s4 = s1 ∖ s2 expectEqual(s1, s4) expectEqual(identity1, s1._rawIdentifier()) expectEqual(identity1, s4._rawIdentifier()) // Subtracting a superset will leave the set empty let s5 = s1 ∖ s3 expectTrue(s5.isEmpty) expectEqual(identity1, s1._rawIdentifier()) expectNotEqual(identity1, s5._rawIdentifier()) // Subtracting the empty set does nothing expectEqual(s1, s1 ∖ Set<Int>()) expectEqual(Set<Int>(), Set<Int>() ∖ s1) expectEqual(identity1, s1._rawIdentifier()) } SetTestSuite.test("subtract") { var s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) let s3 = Set([4040, 5050, 6060]) let identity1 = s1._rawIdentifier() s1.subtract(Set<Int>()) expectEqual(identity1, s1._rawIdentifier()) s1.subtract(s3) expectEqual(identity1, s1._rawIdentifier()) expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) } SetTestSuite.test("∖=") { var s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010, 2020, 3030]) let s3 = Set([4040, 5050, 6060]) let identity1 = s1._rawIdentifier() s1 ∖= Set<Int>() expectEqual(identity1, s1._rawIdentifier()) s1 ∖= s3 expectEqual(identity1, s1._rawIdentifier()) expectEqual(s1, s2) expectEqual(identity1, s1._rawIdentifier()) } SetTestSuite.test("intersect") { let s1 = Set([1010, 2020, 3030]) let s2 = Set([4040, 5050, 6060]) var s3 = Set([1010, 2020, 3030, 4040, 5050, 6060]) var s4 = Set([1010, 2020, 3030]) let identity1 = s1._rawIdentifier() expectEqual(Set([1010, 2020, 3030]), Set([1010, 2020, 3030]).intersection(Set([1010, 2020, 3030])) as Set<Int>) expectEqual(identity1, s1._rawIdentifier()) expectEqual(s1, s1.intersection(s3)) expectEqual(identity1, s1._rawIdentifier()) expectEqual(Set<Int>(), Set<Int>().intersection(Set<Int>())) expectEqual(Set<Int>(), s1.intersection(Set<Int>())) expectEqual(Set<Int>(), Set<Int>().intersection(s1)) } SetTestSuite.test("∩") { let s1 = Set([1010, 2020, 3030]) let s2 = Set([4040, 5050, 6060]) var s3 = Set([1010, 2020, 3030, 4040, 5050, 6060]) var s4 = Set([1010, 2020, 3030]) let identity1 = s1._rawIdentifier() expectEqual(Set([1010, 2020, 3030]), Set([1010, 2020, 3030]) ∩ Set([1010, 2020, 3030]) as Set<Int>) expectEqual(identity1, s1._rawIdentifier()) expectEqual(s1, s1 ∩ s3) expectEqual(identity1, s1._rawIdentifier()) expectEqual(Set<Int>(), Set<Int>() ∩ Set<Int>()) expectEqual(Set<Int>(), s1 ∩ Set<Int>()) expectEqual(Set<Int>(), Set<Int>() ∩ s1) } SetTestSuite.test("formIntersection") { var s1 = Set([1010, 2020, 3030]) let s2 = Set([4040, 5050, 6060]) var s3 = Set([1010, 2020, 3030, 4040, 5050, 6060]) var s4 = Set([1010, 2020, 3030]) let identity1 = s1._rawIdentifier() s1.formIntersection(s4) expectEqual(s1, s4) expectEqual(identity1, s1._rawIdentifier()) s4.formIntersection(s2) expectEqual(Set<Int>(), s4) let identity2 = s3._rawIdentifier() s3.formIntersection(s2) expectEqual(s3, s2) expectTrue(s1.isDisjoint(with: s3)) expectNotEqual(identity1, s3._rawIdentifier()) var s5 = Set<Int>() s5.formIntersection(s5) expectEqual(s5, Set<Int>()) s5.formIntersection(s1) expectEqual(s5, Set<Int>()) } SetTestSuite.test("∩=") { var s1 = Set([1010, 2020, 3030]) let s2 = Set([4040, 5050, 6060]) var s3 = Set([1010, 2020, 3030, 4040, 5050, 6060]) var s4 = Set([1010, 2020, 3030]) let identity1 = s1._rawIdentifier() s1 ∩= s4 expectEqual(s1, s4) expectEqual(identity1, s1._rawIdentifier()) s4 ∩= s2 expectEqual(Set<Int>(), s4) let identity2 = s3._rawIdentifier() s3 ∩= s2 expectEqual(s3, s2) expectTrue(s1.isDisjoint(with: s3)) expectNotEqual(identity1, s3._rawIdentifier()) var s5 = Set<Int>() s5 ∩= s5 expectEqual(s5, Set<Int>()) s5 ∩= s1 expectEqual(s5, Set<Int>()) } SetTestSuite.test("symmetricDifference") { // Overlap with 4040, 5050, 6060 let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([4040, 5050, 6060, 7070, 8080, 9090]) let result = Set([1010, 2020, 3030, 7070, 8080, 9090]) let universe = Set([1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080, 9090]) let identity1 = s1._rawIdentifier() let s3 = s1.symmetricDifference(s2) expectEqual(identity1, s1._rawIdentifier()) expectEqual(s3, result) expectEqual(s1.symmetricDifference(s2), s1.union(s2).intersection(universe.subtracting(s1.intersection(s2)))) expectEqual(s1.symmetricDifference(s2), s1.intersection(universe.subtracting(s2)).union(universe.subtracting(s1).intersection(s2))) expectTrue(s1.symmetricDifference(s1).isEmpty) } SetTestSuite.test("⨁") { // Overlap with 4040, 5050, 6060 let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([4040, 5050, 6060, 7070, 8080, 9090]) let result = Set([1010, 2020, 3030, 7070, 8080, 9090]) let universe = Set([1010, 2020, 3030, 4040, 5050, 6060, 7070, 8080, 9090]) let identity1 = s1._rawIdentifier() let s3 = s1 ⨁ s2 expectEqual(identity1, s1._rawIdentifier()) expectEqual(s3, result) expectEqual(s1 ⨁ s2, (s1 ∪ s2) ∩ (universe ∖ (s1 ∩ s2))) expectEqual(s1 ⨁ s2, s1 ∩ (universe ∖ s2) ∪ (universe ∖ s1) ∩ s2) expectTrue((s1 ⨁ s1).isEmpty) } SetTestSuite.test("formSymmetricDifference") { // Overlap with 4040, 5050, 6060 var s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010]) let result = Set([2020, 3030, 4040, 5050, 6060]) // s1 ⨁ s2 == result let identity1 = s1._rawIdentifier() s1.formSymmetricDifference(s2) // Removing just one element shouldn't cause an identity change expectEqual(identity1, s1._rawIdentifier()) expectEqual(s1, result) // A ⨁ A == {} s1.formSymmetricDifference(s1) expectTrue(s1.isEmpty) // Removing all elements should cause an identity change expectNotEqual(identity1, s1._rawIdentifier()) } SetTestSuite.test("⨁=") { // Overlap with 4040, 5050, 6060 var s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s2 = Set([1010]) let result = Set([2020, 3030, 4040, 5050, 6060]) let identity1 = s1._rawIdentifier() s1 ⨁= s2 // Removing just one element shouldn't cause an identity change expectEqual(identity1, s1._rawIdentifier()) expectEqual(s1, result) s1 ⨁= s1 expectTrue(s1.isEmpty) // Removing all elements should cause an identity change expectNotEqual(identity1, s1._rawIdentifier()) } SetTestSuite.test("removeFirst") { var s1 = Set([1010, 2020, 3030]) let s2 = s1 let empty = Set<Int>() let a1 = s1.removeFirst() expectFalse(s1.contains(a1)) expectTrue(s2.contains(a1)) expectNotEqual(s1._rawIdentifier(), s2._rawIdentifier()) expectTrue(s1.isSubset(of: s2)) expectEmpty(empty.first) } SetTestSuite.test("remove(member)") { let s1 : Set<TestKeyTy> = [1010, 2020, 3030] var s2 = Set<TestKeyTy>(minimumCapacity: 10) for i in [1010, 2020, 3030] { s2.insert(TestKeyTy(i)) } let identity1 = s2._rawIdentifier() // remove something that's not there. let fortyForty = s2.remove(4040) expectEqual(s2, s1) expectEmpty(fortyForty) expectEqual(identity1, s2._rawIdentifier()) // Remove things that are there. let thirtyThirty = s2.remove(3030) expectEqual(3030, thirtyThirty) expectEqual(identity1, s2._rawIdentifier()) s2.remove(2020) expectEqual(identity1, s2._rawIdentifier()) s2.remove(1010) expectEqual(identity1, s2._rawIdentifier()) expectEqual(Set(), s2) expectTrue(s2.isEmpty) } SetTestSuite.test("contains") { let s1 = Set([1010, 2020, 3030]) expectTrue(s1.contains(1010)) expectFalse(s1.contains(999)) } SetTestSuite.test("∈") { let s1 = Set([1010, 2020, 3030]) expectTrue(1010 ∈ s1) expectFalse(999 ∈ s1) } SetTestSuite.test("∉") { let s1 = Set([1010, 2020, 3030]) expectFalse(1010 ∉ s1) expectTrue(999 ∉ s1) } SetTestSuite.test("memberAtIndex") { let s1 = Set([1010, 2020, 3030]) let foundIndex = s1.index(of: 1010)! expectEqual(1010, s1[foundIndex]) } SetTestSuite.test("first") { let s1 = Set([1010, 2020, 3030]) let emptySet = Set<Int>() expectTrue(s1.contains(s1.first!)) expectEmpty(emptySet.first) } SetTestSuite.test("isEmpty") { let s1 = Set([1010, 2020, 3030]) expectFalse(s1.isEmpty) let emptySet = Set<Int>() expectTrue(emptySet.isEmpty) } #if _runtime(_ObjC) @objc class MockSetWithCustomCount : NSSet { init(count: Int) { self._count = count super.init() } override init() { expectUnreachable() super.init() } override init(objects: UnsafePointer<AnyObject>, count: Int) { expectUnreachable() super.init(objects: objects, count: count) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) not implemented by MockSetWithCustomCount") } @objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any { // Ensure that copying this set produces an object of the same // dynamic type. return self } override func member(_ object: Any) -> Any? { expectUnreachable() return object } override func objectEnumerator() -> NSEnumerator { expectUnreachable() return getAsNSSet([1010, 1020, 1030]).objectEnumerator() } override var count: Int { MockSetWithCustomCount.timesCountWasCalled += 1 return _count } var _count: Int = 0 static var timesCountWasCalled = 0 } func getMockSetWithCustomCount(count: Int) -> Set<NSObject> { return MockSetWithCustomCount(count: count) as Set } func callGenericIsEmpty<C : Collection>(_ collection: C) -> Bool { return collection.isEmpty } SetTestSuite.test("isEmpty/ImplementationIsCustomized") { do { var d = getMockSetWithCustomCount(count: 0) MockSetWithCustomCount.timesCountWasCalled = 0 expectTrue(d.isEmpty) expectEqual(1, MockSetWithCustomCount.timesCountWasCalled) } do { var d = getMockSetWithCustomCount(count: 0) MockSetWithCustomCount.timesCountWasCalled = 0 expectTrue(callGenericIsEmpty(d)) expectEqual(1, MockSetWithCustomCount.timesCountWasCalled) } do { var d = getMockSetWithCustomCount(count: 4) MockSetWithCustomCount.timesCountWasCalled = 0 expectFalse(d.isEmpty) expectEqual(1, MockSetWithCustomCount.timesCountWasCalled) } do { var d = getMockSetWithCustomCount(count: 4) MockSetWithCustomCount.timesCountWasCalled = 0 expectFalse(callGenericIsEmpty(d)) expectEqual(1, MockSetWithCustomCount.timesCountWasCalled) } } #endif // _runtime(_ObjC) SetTestSuite.test("count") { let s1 = Set([1010, 2020, 3030]) var s2 = Set([4040, 5050, 6060]) expectEqual(0, Set<Int>().count) expectEqual(3, s1.count) } SetTestSuite.test("contains") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) expectTrue(s1.contains(1010)) expectFalse(s1.contains(999)) expectFalse(Set<Int>().contains(1010)) } SetTestSuite.test("_customContainsEquatableElement") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) expectTrue(s1._customContainsEquatableElement(1010)!) expectFalse(s1._customContainsEquatableElement(999)!) expectFalse(Set<Int>()._customContainsEquatableElement(1010)!) } SetTestSuite.test("index(of:)") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let foundIndex1 = s1.index(of: 1010)! expectEqual(1010, s1[foundIndex1]) expectEmpty(s1.index(of: 999)) } SetTestSuite.test("popFirst") { // Empty do { var s = Set<Int>() let popped = s.popFirst() expectEmpty(popped) expectTrue(s.isEmpty) } do { var popped = [Int]() var s = Set([1010, 2020, 3030]) let expected = Array(s) while let element = s.popFirst() { popped.append(element) } expectEqualSequence(expected, Array(popped)) expectTrue(s.isEmpty) } } SetTestSuite.test("removeAt") { // Test removing from the startIndex, the middle, and the end of a set. for i in 1...3 { var s = Set<Int>([1010, 2020, 3030]) let removed = s.remove(at: s.index(of: i*1010)!) expectEqual(i*1010, removed) expectEqual(2, s.count) expectEmpty(s.index(of: i*1010)) let origKeys: [Int] = [1010, 2020, 3030] expectEqual(origKeys.filter { $0 != (i*1010) }, [Int](s).sorted()) } } SetTestSuite.test("_customIndexOfEquatableElement") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let foundIndex1 = s1._customIndexOfEquatableElement(1010)!! expectEqual(1010, s1[foundIndex1]) expectEmpty(s1._customIndexOfEquatableElement(999)!) } SetTestSuite.test("commutative") { let s1 = Set([1010, 2020, 3030]) let s2 = Set([2020, 3030]) expectTrue(equalsUnordered(s1.intersection(s2), s2.intersection(s1))) expectTrue(equalsUnordered(s1.union(s2), s2.union(s1))) } SetTestSuite.test("associative") { let s1 = Set([1010, 2020, 3030]) let s2 = Set([2020, 3030]) let s3 = Set([1010, 2020, 3030]) let s4 = Set([2020, 3030]) let s5 = Set([7070, 8080, 9090]) expectTrue(equalsUnordered(s1.intersection(s2).intersection(s3), s1.intersection(s2.intersection(s3)))) expectTrue(equalsUnordered(s3.union(s4).union(s5), s3.union(s4.union(s5)))) } SetTestSuite.test("distributive") { let s1 = Set([1010]) let s2 = Set([1010, 2020, 3030, 4040, 5050, 6060]) let s3 = Set([2020, 3030]) expectTrue(equalsUnordered(s1.union(s2.intersection(s3)), s1.union(s2).intersection(s1.union(s3)))) let s4 = Set([2020, 3030]) expectTrue(equalsUnordered(s4.intersection(s1.union(s3)), s4.intersection(s1).union(s4.intersection(s3)))) } SetTestSuite.test("idempotent") { let s1 = Set([1010, 2020, 3030, 4040, 5050, 6060]) expectTrue(equalsUnordered(s1, s1.intersection(s1))) expectTrue(equalsUnordered(s1, s1.union(s1))) } SetTestSuite.test("absorption") { let s1 = Set([1010, 2020, 3030]) let s2 = Set([4040, 5050, 6060]) let s3 = Set([2020, 3030]) expectTrue(equalsUnordered(s1, s1.union(s1.intersection(s2)))) expectTrue(equalsUnordered(s1, s1.intersection(s1.union(s3)))) } SetTestSuite.test("misc") { // Set with other types do { var s = Set([1.1, 2.2, 3.3]) s.insert(4.4) expectTrue(s.contains(1.1)) expectTrue(s.contains(2.2)) expectTrue(s.contains(3.3)) } do { var s = Set(["Hello", "world"]) expectTrue(s.contains("Hello")) expectTrue(s.contains("world")) } } SetTestSuite.test("Hashable") { let s1 = Set([1010]) let s2 = Set([2020]) checkHashable(s1 == s2, s1, s2) // Explicit types help the type checker quite a bit. let ss1 = Set([Set([1010] as [Int]), Set([2020] as [Int]), Set([3030] as [Int])]) let ss11 = Set([Set([2020] as [Int]), Set([3030] as [Int]), Set([2020] as [Int])]) let ss2 = Set([Set([9090] as [Int])]) checkHashable(ss1 == ss11, ss1, ss11) checkHashable(ss1 == ss2, ss1, ss2) } SetTestSuite.test("Operator.Precedence") { let s1 = Set([1010, 2020, 3030]) let s2 = Set([3030, 4040, 5050]) let s3 = Set([6060, 7070, 8080]) let s4 = Set([8080, 9090, 100100]) // intersection higher precedence than union expectEqual(s1 ∪ (s2 ∩ s3) ∪ s4, s1 ∪ s2 ∩ s3 ∪ s4 as Set<Int>) // intersection higher precedence than complement expectEqual(s1 ∖ (s2 ∩ s3) ∖ s4, s1 ∖ s2 ∩ s3 ∖ s4 as Set<Int>) // intersection higher precedence than exclusive-or expectEqual(s1 ⨁ (s2 ∩ s3) ⨁ s4, s1 ⨁ s2 ∩ s3 ⨁ s4 as Set<Int>) // union/complement/exclusive-or same precedence expectEqual((((s1 ∪ s3) ∖ s2) ⨁ s4), s1 ∪ s3 ∖ s2 ⨁ s4 as Set<Int>) // ∪= should happen last. var s5 = Set([1010, 2020, 3030]) s5 ∪= Set([4040, 5050, 6060]) ∪ [7070] expectEqual(Set([1010, 2020, 3030, 4040, 5050, 6060, 7070]), s5) // ∩= should happen last. var s6 = Set([1010, 2020, 3030]) s6 ∩= Set([1010, 2020, 3030]) ∩ [3030] expectEqual(Set([3030]), s6) // ⨁= should happen last. var s7 = Set([1010, 2020, 3030]) s7 ⨁= Set([1010, 2020, 3030]) ⨁ [1010, 3030] expectEqual(Set([1010, 3030]), s7) // ∖= should happen last. var s8 = Set([1010, 2020, 3030]) s8 ∖= Set([2020, 3030]) ∖ [3030] expectEqual(Set([1010, 3030]), s8) } //===--- // Check that iterators traverse a snapshot of the collection. //===--- SetTestSuite.test("mutationDoesNotAffectIterator/remove,1") { var set = Set([1010, 1020, 1030]) var iter = set.makeIterator() expectOptionalEqual(1010, set.remove(1010)) expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter))) } SetTestSuite.test("mutationDoesNotAffectIterator/remove,all") { var set = Set([1010, 1020, 1030]) var iter = set.makeIterator() expectOptionalEqual(1010, set.remove(1010)) expectOptionalEqual(1020, set.remove(1020)) expectOptionalEqual(1030, set.remove(1030)) expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter))) } SetTestSuite.test("mutationDoesNotAffectIterator/removeAll,keepingCapacity=false") { var set = Set([1010, 1020, 1030]) var iter = set.makeIterator() set.removeAll(keepingCapacity: false) expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter))) } SetTestSuite.test("mutationDoesNotAffectIterator/removeAll,keepingCapacity=true") { var set = Set([1010, 1020, 1030]) var iter = set.makeIterator() set.removeAll(keepingCapacity: true) expectEqualsUnordered([1010, 1020, 1030], Array(IteratorSequence(iter))) } runAllTests()
28.34704
278
0.706761
ac8b33c600abcf811e6b82fdcf81eb8611909165
887
// // String+Json.swift // BlockstackCoreApi // // Created by lsease on 7/13/17. // import Foundation //convert a dictionary into a json string extension Dictionary //where Key == String, Value == String { func jsonString() -> String? { if let theJSONData = try? JSONSerialization.data( withJSONObject: self, options: []) { return String(data: theJSONData, encoding: .ascii) } return nil } } //convert a json string into a dictionary extension String { func toJsonDictionary() -> [String : Any]? { if let data = self.data(using: .utf8) { if let dictionary = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] { return dictionary } } return nil } }
22.175
109
0.54115
22d5e55a71f9e5e9f50a10e1bc9db4a1889dd31d
156
// // main.swift // DoYouKnow // // Created by Zijie Wang // Copyright © 2020 Zijie Wang. All rights reserved. // import App try app(.detect()).run()
13
53
0.634615
1d1f9e8079c1aea1d62e8cc8ae959496e6cbc33b
2,145
// // AppDelegate.swift // finalproject // // Created by Aynel Gül on 10-01-17. // Copyright © 2017 Aynel Gül. All rights reserved. // import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FIRApp.configure() 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:. } }
44.6875
285
0.754312
e970aae101f03a8749961914b9fe8d5339bb8dd8
9,567
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit /// A cell displaying the results of sensor(s) snapshot in an Experiment. The cell contains one or /// more SnapshotCardViews, a header and an optional caption. class SnapshotCardCell: FrameLayoutMaterialCardCell { // MARK: - Properties weak var delegate: ExperimentCardCellDelegate? private let captionView = ExperimentCardCaptionView() private let headerView = ExperimentCardHeaderView() private var snapshotViews = [SnapshotCardView]() private var snapshotViewsContainer = UIView() private let separator = SeparatorView(direction: .horizontal, style: .dark) private var snapshotNote: DisplaySnapshotNote? // MARK: - Public override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } override func layoutSubviews() { super.layoutSubviews() var nextOriginY: CGFloat = 0 if !headerView.isHidden { headerView.frame = CGRect(x: 0, y: nextOriginY, width: cellContentView.bounds.width, height: ExperimentCardHeaderView.height) nextOriginY = headerView.frame.maxY } separator.frame = CGRect(x: 0, y: nextOriginY, width: cellContentView.bounds.width, height: SeparatorView.Metrics.dimension) if let snapshots = snapshotNote?.snapshots { let snapshotViewsHeight = ceil(SnapshotCardCell.height(forSnapshots: snapshots, inWidth: cellContentView.bounds.width)) snapshotViewsContainer.frame = CGRect(x: 0, y: separator.frame.maxY, width: cellContentView.bounds.width, height: snapshotViewsHeight) for (index, snapshotView) in snapshotViews.enumerated() { let snapshotViewHeight = snapshotViewsHeight / CGFloat(snapshotViews.count) snapshotView.frame = CGRect(x: 0, y: snapshotViewHeight * CGFloat(index), width: cellContentView.bounds.width, height: snapshotViewHeight) } } if let caption = snapshotNote?.caption { let captionViewHeight = ceil(ExperimentCardCaptionView.heightWithCaption(caption, inWidth: cellContentView.bounds.width)) captionView.frame = CGRect(x: 0, y: snapshotViewsContainer.frame.maxY, width: cellContentView.bounds.width, height: captionViewHeight) } } override func prepareForReuse() { super.prepareForReuse() snapshotNote = nil } /// Sets the snapshot note to show in the cell and whether or not to show the header and /// inline timestamp. /// /// - Parameters: /// - snapshotNote: The snapshot note to show in the cell. /// - shouldShowHeader: Whether or not to show the header. /// - shouldShowInlineTimestamp: Whether or not to show the inline timestamp. /// - shouldShowCaptionButton: Whether or not to show the caption button. func setSnapshotNote(_ snapshotNote: DisplaySnapshotNote, showHeader shouldShowHeader: Bool, showInlineTimestamp shouldShowInlineTimestamp: Bool, showCaptionButton shouldShowCaptionButton: Bool, experimentDisplay: ExperimentDisplay = .normal) { self.snapshotNote = snapshotNote // Remove any snapshot views that are not needed. if snapshotViews.count > snapshotNote.snapshots.count { let rangeOfSnapshotViewsToRemove = snapshotNote.snapshots.count..<snapshotViews.count snapshotViews[rangeOfSnapshotViewsToRemove].forEach { $0.removeFromSuperview() } snapshotViews.removeSubrange(rangeOfSnapshotViewsToRemove) } // Add any snapshot views that are needed. for _ in snapshotViews.count..<snapshotNote.snapshots.count { let snapshotCardView = SnapshotCardView(preferredMaxLayoutWidth: bounds.width, showTimestamp: shouldShowInlineTimestamp) snapshotViews.append(snapshotCardView) snapshotViewsContainer.addSubview(snapshotCardView) } // Update snapshot views with snapshots. for (index, snapshot) in snapshotNote.snapshots.enumerated() { let snapshotView = snapshotViews[index] snapshotView.showTimestamp = shouldShowInlineTimestamp snapshotView.snapshot = snapshot } // Header. headerView.isHidden = !shouldShowHeader // Timestamp. headerView.headerTimestampLabel.text = snapshotNote.timestamp.string headerView.accessibilityLabel = snapshotNote.timestamp.string headerView.isTimestampRelative = snapshotNote.timestamp.isRelative // Caption and add caption button. if let caption = snapshotNote.caption { headerView.showCaptionButton = false captionView.isHidden = false captionView.captionLabel.text = caption } else { headerView.showCaptionButton = shouldShowCaptionButton captionView.isHidden = true } headerView.showMenuButton = experimentDisplay.showMenuButton setNeedsLayout() } /// Calculates the height required to display this view, given the data provided in `snapshots`. /// /// - Parameters: /// - width: Maximum width for this view, used to constrain measurements. /// - snapshotNote: The snapshot note to measure. /// - showingHeader: Whether or not the cell will be showing the header. /// - Returns: The total height of this view. Ideally, controllers would cache this value as it /// will not change for different instances of this view type. static func height(inWidth width: CGFloat, snapshotNote: DisplaySnapshotNote, showingHeader: Bool) -> CGFloat { // Measure the height of the snapshots. var totalHeight = SnapshotCardCell.height(forSnapshots: snapshotNote.snapshots, inWidth: width) // Add the separator height. totalHeight += SeparatorView.Metrics.dimension if showingHeader { // Add the header stack view's height. totalHeight += ExperimentCardHeaderView.height } // The caption, if necessary. if let caption = snapshotNote.caption { totalHeight += ExperimentCardCaptionView.heightWithCaption(caption, inWidth: width) } return totalHeight } // MARK: - Private private func configureView() { // Header view. cellContentView.addSubview(headerView) headerView.timestampButton.addTarget(self, action: #selector(timestampButtonPressed), for: .touchUpInside) headerView.commentButton.addTarget(self, action: #selector(commentButtonPressed), for: .touchUpInside) headerView.menuButton.addTarget(self, action: #selector(menuButtonPressed(sender:)), for: .touchUpInside) // Separator view. cellContentView.addSubview(separator) // Snapshot views container. cellContentView.addSubview(snapshotViewsContainer) // Caption view. cellContentView.addSubview(captionView) // Accessibility wrapping view, which sits behind all other elements to allow a user to "grab" // a cell by tapping anywhere in the empty space of a cell. let accessibilityWrappingView = UIView() cellContentView.configureAccessibilityWrappingView( accessibilityWrappingView, withLabel: String.noteContentDescriptionSnapshot, hint: String.doubleTapToViewDetails) // Set the order of elements to be the wrapping view first, then the header. accessibilityElements = [accessibilityWrappingView, headerView, snapshotViewsContainer] } private static func height(forSnapshots snapshots: [DisplaySnapshotValue], inWidth width: CGFloat) -> CGFloat { return snapshots.reduce(0) { (result, snapshot) in result + SnapshotCardView.heightForSnapshot(snapshot, inWidth: width) } } // MARK: - User actions @objc private func commentButtonPressed() { delegate?.experimentCardCellCommentButtonPressed(self) } @objc private func menuButtonPressed(sender: MenuButton) { delegate?.experimentCardCellMenuButtonPressed(self, button: sender) } @objc private func timestampButtonPressed() { delegate?.experimentCardCellTimestampButtonPressed(self) } }
39.8625
100
0.653601
724364c592b624979e9623b1131d5f3bc333e298
2,237
// // SwiftExtensions.swift // RLShowRoom // // Created by Mikola Dyachok on 24/09/2016. // Copyright © 2016 Mykola Diachok. All rights reserved. // import Foundation extension UITextField{ public func setLeftImage(imageName:String) { let img = UIImageView(image: UIImage(named: imageName)) img.frame = CGRect(x: 0, y: 5, width: 30, height: 20) img.contentMode = .scaleAspectFit self.leftViewMode = .always self.leftView = img self.contentMode = .scaleAspectFit } } //UITextViewDelegate extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } func animateViewMoving (up:Bool, moveValue :CGFloat) { let movementDuration:TimeInterval = 0.3 let movement:CGFloat = ( up ? -moveValue : moveValue) UIView.beginAnimations( "animateView", context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(movementDuration ) self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement) UIView.commitAnimations() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if range.length + range.location > (textField.text?.characters.count)! { return false } let newLength = (textField.text?.characters.count)! + string.characters.count - range.length return newLength <= 30 } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidBeginEditing(textField: UITextField) { //currentResponder = textField animateViewMoving(up: true, moveValue: 100) } func textFieldDidEndEditing(textField: UITextField) { textField.resignFirstResponder() animateViewMoving(up: false, moveValue: 100) } }
30.643836
132
0.657577
d5c9c09b737179266033e8c8b9f73555522928a5
2,225
// ImagePickerController.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Eureka /// Selector Controller used to pick an image open class ImagePickerController : UIImagePickerController, TypedRowControllerType, UIImagePickerControllerDelegate, UINavigationControllerDelegate { /// The row that pushed or presented this controller public var row: RowOf<UIImage>! /// A closure to be called when the controller disappears. public var onDismissCallback : ((UIViewController) -> ())? open override func viewDidLoad() { super.viewDidLoad() delegate = self } open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { (row as? ImageRow)?.imageURL = info[.referenceURL] as? URL row.value = info[.originalImage] as? UIImage onDismissCallback?(self) } open func imagePickerControllerDidCancel(_ picker: UIImagePickerController){ onDismissCallback?(self) } }
41.981132
149
0.739775
62ed49f9bf32e948f650efa09bf43c17f1b3eb9d
1,588
// // LTEasing.swift // LTMorphingLabelDemo // // Created by Lex on 7/1/14. // Copyright (c) 2015 lexrus.com. All rights reserved. // import Foundation // http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js // t = currentTime // b = beginning // c = change // d = duration public struct LTEasing { public static func easeOutQuint(_ t: Float, _ b: Float, _ c: Float, _ d: Float = 1.0) -> Float { return { return c * (pow($0, 5) + 1.0) + b }(t / d - 1.0) } public static func easeInQuint(_ t: Float, _ b: Float, _ c: Float, _ d: Float = 1.0) -> Float { return { return (c * pow($0, 5) + b) }(t / d) } public static func easeOutBack(_ t: Float, _ b: Float, _ c: Float, _ d: Float = 1.0) -> Float { let s: Float = 2.70158 let t2: Float = t / d - 1.0 return Float(c * (t2 * t2 * ((s + 1.0) * t2 + s) + 1.0)) + b } public static func easeOutBounce(_ t: Float, _ b: Float, _ c: Float, _ d: Float = 1.0) -> Float { return { if $0 < 1 / 2.75 { return c * 7.5625 * $0 * $0 + b } else if $0 < 2 / 2.75 { let t = $0 - 1.5 / 2.75 return c * (7.5625 * t * t + 0.75) + b } else if $0 < 2.5 / 2.75 { let t = $0 - 2.25 / 2.75 return c * (7.5625 * t * t + 0.9375) + b } else { let t = $0 - 2.625 / 2.75 return c * (7.5625 * t * t + 0.984375) + b } }(t / d) } }
28.872727
101
0.448363
03c892e2f24bc0ffc296d9ba54a8696b93b3a329
2,103
// // UserService.swift // Projet12 // // Created by Elodie-Anne Parquer on 24/04/2020. // Copyright © 2020 Elodie-Anne Parquer. All rights reserved. // import Foundation protocol UserType { var currentUID: String? { get } func getUsers(callback: @escaping (Result<[User], Error>) -> Void) func getUserData(with uid: String, callback: @escaping (Result<[User], Error>) -> Void) func getUsersWithFamilyFilter(callback: @escaping (Result<[User], Error>) -> Void) func getUsersWithPatientFilter(callback: @escaping (Result<[User], Error>) -> Void) func updateUserInformations(userFirstName: String, userLastName: String, email: String, callback: @escaping (Bool) -> Void) func deleteAccount(callback: @escaping (Bool) -> Void) func deletedUserData(callback: @escaping (Bool) -> Void) } final class UserService { private let user: UserType var currentUID: String? { return user.currentUID} init(user: UserType = UserFirestore()) { self.user = user } func getUsers(callback: @escaping (Result<[User], Error>) -> Void) { user.getUsers(callback: callback) } func getUserData(with uid: String, callback: @escaping (Result<[User], Error>) -> Void) { user.getUserData(with: uid, callback: callback) } func getUsersWithFamilyFilter(callback: @escaping (Result<[User], Error>) -> Void) { user.getUsersWithFamilyFilter(callback: callback) } func getUsersWithPatientFilter(callback: @escaping (Result<[User], Error>) -> Void) { user.getUsersWithPatientFilter(callback: callback) } func updateUserInformations(userFirstName: String, userLastName: String, email: String, callback: @escaping (Bool) -> Void) { user.updateUserInformations(userFirstName: "", userLastName: "", email: "", callback: callback) } func deleteAccount(callback: @escaping (Bool) -> Void) { user.deleteAccount(callback: callback) } func deletedUserData(callback: @escaping (Bool) -> Void) { user.deletedUserData(callback: callback) } }
36.894737
129
0.673799
fee4d3492dae9d8cc3d73cbe68f1c04de47212de
15,678
// // ExponeaInternal.swift // ExponeaSDK // // Created by Ricardo Tokashiki on 06/04/2018. // Copyright © 2018 Exponea. All rights reserved. // import Foundation extension Exponea { /// Shared instance of ExponeaSDK. public internal(set) static var shared = ExponeaInternal() internal static let isBeingTested: Bool = { return ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil }() } public class ExponeaInternal: ExponeaType { /// The configuration object containing all the configuration data necessary for Exponea SDK to work. /// /// The setter of this variable will setup all required tools and managers if the value is not nil, /// otherwise will deactivate everything. This can be useful if you want the user to be able to opt-out of /// Exponea tracking for example in a settings screen of your application. public internal(set) var configuration: Configuration? { get { guard let repository = repository else { return nil } return repository.configuration } set { // If we want to reset Exponea, warn about it and reset everything guard let newValue = newValue else { Exponea.logger.log(.warning, message: "Removing Exponea configuration and resetting everything.") trackingManager = nil repository = nil return } // If we want to re-configure Exponea, warn about it, reset everything and continue setting up with new if configuration != nil { Exponea.logger.log(.warning, message: "Resetting previous Exponea configuration.") trackingManager = nil repository = nil } // Initialise everything sharedInitializer(configuration: newValue) } } /// Cookie of the current customer. Nil before the SDK is configured public var customerCookie: String? { return trackingManager?.customerCookie } /// The manager responsible for tracking data and sessions. internal var trackingManager: TrackingManagerType? /// The manager responsible for flushing data to Exponea servers. internal var flushingManager: FlushingManagerType? /// Repository responsible for fetching or uploading data to the API. internal var repository: RepositoryType? internal var telemetryManager: TelemetryManager? /// Custom user defaults to track basic information internal var userDefaults: UserDefaults = { if UserDefaults(suiteName: Constants.General.userDefaultsSuite) == nil { UserDefaults.standard.addSuite(named: Constants.General.userDefaultsSuite) } return UserDefaults(suiteName: Constants.General.userDefaultsSuite)! }() /// Sets the flushing mode for usage public var flushingMode: FlushingMode { get { guard let flushingManager = flushingManager else { Exponea.logger.log( .warning, message: "Falling back to manual flushing mode. " + Constants.ErrorMessages.sdkNotConfigured ) return .manual } return flushingManager.flushingMode } set { guard var flushingManager = flushingManager else { Exponea.logger.log( .warning, message: "Cannot set flushing mode. " + Constants.ErrorMessages.sdkNotConfigured ) return } flushingManager.flushingMode = newValue } } /// The delegate that gets callbacks about notification opens and/or actions. Only has effect if automatic /// push tracking is enabled, otherwise will never get called. public var pushNotificationsDelegate: PushNotificationManagerDelegate? { get { return trackingManager?.notificationsManager.delegate } set { guard let notificationsManager = trackingManager?.notificationsManager else { Exponea.logger.log( .warning, message: "Cannot set push notifications delegate. " + Constants.ErrorMessages.sdkNotConfigured ) return } notificationsManager.delegate = newValue } } /// Any NSException inside Exponea SDK will be logged and swallowed if flag is enabled, otherwise /// the exception will be rethrown. /// Safemode is enabled for release builds and disabled for debug builds. /// You can set the value to override this behavior for e.g. unit testing. /// We advice strongly against disabling this for production builds. public var safeModeEnabled: Bool { get { if let override = safeModeOverride { return override } var enabled = true inDebugBuild { enabled = false } return enabled } set { safeModeOverride = newValue } } private var safeModeOverride: Bool? /// Once ExponeaSDK runs into a NSException, all further calls will be disabled internal var nsExceptionRaised: Bool = false internal var pushNotificationSelfCheck: PushNotificationSelfCheck? /// To help developers with integration, we can automatically check push notification setup /// when application is started in debug mode. /// When integrating push notifications(or when testing), we /// advise you to turn this feature on before initializing the SDK. /// Self-check only runs in debug mode and does not do anything in release builds. public var checkPushSetup: Bool = false // MARK: - Init - /// The initialiser is internal, so that only the singleton can exist when used in production. internal init() { let version = Bundle(for: Exponea.self).infoDictionary?["CFBundleShortVersionString"] as? String ?? "" Exponea.logger.logMessage("⚙️ Starting ExponeaSDK, version \(version).") } deinit { if !Exponea.isBeingTested { Exponea.logger.log(.error, message: "Exponea has deallocated. This should never happen.") } } internal func sharedInitializer(configuration: Configuration) { Exponea.logger.log(.verbose, message: "Configuring Exponea with provided configuration:\n\(configuration)") let exception = objc_tryCatch { do { let database = try DatabaseManager() if !Exponea.isBeingTested { telemetryManager = TelemetryManager( userDefaults: userDefaults, userId: database.currentCustomer.uuid.uuidString ) telemetryManager?.start() telemetryManager?.report(initEventWithConfiguration: configuration) } let repository = ServerRepository(configuration: configuration) self.repository = repository let flushingManager = try FlushingManager( database: database, repository: repository ) self.flushingManager = flushingManager let trackingManager = try TrackingManager( repository: repository, database: database, flushingManager: flushingManager, userDefaults: userDefaults ) self.trackingManager = trackingManager processSavedCampaignData() configuration.saveToUserDefaults() } catch { telemetryManager?.report(error: error, stackTrace: Thread.callStackSymbols) // Failing gracefully, if setup failed Exponea.logger.log(.error, message: """ Error while creating dependencies, Exponea cannot be configured.\n\(error.localizedDescription) """) } } if let exception = exception { nsExceptionRaised = true telemetryManager?.report(exception: exception) Exponea.logger.log(.error, message: """ Error while creating dependencies, Exponea cannot be configured.\n \(ExponeaError.nsExceptionRaised(exception).localizedDescription) """) } } } // MARK: - Dependencies + Safety wrapper - internal extension ExponeaInternal { /// Alias for dependencies required across various internal and public functions of Exponea. typealias Dependencies = ( configuration: Configuration, repository: RepositoryType, trackingManager: TrackingManagerType, flushingManager: FlushingManagerType ) typealias CompletionHandler<T> = ((Result<T>) -> Void) typealias DependencyTask<T> = (ExponeaInternal.Dependencies, @escaping CompletionHandler<T>) throws -> Void /// Gets the Exponea dependencies. If Exponea wasn't configured it will throw an error instead. /// /// - Returns: The dependencies required to perform any actions. /// - Throws: A not configured error in case Exponea wasn't configured beforehand. func getDependenciesIfConfigured() throws -> Dependencies { guard let configuration = configuration, let repository = repository, let trackingManager = trackingManager, let flushingManager = flushingManager else { throw ExponeaError.notConfigured } return (configuration, repository, trackingManager, flushingManager) } func executeSafelyWithDependencies<T>( _ closure: DependencyTask<T>, completion: @escaping CompletionHandler<T> ) { executeSafely({ let dependencies = try getDependenciesIfConfigured() try closure(dependencies, completion) }, errorHandler: { error in completion(.failure(error)) } ) } func executeSafelyWithDependencies(_ closure: (ExponeaInternal.Dependencies) throws -> Void) { executeSafelyWithDependencies({ dep, _ in try closure(dep) }, completion: {_ in } as CompletionHandler<Any>) } func executeSafely(_ closure: () throws -> Void) { executeSafely(closure, errorHandler: nil) } func executeSafely(_ closure: () throws -> Void, errorHandler: ((Error) -> Void)?) { if nsExceptionRaised { Exponea.logger.log(.error, message: ExponeaError.nsExceptionInconsistency.localizedDescription) errorHandler?(ExponeaError.nsExceptionInconsistency) return } let exception = objc_tryCatch { do { try closure() } catch { Exponea.logger.log(.error, message: error.localizedDescription) telemetryManager?.report(error: error, stackTrace: Thread.callStackSymbols) errorHandler?(error) } } if let exception = exception { telemetryManager?.report(exception: exception) Exponea.logger.log(.error, message: ExponeaError.nsExceptionRaised(exception).localizedDescription) if safeModeEnabled { nsExceptionRaised = true errorHandler?(ExponeaError.nsExceptionRaised(exception)) } else { Exponea.logger.log(.error, message: "Re-raising caugth NSException in debug build.") exception.raise() } } } } // MARK: - Public - public extension ExponeaInternal { // MARK: - Configure - var isConfigured: Bool { return configuration != nil && repository != nil && trackingManager != nil } /// Initialize the configuration without a projectMapping (token mapping) for each type of event. /// /// - Parameters: /// - projectToken: Project token to be used through the SDK. /// - authorization: The authorization type used to authenticate with some Exponea endpoints. /// - baseUrl: Base URL used for the project, for example if you use a custom domain with your Exponea setup. @available(*, deprecated) func configure(projectToken: String, authorization: Authorization, baseUrl: String? = nil, appGroup: String? = nil, defaultProperties: [String: JSONConvertible]? = nil) { do { let configuration = try Configuration(projectToken: projectToken, authorization: authorization, baseUrl: baseUrl, appGroup: appGroup, defaultProperties: defaultProperties) self.configuration = configuration } catch { Exponea.logger.log(.error, message: "Can't create configuration: \(error.localizedDescription)") } } /// Initialize the configuration with a plist file containing the keys for the ExponeaSDK. /// /// - Parameters: /// - plistName: Property list name containing the SDK setup keys /// /// Mandatory keys: /// - projectToken: Project token to be used through the SDK, as a fallback to projectMapping. /// - authorization: The authorization type used to authenticate with some Exponea endpoints. func configure(plistName: String) { do { let configuration = try Configuration(plistName: plistName) self.configuration = configuration } catch { Exponea.logger.log(.error, message: """ Can't parse Configuration from file \(plistName): \(error.localizedDescription). """) } } /// Initialize the configuration with a projectMapping (token mapping) for each type of event. This allows /// you to track events to multiple projects, even the same event to more project at once. /// /// - Parameters: /// - projectToken: Project token to be used through the SDK, as a fallback to projectMapping. /// - projectMapping: The project mapping dictionary providing all the tokens. /// - authorization: The authorization type used to authenticate with some Exponea endpoints. /// - baseUrl: Base URL used for the project, for example if you use a custom domain with your Exponea setup. @available(*, deprecated) func configure(projectToken: String, projectMapping: [EventType: [ExponeaProject]], authorization: Authorization, baseUrl: String? = nil, appGroup: String? = nil, defaultProperties: [String: JSONConvertible]? = nil) { do { let configuration = try Configuration(projectToken: projectToken, projectMapping: projectMapping, authorization: authorization, baseUrl: baseUrl, appGroup: appGroup, defaultProperties: defaultProperties) self.configuration = configuration } catch { Exponea.logger.log(.error, message: "Can't create configuration: \(error.localizedDescription)") } } }
41.041885
116
0.609772
b979dc07358ac0298bb961a79c5510d66133baa5
2,086
// // SettingsSection.swift // CriticalMaps // // Created by Malte Bünz on 19.04.19. // Copyright © 2019 Pokus Labs. All rights reserved. // import Foundation enum Section: Int, CaseIterable { case preferences case github case info struct Model { var title: String? var subtitle: String? var action: Action init(title: String? = nil, subtitle: String? = nil, action: Action) { self.title = title self.subtitle = subtitle self.action = action } } var numberOfRows: Int { return models.count } var title: String? { switch self { case .preferences, .github: return nil case .info: return String.settingsSectionInfo } } var cellClass: IBConstructable.Type { switch self { case .preferences: return SettingsSwitchTableViewCell.self case .github: return SettingsGithubTableViewCellTableViewCell.self case .info: return SettingsInfoTableViewCell.self } } var models: [Model] { switch self { case .preferences: return [ Model(title: String.themeLocalizedString, action: .switch(ThemeController.self)), Model(title: String.obversationModeTitle, subtitle: String.obversationModeDetail, action: .switch(ObservationModePreferenceStore.self)), ] case .github: return [Model(action: .open(url: Constants.criticalMapsiOSGitHubEndpoint))] case .info: return [Model(title: String.settingsWebsite, action: .open(url: Constants.criticalMapsWebsite)), Model(title: String.settingsTwitter, action: .open(url: Constants.criticalMapsTwitterPage)), Model(title: String.settingsFacebook, action: .open(url: Constants.criticalMapsFacebookPage))] } } enum Action { case open(url: URL) case `switch`(_ switchtable: Switchable.Type) } }
28.189189
152
0.599712
3a2f85af5f19ac46bf775439c25186a5bfe9cf36
8,129
// // CameraView.swift // ALCameraViewController // // Created by Alex Littlejohn on 2015/06/17. // Copyright (c) 2015 zero. All rights reserved. // import UIKit import AVFoundation public class CameraView: UIView { var session: AVCaptureSession! var input: AVCaptureDeviceInput! var device: AVCaptureDevice! var imageOutput: AVCaptureStillImageOutput! var preview: AVCaptureVideoPreviewLayer! let cameraQueue = DispatchQueue(label: "com.zero.ALCameraViewController.Queue") let focusView = CropOverlay(frame: CGRect(x: 0, y: 0, width: 80, height: 80)) public var currentPosition = CameraGlobals.shared.defaultCameraPosition public func startSession() { session = AVCaptureSession() session.sessionPreset = AVCaptureSession.Preset.photo device = cameraWithPosition(position: currentPosition) if let device = device , device.hasFlash { do { try device.lockForConfiguration() device.flashMode = .off device.unlockForConfiguration() } catch _ {} } let outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] do { input = try AVCaptureDeviceInput(device: device) } catch let error as NSError { input = nil print("Error: \(error.localizedDescription)") return } if session.canAddInput(input) { session.addInput(input) } imageOutput = AVCaptureStillImageOutput() imageOutput.outputSettings = outputSettings session.addOutput(imageOutput) cameraQueue.sync { session.startRunning() DispatchQueue.main.async() { [weak self] in self?.createPreview() } } } public func stopSession() { cameraQueue.sync { session?.stopRunning() preview?.removeFromSuperlayer() session = nil input = nil imageOutput = nil preview = nil device = nil } } public override func layoutSubviews() { super.layoutSubviews() preview?.frame = bounds } public func configureFocus() { if let gestureRecognizers = gestureRecognizers { gestureRecognizers.forEach({ removeGestureRecognizer($0) }) } let tapGesture = UITapGestureRecognizer(target: self, action: #selector(focus(gesture:))) addGestureRecognizer(tapGesture) isUserInteractionEnabled = true addSubview(focusView) focusView.isHidden = true let lines = focusView.horizontalLines + focusView.verticalLines + focusView.outerLines lines.forEach { line in line.alpha = 0 } } @objc internal func focus(gesture: UITapGestureRecognizer) { let point = gesture.location(in: self) guard focusCamera(toPoint: point) else { return } focusView.isHidden = false focusView.center = point focusView.alpha = 0 focusView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) bringSubviewToFront(focusView) UIView.animateKeyframes(withDuration: 1.5, delay: 0, options: UIView.KeyframeAnimationOptions(), animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.15, animations: { [weak self] in self?.focusView.alpha = 1 self?.focusView.transform = CGAffineTransform.identity }) UIView.addKeyframe(withRelativeStartTime: 0.80, relativeDuration: 0.20, animations: { [weak self] in self?.focusView.alpha = 0 self?.focusView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) }) }, completion: { [weak self] finished in if finished { self?.focusView.isHidden = true } }) } private func createPreview() { preview = AVCaptureVideoPreviewLayer(session: session) preview.videoGravity = AVLayerVideoGravity.resizeAspectFill preview.frame = bounds layer.addSublayer(preview) } private func cameraWithPosition(position: AVCaptureDevice.Position) -> AVCaptureDevice? { let devices = AVCaptureDevice.devices(for: AVMediaType.video) return devices.filter { $0.position == position }.first } public func capturePhoto(completion: @escaping CameraShotCompletion) { isUserInteractionEnabled = false guard let output = imageOutput, let orientation = AVCaptureVideoOrientation(rawValue: UIDevice.current.orientation.rawValue) else { completion(nil) return } let size = frame.size cameraQueue.sync { takePhoto(output, videoOrientation: orientation, cropSize: size) { image in DispatchQueue.main.async() { [weak self] in self?.isUserInteractionEnabled = true completion(image) } } } } public func focusCamera(toPoint: CGPoint) -> Bool { guard let device = device, let preview = preview, device.isFocusModeSupported(.continuousAutoFocus) else { return false } do { try device.lockForConfiguration() } catch { return false } let focusPoint = preview.captureDevicePointConverted(fromLayerPoint: toPoint) device.focusPointOfInterest = focusPoint device.focusMode = .continuousAutoFocus device.exposurePointOfInterest = focusPoint device.exposureMode = .continuousAutoExposure device.unlockForConfiguration() return true } public func cycleFlash() { guard let device = device, device.hasFlash else { return } do { try device.lockForConfiguration() if device.flashMode == .on { device.flashMode = .off } else if device.flashMode == .off { device.flashMode = .auto } else { device.flashMode = .on } device.unlockForConfiguration() } catch _ { } } public func swapCameraInput() { guard let session = session, let currentInput = input else { return } session.beginConfiguration() session.removeInput(currentInput) if currentInput.device.position == AVCaptureDevice.Position.back { currentPosition = .front device = cameraWithPosition(position: currentPosition) } else { currentPosition = .back device = cameraWithPosition(position: currentPosition) } guard let newInput = try? AVCaptureDeviceInput(device: device) else { return } input = newInput session.addInput(newInput) session.commitConfiguration() } public func rotatePreview() { guard preview != nil else { return } switch UIApplication.shared.statusBarOrientation { case .portrait: preview?.connection?.videoOrientation = AVCaptureVideoOrientation.portrait break case .portraitUpsideDown: preview?.connection?.videoOrientation = AVCaptureVideoOrientation.portraitUpsideDown break case .landscapeRight: preview?.connection?.videoOrientation = AVCaptureVideoOrientation.landscapeRight break case .landscapeLeft: preview?.connection?.videoOrientation = AVCaptureVideoOrientation.landscapeLeft break default: break } } }
30.791667
139
0.582482
f725cf63389a92d5aa41c35f09cf1c5dc9b7a9f4
356
// // QueryWallpaper.swift // UnsplashPhotosApp // // Created by Ahmed on 30/01/22. // import Foundation class QueryPhoto: Codable { let total: Int let totalPages: Int let photos: [Photo] enum CodingKeys: String, CodingKey { case total case totalPages = "total_pages" case photos = "results" } }
15.478261
40
0.609551
e67966ba0d3379ccce9d2e0b4039c367dc5955b0
1,506
// // Tutorial.swift // Just Touch // // Created by Fernando Ferreira on 4/26/16. // Copyright © 2016 Fernando Ferreira. All rights reserved. // import SpriteKit final class Tutorial: SKSpriteNode { var isFinished = false var layers = [SKSpriteNode]() override init(texture: SKTexture?, color: UIColor, size: CGSize) { super.init(texture: texture, color: UIColor(), size: size) layers = [ SKSpriteNode(imageNamed: "ret-c"), SKSpriteNode(imageNamed: "ret-b"), SKSpriteNode(imageNamed: "ret-a"), ] let titleTutorial = SKSpriteNode(imageNamed: "Control the speed") titleTutorial.position = CGPoint(x: size.width/2, y: size.height + 40 + titleTutorial.frame.height) titleTutorial.setScale(1.4) addChild(titleTutorial) zPosition = 100 setScale(0.8) layers.forEach { addChild($0) } } func updateLayersPosition(_ force: CGFloat) { for (index, layer) in layers.enumerated() { layer.position = CGPoint(x: 0.0, y: CGFloat(index) * (1.0 - force) * frame.height / CGFloat(layers.count - 1)) } if force > 0.4 && isFinished == false { isFinished = true run(SKAction.fadeOut(withDuration: 3.5), completion: { self.removeFromParent() }) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
25.1
113
0.591633
bf841196e02e8faddff04a639bdd2b293627cd16
496
// // LayoutElement.swift // Example // // Created by Gwangbeom on 2018. 10. 1.. // Copyright © 2018년 Interactive. All rights reserved. // import Foundation /**ㅇ ContentsView layout elements */ public enum SheetLayoutElement: String { case header case footer case cell case sectionHeader case sectionFooter public var id: String { return self.rawValue } public var kind: String { return "Kind\(self.rawValue.capitalized)" } }
17.103448
55
0.645161
1ce084d581c7652b68e6d1d2b1fd3bff75cad4f6
4,590
// // GameDetailView.swift // GGGaming // // Created by Agus Tiyansyah Syam on 19/03/21. // import SwiftUI import Kingfisher struct GameDetailView: View { @ObservedObject var viewModel: GameDetailViewModel var game: GameDetail func addToFavorite() { self.viewModel.addToFavorite(game: Game(id: game.id, name: game.name, released: game.released, backgroundImage: game.backgroundImage, rating: game.rating, metaScore: game.metaScore, playtime: game.playtime)) } func deleteFromFavorite() { self.viewModel.deleteFromFavorite(id: self.game.id ?? 1) } var body: some View { ScrollView(showsIndicators: false) { VStack(alignment: .leading) { KFImage(URL(string: game.backgroundImage ?? "")) .resizable() .scaledToFill() .frame(width: UIScreen.main.bounds.size.width, height: 250, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) .clipped() Spacer() Text(game.name ?? "No name") .fontWeight(.heavy) .font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/) .frame(maxWidth: .infinity, alignment: .leading) .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)) Text("\(game.released?.convertToString(format: "MMM dd, yyyy") ?? "No data released")") .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)) Spacer() Text("About") .fontWeight(.heavy) .font(.title2) .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)) Spacer() Text(game.description ?? "No description") .frame(maxWidth: .infinity, alignment: .leading) .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)) Divider() HStack(alignment: .top) { VStack(alignment: .leading) { Text("Rating") .fontWeight(.bold) .foregroundColor(.gray) Text(String(game.rating ?? 0.0)) Text("Genre") .fontWeight(.bold) .foregroundColor(.gray) .padding(.top) ForEach(game.genres ?? [Genre]()) { genre in Text(genre.name) } } .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) VStack(alignment: .leading) { Text("Metascore") .fontWeight(.bold) .foregroundColor(.gray) Text(String(game.metaScore ?? 0)) Text("Average playtime") .fontWeight(.bold) .foregroundColor(.gray) .padding(.top) Text("\(game.playtime ?? 0) Hours") } .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) } .padding(EdgeInsets(top: 0, leading: 10, bottom: 10, trailing: 0)) } } .navigationBarTitle("Detail", displayMode: .large) .toolbar { ToolbarItem(placement: .navigationBarTrailing) { if self.viewModel.isFavorite { Button(action: { self.deleteFromFavorite() }, label: { Image(systemName: "heart.fill") }) } else { Button(action: { self.addToFavorite() }, label: { Image(systemName: "heart") }) } } } } } struct GameDetailView_Previews: PreviewProvider { static var previews: some View { NavigationView { GameDetailView(viewModel: GameDetailViewModel(), game: GameDetail(id: 1, name: "GTA V", description: "Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.", released: Date(), backgroundImage: "gtav", rating: 4.32, metaScore: 98, playtime: 97, genres: [Genre]())) } } }
39.230769
271
0.47451
e99210244b0131c190db69a66ca7e587be295545
14,220
#if os(iOS) import MediaPlayer #endif class NotificationsHandler { private let reference: SwiftAudioplayersPlugin #if os(iOS) private var infoCenter: MPNowPlayingInfoCenter? = nil private var remoteCommandCenter: MPRemoteCommandCenter? = nil #endif private var headlessServiceInitialized = false private var headlessEngine: FlutterEngine? private var callbackChannel: FlutterMethodChannel? private var updateHandleMonitorKey: Int64? = nil private var title: String? = nil private var albumTitle: String? = nil private var artist: String? = nil private var imageUrl: String? = nil private var duration: Int? = nil init(reference: SwiftAudioplayersPlugin) { self.reference = reference self.initHeadlessService() } func initHeadlessService() { #if os(iOS) // this method is used to listen to audio playpause event // from the notification area in the background. let headlessEngine = FlutterEngine.init(name: "AudioPlayerIsolate") // This is the method channel used to communicate with // `_backgroundCallbackDispatcher` defined in the Dart portion of our plugin. // Note: we don't add a MethodCallDelegate for this channel now since our // BinaryMessenger needs to be initialized first, which is done in // `startHeadlessService` below. self.headlessEngine = headlessEngine self.callbackChannel = FlutterMethodChannel(name: "xyz.luan/audioplayers_callback", binaryMessenger: headlessEngine.binaryMessenger) #endif } // Initializes and starts the background isolate which will process audio // events. `handle` is the handle to the callback dispatcher which we specified // in the Dart portion of the plugin. func startHeadlessService(handle: Int64) { guard let headlessEngine = self.headlessEngine else { return } guard let callbackChannel = self.callbackChannel else { return } #if os(iOS) // Lookup the information for our callback dispatcher from the callback cache. // This cache is populated when `PluginUtilities.getCallbackHandle` is called // and the resulting handle maps to a `FlutterCallbackInformation` object. // This object contains information needed by the engine to start a headless // runner, which includes the callback name as well as the path to the file // containing the callback. let info = FlutterCallbackCache.lookupCallbackInformation(handle)! let entrypoint = info.callbackName let uri = info.callbackLibraryPath // Here we actually launch the background isolate to start executing our // callback dispatcher, `_backgroundCallbackDispatcher`, in Dart. self.headlessServiceInitialized = headlessEngine.run(withEntrypoint: entrypoint, libraryURI: uri) if self.headlessServiceInitialized { // The headless runner needs to be initialized before we can register it as a // MethodCallDelegate or else we get an illegal memory access. If we don't // want to make calls from `_backgroundCallDispatcher` back to native code, // we don't need to add a MethodCallDelegate for this channel. self.reference.registrar.addMethodCallDelegate(reference, channel: callbackChannel) } #endif } func updateHandleMonitorKey(handle: Int64) { self.updateHandleMonitorKey = handle } func onNotificationBackgroundPlayerStateChanged(playerId: String, value: String) { if headlessServiceInitialized { guard let callbackChannel = self.callbackChannel else { return } guard let updateHandleMonitorKey = self.updateHandleMonitorKey else { return } callbackChannel.invokeMethod( "audio.onNotificationBackgroundPlayerStateChanged", arguments: ["playerId": playerId, "updateHandleMonitorKey": updateHandleMonitorKey as Any, "value": value] ) } } func update(playerId: String, time: CMTime, playbackRate: Float) { #if os(iOS) updateForIos(playerId: playerId, time: time, playbackRate: playbackRate) #else // not implemented for macos #endif } func setNotification( playerId: String, title: String?, albumTitle: String?, artist: String?, imageUrl: String?, forwardSkipInterval: Int, backwardSkipInterval: Int, duration: Int?, elapsedTime: Int, enablePreviousTrackButton: Bool?, enableNextTrackButton: Bool? ) { #if os(iOS) setNotificationForIos( playerId: playerId, title: title, albumTitle: albumTitle, artist: artist, imageUrl: imageUrl, forwardSkipInterval: forwardSkipInterval, backwardSkipInterval: backwardSkipInterval, duration: duration, elapsedTime: elapsedTime, enablePreviousTrackButton: enablePreviousTrackButton, enableNextTrackButton: enableNextTrackButton ) #else // not implemented for macos #endif } #if os(iOS) static func geneateImageFromUrl(urlString: String) -> UIImage? { if urlString.hasPrefix("http") { guard let url: URL = URL.init(string: urlString) else { log("Error download image url, invalid url %@", urlString) return nil } do { let data = try Data(contentsOf: url) return UIImage.init(data: data) } catch { log("Error download image url %@", error) return nil } } else { return UIImage.init(contentsOfFile: urlString) } } func updateForIos(playerId: String, time: CMTime, playbackRate: Float) { if (infoCenter == nil || playerId != reference.lastPlayerId) { return } // From `MPNowPlayingInfoPropertyElapsedPlaybackTime` docs -- it is not recommended to update this value frequently. // Thus it should represent integer seconds and not an accurate `CMTime` value with fractions of a second let elapsedTime = Int(time.seconds) var playingInfo: [String: Any?] = [ MPMediaItemPropertyTitle: title, MPMediaItemPropertyAlbumTitle: albumTitle, MPMediaItemPropertyArtist: artist, MPMediaItemPropertyPlaybackDuration: duration, MPNowPlayingInfoPropertyElapsedPlaybackTime: elapsedTime, MPNowPlayingInfoPropertyPlaybackRate: playbackRate ] log("Updating playing info...") // fetch notification image in async fashion to avoid freezing UI DispatchQueue.global().async() { [weak self] in if let imageUrl = self?.imageUrl { let artworkImage: UIImage? = NotificationsHandler.geneateImageFromUrl(urlString: imageUrl) if let artworkImage = artworkImage { let albumArt: MPMediaItemArtwork = MPMediaItemArtwork.init(image: artworkImage) log("Will add custom album art") playingInfo[MPMediaItemPropertyArtwork] = albumArt } } if let infoCenter = self?.infoCenter { let filteredMap = playingInfo.filter { $0.value != nil }.mapValues { $0! } log("Setting playing info: %@", filteredMap) infoCenter.nowPlayingInfo = filteredMap } } } func setNotificationForIos( playerId: String, title: String?, albumTitle: String?, artist: String?, imageUrl: String?, forwardSkipInterval: Int, backwardSkipInterval: Int, duration: Int?, elapsedTime: Int, enablePreviousTrackButton: Bool?, enableNextTrackButton: Bool? ) { self.title = title self.albumTitle = albumTitle self.artist = artist self.imageUrl = imageUrl self.duration = duration self.infoCenter = MPNowPlayingInfoCenter.default() reference.lastPlayerId = playerId reference.updateNotifications(player: reference.lastPlayer()!, time: toCMTime(millis: elapsedTime)) if (remoteCommandCenter == nil) { remoteCommandCenter = MPRemoteCommandCenter.shared() if (forwardSkipInterval > 0 || backwardSkipInterval > 0) { let skipBackwardIntervalCommand = remoteCommandCenter!.skipBackwardCommand skipBackwardIntervalCommand.isEnabled = true skipBackwardIntervalCommand.addTarget(handler: self.skipBackwardEvent) skipBackwardIntervalCommand.preferredIntervals = [backwardSkipInterval as NSNumber] let skipForwardIntervalCommand = remoteCommandCenter!.skipForwardCommand skipForwardIntervalCommand.isEnabled = true skipForwardIntervalCommand.addTarget(handler: self.skipForwardEvent) skipForwardIntervalCommand.preferredIntervals = [forwardSkipInterval as NSNumber] // Max 99 } else { // if skip interval not set using next and previous let nextTrackCommand = remoteCommandCenter!.nextTrackCommand nextTrackCommand.isEnabled = enableNextTrackButton ?? false nextTrackCommand.addTarget(handler: self.nextTrackEvent) let previousTrackCommand = remoteCommandCenter!.previousTrackCommand previousTrackCommand.isEnabled = enablePreviousTrackButton ?? false previousTrackCommand.addTarget(handler: self.previousTrackEvent) } let pauseCommand = remoteCommandCenter!.pauseCommand pauseCommand.isEnabled = true pauseCommand.addTarget(handler: self.playOrPauseEvent) let playCommand = remoteCommandCenter!.playCommand playCommand.isEnabled = true playCommand.addTarget(handler: self.playOrPauseEvent) let togglePlayPauseCommand = remoteCommandCenter!.togglePlayPauseCommand togglePlayPauseCommand.isEnabled = true togglePlayPauseCommand.addTarget(handler: self.playOrPauseEvent) if #available(iOS 9.1, *) { let changePlaybackPositionCommand = remoteCommandCenter!.changePlaybackPositionCommand changePlaybackPositionCommand.isEnabled = true changePlaybackPositionCommand.addTarget(handler: self.onChangePlaybackPositionCommand) } } } func skipBackwardEvent(skipEvent: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus { let interval = (skipEvent as! MPSkipIntervalCommandEvent).interval log("Skip backward by %f", interval) guard let player = reference.lastPlayer() else { return MPRemoteCommandHandlerStatus.commandFailed } player.skipBackward(interval: interval) return MPRemoteCommandHandlerStatus.success } func skipForwardEvent(skipEvent: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus { let interval = (skipEvent as! MPSkipIntervalCommandEvent).interval log("Skip forward by %f", interval) guard let player = reference.lastPlayer() else { return MPRemoteCommandHandlerStatus.commandFailed } player.skipForward(interval: interval) return MPRemoteCommandHandlerStatus.success } func nextTrackEvent(event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus { guard let player = reference.lastPlayer() else { return MPRemoteCommandHandlerStatus.commandFailed } reference.onGotNextTrackCommand(playerId: player.playerId) return MPRemoteCommandHandlerStatus.success } func previousTrackEvent(event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus { guard let player = reference.lastPlayer() else { return MPRemoteCommandHandlerStatus.commandFailed } reference.onGotPreviousTrackCommand(playerId: player.playerId) return MPRemoteCommandHandlerStatus.success } func playOrPauseEvent(event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus { guard let player = reference.lastPlayer() else { return MPRemoteCommandHandlerStatus.commandFailed } // TODO(luan) incorporate this into WrappedMediaPlayer let playerState: String if #available(iOS 10.0, *) { if (player.isPlaying) { player.pause() playerState = "paused" } else { player.resume() playerState = "playing" } } else { // No fallback on earlier versions return MPRemoteCommandHandlerStatus.commandFailed } reference.onNotificationPlayerStateChanged(playerId: player.playerId, isPlaying: player.isPlaying) onNotificationBackgroundPlayerStateChanged(playerId: player.playerId, value: playerState) return MPRemoteCommandHandlerStatus.success } func onChangePlaybackPositionCommand(changePositionEvent: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus { guard let player = reference.lastPlayer() else { return MPRemoteCommandHandlerStatus.commandFailed } let positionTime = (changePositionEvent as! MPChangePlaybackPositionCommandEvent).positionTime log("changePlaybackPosition to %f", positionTime) let newTime = toCMTime(millis: positionTime) player.seek(time: newTime) return MPRemoteCommandHandlerStatus.success } #endif }
42.447761
140
0.646484
3ac899536a19fbcdddf1d2f880bb2007ea69b0cd
226
import Alamofire class MusixmatchLyricsParser: LyricsParser { override var domain: String { return "www.musixmatch.com" } override var selector: String { return ".mxm-lyrics__content" } }
18.833333
44
0.654867
3936456ebecd4a59199baa4c5e3f857a93c814c4
309
// // InputTableViewCell.swift // rx-sample-code // // Created by DianQK on 14/03/2017. // Copyright © 2017 T. All rights reserved. // import UIKit class InputTableViewCell: ReactiveTableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
16.263158
49
0.66343
1db1252746b7d41eeec71392577a02c20c159294
8,928
//===--- DropWhile.swift - Lazy views for drop(while:) --------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A sequence whose elements consist of the elements that follow the initial /// consecutive elements of some base sequence that satisfy a given predicate. @_fixed_layout // FIXME(sil-serialize-all) public struct LazyDropWhileSequence<Base: Sequence> { public typealias Element = Base.Element /// Create an instance with elements `transform(x)` for each element /// `x` of base. @inlinable // FIXME(sil-serialize-all) internal init(_base: Base, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base @usableFromInline // FIXME(sil-serialize-all) internal let _predicate: (Element) -> Bool } extension LazyDropWhileSequence { /// An iterator over the elements traversed by a base iterator that follow the /// initial consecutive elements that satisfy a given predicate. /// /// This is the associated iterator for the `LazyDropWhileSequence`, /// `LazyDropWhileCollection`, and `LazyDropWhileBidirectionalCollection` /// types. @_fixed_layout // FIXME(sil-serialize-all) public struct Iterator { public typealias Element = Base.Element @inlinable // FIXME(sil-serialize-all) internal init(_base: Base.Iterator, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // FIXME(sil-serialize-all) internal var _predicateHasFailed = false @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base.Iterator @usableFromInline // FIXME(sil-serialize-all) internal let _predicate: (Element) -> Bool } } extension LazyDropWhileSequence.Iterator: IteratorProtocol { @inlinable // FIXME(sil-serialize-all) public mutating func next() -> Element? { // Once the predicate has failed for the first time, the base iterator // can be used for the rest of the elements. if _predicateHasFailed { return _base.next() } // Retrieve and discard elements from the base iterator until one fails // the predicate. while let nextElement = _base.next() { if !_predicate(nextElement) { _predicateHasFailed = true return nextElement } } return nil } } extension LazyDropWhileSequence: Sequence { public typealias SubSequence = AnySequence<Element> // >:( /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), predicate: _predicate) } } extension LazyDropWhileSequence: LazySequenceProtocol { public typealias Elements = LazyDropWhileSequence } extension LazySequenceProtocol { /// Returns a lazy sequence that skips any initial elements that satisfy /// `predicate`. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns `true` if the element should be skipped or /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @inlinable // FIXME(sil-serialize-all) public func drop( while predicate: @escaping (Elements.Element) -> Bool ) -> LazyDropWhileSequence<Self.Elements> { return LazyDropWhileSequence(_base: self.elements, predicate: predicate) } } /// A lazy wrapper that includes the elements of an underlying /// collection after any initial consecutive elements that satisfy a /// predicate. /// /// - Note: The performance of accessing `startIndex`, `first`, or any methods /// that depend on `startIndex` depends on how many elements satisfy the /// predicate at the start of the collection, and may not offer the usual /// performance given by the `Collection` protocol. Be aware, therefore, /// that general operations on lazy collections may not have the /// documented complexity. @_fixed_layout // FIXME(sil-serialize-all) public struct LazyDropWhileCollection<Base: Collection> { public typealias Element = Base.Element @inlinable // FIXME(sil-serialize-all) internal init(_base: Base, predicate: @escaping (Element) -> Bool) { self._base = _base self._predicate = predicate } @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base @usableFromInline // FIXME(sil-serialize-all) internal let _predicate: (Element) -> Bool } extension LazyDropWhileCollection: Sequence { public typealias Iterator = LazyDropWhileSequence<Base>.Iterator /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), predicate: _predicate) } } extension LazyDropWhileCollection { public typealias SubSequence = Slice<LazyDropWhileCollection<Base>> /// A position in a `LazyDropWhileCollection` or /// `LazyDropWhileBidirectionalCollection` instance. @_fixed_layout // FIXME(sil-serialize-all) public struct Index { /// The position corresponding to `self` in the underlying collection. public let base: Base.Index @inlinable // FIXME(sil-serialize-all) internal init(_base: Base.Index) { self.base = _base } } } extension LazyDropWhileCollection.Index: Equatable, Comparable { @inlinable // FIXME(sil-serialize-all) public static func == ( lhs: LazyDropWhileCollection<Base>.Index, rhs: LazyDropWhileCollection<Base>.Index ) -> Bool { return lhs.base == rhs.base } @inlinable // FIXME(sil-serialize-all) public static func < ( lhs: LazyDropWhileCollection<Base>.Index, rhs: LazyDropWhileCollection<Base>.Index ) -> Bool { return lhs.base < rhs.base } } extension LazyDropWhileCollection.Index: Hashable where Base.Index: Hashable { @inlinable // FIXME(sil-serialize-all) public var hashValue: Int { return base.hashValue } @inlinable // FIXME(sil-serialize-all) public func _hash(into hasher: inout _Hasher) { hasher.combine(base) } } extension LazyDropWhileCollection: Collection { @inlinable // FIXME(sil-serialize-all) public var startIndex: Index { var index = _base.startIndex while index != _base.endIndex && _predicate(_base[index]) { _base.formIndex(after: &index) } return Index(_base: index) } @inlinable // FIXME(sil-serialize-all) public var endIndex: Index { return Index(_base: _base.endIndex) } @inlinable // FIXME(sil-serialize-all) public func index(after i: Index) -> Index { _precondition(i.base < _base.endIndex, "Can't advance past endIndex") return Index(_base: _base.index(after: i.base)) } @inlinable // FIXME(sil-serialize-all) public subscript(position: Index) -> Element { return _base[position.base] } } extension LazyDropWhileCollection: LazyCollectionProtocol { } extension LazyDropWhileCollection: BidirectionalCollection where Base: BidirectionalCollection { @inlinable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { _precondition(i > startIndex, "Can't move before startIndex") return Index(_base: _base.index(before: i.base)) } } extension LazyCollectionProtocol { /// Returns a lazy collection that skips any initial elements that satisfy /// `predicate`. /// /// - Parameter predicate: A closure that takes an element of the collection /// as its argument and returns `true` if the element should be skipped or /// `false` otherwise. Once `predicate` returns `false` it will not be /// called again. @inlinable // FIXME(sil-serialize-all) public func drop( while predicate: @escaping (Elements.Element) -> Bool ) -> LazyDropWhileCollection<Self.Elements> { return LazyDropWhileCollection( _base: self.elements, predicate: predicate) } } @available(*, deprecated, renamed: "LazyDropWhileSequence.Iterator") public typealias LazyDropWhileIterator<T> = LazyDropWhileSequence<T>.Iterator where T: Sequence @available(*, deprecated, renamed: "LazyDropWhileCollection.Index") public typealias LazyDropWhileIndex<T> = LazyDropWhileCollection<T>.Index where T: Collection @available(*, deprecated, renamed: "LazyDropWhileCollection") public typealias LazyDropWhileBidirectionalCollection<T> = LazyDropWhileCollection<T> where T: BidirectionalCollection
34.338462
118
0.712366
f9b33c8b0c8f5d04b561535b8dd35eedd16c4b85
4,339
// // SignViewController.swift // Timer // // Created by Hideo on 5/12/16. // // import UIKit import Firebase class SignViewController: UIViewController, UIActionSheetDelegate, UITextFieldDelegate { @IBOutlet weak var photoView: UIImageView! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var emailField: UITextField! override func viewDidLoad() { super.viewDidLoad() emailField.layer.masksToBounds = true emailField.layer.borderWidth = 1 emailField.layer.borderColor = UIColor.whiteColor().CGColor emailField.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()]) usernameField.layer.masksToBounds = true usernameField.layer.borderWidth = 1 usernameField.layer.borderColor = UIColor.whiteColor().CGColor usernameField.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()]) passwordField.layer.masksToBounds = true passwordField.layer.borderWidth = 1 passwordField.layer.borderColor = UIColor.whiteColor().CGColor passwordField.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()]) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SignViewController.photoTapped)) photoView.userInteractionEnabled = true photoView.addGestureRecognizer(tapGestureRecognizer) emailField.delegate = self passwordField.delegate = self usernameField.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: false) } @IBAction func clearBtnPressed(sender: AnyObject) { emailField.text = "" passwordField.text = "" usernameField.text = "" } @IBAction func registerBtnPressed(sender: AnyObject) { if emailField.text != "" && passwordField.text != "" && usernameField.text != "" { NSLog("Register progress") let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate var _ : NSError var _: NSDictionary appDelegate.appRootRef.createUser(emailField.text, password: passwordField.text, withValueCompletionBlock: { error, result in if error != nil { }else { let uid = result["uid"] as? String NSLog("successfully created user account with uid: \(uid)") } }) }else { NSLog("Register Warning") let alertController = UIAlertController(title: "Warning!", message: "Please input your info", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title:"Dismiss", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } func textFieldShouldReturn(textField: UITextField) -> Bool { emailField.resignFirstResponder() usernameField.resignFirstResponder() passwordField.resignFirstResponder() return true } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { switch buttonIndex { case 1: NSLog("take photo") case 2: NSLog("photo library") default: break } } func photoTapped() { let actionSheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Take Photo", "Photo Library") actionSheet.showInView(self.view) } }
36.158333
175
0.642544
62e06a6da8ff5749ce778c0bb1a608efdcb24807
367
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a{let a<T where{class A{func e{class n{class n{class C{class c{class b{{}{}class A{func p(){(){(T{struct c{func a{func a{let a{{e,{e,{.{func a{(f={
45.875
151
0.702997
e68755d8e24a87855ba9e0cc312f18ae566cb4fa
2,490
// // UXKit // // Copyright © 2016-2020 ZeeZide GmbH. All rights reserved. // /** * A common protocol for "view controllers". Note that this itself is * unfortunately NOT a view controller (because a protocol can't be restricted * to a class). * But you can piggy back to the real thing using the `uxViewController` * property. * * The `UXViewController` alias either directly maps to `NSViewController` or * `UIViewController`. */ @objc public protocol UXViewControllerType : UXObjectPresentingType, UXUserInterfaceItemIdentification { // Too bad that we can't adopt NSViewController as a protocol. // MARK: - Getting the actual VC var uxViewController : UXViewController { get } // MARK: - The View /// Note: `view` is `UXView` on macOS and `UXView!` on iOS var rootView : UXView { get } // MARK: - View Controllers func uxAddChild(_ childViewController: UXViewController) func uxRemoveFromParent() var uxChildren : [ UXViewController ] { get } var uxParent : UXViewController? { get } } #if os(macOS) import Cocoa public typealias UXViewController = NSViewController public typealias UXDocument = NSDocument #else // iOS import UIKit fileprivate var uivcID : UInt8 = 42 public typealias UXViewController = UIViewController public typealias UXDocument = UIDocument extension UIViewController : UXUserInterfaceItemIdentification { /// Add `identifier` to UIViewController @objc open var identifier : UXUserInterfaceItemIdentifier? { set { objc_setAssociatedObject(self, &uivcID, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } get { return objc_getAssociatedObject(self, &uivcID) as? String } } } #endif // end: iOS @objc extension UXViewController : UXViewControllerType { public var uxViewController : UXViewController { return self } public var rootView : UXView { return view } // Note: The ux prefixes are necessary due to Swift compiler madness where // it gets confused what uses selectors in #ifs and when and how. Sigh. public func uxAddChild(_ vc: UXViewController) { addChild(vc) } public var uxChildren : [ UXViewController ] { return children } public func uxRemoveFromParent() { removeFromParent() } public var uxParent : UXViewController? { return parent } }
30.740741
80
0.678715
5bccc73c4aeccc034780c7821f425a70cf74b9d8
9,636
import UIKit import React import ZIPFoundation import Foundation struct RNUrl { var search: String var publicUrl: String var path: String } private let kCachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first private let kTempPath = NSTemporaryDirectory() class RNCrossController: UIViewController { var BUNDLE_REMOTE_SUFFIX_URL = "/ios/index.json" var loadedBundle = false var storeName = "" var moduleName = "" var remotePath = "" var localPath = "" var rootPath = "" var moduleMd5 = "" var downloadUrl = "" var href = "" open func initReactContent(publicUrl: String) { // let jsCodeLocation = URL(string: "http://localhost:8081/index.bundle?platform=ios") // self.moduleName = "ReactKitsTest" // loadBundleFromUrl(jsCodeLocation: jsCodeLocation!) // return // self.href = publicUrl let url = getUrlInfo(url: publicUrl) storeName = "rn-cross_" + url.publicUrl.md5 + ".plist" loadedBundle = false preloadBundleFile() let configUrl = url.publicUrl + BUNDLE_REMOTE_SUFFIX_URL; print("request URL: " + configUrl) FileTool.getRequest(url: configUrl) { (resp) -> Void in self.moduleName = resp["moduleName"] as! String self.downloadUrl = resp["downloadUrl"] as! String self.moduleMd5 = resp["md5"] as! String print("JSON Config: \(resp)") self.rootPath = "/rn-modules" + "/" + self.moduleName self.localPath = self.rootPath + "/" + self.moduleMd5 let values = self.readInfo(); let remotePath = values["remotePath"] as? String // 如果缓存路径与远程路径一致,则不做任何处理 if (!self.isEmptyString(str: remotePath) && remotePath == self.localPath) { return } DispatchQueue.main.async { self.startDownload() } } // let m = publicUrl.split(separator: "#") } func startDownload() { let downLoader = DownLoader() let zipUrl = NSURL(string: self.downloadUrl) downLoader.addDownListener { print("文件下载成功!!!" + downLoader.getFilePath()) print("local path: " + self.localPath) var values = self.readInfo() values["remotePath"] = self.localPath values["remoteMd5"] = self.moduleMd5 self.writeInfo(info: values) if (!self.loadedBundle) { self.UnzipFile() } } downLoader.downLoader(url: zipUrl!, dir: "rn-modules/" + self.moduleName) } func UnzipFile() { let zipPath = kCachePath! + self.rootPath + "/" + self.moduleMd5 + ".zip" let targetPath = kCachePath! + self.localPath print("zip path: " + zipPath + "---" + targetPath) if (FileTool.fileExists(filePath: targetPath)) { FileTool.removeFile(targetPath) } let targetURL = URL(fileURLWithPath: targetPath) let zipURL = URL(fileURLWithPath: zipPath) print("local file:\(zipURL)") print("target url:\(targetURL)") do { let fileManager = FileManager() try fileManager.unzipItem(at: zipURL, to: targetURL); let filepath = targetPath + "/index.ios.bundle" if (FileTool.fileExists(filePath: filepath)) { let jsCodeLocation = URL(fileURLWithPath: filepath) loadBundleFromUrl(jsCodeLocation: jsCodeLocation); } else { self.resetRemoteValue() print("文件不存在") } } catch { print("Creation of ZIP archive failed with error:\(error)") self.resetRemoteValue() return } } func resetRemoteValue() { var values = self.readInfo() values["remotePath"] = "" self.writeInfo(info: values) } func resetLocalValue() { var values = self.readInfo() values["localPath"] = "" self.writeInfo(info: values) } func preloadBundleFile() { // // self.resetRemoteValue(); // self.resetLocalValue(); // let values = readInfo() // 解压完成并且正在使用的 bundle path let localPath = values["localPath"] as? String let moduleName = values["moduleName"] as? String // 已经下载完成的 bundle path let remotePath = values["remotePath"] as? String let remoteMd5 = values["remoteMd5"] as? String print("localPath: \(localPath), moduleName: \(moduleName), remotePath: \(remotePath), remoteMd5: \(remoteMd5)") if (isEmptyString(str: localPath) || isEmptyString(str: moduleName)) { self.resetRemoteValue(); self.resetLocalValue(); return; } //如果文件路径发生变动 if (!isEmptyString(str: remotePath) && localPath != remotePath) { self.localPath = remotePath!; self.moduleName = moduleName!; self.moduleName = remoteMd5!; self.rootPath = "/rn-modules" + "/" + self.moduleName if (!isEmptyString(str: remoteMd5)) { UnzipFile(); } else { resetRemoteValue(); resetLocalValue(); } return; } self.localPath = localPath! self.moduleName = moduleName! let targetPath = kCachePath! + self.localPath let filepath = targetPath + "/index.ios.bundle" if (FileTool.fileExists(filePath: filepath)) { let jsCodeLocation = URL(fileURLWithPath: filepath) loadBundleFromUrl(jsCodeLocation: jsCodeLocation); } // // 解压完成并且正在使用的 bundle path // String localPath = pref.getString("localPath", ""); // String moduleName = pref.getString("moduleName", ""); // // 已经下载完成的 bundle path // String remotePath = pref.getString("remotePath", ""); // String remoteMd5 = pref.getString("remoteMd5", ""); // Log.i(TAG, "store: " + remotePath + "---" + localPath + "---" + moduleName); // // // 如果没有历史缓存则不做任何处理 // if (isEmptyString(localPath) || isEmptyString(moduleName)) { // resetRemoteValue(); // resetLocalValue(); // return; // } // // 如果文件路径发生变动 // if (!isEmptyString(remotePath) && !localPath.equals(remotePath)) { // mLocalPath = remotePath; // mModuleName = moduleName; // mModuleMd5 = remoteMd5; // mRootPath = RN_BUNDLE_LOCAL_PATH + File.separator + mModuleName; // if (!isEmptyString(remoteMd5)) { // unzipFile(); // } else { // resetRemoteValue(); // resetLocalValue(); // } // return; // } // mLocalPath = localPath; // mModuleName = moduleName; // mRootPath = RN_BUNDLE_LOCAL_PATH + File.separator + mModuleName; // // 若缓存文件存在,则渲染缓存文件 // File file = getBundleFile(JS_BUNDLE_SUFFIX); // if (file.exists()) { // loadBundleFromFile(file); // } } override func viewDidLoad() { super.viewDidLoad() let view = UIView() view.backgroundColor = UIColor.systemBackground self.view = view } func getUrlInfo(url: String) -> RNUrl { let m = url.split(separator: "?").compactMap({ "\($0)" }) let publicUrl = m[0] let search = "?" + m[1] return RNUrl(search: search, publicUrl: publicUrl, path: "/") } func loadBundleFromUrl(jsCodeLocation: URL) { let url = getUrlInfo(url: self.href) let props = [ "publicUrl": url.publicUrl, "path": url.path, "search": url.search ] let rootView = RCTRootView( bundleURL: jsCodeLocation, moduleName: moduleName, initialProperties: props, launchOptions: nil ) self.view = rootView self.loadedBundle = true var values = self.readInfo() values["localPath"] = self.localPath values["moduleName"] = self.moduleName self.writeInfo(info: values) } func isEmptyString(str: String?) -> Bool { if (str == nil) { return true } return str == "" } func writeInfo(info: Dictionary<String, Any>) { let defaults = UserDefaults.standard let data: NSData = NSKeyedArchiver.archivedData(withRootObject: info) as NSData defaults.set(data, forKey: storeName) defaults.synchronize() } func readInfo() -> Dictionary<String, Any> { let defaults = UserDefaults.standard let data = defaults.object(forKey: storeName) if data != nil { let ary = NSKeyedUnarchiver.unarchiveObject(with:data as! Data)! as! Dictionary<String, Any> return ary } else { return [:] } } } extension String { var md5:String { let utf8 = cString(using: .utf8) var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) CC_MD5(utf8, CC_LONG(utf8!.count - 1), &digest) return digest.reduce("") { $0 + String(format:"%02x", $1) } } }
32.33557
170
0.553757
f70b6834998df811bcae2139ab19ee6786b1bd49
2,838
/* ----------------------------------------------------------------------------- This source file is part of SecurityKit. Copyright 2017-2018 Jon Griffeth Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- */ import XCTest @testable import SecurityKit class X509AlgorithmTests: XCTestCase { func testClassConstants() { // oid property XCTAssert(X509Algorithm.md5WithRSAEncryption.oid == pkcs1MD5WithRSAEncryption) XCTAssert(X509Algorithm.sha1WithRSAEncryption.oid == pkcs1SHA1WithRSAEncryption) XCTAssert(X509Algorithm.sha256WithRSAEncryption.oid == pkcs1SHA256WithRSAEncryption) XCTAssert(X509Algorithm.sha384WithRSAEncryption.oid == pkcs1SHA384WithRSAEncryption) XCTAssert(X509Algorithm.sha512WithRSAEncryption.oid == pkcs1SHA512WithRSAEncryption) // parameters property XCTAssert(X509Algorithm.md5WithRSAEncryption.parameters == nil) XCTAssert(X509Algorithm.sha1WithRSAEncryption.parameters == nil) XCTAssert(X509Algorithm.sha256WithRSAEncryption.parameters == nil) XCTAssert(X509Algorithm.sha384WithRSAEncryption.parameters == nil) XCTAssert(X509Algorithm.sha512WithRSAEncryption.parameters == nil) // digest property XCTAssert(X509Algorithm.md5WithRSAEncryption.digest == .md5) XCTAssert(X509Algorithm.sha1WithRSAEncryption.digest == .sha1) XCTAssert(X509Algorithm.sha256WithRSAEncryption.digest == .sha256) XCTAssert(X509Algorithm.sha384WithRSAEncryption.digest == .sha384) XCTAssert(X509Algorithm.sha512WithRSAEncryption.digest == .sha512) // localized description property XCTAssert(X509Algorithm.md5WithRSAEncryption.localizedDescription == "MD5 with RSA Encryption") XCTAssert(X509Algorithm.sha1WithRSAEncryption.localizedDescription == "SHA-1 with RSA Encryption") XCTAssert(X509Algorithm.sha256WithRSAEncryption.localizedDescription == "SHA-256 with RSA Encryption") XCTAssert(X509Algorithm.sha384WithRSAEncryption.localizedDescription == "SHA-384 with RSA Encryption") XCTAssert(X509Algorithm.sha512WithRSAEncryption.localizedDescription == "SHA-512 with RSA Encryption") } } // End of File
45.047619
110
0.707893
c1a0a7cec4b688b3d1741cc978b6559a71501036
2,065
// // Float+Extension.swift // SwiftExtensions // // The MIT License (MIT) // // Copyright (c) 2018 Alexander Borovikov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation public extension Float { public var abs: Float { return fabsf(self) } public var ceil: Float { return ceilf(self) } public var floor: Float { return floorf(self) } public var isPositive: Bool { return self > 0 } public var isNegative: Bool { return self < 0 } public var sqrt: Float { return sqrtf(self) } public var round: Float { return Foundation.round(self) } public func clamp (min: Float, _ max: Float) -> Float { return Swift.max(min, Swift.min(max, self)) } public var degreesToRadians: Float { return Float.pi * self / Float(180) } public var radiansToDegrees: Float { return self * Float(180) / Float.pi } }
28.680556
82
0.66247
5b2645699c033334db0b0e9fa2129552287c27be
783
import UIKit import XCTest import TTHorizontalGradientAnimationView class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
26.1
111
0.616858
01f67acec3be4a6c1d87452da55cb918955236e6
2,881
import BigInt import Foundation class ContractCallDecorator: IDecorator { private class RecognizedContractMethod { let name: String let signature: String? let arguments: [Any]? let methodId: Data init(name: String, signature: String, arguments: [Any]) { self.name = name self.signature = signature self.arguments = arguments methodId = ContractMethodHelper.methodId(signature: signature) } init(name: String, methodId: Data) { self.name = name self.methodId = methodId signature = nil arguments = nil } } private var address: Address private var methods = [Data: RecognizedContractMethod]() init(address: Address) { self.address = address addMethod(name: "Deposit", signature: "deposit(uint256)", arguments: [BigUInt.self]) addMethod(name: "TradeWithHintAndFee", signature: "tradeWithHintAndFee(address,uint256,address,address,uint256,uint256,address,uint256,bytes)", arguments: [Address.self, BigUInt.self, Address.self, Address.self, BigUInt.self, BigUInt.self, Address.self, BigUInt.self, Data.self]) addMethod(name: "Farm Deposit", methodId: "0xe2bbb158") addMethod(name: "Farm Withdrawal", methodId: "0x441a3e70") addMethod(name: "Pool Deposit", methodId: "0xf305d719") addMethod(name: "Pool Withdrawal", methodId: "0xded9382a") addMethod(name: "Stake", methodId: "0xa59f3e0c") addMethod(name: "Unstake", methodId: "0x67dfd4c9") } private func addMethod(name: String, signature: String, arguments: [Any]) { let method = RecognizedContractMethod(name: name, signature: signature, arguments: arguments) methods[method.methodId] = method } private func addMethod(name: String, methodId: String) { let method = RecognizedContractMethod(name: name, methodId: Data(hex: methodId)!) methods[method.methodId] = method } func decorate(transactionData: TransactionData, fullTransaction: FullTransaction?) -> ContractMethodDecoration? { guard let transaction = fullTransaction?.transaction, transaction.from == address else { return nil } let methodId = Data(transactionData.input.prefix(4)) let inputArguments = Data(transactionData.input.suffix(from: 4)) guard let method = methods[methodId] else { return nil } let arguments = method.arguments.flatMap { ContractMethodHelper.decodeABI(inputArguments: inputArguments, argumentTypes: $0) } ?? [] return RecognizedMethodDecoration(method: method.name, arguments: arguments) } func decorate(logs: [TransactionLog]) -> [ContractEventDecoration] { [] } }
36.468354
151
0.648386
236a2148a76e3d9ce3adb4d991ecea1b7068622f
972
@testable import ITEvents class SearchViewMock: ISearchView { var loadingIndicatorShownCount = 0 var loadingIndicatorHidedCount = 0 var backgroundViewShownCount = 0 var backgroundViewHidedCount = 0 var toggleLayoutCallsCount = 0 var setEventsCount = 0 var eventsCleanedCount = 0 var eventViweModels: [EventCollectionCellViewModel] = [] func setEvents(_ events: [EventCollectionCellViewModel]) { eventViweModels = events setEventsCount += 1 } func clearEvents() { eventViweModels = [] eventsCleanedCount += 1 } func showLoadingIndicator() { loadingIndicatorShownCount += 1 } func hideLoadingIndicator() { loadingIndicatorHidedCount += 1 } func showBackgroundView() { backgroundViewShownCount += 1 } func hideBackgroundView() { backgroundViewHidedCount += 1 } func toggleLayout(value isListLayout: Bool) { toggleLayoutCallsCount += 1 } }
29.454545
79
0.688272
7620520a7863a35ddb41125f66f03ff8df775e9c
879
import Foundation import CommonCrypto func pbkdf2(hash: CCPBKDFAlgorithm, password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? { let passwordData = password.data(using: String.Encoding.utf8)! var derivedKeyData = Data(repeating: 0, count: keyByteCount) let derivedKeyDataCount = derivedKeyData.count let derivationStatus = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes in salt.withUnsafeBytes { saltBytes in CCKeyDerivationPBKDF( CCPBKDFAlgorithm(kCCPBKDF2), password, passwordData.count, saltBytes, salt.count, hash, UInt32(rounds), derivedKeyBytes, derivedKeyDataCount) } } if derivationStatus != 0 { print("Error: \(derivationStatus)") return nil } return derivedKeyData }
32.555556
108
0.645051
011477ec2c09599a8ddc5fd4c0f376b6f3d1a098
2,037
// Copyright (c) 2017-2020 Shawn Moore and XMLCoder contributors // // This software is released under the MIT License. // https://opensource.org/licenses/MIT // // Created by Shawn Moore on 11/21/17. // import Foundation // MARK: - Error Utilities extension DecodingError { /// Returns a `.typeMismatch` error describing the expected type. /// /// - parameter path: The path of `CodingKey`s taken to decode a value of this type. /// - parameter expectation: The type expected to be encountered. /// - parameter reality: The value that was encountered instead of the expected type. /// - returns: A `DecodingError` with the appropriate path and debug description. static func typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Box) -> DecodingError { let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead." return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description)) } /// Returns a description of the type of `value` appropriate for an error message. /// /// - parameter value: The value whose type to describe. /// - returns: A string describing `value`. /// - precondition: `value` is one of the types below. static func _typeDescription(of box: Box) -> String { switch box { case is NullBox: return "a null value" case is BoolBox: return "a boolean value" case is DecimalBox: return "a decimal value" case is IntBox: return "a signed integer value" case is UIntBox: return "an unsigned integer value" case is FloatBox: return "a floating-point value" case is DoubleBox: return "a double floating-point value" case is UnkeyedBox: return "a array value" case is KeyedBox: return "a dictionary value" case _: return "\(type(of: box))" } } }
37.036364
113
0.635739
26b0d40c22d7384611068b5e43f0337d894aaa68
3,065
// // Array+Extension.swift // U17 // // Created by Lee on 2/22/20. // Copyright © 2020 Lee. All rights reserved. // import UIKit extension Array { /// 使用下标取数组元素 防止越界 自动判断是否 func bwy_obj(in idx:Int?) -> Element?{ // 是否传入了 idx guard let idx = idx else {return nil} // 是否越界 guard count > idx else {return nil} // 是否小于0 guard idx >= 0 else {return nil} return self[idx] } /// 安全的设置一个下标的元素,如果越界,则 append 到数组最后 /// /// - Parameters: /// - index: 下标 /// - obj: 对象 mutating func bwy_set(index : Int , obj : Element){ guard index >= 0 else {return} if index >= count { append(obj) }else{ self[index] = obj } } /// 从 last 开始去下标 , 防止越界 /// /// - Parameter offset: 0为 last, 1 取 last - 1 func bwy_obj(last offset:Int?) -> Element?{ guard let offset = offset else {return nil} let idx = count - 1 - offset return self.bwy_obj(in: idx) } func bwy_mergeAllDictionary()->[String:Any]?{ var json = [String:Any]() guard let dicArr = self as? [[String : Any?]] else {return nil} dicArr.zf_enumerate { (_, dic) in dic.zf_enumerate({ (key, value) in json[key] = value }) } guard json.count > 0 else {return nil} return json } func bwy_mergeAllArray()->[Any]?{ var allArray : [Any] = [] (self as? [[Any]])?.zf_enumerate({allArray = allArray + $1}) return allArray.isEmpty ? nil : allArray } /// 给一个数组如[2,1,0,4] 来取出多维数组内的元素 func objIn(indexs : [Int])->Any?{ var obj : Any = self for i in 0..<indexs.count{ // 判断是否是数组 guard let objArr = obj as? [Any] else{ return nil } // 防止越界 if objArr.count == 0 || indexs[i] >= objArr.count { return nil } obj = objArr[indexs[i]] } // 判断是否是数组 if let objArr = obj as? [Any]{ // 返回数组 return objArr }else{ // 不是,返回目标 obj return obj } } func mapObj(indexs : [Int])->[Element]?{ var returnValue : [Element] = [] indexs.zf_enumerate { (_, idx) in guard let v = self.bwy_obj(in: idx) else{return} returnValue.append(v) } guard returnValue.count == indexs.count else {return nil} return returnValue } } public func findIndex<T: Equatable>(of valueToFind: T, in array:[T]) -> Int? { for (index, value) in array.enumerated() { if value == valueToFind { return index } } return nil } public func shuffleArray<T:Any>(arr:[T]) -> [T] { var data:[T] = arr for i in 1..<arr.count { let index:Int = Int(arc4random()) % i if index != i { data.swapAt(i, index) } } return data }
24.918699
78
0.490701
e6c7c133554728a3fcffbd3d3da4c63307fbcaaf
2,355
import Foundation import TSCBasic import TuistCore import TuistGraph import TuistSupport protocol ProjectLinting: AnyObject { func lint(_ project: Project) -> [LintingIssue] } class ProjectLinter: ProjectLinting { // MARK: - Attributes let targetLinter: TargetLinting let settingsLinter: SettingsLinting let schemeLinter: SchemeLinting let packageLinter: PackageLinting // MARK: - Init init(targetLinter: TargetLinting = TargetLinter(), settingsLinter: SettingsLinting = SettingsLinter(), schemeLinter: SchemeLinting = SchemeLinter(), packageLinter: PackageLinting = PackageLinter()) { self.targetLinter = targetLinter self.settingsLinter = settingsLinter self.schemeLinter = schemeLinter self.packageLinter = packageLinter } // MARK: - ProjectLinting func lint(_ project: Project) -> [LintingIssue] { var issues: [LintingIssue] = [] issues.append(contentsOf: lintTargets(project: project)) issues.append(contentsOf: settingsLinter.lint(project: project)) issues.append(contentsOf: schemeLinter.lint(project: project)) issues.append(contentsOf: lintPackages(project: project)) return issues } // MARK: - Fileprivate private func lintPackages(project: Project) -> [LintingIssue] { project.packages.flatMap(packageLinter.lint) } private func lintTargets(project: Project) -> [LintingIssue] { var issues: [LintingIssue] = [] issues.append(contentsOf: project.targets.flatMap(targetLinter.lint)) issues.append(contentsOf: lintNotDuplicatedTargets(project: project)) return issues } private func lintNotDuplicatedTargets(project: Project) -> [LintingIssue] { var issues: [LintingIssue] = [] let duplicatedTargets = project.targets.map(\.name) .reduce(into: [String: Int]()) { $0[$1] = ($0[$1] ?? 0) + 1 } .filter { $0.value > 1 } .keys if !duplicatedTargets.isEmpty { let issue = LintingIssue( reason: "Targets \(duplicatedTargets.joined(separator: ", ")) from project at \(project.path.pathString) have duplicates.", severity: .error ) issues.append(issue) } return issues } }
32.708333
139
0.650531
2fabdc3a4d5398d24dc9f346e488b6201af2e01a
10,421
// Copyright (c) 2019 Razeware LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, // distribute, sublicense, create a derivative work, and/or sell copies of the // Software in any work that is designed, intended, or marketed for pedagogical or // instructional purposes related to programming, coding, application development, // or information technology. Permission for such use, copying, modification, // merger, publication, distribution, sublicensing, creation of derivative works, // or sale is expressly withheld. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import GRDB import Combine @testable import Emitron class DownloadQueueManagerTest: XCTestCase { private var database: DatabaseWriter! private var persistenceStore: PersistenceStore! private var videoService = VideosServiceMock() private var downloadService: DownloadService! private var queueManager: DownloadQueueManager! private var subscriptions = Set<AnyCancellable>() private var settingsManager: SettingsManager! override func setUp() { super.setUp() // There's one already running—let's stop that if downloadService != nil { downloadService.stopProcessing() } // swiftlint:disable:next do { database = try EmitronDatabase.testDatabase() } catch { fatalError("Failed trying to test database") } persistenceStore = PersistenceStore(db: database) settingsManager = EmitronApp.emitronObjects().settingsManager let userModelController = UserMCMock(user: .withDownloads) downloadService = DownloadService(persistenceStore: persistenceStore, userModelController: userModelController, videosServiceProvider: { _ in self.videoService }, settingsManager: settingsManager) queueManager = DownloadQueueManager(persistenceStore: persistenceStore) downloadService.stopProcessing() } override func tearDown() { super.tearDown() videoService.reset() subscriptions = [] } func getAllContents() -> [Content] { // swiftlint:disable:next force_try try! database.read { db in try Content.fetchAll(db) } } func getAllDownloads() -> [Download] { // swiftlint:disable:next force_try try! database.read { db in try Download.fetchAll(db) } } func persistableState(for content: Content, with cacheUpdate: DataCacheUpdate) -> ContentPersistableState { var parentContent: Content? if let groupId = content.groupId { // There must be parent content if let parentGroup = cacheUpdate.groups.first(where: { $0.id == groupId }) { parentContent = cacheUpdate.contents.first { $0.id == parentGroup.contentId } } } let groups = cacheUpdate.groups.filter { $0.contentId == content.id } let groupIds = groups.map(\.id) let childContent = cacheUpdate.contents.filter { groupIds.contains($0.groupId ?? -1) } return ContentPersistableState( content: content, contentDomains: cacheUpdate.contentDomains.filter({ $0.contentId == content.id }), contentCategories: cacheUpdate.contentCategories.filter({ $0.contentId == content.id }), bookmark: cacheUpdate.bookmarks.first(where: { $0.contentId == content.id }), parentContent: parentContent, progression: cacheUpdate.progressions.first(where: { $0.contentId == content.id }), groups: groups, childContents: childContent ) } func sampleDownload() throws -> Download { let screencast = ContentTest.Mocks.screencast let recorder = downloadService.requestDownload(contentId: screencast.0.id) { _ in self.persistableState(for: screencast.0, with: screencast.1) } .record() let completion = try wait(for: recorder.completion, timeout: 10) XCTAssert(completion == .finished) return getAllDownloads().first! } @discardableResult func samplePersistedDownload(state: Download.State = .pending) throws -> Download { try database.write { db in let content = PersistenceMocks.content try content.save(db) var download = PersistenceMocks.download(for: content) download.state = state try download.save(db) return download } } func testPendingStreamSendsNewDownloads() throws { let recorder = queueManager.pendingStream.record() var download = try sampleDownload() try database.write { db in try download.save(db) } let downloads = try wait(for: recorder.next(2), timeout: 10, description: "PendingDownloads") XCTAssertEqual([nil, download], downloads.map { $0?.download }) } func testPendingStreamSendingPreExistingDownloads() throws { var download = try sampleDownload() try database.write { db in try download.save(db) } let recorder = queueManager.pendingStream.record() let pending = try wait(for: recorder.next(), timeout: 10) XCTAssertEqual(download, pending!.download) } func testReadyForDownloadStreamSendsUpdatesAsListChanges() throws { var download1 = try samplePersistedDownload(state: .readyForDownload) var download2 = try samplePersistedDownload(state: .readyForDownload) var download3 = try samplePersistedDownload(state: .urlRequested) let recorder = queueManager.readyForDownloadStream.record() var readyForDownload = try wait(for: recorder.next(), timeout: 10) XCTAssertEqual(download1, readyForDownload!.download) try database.write { db in download3.state = .readyForDownload try download3.save(db) } // This shouldn't fire cos it doesn't affect the stream // readyForDownload = try wait(for: recorder.next(), timeout: 10) // XCTAssertEqual(download1, readyForDownload!!.download) try database.write { db in download1.state = .enqueued try download1.save(db) } readyForDownload = try wait(for: recorder.next(), timeout: 10) XCTAssertEqual(download2, readyForDownload!.download) try database.write { db in download2.state = .enqueued try download2.save(db) } readyForDownload = try wait(for: recorder.next(), timeout: 10) XCTAssertEqual(download3, readyForDownload!.download) try database.write { db in download3.state = .enqueued try download3.save(db) } readyForDownload = try wait(for: recorder.next(), timeout: 10) XCTAssertNil(readyForDownload) } func testDownloadQueueStreamRespectsTheMaxLimit() throws { let recorder = queueManager.downloadQueue.record() let download1 = try samplePersistedDownload(state: .enqueued) let download2 = try samplePersistedDownload(state: .enqueued) _ = try samplePersistedDownload(state: .enqueued) let queue = try wait(for: recorder.next(4), timeout: 30) XCTAssertEqual( [ [], // Empty to start [download1], // d1 Enqueued [download1, download2], // d2 Enqueued [download1, download2] // Final download makes no difference ], queue.map { $0.map(\.download) } ) } func testDownloadQueueStreamSendsFromThePast() throws { let download1 = try samplePersistedDownload(state: .enqueued) let download2 = try samplePersistedDownload(state: .enqueued) try samplePersistedDownload(state: .enqueued) let recorder = queueManager.downloadQueue.record() let queue = try wait(for: recorder.next(), timeout: 10) XCTAssertEqual([download1, download2], queue.map(\.download)) } func testDownloadQueueStreamSendsInProgressFirst() throws { try samplePersistedDownload(state: .enqueued) let download2 = try samplePersistedDownload(state: .inProgress) try samplePersistedDownload(state: .enqueued) let download4 = try samplePersistedDownload(state: .inProgress) let recorder = queueManager.downloadQueue.record() let queue = try wait(for: recorder.next(), timeout: 10) XCTAssertEqual([download2, download4], queue.map(\.download)) } func testDownloadQueueStreamUpdatesWhenInProgressCompleted() throws { let download1 = try samplePersistedDownload(state: .enqueued) var download2 = try samplePersistedDownload(state: .inProgress) try samplePersistedDownload(state: .enqueued) let download4 = try samplePersistedDownload(state: .inProgress) let recorder = queueManager.downloadQueue.record() var queue = try wait(for: recorder.next(), timeout: 10) XCTAssertEqual([download2, download4], queue.map(\.download)) try database.write { db in download2.state = .complete try download2.save(db) } queue = try wait(for: recorder.next(), timeout: 10) XCTAssertEqual([download4, download1], queue.map(\.download)) } func testDownloadQueueStreamDoesNotChangeIfAtCapacity() throws { let download1 = try samplePersistedDownload(state: .enqueued) let download2 = try samplePersistedDownload(state: .enqueued) let recorder = queueManager.downloadQueue.record() var queue = try wait(for: recorder.next(), timeout: 10) XCTAssertEqual([download1, download2], queue.map(\.download)) try samplePersistedDownload(state: .enqueued) queue = try wait(for: recorder.next(), timeout: 10) XCTAssertEqual([download1, download2], queue.map(\.download)) } }
38.032847
200
0.710009
1d4e8ed67a5ceba86f1dd1c22fe6f8c2f804e04b
1,172
import UIKit //Homework 3 var sum: Double = 1 + 2 var pr: Double = 2 - 1 var tot: Double = sum * pr var oto = pr / sum var res = 20 var res2 = 12.43 var res3 = res2 / Double(res) //Double.init(res) res2 += res3 res2 += 5 let cons1: Int, cons2: Float, cons3: Double cons1 = 18; cons2 = 16.4; cons3 = 5.7 var summa: Float = Float(cons1) + cons2 + Float(cons3) var proizvedenie: Int = cons1 * Int((Double(cons2) * cons3)) var ostatok: Double = Double(cons2).truncatingRemainder(dividingBy: cons3) print("Сумма/произведение/остаток от деления констант равны \(summa), \(proizvedenie) и \(ostatok), соответственно") //Homework 4 var a = 2, b = 3 var uravnenie = ((a + (4 * b)) * (a - (3 * b))) + Int(pow(Double(a), 2)) print("Уравнение равно \(uravnenie)") //Homework 5 var c = 1.75, d = 3.25 var uravnenie2 = (2 * pow((c + 1), 2)) + (3 * (d + 1)) print("Уравнение 2 равно \(uravnenie2)") //Homework 5 let length = 28 let ploshyad = pow(Double(length), 2) let dlinaOkruzhnosty = Double.pi * Double(length) print("Площадь квадрата со стороной длиной \(length) равна \(ploshyad). \n А длина окружности радиусом \(length) равна \(dlinaOkruzhnosty).")
19.864407
141
0.654437
915a64f7ff29e2d63ae8d29a56b5f1c963a3a9c7
3,665
// // FBFile.swift // FileBrowser // // Created by Roy Marmelstein on 14/02/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation import UIKit /// FBFile is a class representing a file in FileBrowser @objc open class FBFile: NSObject { /// Display name. String. @objc public let displayName: String // is Directory. Bool. public let isDirectory: Bool /// File extension. public let fileExtension: String? /// File attributes (including size, creation date etc). public let fileAttributes: NSDictionary? /// NSURL file path. public let filePath: URL // FBFileType public let type: FBFileType open func delete() { do { try FileManager.default.removeItem(at: self.filePath) } catch { print("An error occured when trying to delete file:\(self.filePath) Error:\(error)") } } /** Initialize an FBFile object with a filePath - parameter filePath: NSURL filePath - returns: FBFile object. */ init(filePath: URL) { self.filePath = filePath let isDirectory = checkDirectory(filePath) self.isDirectory = isDirectory if self.isDirectory { self.fileAttributes = nil self.fileExtension = nil self.type = .Directory } else { self.fileAttributes = getFileAttributes(self.filePath) self.fileExtension = filePath.pathExtension if let fileExtension = fileExtension { self.type = FBFileType(rawValue: fileExtension) ?? .Default } else { self.type = .Default } } self.displayName = filePath.lastPathComponent } } /** FBFile type */ public enum FBFileType: String { /// Directory case Directory = "directory" /// GIF file case GIF = "gif" /// JPG file case JPG = "jpg" /// PLIST file case JSON = "json" /// PDF file case PDF = "pdf" /// PLIST file case PLIST = "plist" /// PNG file case PNG = "png" /// ZIP file case ZIP = "zip" /// Any file case Default = "file" /** Get representative image for file type - returns: UIImage for file type */ public func image() -> UIImage? { let bundle = Bundle(for: FileParser.self) var fileName = String() switch self { case .Directory: fileName = "[email protected]" case .JPG, .PNG, .GIF: fileName = "[email protected]" case .PDF: fileName = "[email protected]" case .ZIP: fileName = "[email protected]" default: fileName = "[email protected]" } let file = UIImage(named: fileName, in: bundle, compatibleWith: nil) return file } } /** Check if file path NSURL is directory or file. - parameter filePath: NSURL file path. - returns: isDirectory Bool. */ func checkDirectory(_ filePath: URL) -> Bool { var isDirectory = false do { var resourceValue: AnyObject? try (filePath as NSURL).getResourceValue(&resourceValue, forKey: URLResourceKey.isDirectoryKey) if let number = resourceValue as? NSNumber , number == true { isDirectory = true } } catch { } return isDirectory } func getFileAttributes(_ filePath: URL) -> NSDictionary? { let path = filePath.path let fileManager = FileParser.sharedInstance.fileManager do { let attributes = try fileManager.attributesOfItem(atPath: path) as NSDictionary return attributes } catch {} return nil }
26.178571
103
0.593179
895fe9eb0c91e5b2b652973dfe2325274e2bbc42
1,940
// // AddFolderItemsAddFolderItemsViewController.swift // TOTP // // Created by Tarik on 15/02/2021. // Copyright © 2021 Taras Markevych. All rights reserved. // import UIKit import Firebase import GoogleMobileAds class AddFolderItemsViewController: UITableViewController { // MARK: - // MARK: Properties var output: AddFolderItemsViewOutput! var bannerView: GADBannerView! // MARK: - // MARK: Life cycle override func viewDidLoad() { super.viewDidLoad() tableView.delegate = output tableView.dataSource = output output.viewIsReady() setupAddsViewElements() } func setupAddsViewElements() { bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait) addBannerViewToView(bannerView) bannerView.adUnitID = Constants.adds.bannerId bannerView.rootViewController = self bannerView.delegate = self } override func viewWillAppear(_ animated: Bool) { bannerView.load(GADRequest()) } static func instantiate(with folder: Folder) -> AddFolderItemsViewController { let viewController = AddFolderItemsViewController.instantiate(useSwinject: true) let output = container.resolve(AddFolderItemsPresenter.self, arguments: viewController, folder) viewController.output = output return viewController } } // MARK: - // MARK: AddFolderItemsViewInput extension AddFolderItemsViewController: AddFolderItemsViewInput { func showError(error: Error) { UIManager.shared.showAlert(title: "", message: error.localizedDescription) } func reloadTable() { tableView.reloadData() } func setupInitialState() { } } extension AddFolderItemsViewController: NibIdentifiable { static var nibNameIdentifier: String { return "Main" } static var controllerIdentifier: String { return "AddFolderItemsViewController" } }
25.194805
103
0.702062
083b336d223c31b501af8b2fac3738caa63cf7f0
4,682
// // ViewController.swift // Watson Waste Sorter // // Created by XiaoguangMo on 12/4/17. // Copyright © 2017 IBM Inc. All rights reserved. // import UIKit import Alamofire import CameraManager import SimpleAlert import NVActivityIndicatorView class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var loadingView: NVActivityIndicatorView! @IBOutlet weak var main: UIView! @IBOutlet weak var shoot: UIImageView! var myImage: UIImage! let cameraManager = CameraManager() let SERVER_API_ENDPOINT = Bundle.main.infoDictionary!["SERVER_API_ENDPOINT"] as! String override func viewDidLoad() { super.viewDidLoad() cameraManager.addPreviewLayerToView(self.main) cameraManager.cameraOutputQuality = .medium } @IBAction func takePhoto(_ sender: Any) { if loadingView.animating { return } self.loadingView.startAnimating() self.view.bringSubview(toFront: loadingView) main.bringSubview(toFront: loadingView) cameraManager.capturePictureWithCompletion({ (image, error) -> Void in self.myImage = image let imageData = UIImageJPEGRepresentation(image!, 1)! Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(imageData, withName: "images_file", fileName: "image.jpg", mimeType: "image/jpg") }, to: self.SERVER_API_ENDPOINT, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in if let status = response.response?.statusCode { switch(status){ case 200: if let result = response.result.value { let JSON = result as! NSDictionary print(JSON) if let res = JSON["result"] as? String { if let confs = JSON["confident score"] as? Double { self.showAlert(text: res, conf:Int(confs * 100)) } } } default: print("error with response status: \(status)") } } // debugPrint(response) // print(response.description) } case .failure(let encodingError): print(encodingError) } } ) }) } func showAlert(text:String, conf:Int) { var res = text if res == "Image is either not a waste or it's too blurry, please try it again."{ res = "Unclassified" } let alert = AlertController(view: UIView(), style: .alert) alert.contentWidth = 200 alert.contentCornerRadius = 100 alert.contentColor = .white let action = AlertAction(title: "\(res)", style: .cancel) { action in } let confView = UILabel(frame:CGRect(x: 0, y: 125, width: 200, height: 21)) confView.text = "Confident Score: \(conf)%" confView.font = UIFont(name: "Halvetica", size: 15) confView.textAlignment = .center action.button.addSubview(confView) action.button.bringSubview(toFront: confView) alert.addAction(action) action.button.frame.size.height = 200 action.button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 30) switch(res){ case "Unclassified": action.button.setTitleColor(UIColor.red, for: .normal) case "Landfill": action.button.setTitleColor(UIColor.black, for: .normal) case "Compost": action.button.setTitleColor(UIColor.green, for: .normal) default: action.button.setTitleColor(UIColor.blue, for: .normal) } self.loadingView.stopAnimating() self.present(alert, animated: true, completion: nil) } // MARK: - UIImagePickerControllerDelegate Methods override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
38.694215
126
0.54528
89d34c6745e5ede57c3d723f0b1571ddd3bb66ee
4,187
import Foundation import MultipeerConnectivity let IntrospectionClientServiceName = "compose-client" class IntrospectionClient : NSObject { ///Internal identifier of a client fileprivate let discoveryInfo = [ "id" : UUID().uuidString ] ///Current peer identifier. fileprivate let peerIdentifier = MCPeerID(displayName: UIDevice.current.name) ///Currently active session. fileprivate let session : MCSession ///Service advertiser to let Compose know about this device. fileprivate let advertiser : MCNearbyServiceAdvertiser fileprivate(set) var connectionState : ConnectionState = .disconnected override init() { self.advertiser = MCNearbyServiceAdvertiser(peer: peerIdentifier, discoveryInfo: discoveryInfo, serviceType: IntrospectionClientServiceName) self.session = MCSession(peer: peerIdentifier, securityIdentity: nil, encryptionPreference: .none) super.init() session.delegate = self self.advertiser.delegate = self self.advertiser.startAdvertisingPeer() print("[IntrospectionClient] Introspection client is ready.") } } extension IntrospectionClient { func send<T : Encodable>(_ value : T) throws { let encoder = PropertyListEncoder() let data = try encoder.encode(value) try send(data) } func send(_ data : Data) throws { guard session.connectedPeers.count > 0 else { return } try session.send(data, toPeers: session.connectedPeers, with: .reliable) } } extension IntrospectionClient : MCNearbyServiceAdvertiserDelegate { func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) { print("[IntrospectionClient] Error while advertising remote rendering client: \(error)") } func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) { invitationHandler(true, session) print("[IntrospectionClient] Introspection session initiated.") } } extension IntrospectionClient : MCSessionDelegate { ///State of connection with the server. enum ConnectionState { ///Connected to remote host, but idle case connected ///Disconnected from remote host case disconnected } func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { switch state { case .notConnected: print("[IntrospectionClient] Not connected to server") self.connectionState = .disconnected case .connecting: print("[IntrospectionClient] Connecting to server") case .connected: print("[IntrospectionClient] Connected to server") self.connectionState = .connected default: break } } func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) { } }
29.907143
106
0.590638
69ffe1ae2b3319c1aef5e53a65f12a0420ab36fc
2,442
// // Copyright 2018-2020 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // import Foundation /// Types that conform to the `Persistable` protocol represent values that can be /// persisted in a database. /// /// Core Types that conform to this protocol: /// - `Bool` /// - `Double` /// - `Int` /// - `String` /// - `Temporal.Date` /// - `Temporal.DateTime` /// - `Temporal.Time` /// - Warning: Although this has `public` access, it is intended for internal use and should not be used directly /// by host applications. The behavior of this may change without warning. public protocol Persistable {} extension Bool: Persistable {} extension Double: Persistable {} extension Int: Persistable {} extension String: Persistable {} extension Temporal.Date: Persistable {} extension Temporal.DateTime: Persistable {} extension Temporal.Time: Persistable {} struct PersistableHelper { /// Polymorphic utility that allows two persistable references to be checked /// for equality regardless of their concrete type. /// /// - Note: Maintainers need to keep this utility updated when news types that conform /// to `Persistable` are added. /// /// - Parameters: /// - lhs: a reference to a Persistable object /// - rhs: another reference /// - Returns: `true` in case both values are equal or `false` otherwise /// - Warning: Although this has `public` access, it is intended for internal use and should not be used directly /// by host applications. The behavior of this may change without warning. public static func isEqual(_ lhs: Persistable?, _ rhs: Persistable?) -> Bool { if lhs == nil && rhs == nil { return true } switch (lhs, rhs) { case let (lhs, rhs) as (Bool, Bool): return lhs == rhs case let (lhs, rhs) as (Temporal.Date, Temporal.Date): return lhs == rhs case let (lhs, rhs) as (Temporal.DateTime, Temporal.DateTime): return lhs == rhs case let (lhs, rhs) as (Temporal.Time, Temporal.Time): return lhs == rhs case let (lhs, rhs) as (Double, Double): return lhs == rhs case let (lhs, rhs) as (Int, Int): return lhs == rhs case let (lhs, rhs) as (String, String): return lhs == rhs default: return false } } }
34.394366
117
0.630631
29b0279c37bf6eb461c2fe2603c85d7bb791f9c1
7,050
// // MessageToolbar.swift // Pods // // Created by Kenneth on 1/2/2016. // // import Cartography protocol LiveChatToolbarDelegate { func keyboardDidChangeHeight(height: CGFloat) } final class LiveChatToolbar: UIView { //MARK: Init private weak var socket: SocketIOChatClient? private weak var heightConstraint: NSLayoutConstraint? private var centerContext = 0 var delegate: LiveChatToolbarDelegate? lazy private var textView: GrowingTextView = { let _textView = GrowingTextView() _textView.delegate = self _textView.growingDelegate = self _textView.returnKeyType = .Send _textView.font = UIFont.systemFontOfSize(15) _textView.placeHolder = "Say something..." _textView.placeHolderColor = UIColor(white: 1.0, alpha: 0.5) _textView.keyboardDismissMode = .Interactive _textView.keyboardAppearance = .Dark return _textView }() lazy private var sendButton: UIButton = { let _button = UIButton(type: .System) _button.setTitle("Send", forState: .Normal) _button.setTitleColor(UIColor.whiteColor(), forState: .Normal) _button.titleLabel?.font = UIFont.systemFontOfSize(15) _button.addTarget(self, action: "sendButtonTapped", forControlEvents: .TouchUpInside) _button.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal) return _button }() lazy private var activityIndicatorView: UIActivityIndicatorView = { let _activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .White) _activityIndicatorView.hidesWhenStopped = true return _activityIndicatorView }() convenience init(socket: SocketIOChatClient) { self.init(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: 50)) self.socket = socket backgroundColor = UIColor.clearColor() let line = UIView() line.backgroundColor = UIColor(white: 1.0, alpha: 0.5) let colorTop = UIColor(white: 0.0, alpha: 0.0).CGColor let colorBottom = UIColor(white: 0.0, alpha: 0.6).CGColor let locations = [0.0, 1.0] let gradientView = GradientView(colors: [colorTop, colorBottom], locations: locations) addSubview(gradientView) addSubview(line) addSubview(textView) addSubview(sendButton) addSubview(activityIndicatorView) constrain(self, line, gradientView) { view, line, gradientView in gradientView.edges == inset(view.edges, -20, 0, -44, 0) line.top == view.top line.left == view.left + 10 line.right == view.right - 10 line.height == max(0.5, 1.0 / UIScreen.mainScreen().scale) } constrain(self, sendButton, textView, activityIndicatorView) { view, sendButton, textView, activityIndicatorView in sendButton.top == view.top sendButton.bottom == view.bottom sendButton.right == view.right - 10 textView.left == view.left + 10 textView.right == sendButton.left - 10 textView.centerY == view.centerY activityIndicatorView.center == sendButton.center } } //MARK: Layout override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) guard let newSuperview = newSuperview else { self.superview?.removeObserver(self, forKeyPath: "center") return } let options = NSKeyValueObservingOptions([.New, .Old]) newSuperview.addObserver(self, forKeyPath: "center", options: options, context: &centerContext) } override func addConstraint(constraint: NSLayoutConstraint) { if constraint.firstItem === self { self.heightConstraint = constraint } super.addConstraint(constraint) } //MARK: Send/Receive Message func sendButtonTapped() { guard let message = textView.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) else { return } if message.isEmpty { return } if socket?.sendMessage(message) == true{ textView.text = nil } } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if context == &centerContext { guard let superViewFrame = superview?.frame else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) return } //Calculate keyboard Height let keyboardHeight = UIScreen.mainScreen().bounds.size.height - superViewFrame.origin.y //Set textview alpha if textView.text?.isEmpty != false { var textViewAlpha = (keyboardHeight - bounds.size.height)/200 textViewAlpha = max(min(textViewAlpha, 0.9), 0.2) textView.backgroundColor = UIColor(white: 1.0, alpha: textViewAlpha) } else { textView.backgroundColor = UIColor(white: 1.0, alpha: 0.9) } //Callback delegate?.keyboardDidChangeHeight(keyboardHeight) } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } func startLoading() { sendButton.hidden = true activityIndicatorView.startAnimating() } func stopLoading() { activityIndicatorView.stopAnimating() sendButton.hidden = false } } //MARK: UITextViewDelegate (Press Enter, Characters Limit) extension LiveChatToolbar: UITextViewDelegate { func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if text == "\n" { sendButtonTapped() return false } return true } func textViewDidChange(textView: UITextView) { guard let maxMessageLength = socket?.liveChatView.maxMessageLength else { return } if textView.text.characters.count > maxMessageLength { let endIndex = textView.text.startIndex.advancedBy(maxMessageLength) textView.text = textView.text.substringToIndex(endIndex) textView.undoManager?.removeAllActions() } } } extension LiveChatToolbar: GrowingTextViewDelegate { func growingTextViewDidChangeHeight(height: CGFloat) { if let heightConstraint = heightConstraint { heightConstraint.constant = height + 16 UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.CurveLinear], animations: { () -> Void in self.superview?.layoutIfNeeded() }, completion: nil) } } }
38.52459
165
0.640851
232f2084c29a18d257285cecc20885ee4796e85d
1,421
// // PreworkUITests.swift // PreworkUITests // // Created by Admin Mac on 1/14/22. // 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.046512
182
0.654469
e5045f0d0d5127df446e635d23268c4fc7408f61
693
// // GoalsTableViewCell.swift // Master Your Money Build Week // // Created by Seschwan on 8/23/19. // Copyright © 2019 Seschwan. All rights reserved. // import UIKit class GoalsTableViewCell: UITableViewCell { // MARK: - Outlets @IBOutlet weak var title: UILabel! @IBOutlet weak var goalProgressBar: UIProgressView! @IBOutlet weak var endGoalLbl: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
22.354839
65
0.655123
3ad30ba7b0565f415d363124b9b4066b6f8f27b6
950
// // GraphicView.swift // PDFTester // // Created by Carmelo I. Uria on 9/16/15. // Copyright © 2015 Carmelo I. Uria. All rights reserved. // import UIKit class GraphicView: UIView { // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() let myShadowOffset = CGSizeMake (-10, 15) CGContextSaveGState(context) CGContextSetShadow (context, myShadowOffset, 5) CGContextSetLineWidth(context, 4.0) CGContextSetStrokeColorWithColor(context, UIColor.blueColor().CGColor) let rectangle = CGRectMake(60,170,200,80) CGContextAddEllipseInRect(context, rectangle) CGContextStrokePath(context) CGContextRestoreGState(context) } }
25
78
0.652632
090b22e8645c0ec61bee2d223e0bbc90400459fc
655
// // MessageListener.swift // cimsdk // // Created by FeiYu on 2021/10/1. // import Foundation public protocol MessageListener { var uniqueID: String { get } func receiveMessage(_ message: Transportable) func receiveMessageWithError(_ error: Error) } public protocol MessageSendListener { func sendMessage(_ message: Transportable) } extension MessageListener { func receiveMessage(_ message: Transportable) { } func receiveMessageWithError(_ error: Error) { } } extension MessageSendListener { func sendMessage(_ message: Transportable) { } }
15.97561
51
0.648855
48641c4817b53b0b788f092e205e01db2b130d99
17,994
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension Rocket.Content { /** Search the catalog of items and people. */ public enum Search { public static let service = APIService<Response>(id: "search", tag: "content", method: "GET", path: "/search", hasBody: false, securityRequirements: []) /** By default people, movies and tv (shows + programs) will be included in the search results. If you don't want all of these types you can specifiy the specific includes you care about. */ public enum Include: String, Codable, Equatable, CaseIterable { case tv = "tv" case movies = "movies" case people = "people" } public final class Request: APIRequest<Response> { public struct Options { /** The search term to query. */ public var term: String /** By default people, movies and tv (shows + programs) will be included in the search results. If you don't want all of these types you can specifiy the specific includes you care about. */ public var include: [Include]? /** When this option is set, instead of all search result items being returned in a single list, they will instead be returned under two lists. One for movies and another for tv (shows + programs). Default is undefined meaning items will be returned in a single list. The array of `people` results will alway be separate from items. */ public var group: Bool? /** The maximum number of results to return. */ public var maxResults: Int? /** The maximum rating (inclusive) of items returned, e.g. 'auoflc-pg'. */ public var maxRating: String? /** The type of device the content is targeting. */ public var device: String? /** The active subscription code. */ public var sub: String? /** The list of segments to filter the response by. */ public var segments: [String]? /** The set of opt in feature flags which cause breaking changes to responses. While Rocket APIs look to avoid breaking changes under the active major version, the formats of responses may need to evolve over this time. These feature flags allow clients to select which response formats they expect and avoid breaking clients as these formats evolve under the current major version. ### Flags - `all` - Enable all flags. Useful for testing. _Don't use in production_. - `idp` - Dynamic item detail pages with schedulable rows. - `ldp` - Dynamic list detail pages with schedulable rows. See the `feature-flags.md` for available flag details. */ public var ff: [FeatureFlags]? public init(term: String, include: [Include]? = nil, group: Bool? = nil, maxResults: Int? = nil, maxRating: String? = nil, device: String? = nil, sub: String? = nil, segments: [String]? = nil, ff: [FeatureFlags]? = nil) { self.term = term self.include = include self.group = group self.maxResults = maxResults self.maxRating = maxRating self.device = device self.sub = sub self.segments = segments self.ff = ff } } public var options: Options public init(options: Options) { self.options = options super.init(service: Search.service) } /// convenience initialiser so an Option doesn't have to be created public convenience init(term: String, include: [Include]? = nil, group: Bool? = nil, maxResults: Int? = nil, maxRating: String? = nil, device: String? = nil, sub: String? = nil, segments: [String]? = nil, ff: [FeatureFlags]? = nil) { let options = Options(term: term, include: include, group: group, maxResults: maxResults, maxRating: maxRating, device: device, sub: sub, segments: segments, ff: ff) self.init(options: options) } public override var queryParameters: [String: Any] { var params: [String: Any] = [:] params["term"] = options.term if let include = options.include?.encode().map({ String(describing: $0) }).joined(separator: ",") { params["include"] = include } if let group = options.group { params["group"] = group } if let maxResults = options.maxResults { params["max_results"] = maxResults } if let maxRating = options.maxRating { params["max_rating"] = maxRating } if let device = options.device { params["device"] = device } if let sub = options.sub { params["sub"] = sub } if let segments = options.segments?.joined(separator: ",") { params["segments"] = segments } if let ff = options.ff?.encode().map({ String(describing: $0) }).joined(separator: ",") { params["ff"] = ff } return params } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { /** Search the catalog of items and people. */ public class Status200: APIModel { /** The search term. */ public var term: String /** The total number of results. */ public var total: Int public var items: ItemList? public var movies: ItemList? /** The list of people relevant to the search term. */ public var people: [Person]? public var tv: ItemList? public init(term: String, total: Int, items: ItemList? = nil, movies: ItemList? = nil, people: [Person]? = nil, tv: ItemList? = nil) { self.term = term self.total = total self.items = items self.movies = movies self.people = people self.tv = tv } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) term = try container.decode("term") total = try container.decode("total") items = try container.decodeIfPresent("items") movies = try container.decodeIfPresent("movies") people = try container.decodeArrayIfPresent("people") tv = try container.decodeIfPresent("tv") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(term, forKey: "term") try container.encode(total, forKey: "total") try container.encodeIfPresent(items, forKey: "items") try container.encodeIfPresent(movies, forKey: "movies") try container.encodeIfPresent(people, forKey: "people") try container.encodeIfPresent(tv, forKey: "tv") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status200 else { return false } guard self.term == object.term else { return false } guard self.total == object.total else { return false } guard self.items == object.items else { return false } guard self.movies == object.movies else { return false } guard self.people == object.people else { return false } guard self.tv == object.tv else { return false } return true } public static func == (lhs: Status200, rhs: Status200) -> Bool { return lhs.isEqual(to: rhs) } } /** Search the catalog of items and people. */ public class Status400: APIModel { /** A description of the error. */ public var message: String /** An optional code classifying the error. Should be taken in the context of the http status code. */ public var code: Int? public init(message: String, code: Int? = nil) { self.message = message self.code = code } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) message = try container.decode("message") code = try container.decodeIfPresent("code") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(message, forKey: "message") try container.encodeIfPresent(code, forKey: "code") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status400 else { return false } guard self.message == object.message else { return false } guard self.code == object.code else { return false } return true } public static func == (lhs: Status400, rhs: Status400) -> Bool { return lhs.isEqual(to: rhs) } } /** Search the catalog of items and people. */ public class Status404: APIModel { /** A description of the error. */ public var message: String /** An optional code classifying the error. Should be taken in the context of the http status code. */ public var code: Int? public init(message: String, code: Int? = nil) { self.message = message self.code = code } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) message = try container.decode("message") code = try container.decodeIfPresent("code") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(message, forKey: "message") try container.encodeIfPresent(code, forKey: "code") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status404 else { return false } guard self.message == object.message else { return false } guard self.code == object.code else { return false } return true } public static func == (lhs: Status404, rhs: Status404) -> Bool { return lhs.isEqual(to: rhs) } } /** Search the catalog of items and people. */ public class Status500: APIModel { /** A description of the error. */ public var message: String /** An optional code classifying the error. Should be taken in the context of the http status code. */ public var code: Int? public init(message: String, code: Int? = nil) { self.message = message self.code = code } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) message = try container.decode("message") code = try container.decodeIfPresent("code") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(message, forKey: "message") try container.encodeIfPresent(code, forKey: "code") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? Status500 else { return false } guard self.message == object.message else { return false } guard self.code == object.code else { return false } return true } public static func == (lhs: Status500, rhs: Status500) -> Bool { return lhs.isEqual(to: rhs) } } /** Search the catalog of items and people. */ public class DefaultResponse: APIModel { /** A description of the error. */ public var message: String /** An optional code classifying the error. Should be taken in the context of the http status code. */ public var code: Int? public init(message: String, code: Int? = nil) { self.message = message self.code = code } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) message = try container.decode("message") code = try container.decodeIfPresent("code") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encode(message, forKey: "message") try container.encodeIfPresent(code, forKey: "code") } public func isEqual(to object: Any?) -> Bool { guard let object = object as? DefaultResponse else { return false } guard self.message == object.message else { return false } guard self.code == object.code else { return false } return true } public static func == (lhs: DefaultResponse, rhs: DefaultResponse) -> Bool { return lhs.isEqual(to: rhs) } } public typealias SuccessType = Status200 /** OK. */ case status200(Status200) /** Bad request. */ case status400(Status400) /** Not found. */ case status404(Status404) /** Internal server error. */ case status500(Status500) /** Service error. */ case defaultResponse(statusCode: Int, DefaultResponse) public var success: Status200? { switch self { case .status200(let response): return response default: return nil } } public var response: Any { switch self { case .status200(let response): return response case .status400(let response): return response case .status404(let response): return response case .status500(let response): return response case .defaultResponse(_, let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 case .status400: return 400 case .status404: return 404 case .status500: return 500 case .defaultResponse(let statusCode, _): return statusCode } } public var successful: Bool { switch self { case .status200: return true case .status400: return false case .status404: return false case .status500: return false case .defaultResponse: return false } } public init(statusCode: Int, data: Data, decoder: ResponseDecoder) throws { switch statusCode { case 200: self = try .status200(decoder.decode(Status200.self, from: data)) case 400: self = try .status400(decoder.decode(Status400.self, from: data)) case 404: self = try .status404(decoder.decode(Status404.self, from: data)) case 500: self = try .status500(decoder.decode(Status500.self, from: data)) default: self = try .defaultResponse(statusCode: statusCode, decoder.decode(DefaultResponse.self, from: data)) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
41.082192
245
0.524564
2f91b24903d048c7cda106be482313f87e138263
3,299
// // CityTableViewController.swift // Project // // Created by PFei_He on 16/5/10. // Copyright © 2016年 PFei_He. All rights reserved. // // __________ __________ _________ ___________ ___________ __________ ___________ // | _______ \ | _______ \ / _______ \ |______ __|| _________| / _________||____ ____| // | | \ || | \ || / \ | | | | | | / | | // | |_______/ || |_______/ || | | | | | | |_________ | | | | // | ________/ | _____ _/ | | | | _ | | | _________|| | | | // | | | | \ \ | | | || | | | | | | | | | // | | | | \ \ | \_______/ || \____/ | | |_________ | \_________ | | // |_| |_| \_\ \_________/ \______/ |___________| \__________| |_| // // // The framework design by https://github.com/PFei-He/Project-Swift // // 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 class CityTableViewController: BaseTableViewController { // MARK: - Life Cycle override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UITableViewDataSource Methods override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("identifier") if cell == nil { } cell?.textLabel?.text = ["北京", "上海", "广州"][indexPath.row] cell?.textLabel?.textColor = Settings.appColor() return cell! } // MARK: - UITableViewDelegate Methods override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { UserSettings.setUserSettings(["api": Api.sharedInstance().api[indexPath.row]]) navigationController?.popViewControllerAnimated(true) } }
41.2375
118
0.613519
bbd3c947de81ceb720815df60bd29b46cb84f5ed
412
public struct Filters: Equatable { public let status: Character.Status? public let gender: Character.Gender? public init(status: Character.Status?, gender: Character.Gender?) { self.status = status self.gender = gender } } extension Filters { public static let `default` = Filters(status: nil, gender: nil) public var isDefault: Bool { self == .default } }
22.888889
71
0.650485
33906fe33a157a04bb5f545eaf332f383ac7c671
1,741
import Cocoa import Intents extension Color_ { fileprivate convenience init(_ nsColor: NSColor) { let sRGBColor = nsColor.usingColorSpace(.sRGB)! let thumbnail = NSImage.color(nsColor, size: CGSize(width: 1, height: 1)) self.init( identifier: "color", display: sRGBColor.hexString, subtitle: sRGBColor.format(.cssRGB), image: thumbnail.inImage ) hex = sRGBColor.format(.hex()) hexNumber = sRGBColor.hex as NSNumber hsl = sRGBColor.format(.cssHSL) rgb = sRGBColor.format(.cssRGB) lch = nsColor.format(.cssLCH) hslLegacy = sRGBColor.format(.cssHSLLegacy) rgbLegacy = sRGBColor.format(.cssRGBLegacy) } } @MainActor final class SampleColorIntentHandler: NSObject, SampleColorIntentHandling { func handle(intent: SampleColorIntent) async -> SampleColorIntentResponse { guard let color = await NSColorSampler().sample() else { return .init(code: .failure, userActivity: nil) } let response = SampleColorIntentResponse(code: .success, userActivity: nil) response.color = Color_(color) return response } } @MainActor final class GetRandomColorIntentHandler: NSObject, GetRandomColorIntentHandling { func handle(intent: GetRandomColorIntent) async -> GetRandomColorIntentResponse { let response = GetRandomColorIntentResponse(code: .success, userActivity: nil) response.color = Color_(.randomAvoidingBlackAndWhite()) return response } } @MainActor final class IntentHandler: INExtension { override func handler(for intent: INIntent) -> Any? { switch intent { case is SampleColorIntent: return SampleColorIntentHandler() case is GetRandomColorIntent: return GetRandomColorIntentHandler() default: assertionFailure("No handler for this intent") return nil } } }
28.080645
82
0.756462
e4d0423660768f17e887d8f21a397b0bac159fae
9,696
// Copyright 2018-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // A copy of the License is located at // // http://www.apache.org/licenses/LICENSE-2.0 // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. // // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment // swiftlint:disable type_body_length function_body_length generic_type_name cyclomatic_complexity // -- Generated Code; do not edit -- // // ElasticContainerModelErrors.swift // ElasticContainerModel // import Foundation import Logging public typealias ElasticContainerErrorResult<SuccessPayload> = Result<SuccessPayload, ElasticContainerError> public extension Swift.Error { func asUnrecognizedElasticContainerError() -> ElasticContainerError { let errorType = String(describing: type(of: self)) let errorDescription = String(describing: self) return .unrecognizedError(errorType, errorDescription) } } private let accessDeniedIdentity = "AccessDeniedException" private let attributeLimitExceededIdentity = "AttributeLimitExceededException" private let blockedIdentity = "BlockedException" private let clientIdentity = "ClientException" private let clusterContainsContainerInstancesIdentity = "ClusterContainsContainerInstancesException" private let clusterContainsServicesIdentity = "ClusterContainsServicesException" private let clusterContainsTasksIdentity = "ClusterContainsTasksException" private let clusterNotFoundIdentity = "ClusterNotFoundException" private let invalidParameterIdentity = "InvalidParameterException" private let limitExceededIdentity = "LimitExceededException" private let missingVersionIdentity = "MissingVersionException" private let noUpdateAvailableIdentity = "NoUpdateAvailableException" private let platformTaskDefinitionIncompatibilityIdentity = "PlatformTaskDefinitionIncompatibilityException" private let platformUnknownIdentity = "PlatformUnknownException" private let resourceInUseIdentity = "ResourceInUseException" private let resourceNotFoundIdentity = "ResourceNotFoundException" private let serverIdentity = "ServerException" private let serviceNotActiveIdentity = "ServiceNotActiveException" private let serviceNotFoundIdentity = "ServiceNotFoundException" private let targetNotConnectedIdentity = "TargetNotConnectedException" private let targetNotFoundIdentity = "TargetNotFoundException" private let taskSetNotFoundIdentity = "TaskSetNotFoundException" private let unsupportedFeatureIdentity = "UnsupportedFeatureException" private let updateInProgressIdentity = "UpdateInProgressException" public enum ElasticContainerError: Swift.Error, Decodable { case accessDenied(AccessDeniedException) case attributeLimitExceeded(AttributeLimitExceededException) case blocked(BlockedException) case client(ClientException) case clusterContainsContainerInstances(ClusterContainsContainerInstancesException) case clusterContainsServices(ClusterContainsServicesException) case clusterContainsTasks(ClusterContainsTasksException) case clusterNotFound(ClusterNotFoundException) case invalidParameter(InvalidParameterException) case limitExceeded(LimitExceededException) case missingVersion(MissingVersionException) case noUpdateAvailable(NoUpdateAvailableException) case platformTaskDefinitionIncompatibility(PlatformTaskDefinitionIncompatibilityException) case platformUnknown(PlatformUnknownException) case resourceInUse(ResourceInUseException) case resourceNotFound(ResourceNotFoundException) case server(ServerException) case serviceNotActive(ServiceNotActiveException) case serviceNotFound(ServiceNotFoundException) case targetNotConnected(TargetNotConnectedException) case targetNotFound(TargetNotFoundException) case taskSetNotFound(TaskSetNotFoundException) case unsupportedFeature(UnsupportedFeatureException) case updateInProgress(UpdateInProgressException) case validationError(reason: String) case unrecognizedError(String, String?) enum CodingKeys: String, CodingKey { case type = "__type" case message = "message" } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) var errorReason = try values.decode(String.self, forKey: .type) let errorMessage = try values.decodeIfPresent(String.self, forKey: .message) if let index = errorReason.firstIndex(of: "#") { errorReason = String(errorReason[errorReason.index(index, offsetBy: 1)...]) } switch errorReason { case accessDeniedIdentity: let errorPayload = try AccessDeniedException(from: decoder) self = ElasticContainerError.accessDenied(errorPayload) case attributeLimitExceededIdentity: let errorPayload = try AttributeLimitExceededException(from: decoder) self = ElasticContainerError.attributeLimitExceeded(errorPayload) case blockedIdentity: let errorPayload = try BlockedException(from: decoder) self = ElasticContainerError.blocked(errorPayload) case clientIdentity: let errorPayload = try ClientException(from: decoder) self = ElasticContainerError.client(errorPayload) case clusterContainsContainerInstancesIdentity: let errorPayload = try ClusterContainsContainerInstancesException(from: decoder) self = ElasticContainerError.clusterContainsContainerInstances(errorPayload) case clusterContainsServicesIdentity: let errorPayload = try ClusterContainsServicesException(from: decoder) self = ElasticContainerError.clusterContainsServices(errorPayload) case clusterContainsTasksIdentity: let errorPayload = try ClusterContainsTasksException(from: decoder) self = ElasticContainerError.clusterContainsTasks(errorPayload) case clusterNotFoundIdentity: let errorPayload = try ClusterNotFoundException(from: decoder) self = ElasticContainerError.clusterNotFound(errorPayload) case invalidParameterIdentity: let errorPayload = try InvalidParameterException(from: decoder) self = ElasticContainerError.invalidParameter(errorPayload) case limitExceededIdentity: let errorPayload = try LimitExceededException(from: decoder) self = ElasticContainerError.limitExceeded(errorPayload) case missingVersionIdentity: let errorPayload = try MissingVersionException(from: decoder) self = ElasticContainerError.missingVersion(errorPayload) case noUpdateAvailableIdentity: let errorPayload = try NoUpdateAvailableException(from: decoder) self = ElasticContainerError.noUpdateAvailable(errorPayload) case platformTaskDefinitionIncompatibilityIdentity: let errorPayload = try PlatformTaskDefinitionIncompatibilityException(from: decoder) self = ElasticContainerError.platformTaskDefinitionIncompatibility(errorPayload) case platformUnknownIdentity: let errorPayload = try PlatformUnknownException(from: decoder) self = ElasticContainerError.platformUnknown(errorPayload) case resourceInUseIdentity: let errorPayload = try ResourceInUseException(from: decoder) self = ElasticContainerError.resourceInUse(errorPayload) case resourceNotFoundIdentity: let errorPayload = try ResourceNotFoundException(from: decoder) self = ElasticContainerError.resourceNotFound(errorPayload) case serverIdentity: let errorPayload = try ServerException(from: decoder) self = ElasticContainerError.server(errorPayload) case serviceNotActiveIdentity: let errorPayload = try ServiceNotActiveException(from: decoder) self = ElasticContainerError.serviceNotActive(errorPayload) case serviceNotFoundIdentity: let errorPayload = try ServiceNotFoundException(from: decoder) self = ElasticContainerError.serviceNotFound(errorPayload) case targetNotConnectedIdentity: let errorPayload = try TargetNotConnectedException(from: decoder) self = ElasticContainerError.targetNotConnected(errorPayload) case targetNotFoundIdentity: let errorPayload = try TargetNotFoundException(from: decoder) self = ElasticContainerError.targetNotFound(errorPayload) case taskSetNotFoundIdentity: let errorPayload = try TaskSetNotFoundException(from: decoder) self = ElasticContainerError.taskSetNotFound(errorPayload) case unsupportedFeatureIdentity: let errorPayload = try UnsupportedFeatureException(from: decoder) self = ElasticContainerError.unsupportedFeature(errorPayload) case updateInProgressIdentity: let errorPayload = try UpdateInProgressException(from: decoder) self = ElasticContainerError.updateInProgress(errorPayload) default: self = ElasticContainerError.unrecognizedError(errorReason, errorMessage) } } }
52.983607
108
0.768152
20a7c450da5afbdef4089596b9a85c78d3aed99e
634
// // ChatImage.swift // SendBird-iOS // // Created by Jed Gyeong on 3/15/17. // Copyright © 2017 SendBird. All rights reserved. // import UIKit import NYTPhotoViewer class ChatImage: NSObject, NYTPhoto { var image: UIImage? var imageData: Data? var placeholderImage: UIImage? var attributedCaptionTitle: NSAttributedString? var attributedCaptionSummary: NSAttributedString? var attributedCaptionCredit: NSAttributedString? init(image: UIImage? = nil, imageData: NSData? = nil) { super.init() self.image = image self.imageData = imageData as Data? } }
21.862069
59
0.671924
629215753395934a79c29e8ec145dc85ef98d58e
279
import Foundation struct ImageData { let id = UUID().uuidString } protocol ImageCaptureContext { var title: String { get } } protocol ImageCaptureWorkflow { var captureContext: ImageCaptureContext { get } func captured(_ image: ImageData) func cancel() }
16.411765
51
0.709677
b960c6af7dd64f7b6a45fe491b641ba0d3f37d82
1,442
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-cxx-interop import MemberwiseInitializer let structPrivateOnly = StructPrivateOnly(varPrivate: 42) // expected-error {{argument passed to call that takes no arguments}} let structPublicOnly = StructPublicOnly(varPublic: 42) let structEmptyPrivateSetion = StructEmptyPrivateSection(varPublic: 42) let structPublicAndPrivate1 = StructPublicAndPrivate(varPublic: 42) // expected-error {{argument passed to call that takes no arguments}} let structPublicAndPrivate2 = StructPublicAndPrivate(varPublic: 42, varPrivate: 23) // expected-error {{argument passed to call that takes no arguments}} let structWithUnimportedMemberFunction = StructWithUnimportedMemberFunction(varPublic: 42) let classPrivateOnly = ClassPrivateOnly(varPrivate: 42) // expected-error {{argument passed to call that takes no arguments}} let classPublicOnly = ClassPublicOnly(varPublic: 42) let classEmptyPublicSetion = ClassEmptyPublicSection(varPrivate: 42) // expected-error {{argument passed to call that takes no arguments}} let classPublicAndPrivate1 = ClassPrivateAndPublic(varPublic: 23) // expected-error {{argument passed to call that takes no arguments}} let classPublicAndPrivate2 = ClassPrivateAndPublic(varPrivate: 42, varPublic: 23) // expected-error {{argument passed to call that takes no arguments}} let classWithUnimportedMemberFunction = ClassWithUnimportedMemberFunction(varPublic: 42)
80.111111
154
0.816921
164bb0b3c2a05346367492d7c65eaba8a6e7c49d
1,213
// // AVSpeechSynthesizerSampleUITests.swift // AVSpeechSynthesizerSampleUITests // // Created by R.miyamoto on 2019/09/16. // Copyright © 2019 R.Miyamoto. All rights reserved. // import XCTest class AVSpeechSynthesizerSampleUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.657143
182
0.703215
fe53987b7a283092a3c389973d2e0409bb23214a
2,386
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct FailoverGroupUpdatePropertiesData : FailoverGroupUpdatePropertiesProtocol { public var readWriteEndpoint: FailoverGroupReadWriteEndpointProtocol? public var readOnlyEndpoint: FailoverGroupReadOnlyEndpointProtocol? public var databases: [String]? enum CodingKeys: String, CodingKey {case readWriteEndpoint = "readWriteEndpoint" case readOnlyEndpoint = "readOnlyEndpoint" case databases = "databases" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.readWriteEndpoint) { self.readWriteEndpoint = try container.decode(FailoverGroupReadWriteEndpointData?.self, forKey: .readWriteEndpoint) } if container.contains(.readOnlyEndpoint) { self.readOnlyEndpoint = try container.decode(FailoverGroupReadOnlyEndpointData?.self, forKey: .readOnlyEndpoint) } if container.contains(.databases) { self.databases = try container.decode([String]?.self, forKey: .databases) } if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if self.readWriteEndpoint != nil {try container.encode(self.readWriteEndpoint as! FailoverGroupReadWriteEndpointData?, forKey: .readWriteEndpoint)} if self.readOnlyEndpoint != nil {try container.encode(self.readOnlyEndpoint as! FailoverGroupReadOnlyEndpointData?, forKey: .readOnlyEndpoint)} if self.databases != nil {try container.encode(self.databases as! [String]?, forKey: .databases)} } } extension DataFactory { public static func createFailoverGroupUpdatePropertiesProtocol() -> FailoverGroupUpdatePropertiesProtocol { return FailoverGroupUpdatePropertiesData() } }
45.884615
152
0.739732